http://stackoverflow.com/comment/82060201
type: Comment
comment on: http://stackoverflow.com/q/47551654
score: 0
has text: for i in range(len(string1)): print ('i: %d, char: %s'%(i,string1[i]))
type: QuestionComment

http://stackoverflow.com/a/53064059
upvote count: 8
has comment: http://stackoverflow.com/comment/112720769
has comment: http://stackoverflow.com/comment/93075051
type: Answer
has body: Use Ellipsis! For quick breakpoints or something that make minimum visual impact to you code, you may insert and break on an ... (Ellipsis): For example: while some_condition(): do_something() ... # &lt;&lt;&lt; set break point here! this may the most clean way towards me. Some background Ellipsis is a special built-in python object mainly for Slice notating. Here I (ab)use it to do something else. See: What does the Python Ellipsis object do? It is OK to insert a bare integer, variable name or something into code to set break point on certain place, but it may look odd and clutter your code, but ... is visually harmless. Compare with this: break_point = 0 while some_condition(): do_something() break_point # &lt;&lt;&lt; set break point here! or this: while some_condition(): do_something() if False: # &lt;&lt;&lt; set break point here! pass some other tricks tested: del [] # works(with warning: "cannot assign to []") [] # works(with warning: Statement seems to have no effect) setbreakpoint = 1 # works(with warning: "local variable value is not used") Ellipsis # works(with warning: Statement seems to have no effect) another interesting thing that happens to me is, when i set breakpoints on pass it may or may not break, depending to its location in code, but the exact rule for break or not is somehow unclear.
has comment: http://stackoverflow.com/comment/93074419
score: 8
has comment: http://stackoverflow.com/comment/93046556
has comment: http://stackoverflow.com/comment/93049044
downvote count: 0
answers question: http://stackoverflow.com/q/47625526

http://stackoverflow.com/comment/82232380
comment on: http://stackoverflow.com/a/47589259
score: 0
type: Comment
has text: I've posted the entirety of my code above; as you can see, there's not a lot going on there in terms of memory-intensiveness. As for "what else is in the workbook", it's just a workbook with text (and integers) in cells. There are no formulas, no references, no gigantic amounts of text in any cell, and nothing is calculated within the worksheet. I can't share the file because it's participant data but I'm happy to look further if you can point me in the direction of what to look for!
type: AnswerComment

http://stackoverflow.com/q/47664874
has title: matplotlib how to make text to have the same length visually after filling space
accepted answer: http://stackoverflow.com/a/47672736
tagged with: python
tagged with: string-length
tagged with: text
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47672736
tagged with: matplotlib
linked to: http://stackoverflow.com/q/47611399
answer count: 1
favorite count: 0
type: Question
has body: I am struggling to make the text in matplotlib to have the same visual length after filling space. It always doesn't work for me. Here is what I have tried, from matplotlib import pyplot as plt fig = plt.figure() plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5)) plt.text(0,0,'how'.ljust(len('how are you'), bbox=dict(facecolor='red', alpha=0.5)) plt.show() And ideas? Thanks!

http://stackoverflow.com/comment/82070786
comment on: http://stackoverflow.com/q/47556360
score: 0
type: QuestionComment
type: Comment
has text: Why you do not iterate twice with for loop. It will tell you that `for loop` is the bottleneck here!

http://stackoverflow.com/q/47557240
has comment: http://stackoverflow.com/comment/82077689
type: UnansweredQuestion
has body: I'm writing an editor that is used to configure some properties for a different system. I have a table model working for displaying and editing all the data, it's setup like: RowCount | Text1Position | Text1 | Text2Position | Text2 | text3Position | .... +----------+---------------+-------+---------------+-------+---------------+-----+ Graphic1 | 8 | 1 | 'xyz' | 3 | 'abc' | 2 | +----------+---------------+-------+---------------+-------+---------------+-----+ Graphic2 | 16 | 16 | 'xyz' | 15 | 'abc' | 14 | +----------+---------------+-------+---------------+-------+---------------+-----+ There are 32 pairs of texts and positions and a column to for row count. (This is for an HMI popup populated from values stored in a PLC AOI, it has 32 possible rows that can be rearranged in any order) The row count column is used to determine the popup graphic, there's sizes like 8/16/32. For my GUI, I used QDataWidgetMapper to map each control on my editor panel to a column in the model. Then I have a listview that changes the current index of the mapper. Each position column is mapped to a QComboBox. I would like to set it up to where the dropdown of each combobox only shows the positions left. Position 0 is 'Hidden', so that should be always be an option. So for the row Graphic1 above, the only items in the drop down should be: ['Hidden', 4, 5, 6, 7, 8]. I think I want to use a proxy model that only shows the available positions, but I haven't been able to find an example. Right now I'm using one QStringListModel as the source model for the all comboboxes. I have also tried overriding the showPopup method to populate each combobox's items with the available ones, but that breaks the column mapping and then it no longer updates. In the sample code below, I want the combobox dropdowns to only show values between 0 and the whatever is selected in cboRows minus any numbers selected in the other comboboxes. Any advice on how to implement that? from PyQt5.QtWidgets import QApplication…
tagged with: python
has title: QDataWidgetMapper with QComboBox controls, dynamically changing the available items in the drop down
tagged with: qt5
tagged with: qt
score: 0
answer count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/82085671
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/82085627
type: Question
has comment: http://stackoverflow.com/comment/82085539

http://stackoverflow.com/q/47649987
has comment: http://stackoverflow.com/comment/82260552
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47653226
has title: How to save NLTK concordance results in a list?
tagged with: nltk
accepted answer: http://stackoverflow.com/a/47653381
linked to: http://stackoverflow.com/q/11044072
has body: I'm using the NLTK to find word in a text. I need to save result of concordance function into a list. The question is already asked here but i cannot see the changes. I try to find the type of returnde value of the function by : type(text.concordance('myword')) the result was : &lt;class 'NoneType'&gt;
tagged with: corpus
tagged with: python
linked to: http://stackoverflow.com/q/41135369
linked to: http://stackoverflow.com/q/4675728
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82259279
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/47653381
has answer: http://stackoverflow.com/a/57143185
possible better answer: http://stackoverflow.com/a/57143185
has comment: http://stackoverflow.com/comment/82264824
tagged with: nlp

http://stackoverflow.com/q/47657424
answer count: 1
tagged with: file
has title: key error while trying to pass data as a parameter using a json file
favorite count: 0
type: Question
has body: code is given below import time import unittest import logging as log from loggenerator import set_log_params,move_latest_log_to_persistent_file from parse_test_json import get_test_params from scrapping import SC class ScrapeTest(unittest.TestCase): def setup(self): self.start_time=time.time() def teardown(self): self.end_time=time.time() def test_SC_scrape(self): try: test_name="test scrape" set_log_params(log_file=test_name,level=log.INFO) log.info("step1:set all test params") test_params = get_test_params(self.__class__.__name__, test_name=test_name) log.info("step 2:set") ik=SC() log.info("step3:calling scrapper for") log.debug(ik.parseURL(party_name=test_params["party_name"],start_date=test_params["start_date"],end_date=test_params["end_date"])) except Exception as e: raise e move_latest_log_to_persistent_file(log_file=test_name) #### import json, os from builtins import * def get_test_params(test_class_name = None, test_name = None): dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = "/test_param_jsons/" + test_class_name + "params.json" json_file = dir_path + file_path with open(json_file) as test_data: test_json = json.load(test_data) return test_json[test_class_name][test_name] this function is raising error key error.
type: UnansweredQuestion
score: -2
tagged with: io
tagged with: python
has answer: http://stackoverflow.com/a/47658485
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
downvote count: 2

http://stackoverflow.com/comment/82281073
has text: `for row in csv.reader(file_object):` will read one line at a time. See [**`csv.reader`**](https://docs.python.org/3/library/csv.html#csv.reader)
type: Comment
comment on: http://stackoverflow.com/q/47648983
score: 0
type: QuestionComment

http://stackoverflow.com/a/47613762
score: 0
answers question: http://stackoverflow.com/q/47613121
type: Answer
has body: If you have list with positions then use for loop to draw it. Here position is in pixels # --- constants --- (UPPER_CASE_NAMES) WIDTH = 50 HEIGHT = 50 RED = (255,0,0) # --- main --- rectangles_XY = [ (0, 0), (50, 0), (100, 0) ] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: # PLEASE, don't put all in one line # it makes code less readable. pygame.quit() sys.exit () for x, y in rectangles_XY: pygame.draw.rect(screen, RED, (x, y, WIDTH, HEIGHT), 0) pygame.display.update() Here position is in cell positon (column, row) # --- constants --- (UPPER_CASE_NAMES) WIDTH = 50 HEIGHT = 50 RED = (255,0,0) # --- main --- rectangles = [ (0, 0), (1, 0), (2, 0) ] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: # PLEASE, don't put all in one line # it makes code less readable. pygame.quit() sys.exit () for column, row in rectangles: x = column * WIDTH y = row * HEIGHT pygame.draw.rect(screen, RED, (x, y, WIDTH, HEIGHT), 0) pygame.display.update()

http://stackoverflow.com/q/47687619
has comment: http://stackoverflow.com/comment/82334754
has comment: http://stackoverflow.com/comment/82334800
tagged with: python
has comment: http://stackoverflow.com/comment/82334686
has body: In python, suppose the code is: import.math a = math.sqrt(2.0) if a * a == 2.0: x = 2 else: x = 1
answer count: 2
has title: How are data types interpreted, calculated, and/or stored?
has comment: http://stackoverflow.com/comment/82334917
has answer: http://stackoverflow.com/a/47687752
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47687859
type: Question
has comment: http://stackoverflow.com/comment/82334642
score: 0

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

http://stackoverflow.com/q/47560087
has answer: http://stackoverflow.com/a/47560985
has body: I have a list of strings in a file. I am trying to extract a substring from each string and printing them. The strings look like the following - Box1 is lifted\nInform the manufacturer Box2 is lifted\nInform the manufacturer Box3, Box4 is lifted\nInform the manufacturer Box5, Box6 is lifted\nInform the manufacturer Box7 is lifted\nInform the manufacturer From each line I have to extract the string before \n and print them. I used the following Python regex to do that - term = r'.*-\s([\w\s]+)\\n' This regex works fine for the 1st, 2nd and last line. But it doesn't work for the 3rd and 4th lines since there is a , in the string. How should I modify my regex expression to fit in that? Expected results - Box1 is lifted Box2 is lifted Box3 Box4 is lifted Box5 Box6 is lifted Box7 is lifted Results obtained currently - Box1 is lifted Box2 is lifted Box2 is lifted Box2 is lifted Box7 is lifted
has answer: http://stackoverflow.com/a/47560270
has answer: http://stackoverflow.com/a/47560242
has comment: http://stackoverflow.com/comment/82078352
tagged with: python
has answer: http://stackoverflow.com/a/47560145
has comment: http://stackoverflow.com/comment/82078768
type: Question
linked to: http://stackoverflow.com/q/5749195
upvote count: 2
has answer: http://stackoverflow.com/a/47560418
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47560202
downvote count: 1
answer count: 7
tagged with: string
favorite count: 0
has title: Extract a substring from a string including a comma
has answer: http://stackoverflow.com/a/47560165

http://stackoverflow.com/a/47739645
answers question: http://stackoverflow.com/q/47582199
has comment: http://stackoverflow.com/comment/82484309
type: Answer
has comment: http://stackoverflow.com/comment/82485821
has body: If pip finds that this specific dependency isn't installed, I want to either abort the install... If I understand you correctly, you could check if the proprietary package is installed by simply trying to import a module from that package in your setup.py, aborting on ImportError. As an example, let's say your dependency that should abort the installation is numpy: from distutils.command.build import build as build_orig from distutils.errors import DistutilsModuleError from setuptools import setup class build(build_orig): def finalize_options(self): try: import numpy except ImportError: raise DistutilsModuleError('numpy is not installed. Installation will be aborted.') super().finalize_options() setup( name='spam', version='0.1', author='nobody', author_email='nobody@nowhere.com', packages=[], install_requires=[ # all the other dependencies except numpy go here as usual ], cmdclass={'build': build,}, ) Now, you should distribute your package as source tar because wheels won't invoke setup.py on installation: $ python setup.py sdist Trying to install the built tar when numpy is missing will result in: $ pip install dist/spam-0.1.tar.gz Processing ./dist/spam-0.1.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/spam.egg-info writing pip-egg-info/spam.egg-info/PKG-INFO writing dependency_links to pip-egg-info/spam.egg-info/dependency_links.txt writing top-level names to pip-egg-info/spam.egg-info/top_level.txt writing manifest file 'pip-egg-info/spam.egg-info/SOURCES.txt' reading manifest file 'pip-egg-info/spam.egg-info/SOURCES.txt' error: numpy is not installed. Installation will be aborted. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/_y/2qk6029j4c7bwv0ddk3p96r00000gn/T/pip-s8sqn20t-build/ Note that I could do the import check on top of the setup script: from setuptools import setup try: import numpy except ImportError: raise DistutilsM…
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47542643
type: Question
has answer: http://stackoverflow.com/a/47542859
tagged with: numpy
tagged with: python-2.7
has title: Separate last column from the actual dataset using numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/82042585
type: AnsweredQuestion
has body: I have a dataset in csv format (without headers) where I want to split it into two parts: (1) The actual dataset without the last column, (2) the last column (class label). My dataset has 100K rows and 65 features ( where the last column, column 65, is the class label that I want to separate). I wrote the following: dataset_path = 'dataset.csv' dataset = np.genfromtxt(dataset_path, delimiter=',') class_label = dataset[:-1] dataset.drop(class_label, axis=1, inplace=True) print dataset.shape print class_label This is in fact wrong. I am not able to achieve what I want. Any help is appreciated.
answer count: 3
has answer: http://stackoverflow.com/a/74175440
tagged with: python
accepted answer: http://stackoverflow.com/a/47542892
possible better answer: http://stackoverflow.com/a/47542859
has answer: http://stackoverflow.com/a/47542892
upvote count: 11
favorite count: 0
score: 11

http://stackoverflow.com/q/47590595
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47590715
has comment: http://stackoverflow.com/comment/82138203
answer count: 2
tagged with: functional-programming
has answer: http://stackoverflow.com/a/70096979
has title: summing nested iterables with map-reduce/itertools
downvote count: 0
tagged with: mapreduce
has body: I've been stuck with this data structure for a while now: iter([iter([1,0]),iter([1,1]),iter([0,0])]) I want to get to sum of the inner-most elements using map-reduce/itertools. I am able to get to the answer fairly quickly using for loops: outer_iter = iter([iter([1,0]),iter([1,1]),iter([0,0])]) for inner_iter in outer_iter: for inner_list in inner_iter: total = total + inner_list I am struggling to "translate" the code.
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/70096979
linked to: http://stackoverflow.com/q/29403401
upvote count: 2
tagged with: python-itertools
tagged with: python
accepted answer: http://stackoverflow.com/a/47590715
score: 2

http://stackoverflow.com/comment/82431152
comment on: http://stackoverflow.com/q/47636534
score: 0
type: QuestionComment
has text: What does `curl https://pypi.python.org` say?
type: Comment

http://stackoverflow.com/comment/82218282
type: QuestionComment
comment on: http://stackoverflow.com/q/47630263
has text: what is your expected output ?
score: 0
type: Comment

http://stackoverflow.com/q/47598177
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82154884
has body: First off, I'm sure this has been asked before, but I lack the vocabulary to properly find the answer I'm looking for. Sorry for the newbie question, and thanks for the help in advance. So I'm creating a python test web application abstraction layer for use in test cases down the road. The problem that I'm running into is that the web application I'm testing is HUGE, and my class is growing out of control. So far the code I've created works like this... app = ApplicationUi(browser=Chrome) app.login(USER, PASS) app.menu_network_settings() app.network_dns3("192.168.1.1") app.network_save() app.menu_user_settings() app.user_change_password(USER, PASS) app.logout() So everything works fine, I'm plugging away at defining all of the methods, and things are going kinda smoothly. The problem that I'm concerned about is there are literally thousands of elements in this configuration application, and I'd like to break it up into smaller files. I'm not really what would be the best way to do it however. For example here is a bit of code structure that I have. class ApplicationUi(object): def __init__(self, url, browser="chrome"): display = Display(visible=0, size=(1366, 1920)) display.start() self.driver = _driver_init(browser) self.driver.set_window_size(1366, 1920) self.driver.get(url) time.sleep(BASE_SLEEP) def __del__(self): if "driver" in self.__dict__.keys(): self.driver.close() def logon(self, user, passwd): self.driver.find_element_by_xpath('//*[@id="userName"]').send_keys(user) self.driver.find_element_by_xpath('//*[@id="password"]').send_keys(passwd) self.driver.find_element_by_xpath('//*[@id="buttonid"]').click() time.sleep(BASE_SLEEP) def menu_audit(self): self.driver.find_element_by_xpath('//*[@id="toolsMenu"]/span').click() time.sleep(BASE_SLEEP) def menu_resources(self): self.driver.find_element_by_xpath('//*[@id="PrimaryNavigationCollapse"]/ul/li[2]/ul/li[1]/ul/li[1]').click() time.sleep(BASE_SLEEP) def menu_notifications(self): self.driver.find_element_by_xpat…
has comment: http://stackoverflow.com/comment/82155574
has comment: http://stackoverflow.com/comment/82154759
tagged with: code-structure
answer count: 0
downvote count: 0
has title: Python how to break up a large class / generic class code structure
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82158445
tagged with: oop
type: Question

http://stackoverflow.com/comment/82204381
comment on: http://stackoverflow.com/a/47623192
type: Comment
has text: @Blckknght: That's exactly why I hedged what I said a bit and wrote "assuming you have good reason" (for having two separate classes). I think it's a fairly common mistake for folks to think they need a separate class whenever something that could be handled by simply storing different attribute values within a single class (and using them to control instances's behavior).
score: 0
type: AnswerComment

csrf
tags question: http://stackoverflow.com/q/47687307
tags question: http://stackoverflow.com/q/47697465
tag name: csrf
type: Tag

http://stackoverflow.com/comment/82177304
type: Comment
has text: did you `print(wins)` to see what you have in variable ?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47609281

http://stackoverflow.com/comment/82253025
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47646944
type: AnswerComment
has text: @BrandonDube My understanding is that for tensors, `dot` is looping at some level (most probably at C level), while `tensordot` avoids it.

http://stackoverflow.com/q/47687564
linked to: http://stackoverflow.com/q/1167398
favorite count: 0
type: Question
upvote count: 3
type: UnansweredQuestion
tagged with: undo
has comment: http://stackoverflow.com/comment/82375901
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82337243
has comment: http://stackoverflow.com/comment/82334932
has comment: http://stackoverflow.com/comment/82336654
has comment: http://stackoverflow.com/comment/82336997
has answer: http://stackoverflow.com/a/47693987
score: 3
has comment: http://stackoverflow.com/comment/82334897
answer count: 2
has comment: http://stackoverflow.com/comment/82352779
linked to: http://stackoverflow.com/q/7509129
has body: This appears simple, but I can't find a good solution. It's the old 'pass by reference'/ 'pass by value' / 'pass by object reference' problem. I understand what is happening, but I can't find a good work around. I am aware of solutions for small problems, but my state is very large and extremely expensive to save/ recalculate. Given these constraints, I can't find a solution. Here is some simple pseudocode to illustrate what I would like to do (if Python would let me pass by reference): class A: def __init__(self,x): self.g=x self.changes=[] def change_something(self,what,new): # I want to pass 'what' by reference old=what # and then de-reference it here to read the value self.changes.append([what,old]) # store a reference what=new # dereference and change the value def undo_changes(): for c in self.changes: c[0]=c[1] # dereference and restore old value Edit: Adding some more pseudocode to show how I would like the use the above test=A(1) # initialise test.g as 1 print(test.g) out: 1 test.change_something(test.g,2) # if my imaginary code above functioned as described in its comments, # this would change test.g to 2 and store the old value in the list of changes print(test.g) out: 2 test.undo_changes() print(test.g) out: 1 Obviously the above code doesnt work in python due to being 'pass by object reference'. Also I'd like to be able to undo a single change, not just all of them as in the code above. The thing is... I can't seem to find a good work around. There are solutions out there like these: Do/Undo using command pattern in Python making undo in python Which involve storing a stack of commands. 'Undo' then involves removing the last command and then re-building the final state by taking the initial state and re-applying everything but the last command. My state is too large for this to be feasible, the issues are: The state is very large. Saving it entirely is prohibitively expensive. 'Do' operations are costly (making recalculating from a saved state infeasibl…
has comment: http://stackoverflow.com/comment/82337546
has comment: http://stackoverflow.com/comment/82335037
has comment: http://stackoverflow.com/comment/82334805
has comment: http://stackoverflow.com/comment/82334837
has title: Undo in Python with a very large state. Is it possible?
has comment: http://stackoverflow.com/comment/82337560
linked to: http://stackoverflow.com/q/2006404
has answer: http://stackoverflow.com/a/47689441

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/47551557
tags question: http://stackoverflow.com/q/47630631
tags question: http://stackoverflow.com/q/47638670
tags question: http://stackoverflow.com/q/47656815
tags question: http://stackoverflow.com/q/47650800
type: Tag
tags question: http://stackoverflow.com/q/47628131
tags question: http://stackoverflow.com/q/47637288
tags question: http://stackoverflow.com/q/47631925
tags question: http://stackoverflow.com/q/47547755
tags question: http://stackoverflow.com/q/47662152
tags question: http://stackoverflow.com/q/47592822
tags question: http://stackoverflow.com/q/47687333
tags question: http://stackoverflow.com/q/47689968
tags question: http://stackoverflow.com/q/47551526
tag name: r
tags question: http://stackoverflow.com/q/47549176
tags question: http://stackoverflow.com/q/47560931
tags question: http://stackoverflow.com/q/47575228

graph
tags question: http://stackoverflow.com/q/47579442
tags question: http://stackoverflow.com/q/47608244
tags question: http://stackoverflow.com/q/47687610
tags question: http://stackoverflow.com/q/47661180
tags question: http://stackoverflow.com/q/47585820
tags question: http://stackoverflow.com/q/47624014
tags question: http://stackoverflow.com/q/47612702
tag name: graph
type: Tag
tags question: http://stackoverflow.com/q/47598789
tags question: http://stackoverflow.com/q/47694534
tags question: http://stackoverflow.com/q/47685350
tags question: http://stackoverflow.com/q/47663030
tags question: http://stackoverflow.com/q/47586269
tags question: http://stackoverflow.com/q/47652299
tags question: http://stackoverflow.com/q/47597418

http://stackoverflow.com/comment/82424275
comment on: http://stackoverflow.com/q/47660171
type: Comment
has text: FWIW, errno 24 on MacOS is `EMFILE`, too many open files in process, which means that the process calling `os.pipe` here has reached its open-file-descriptor limit which appears to default to 256. It could be worth poking around to see which file descriptors are open, and why.
score: 0
type: QuestionComment

http://stackoverflow.com/q/47598095
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47598200
score: 0
has body: This is closely related to this question - but I would like to find the % difference based on the previous row and not the first row as in the example. So my input would be security date price IBM 1/1/2016 100 IBM 1/2/2016 102 IBM 1/3/2016 108 AAPL 1/1/2016 1000 AAPL 1/2/2016 980 AAPL 1/3/2016 1050 AAPL 1/4/2016 1070 And my resultant output would be security date price change IBM 1/1/2016 100 NA IBM 1/2/2016 102 2% IBM 1/3/2016 108 5.8% AAPL 1/1/2016 1000 NA AAPL 1/2/2016 980 -2% AAPL 1/3/2016 1050 7.14% AAPL 1/4/2016 1070 1.9%
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47598200
possible better answer: http://stackoverflow.com/a/47598194
linked to: http://stackoverflow.com/q/35090498
has answer: http://stackoverflow.com/a/47598194
has title: Pandas - percent difference within column
tagged with: pandas

http://stackoverflow.com/q/47617158
has comment: http://stackoverflow.com/comment/82199416
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/82192808
linked to: http://stackoverflow.com/q/41440634
has body: I'm trying to build an ETL to load a Dimension table. I'm ussign Apache Bea, with Python and DataFlow, and BigQuery. I need to assign a sequence number to each element of a pcollection in order to load its into BigQuery, but I cant find any way to do this. I think I need DataFlow to make the previous aggregation and joins to get my final pcollection to add the sequence number, but in this moment I need to stop parallel processing and cast my pcollection to a list (as in Spark when you use .collect()) and then make an easy loop to assign the sequence number. is it right? This is the pipeline I've coded: p | ReadFromAvro(known_args.input) | beam.Map(adapt) | beam.GroupByKey() | beam.Map(adaptGroupBy) I've read there is no way to get a list from pcollection: How to get a list of elements out of a PCollection in Google Dataflow and use it in the pipeline to loop Write Transforms? How can I achieve it? Any help?
accepted answer: http://stackoverflow.com/a/47643626
has title: Apache-Beam add sequence number to a PCollection
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47643626
downvote count: 0
has comment: http://stackoverflow.com/comment/82192770
score: 1
tagged with: google-bigquery
answer count: 1
favorite count: 0
tagged with: dataflow
type: Question
has comment: http://stackoverflow.com/comment/82201924
has comment: http://stackoverflow.com/comment/82210271
tagged with: apache-beam
upvote count: 1
tagged with: python

http://stackoverflow.com/a/51051401
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47676248
type: Answer
score: 1
has body: I was locking for solution for the same problem, then I find yours and another solution in the accepted answer here. If the second solution work, I think it will be better than iterating thorough all validation again at " on epoch end" The idea is to save the target and pred placeholders in variables and update the variables through custom callback at " on batch end"

http://stackoverflow.com/a/47550726
upvote count: 1
answers question: http://stackoverflow.com/q/47550041
type: Answer
has body: As others have said, you need to initialize your dictionary outside the loop, and use .append. This seems to be a succinct we of doing it: exData = {"param"+str(i+1):[]} for i in range(10)} for i in range(3, lastRow): exData["param1"].append(sheet.cell(row=i, column=1).value) for j in range(9): exData["param"+str(j+2)].append(float(sheet.cell(row=i, column=j+2).value))
score: 1
downvote count: 0

http://stackoverflow.com/comment/82111416
score: 0
type: Comment
type: AnswerComment
has text: It basically does't matter if its string of integer or any other type because it is being sent over serial port to HW which reads it as bites. But it has to be one byte, not 8 bytes. That is the point.
comment on: http://stackoverflow.com/a/47576371

opencv
tags question: http://stackoverflow.com/q/47585666
tags question: http://stackoverflow.com/q/47621718
tags question: http://stackoverflow.com/q/47665824
type: Tag
tags question: http://stackoverflow.com/q/47609843
tags question: http://stackoverflow.com/q/47632758
tags question: http://stackoverflow.com/q/47592777
tags question: http://stackoverflow.com/q/47543754
tags question: http://stackoverflow.com/q/47662245
tags question: http://stackoverflow.com/q/47652129
tags question: http://stackoverflow.com/q/47659048
tags question: http://stackoverflow.com/q/47595684
tags question: http://stackoverflow.com/q/47566777
tags question: http://stackoverflow.com/q/47597203
tags question: http://stackoverflow.com/q/47641111
tags question: http://stackoverflow.com/q/47582856
tags question: http://stackoverflow.com/q/47692062
tags question: http://stackoverflow.com/q/47667233
tags question: http://stackoverflow.com/q/47580884
tags question: http://stackoverflow.com/q/47555670
tags question: http://stackoverflow.com/q/47631839
tags question: http://stackoverflow.com/q/47557810
tags question: http://stackoverflow.com/q/47630940
tags question: http://stackoverflow.com/q/47597358
tags question: http://stackoverflow.com/q/47667238
tags question: http://stackoverflow.com/q/47663683
tags question: http://stackoverflow.com/q/47689976
tags question: http://stackoverflow.com/q/47631852
tags question: http://stackoverflow.com/q/47613705
tags question: http://stackoverflow.com/q/47577184
tags question: http://stackoverflow.com/q/47571786
tags question: http://stackoverflow.com/q/47694802
tags question: http://stackoverflow.com/q/47612157
tags question: http://stackoverflow.com/q/47574173
tags question: http://stackoverflow.com/q/47550518
tags question: http://stackoverflow.com/q/47615309
tags question: http://stackoverflow.com/q/47616809
tags question: http://stackoverflow.com/q/47632535
tags question: http://stackoverflow.com/q/47549395
tags question: http://stackoverflow.com/q/47591359
tags question: http://stackoverflow.com/q/47647512
tags question: http://stackoverflow.com/q/47644042
tags question: http://stackoverflow.com/q/47586587
tags question: http://stackoverflow.com/q/47580887
tags question: http://stackoverflow.com/q/47614396
tags question: http://stackoverflow.com/q/47567349
tags question: http://stackoverflow.com/q/47678708
tags question: http://stackoverflow.com/q/47674761
tags question: http://stackoverflow.com/q/47598968
tags question: http://stackoverflow.com/q/47656211
tags question: http://stackoverflow.com/q/47568992
tags question: http://stackoverflow.com/q/47658365
tags question: http://stackoverflow.com/q/47597759
tags question: http://stackoverflow.com/q/47621395
tags question: http://stackoverflow.com/q/47660439
tags question: http://stackoverflow.com/q/47687275
tags question: http://stackoverflow.com/q/47638580
tag name: opencv
tags question: http://stackoverflow.com/q/47579944
tags question: http://stackoverflow.com/q/47600315
tags question: http://stackoverflow.com/q/47616186
tags question: http://stackoverflow.com/q/47697476

assert
tags question: http://stackoverflow.com/q/47549202
type: Tag
tags question: http://stackoverflow.com/q/47550664
tag name: assert

http://stackoverflow.com/comment/82140017
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47590967
score: 0
has text: Collecting pandas==0.17 Downloading pandas-0.17.0-cp33-none-win32.whl (5.3MB) 100% |################################| 5.3MB 76kB/s

http://stackoverflow.com/a/47576442
answers question: http://stackoverflow.com/q/47574112
has comment: http://stackoverflow.com/comment/82113351
has comment: http://stackoverflow.com/comment/82110514
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47574112
has comment: http://stackoverflow.com/comment/82113185
type: Answer
has body: Your window is formatted like that because unless configured further grid makes the widget to have around as least amount of pixels as possible for a given content, and that it also assumes every node in a grid occupies the same amount of space (maximum least required among all nodes, in the example entry widget has the largest pixel requirement) for that row or column. An entry widget as far as I know defaults to 20 characters wide width and 1 character tall height. And the button widget requires exactly the amount of space required by what's inside, "1", "2", "3" etc. in your case. And since 20 character is wider than 1 character there's an empty space around 1 character button in order to match that of entry widget's width. There can be some ways of preventing that, one that I can think of is: changing text.grid(row = 0, column = 0) to text.grid(row = 0, column = 0, columnspan=4) so that it spans not only 1 column but 4 so that it matches the entirety of the buttons under it.

http://stackoverflow.com/comment/82243142
has text: @juanpa.arrivillaga read your comment... that's true, removed my answer. I thought that vectorized will run always parallel?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47642211
type: Comment

http://stackoverflow.com/q/47596899
score: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50184070
has answer: http://stackoverflow.com/a/47611069
favorite count: 0
tagged with: weblate
type: Question
has body: I am trying to force Weblate running in docker to support SAML2 authentication (we have corporate ADFS). I found plugin for django. So I create own Dockerfile: from weblate/weblate RUN set -x \ &amp;&amp; apt-get install --no-install-recommends -y xmlsec1 build-essential \ &amp;&amp; pip install django_saml2_auth RUN (echo &amp;&amp; echo 'execfile("/app/data/settings.override.py")') &gt;&gt; /app/etc/settings.py content of settings.override.py: INSTALLED_APPS = INSTALLED_APPS + ('django_saml2_auth',) SAML2_AUTH = { 'METADATA_AUTO_CONF_URL': 'https://adfs.homecredit.net/federationmetadata/2007-06/federationmetadata.xml', } I failed with setting of 'urls.py' as mantioned in plugin's manual (I cannot find this file inside docker container) - I am not python/django developer and don't know how to continue. Thanks for help.
tagged with: django
type: UnansweredQuestion
tagged with: python
has title: Use SAML2 auth with Weblate
linked to: http://stackoverflow.com/q/50162705
upvote count: 2

linear-regression
tags question: http://stackoverflow.com/q/47569966
tags question: http://stackoverflow.com/q/47593225
tag name: linear-regression
tags question: http://stackoverflow.com/q/47692054
type: Tag
tags question: http://stackoverflow.com/q/47543589
tags question: http://stackoverflow.com/q/47646183

http://stackoverflow.com/a/47683915
type: Answer
score: 4
has body: Here you go import re string = """TRAFALGAR LAW You shall not be the pirate king. MONKEY D LUFFY Now! DOFLAMINGO'S UNDERLINGS: Noooooo! """ rx = re.compile(r"^([A-Z ':]+$)", re.M) UPPERCASE = [line for line in string.split("\n") if rx.match(line)] print(UPPERCASE) Or: rx = re.compile(r"^([A-Z ':]+$)", re.M) UPPERCASE = rx.findall(string) print(UPPERCASE) Both will yield ['TRAFALGAR LAW', 'MONKEY D LUFFY', "DOFLAMINGO'S UNDERLINGS:"]
accepted answer of: http://stackoverflow.com/q/47683871
upvote count: 4
has comment: http://stackoverflow.com/comment/123872431
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82328158
answers question: http://stackoverflow.com/q/47683871
has comment: http://stackoverflow.com/comment/82327609

python
tags question: http://stackoverflow.com/q/47593477
tags question: http://stackoverflow.com/q/47665777
tags question: http://stackoverflow.com/q/47640454
tags question: http://stackoverflow.com/q/47598004
tags question: http://stackoverflow.com/q/47641680
tags question: http://stackoverflow.com/q/47693924
tags question: http://stackoverflow.com/q/47575665
tags question: http://stackoverflow.com/q/47675367
tags question: http://stackoverflow.com/q/47544053
tags question: http://stackoverflow.com/q/47621511
tags question: http://stackoverflow.com/q/47601064
tags question: http://stackoverflow.com/q/47691262
tags question: http://stackoverflow.com/q/47692684
tags question: http://stackoverflow.com/q/47579297
tags question: http://stackoverflow.com/q/47634530
tags question: http://stackoverflow.com/q/47592839
tags question: http://stackoverflow.com/q/47582475
tags question: http://stackoverflow.com/q/47667045
tags question: http://stackoverflow.com/q/47544194
tags question: http://stackoverflow.com/q/47558723
tags question: http://stackoverflow.com/q/47630400
tags question: http://stackoverflow.com/q/47651342
tags question: http://stackoverflow.com/q/47597476
tags question: http://stackoverflow.com/q/47658559
tags question: http://stackoverflow.com/q/47682919
tags question: http://stackoverflow.com/q/47676677
tags question: http://stackoverflow.com/q/47629570
tags question: http://stackoverflow.com/q/47640354
tags question: http://stackoverflow.com/q/47660930
tags question: http://stackoverflow.com/q/47605357
tags question: http://stackoverflow.com/q/47634500
tags question: http://stackoverflow.com/q/47552255
tags question: http://stackoverflow.com/q/47673144
tags question: http://stackoverflow.com/q/47656322
tags question: http://stackoverflow.com/q/47648005
tags question: http://stackoverflow.com/q/47657841
tags question: http://stackoverflow.com/q/47597022
tags question: http://stackoverflow.com/q/47580701
tags question: http://stackoverflow.com/q/47684051
tags question: http://stackoverflow.com/q/47560880
tags question: http://stackoverflow.com/q/47553821
tags question: http://stackoverflow.com/q/47577395
tags question: http://stackoverflow.com/q/47609584
tags question: http://stackoverflow.com/q/47582033
tags question: http://stackoverflow.com/q/47603964
tags question: http://stackoverflow.com/q/47637477
tags question: http://stackoverflow.com/q/47567397
tags question: http://stackoverflow.com/q/47693834
tags question: http://stackoverflow.com/q/47660924
tags question: http://stackoverflow.com/q/47642737
tags question: http://stackoverflow.com/q/47579314
tags question: http://stackoverflow.com/q/47690140
tags question: http://stackoverflow.com/q/47614538
tags question: http://stackoverflow.com/q/47593472
tags question: http://stackoverflow.com/q/47595669
tags question: http://stackoverflow.com/q/47674239
tags question: http://stackoverflow.com/q/47586614
tags question: http://stackoverflow.com/q/47688235
tags question: http://stackoverflow.com/q/47649830
tags question: http://stackoverflow.com/q/47671732
tags question: http://stackoverflow.com/q/47544451
tags question: http://stackoverflow.com/q/47581768
tags question: http://stackoverflow.com/q/47626431
tags question: http://stackoverflow.com/q/47569973
tags question: http://stackoverflow.com/q/47561658
tags question: http://stackoverflow.com/q/47610308
tags question: http://stackoverflow.com/q/47548935
tags question: http://stackoverflow.com/q/47642991
tags question: http://stackoverflow.com/q/47675504
tags question: http://stackoverflow.com/q/47684222
tags question: http://stackoverflow.com/q/47564452
tags question: http://stackoverflow.com/q/47566070
tags question: http://stackoverflow.com/q/47565780
tags question: http://stackoverflow.com/q/47683896
tags question: http://stackoverflow.com/q/47662978
tags question: http://stackoverflow.com/q/47660378
tags question: http://stackoverflow.com/q/47683265
tags question: http://stackoverflow.com/q/47580407
tags question: http://stackoverflow.com/q/47658857
tags question: http://stackoverflow.com/q/47691425

http://stackoverflow.com/q/47692014
has answer: http://stackoverflow.com/a/47692086
has answer: http://stackoverflow.com/a/47692130
score: 2
type: AnsweredQuestion
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/82343102
has body: I have a list that looks like this: commands = [ {'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}, {'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}, {'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False} ] And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.
possible better answer: http://stackoverflow.com/a/47692130
downvote count: 0
has answer: http://stackoverflow.com/a/47694463
favorite count: 0
type: Question
has title: Filtering a list in python with many key-value pairs
accepted answer: http://stackoverflow.com/a/47692086
tagged with: python

http://stackoverflow.com/comment/82129905
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47585843
score: 0
has text: Can you share your complete code so that I can reproduce it?

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

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47580186
tags question: http://stackoverflow.com/q/47641181
tags question: http://stackoverflow.com/q/47640568
tags question: http://stackoverflow.com/q/47623026
tags question: http://stackoverflow.com/q/47642400
tags question: http://stackoverflow.com/q/47575560
tags question: http://stackoverflow.com/q/47621228
tags question: http://stackoverflow.com/q/47655470
tags question: http://stackoverflow.com/q/47611721
tags question: http://stackoverflow.com/q/47590724
tags question: http://stackoverflow.com/q/47671551
tags question: http://stackoverflow.com/q/47627293
tags question: http://stackoverflow.com/q/47602225
tags question: http://stackoverflow.com/q/47590361
tags question: http://stackoverflow.com/q/47573081
tags question: http://stackoverflow.com/q/47682369
tags question: http://stackoverflow.com/q/47565885
tags question: http://stackoverflow.com/q/47694493
tags question: http://stackoverflow.com/q/47577823
tags question: http://stackoverflow.com/q/47635726
tags question: http://stackoverflow.com/q/47691050
tags question: http://stackoverflow.com/q/47684719
tags question: http://stackoverflow.com/q/47618563
tags question: http://stackoverflow.com/q/47670181
tags question: http://stackoverflow.com/q/47639263
tags question: http://stackoverflow.com/q/47613627
tags question: http://stackoverflow.com/q/47695466
tags question: http://stackoverflow.com/q/47578810
tags question: http://stackoverflow.com/q/47694188
tags question: http://stackoverflow.com/q/47556046
tags question: http://stackoverflow.com/q/47583844
tags question: http://stackoverflow.com/q/47683278
tags question: http://stackoverflow.com/q/47555854
tags question: http://stackoverflow.com/q/47627698
type: Tag
tags question: http://stackoverflow.com/q/47625659

http://stackoverflow.com/a/47581564
has comment: http://stackoverflow.com/comment/82121166
has comment: http://stackoverflow.com/comment/82120939
has comment: http://stackoverflow.com/comment/82158663
has comment: http://stackoverflow.com/comment/82209711
answers question: http://stackoverflow.com/q/47581326
has comment: http://stackoverflow.com/comment/82166191
has comment: http://stackoverflow.com/comment/82152739
has comment: http://stackoverflow.com/comment/82126713
has comment: http://stackoverflow.com/comment/82140268
has comment: http://stackoverflow.com/comment/82166180
has comment: http://stackoverflow.com/comment/82168754
type: Answer
has comment: http://stackoverflow.com/comment/82121769
has comment: http://stackoverflow.com/comment/82145987
has comment: http://stackoverflow.com/comment/82162639
has comment: http://stackoverflow.com/comment/82172881
has body: Constant time isn't possible. All 1 million digits need to be looked at at least once, so that is a time complexity of O(n), where n = 1 million in this case. For a simple O(n) solution, create an array of size 1000 that represents the number of occurrences of each possible 3 digit number. Advance 1 digit at a time, first index == 0, last index == 999997, and increment array[3 digit number] to create a histogram (count of occurrences for each possible 3 digit number). Then output the content of the array with counts > 1.
has comment: http://stackoverflow.com/comment/82171612
score: 79
upvote count: 79
has comment: http://stackoverflow.com/comment/82149609
has comment: http://stackoverflow.com/comment/82169720
has comment: http://stackoverflow.com/comment/82148188
downvote count: 0
has comment: http://stackoverflow.com/comment/82209696

http://stackoverflow.com/a/47673236
answers question: http://stackoverflow.com/q/47670635
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Goal 2: You use the same timer for all powerups in time_difference2 = pygame.time.get_ticks() - self.now2 ... if time_difference2 &gt;= 5000: so it removes all powerups in the same time. Every powerup needs own timer inside class. I use name kill_time with current_time+5000 time_difference1 = pygame.time.get_ticks() - self.now1 # --- current_time = pygame.time.get_ticks() if time_difference1 &gt;= 2000: powerup = classes.PowerUp(screen_size, 40, 40, "ramen.png") powerup.kill_time = current_time + 5000 self.powerup_group.add(power) self.now1 = pygame.time.get_ticks() # ---- current_time = pygame.time.get_ticks() for powerup in self.powerup_group: if powerup.kill_time &lt;= current_time: self.powerup_group.remove(powerup)

http://stackoverflow.com/a/47610267
upvote count: 1
has body: Here's a small regex to do that: &gt;&gt;&gt; import re &gt;&gt;&gt; s = "I was searching my #source to make a big desk yesterday." &gt;&gt;&gt; re.findall(r"#(\w+)", s) ['source'] If you want to include the hashtag then use: &gt;&gt;&gt; re.findall(r"#.\w+", s) ['#source']
type: Answer
answers question: http://stackoverflow.com/q/47610235
downvote count: 0
score: 1

http://stackoverflow.com/q/47630881
tagged with: database-replication
has body: I am trying, to get replication-delay using db.rs.printSlaveReplicationInfo from python with pymongo, but not getting any proper way to do so. I tried the following, but no help. >>>from pymongo import MongoClient >>>client = MongoClient() >>>db = client.test_database >>>db.rs.printSlaveReplicationInfo Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs.printSlaveReplicationInfo') db.rs.printSlaveReplicationInfo() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib64/python2.7/site-packages/pymongo/collection.py", line 2413, in __call__ self.__name.split(".")[-1]) TypeError: 'Collection' object is not callable. If you meant to call the 'printSlaveReplicationInfo' method on a 'Collection' object it is failing because no such method exists. >>> db.rs Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs') Can anyone help with this? or how to do it? Thanks in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/47648526
type: Question
tagged with: python-2.7
tagged with: mongodb
has title: Get replicationLag in mongo with pyMongo
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: pymongo
has answer: http://stackoverflow.com/a/47648526
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/82321784
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47679648
type: Comment
has text: This is appropriate for the DataScience Stack Exchange (not StackOverflow)

http://stackoverflow.com/a/71941053
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47550523
has body: I had the same problem. The problem was in the encoding. By default, ConfigParser.read() uses the encoding=none parameter. I specified utf-8 and it worked. config = configparser.ConfigParser() config.read(configFilePath, encoding='utf-8')
downvote count: 0
score: 1

http://stackoverflow.com/q/47639850
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/47639860
downvote count: 0
tagged with: keras
favorite count: 0
has body: I'm implementing a triplet loss function in Keras. In general, loss functions take predicted values with ground truth as arguments. But triplet loss doesn't use labels, just the output. I tried to write the function with just one parameter: def triplet_loss(y_pred): margin = 1 return K.mean(K.square(y_pred[0]) - K.square(y_pred[1]) + margin) It failed saying triplet_loss() takes 1 argument but two arguments were given (in score_array = fn(y_true, y_pred). When I write the function with two arguments y_true, y_pred, the program runs without error. Why is that? Should I just implement this function with these two arguments although y_true won't be used? Is this correct or is there another way of doing it?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50719592
possible better answer: http://stackoverflow.com/a/50719592
has title: Writing a custom loss function without y_true in Keras
upvote count: 5
accepted answer: http://stackoverflow.com/a/47639860
tagged with: python

http://stackoverflow.com/a/47555043
downvote count: 0
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47554554
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47554554
has body: You have two choices here, that can be complementary : Change your tokenization with stronger rules using regex to remove numbers or other tokens you are not interested in. Use feature selection to keep a subset of your features that are relevant for the classification. Here is a demo sample of code to keep 50% of the features in data: from sklearn.datasets import load_iris from sklearn.feature_selection import SelectPercentile from sklearn.feature_selection import chi2 import numpy iris = load_iris() X, y = iris.data, iris.target selector = SelectPercentile(score_func=chi2, percentile=50) X_reduced = selector.fit_transform(X, y)
has comment: http://stackoverflow.com/comment/82138786

http://stackoverflow.com/q/47659757
upvote count: 2
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47660052
downvote count: 0
has answer: http://stackoverflow.com/a/47660052
answer count: 1
favorite count: 0
type: Question
has title: Python Pandas: How to split a column on parenthesis from a column of dataframe?
tagged with: python
has body: I have a pandas data frame: In [8]: test Out[8]: Product Price 0 Berlin Stret (E10) 12 1 Paris Ave (C12) 34 2 5th Ave (D30) 56 I am trying to split the column product in 2 columns such as Product Room Price 0 Berlin Stret E10 12 1 Paris Ave C12 34 2 5th Ave D30 56 I tried to use df['Product'], df['Room'] = df['Product'].str.split('()', 1).str

http://stackoverflow.com/comment/82312030
type: QuestionComment
score: 0
has text: I **strongly** recommend you try this again with Python 3, so we can diagnose and fix the problem in a reasonable way. I cannot recommend this strongly enough; using Python 2 to learn about encodings is a recipe for needless pain.
comment on: http://stackoverflow.com/q/47672316
type: Comment

http://stackoverflow.com/comment/82184427
comment on: http://stackoverflow.com/q/47612900
type: Comment
type: QuestionComment
has text: @GrzegorzOledzki I don't think so. They're just English letters and numbers. And this happens on Heroku but not on my laptop!
score: 0

http://stackoverflow.com/q/47596137
tagged with: recurrent-neural-network
linked to: http://stackoverflow.com/q/47543113
type: AnsweredQuestion
tagged with: deep-learning
score: 1
upvote count: 1
answer count: 1
downvote count: 0
tagged with: keras
has title: How to use Conv1D and Bidirectional LSTM in keras to do multiclass classification of each timestep?
has answer: http://stackoverflow.com/a/47596267
accepted answer: http://stackoverflow.com/a/47596267
favorite count: 0
type: Question
tagged with: convolution
has body: I am trying to use a Conv1D and Bidirectional LSTM in keras (much like in this question) for signal processing, but doing a multiclass classification of each time step. The problem is that even though the shapes used by Conv1D and LSTM are somewhat equivalent: Conv1D: (batch, length, channels) LSTM: (batch, timeSteps, features) The output of the Conv1D is = (length - (kernel_size - 1)/strides), and therefore doesn't match the LSTM shape anymore, even without using MaxPooling1D and Dropout. To be more specific, my training set X has n samples with 1000 time steps and one channel (n_samples, 1000, 1), and I used LabelEncoder and OneHotEncoder so y has n samples, 1000 time steps and 5 one hot encoded classes (n_samples, 1000, 5). Since one class is much more prevalent than the others (is actually the absence of signal), I am using loss='sparse_categorical_crossentropy', sample_weight_mode="temporal" and sample_weight to give a higher weight to time steps containing meaningful classes. model = Sequential() model.add(Conv1D(128, 3, strides=1, input_shape = (1000, 1), activation = 'relu')) model.add(Bidirectional(LSTM(128, return_sequences=True))) model.add(TimeDistributed(Dense(5, activation='softmax'))) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'], sample_weight_mode="temporal") print(model.summary()) Model When I try to fit the model I get this error message: Error when checking target: expected time_distributed_1 to have shape (None, 998, 1) but got array with shape (100, 1000, 5). Is there a way to make such a neural network configuration work?
tagged with: python

http://stackoverflow.com/q/47621294
has answer: http://stackoverflow.com/a/47621443
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82200595
tagged with: python
score: 0
has body: inputFile = open("Students_1.txt" , 'w') inputFile.write("John Smith 80 90\n") inputFile.write("Ryan Brown 80 60\n") inputFile.write("Anna Myers 95 85\n") inputFile.close() inputFile = open("Students_1.txt" , 'r') for line in inputFile: y = line.split() print(y) This is the code I have so far but I am stuck trying to figure out how to convert it to an integer.
answer count: 2
has title: How do I convert a list member to a number from a list while working in a file?
has comment: http://stackoverflow.com/comment/82202026
has answer: http://stackoverflow.com/a/47621450
type: Question

http://stackoverflow.com/comment/82135178
has text: Well that sounds like `uint8`. So, I would suggest using `dtype=np.uint8` in that case.
comment on: http://stackoverflow.com/q/47588234
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82045856
type: QuestionComment
comment on: http://stackoverflow.com/q/47542168
has text: OS? What is the full traceback, which will show what line is failing? I suspect you are on Linux, and your terminal is configured to support `latin-1` instead of UTF-8. Python 2, when printing a dictionary, won't print non-ASCII to the terminal (for example, `u'Apple\u2019s'`), but Python 3 will (`u'Apple’s'`). Check your `LANG` environment setting. `latin-1` doesn't support that character.
score: 0
type: Comment

http://stackoverflow.com/comment/82334386
has text: I didn't reproduce your error. but you can try to change the last line to `.apply(lambda x: ' v '.join(x.astype(str)), 1)`
comment on: http://stackoverflow.com/q/47687432
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82083552
has text: this is the server side it accepts connection from the client in the while loop in the end conn,addr=s.accept()
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47562457

http://stackoverflow.com/q/47601634
has body: I think this is a pretty simple issue, however I can't figure it out for the life of me. I am trying to reach the NBA Player Performance Prop Page: https://www.bet365.com/#/AC/B18/C20559797/D47/E1/F43/P^47/Q^1/I which is required to be loaded twice (weird ad splash screen shown at first). So I have my code load the main page (www.bet365.com), and then select basketball on the left, then I attempt to find the "Player Performances" button on the page. This is where my difficulty's come in. I have been trying to click it automated by using the css selector or the xpath. However anything I try is unclickable. Here is my code so far, does anyone have any advice as to how to programatically navigate to the NBA Player Performances page. The url on the page changes on a daily basis so I am going to be required to find it by code: url = "https://www.bet365.com/" driver = webdriver.Chrome('./chromedriver.exe ') driver.get(url); print("Waiting To Ensure Data Load 1 of 2") time.sleep(5) # Let the user actually see something! driver.get(url); print("Waiting To Ensure Data Load 2 of 2") time.sleep(5) print("Naviagating to BasketballSection Section") driver.find_element_by_css_selector("body &gt; div:nth-child(1) &gt; div &gt; div.wc-PageView &gt; div.wc-PageView_Main.wc-HomePage_PageViewMain &gt; div &gt; div.wc-HomePage_ClassificationWrapper.wc-CommonElementStyle_WebNav &gt; div &gt; div &gt; div:nth-child(7)").click(); time.sleep(5) urltwo = "body &gt; div:nth-child(1) &gt; div &gt; div.wc-PageView &gt; div.wc-PageView_Main &gt; div &gt; div.wc-CommonElementStyle_PrematchCenter.wc-SplashPage_CenterColumn &gt; div.sm-SplashModule &gt; div:nth-child(1) &gt; div:nth-child(3) &gt; div.sm-MarketGroup_Open &gt; div &gt; div.sm-MarketContainer.sm-MarketContainer_NumColumns1.sm-Market_Open &gt; div &gt; div" submit = driver.find_element_by_css_selector(urltwo) submit.click() Not sure what to make of it, I am able to navigate to Basketball on the left bar with ease. Basically my goal is…
tagged with: webdriver
favorite count: 0
type: Question
has title: Trying to Automate Pressing a Button
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47601986
tagged with: selenium-webdriver
downvote count: 0
upvote count: 1
score: 1
answer count: 1

http://stackoverflow.com/a/48665283
has body: You can't directly pass a masked image to greycomatrix. The good news is that you can compute the approximate value of Haralick features extracted from a region of interest of an image by introducing small changes in your code. The basic idea consists in saving a grey level, say 0, to flag those image pixels that fall outside the region of interest (ROI). For this approach to work properly, you need to change the intensity of those pixels inside the ROI whose original intensity was 0 to a different (but similar) value, for example 1. Notice that modifying the image in this way inevitably introduces inaccuracies in the co-occurrence matrix, but as long as your image is sufficiently large and has a smooth histogram, you can safely assume that the obtained features are a pretty good approximation to the exact values. It is also important to note that you have to get rid of the 0th row and the 0th column of the co-occurrence matrix in order not to take into account the grey level used to flag non-ROI pixels. To implement the workaround described above you just need to change the following two lines: mancha = cruda[imaskc] glcm = greycomatrix(mancha, [2], [0], levels=None, symmetric=True, normed=True) to: mancha = cruda.copy() mancha[mancha == 0] = 1 mancha[~imaskc] = 0 glcm = greycomatrix(mancha, [2], [0], levels=None, symmetric=True, normed=True)[1:, 1:, :, :]
downvote count: 0
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/139900807
answers question: http://stackoverflow.com/q/47591359

http://stackoverflow.com/comment/82279148
type: QuestionComment
has text: Found it. I let 'choice' be a empty string so it's defined when it comes to the while loop
comment on: http://stackoverflow.com/q/47660114
score: 0
type: Comment

django
tags question: http://stackoverflow.com/q/47573382
tags question: http://stackoverflow.com/q/47585568
tags question: http://stackoverflow.com/q/47676426
tags question: http://stackoverflow.com/q/47641889
tags question: http://stackoverflow.com/q/47620820
tags question: http://stackoverflow.com/q/47572659
tags question: http://stackoverflow.com/q/47547590
tags question: http://stackoverflow.com/q/47592729
tags question: http://stackoverflow.com/q/47578807
tags question: http://stackoverflow.com/q/47668709
tags question: http://stackoverflow.com/q/47618357
tags question: http://stackoverflow.com/q/47631589
tags question: http://stackoverflow.com/q/47649792
tags question: http://stackoverflow.com/q/47695212
tags question: http://stackoverflow.com/q/47577948
tags question: http://stackoverflow.com/q/47691718
tags question: http://stackoverflow.com/q/47636246
tags question: http://stackoverflow.com/q/47627187
tags question: http://stackoverflow.com/q/47551989
tags question: http://stackoverflow.com/q/47548490
tags question: http://stackoverflow.com/q/47641493
tags question: http://stackoverflow.com/q/47621716
tags question: http://stackoverflow.com/q/47668906
tags question: http://stackoverflow.com/q/47694931
tags question: http://stackoverflow.com/q/47548076
tags question: http://stackoverflow.com/q/47643193
tags question: http://stackoverflow.com/q/47629896
tags question: http://stackoverflow.com/q/47671284
tags question: http://stackoverflow.com/q/47618971
tags question: http://stackoverflow.com/q/47644919
tags question: http://stackoverflow.com/q/47609339
tags question: http://stackoverflow.com/q/47666883
tags question: http://stackoverflow.com/q/47639525
tags question: http://stackoverflow.com/q/47641680
tags question: http://stackoverflow.com/q/47663641
tags question: http://stackoverflow.com/q/47693834
tags question: http://stackoverflow.com/q/47674239
tags question: http://stackoverflow.com/q/47556339
tags question: http://stackoverflow.com/q/47604233
tags question: http://stackoverflow.com/q/47649854
tags question: http://stackoverflow.com/q/47635626
tags question: http://stackoverflow.com/q/47580947
tags question: http://stackoverflow.com/q/47592229
tags question: http://stackoverflow.com/q/47663109
tags question: http://stackoverflow.com/q/47664064
tags question: http://stackoverflow.com/q/47605387
tags question: http://stackoverflow.com/q/47548360
tags question: http://stackoverflow.com/q/47636968
tags question: http://stackoverflow.com/q/47578810
tags question: http://stackoverflow.com/q/47585513
tags question: http://stackoverflow.com/q/47572535
tags question: http://stackoverflow.com/q/47609208
tags question: http://stackoverflow.com/q/47684498
tags question: http://stackoverflow.com/q/47585826
tags question: http://stackoverflow.com/q/47604425
tags question: http://stackoverflow.com/q/47583844
tags question: http://stackoverflow.com/q/47657871
tags question: http://stackoverflow.com/q/47542456
tags question: http://stackoverflow.com/q/47632093
tags question: http://stackoverflow.com/q/47577304
tags question: http://stackoverflow.com/q/47587708
tags question: http://stackoverflow.com/q/47599725
tags question: http://stackoverflow.com/q/47566489
tags question: http://stackoverflow.com/q/47683278
tags question: http://stackoverflow.com/q/47655470
tags question: http://stackoverflow.com/q/47634563
tags question: http://stackoverflow.com/q/47668723
tags question: http://stackoverflow.com/q/47591727
tags question: http://stackoverflow.com/q/47696515
tags question: http://stackoverflow.com/q/47597615
tags question: http://stackoverflow.com/q/47546420
tags question: http://stackoverflow.com/q/47558374
tags question: http://stackoverflow.com/q/47550789
tags question: http://stackoverflow.com/q/47652210
tags question: http://stackoverflow.com/q/47575979
tags question: http://stackoverflow.com/q/47640057
tags question: http://stackoverflow.com/q/47559245
tags question: http://stackoverflow.com/q/47563099
tags question: http://stackoverflow.com/q/47597866
tags question: http://stackoverflow.com/q/47560003

http://stackoverflow.com/q/47584723
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47584892
has title: Nested dictionary keeps overwriting data
has answer: http://stackoverflow.com/a/47584892
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47584846
accepted answer: http://stackoverflow.com/a/47584846
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
has body: I am trying to read in from a data file that has lines like: 2007 ANDREA 30 31.40 -71.90 05/13/18Z 25 1007 LOW 2007 ANDREA 31 31.80 -69.40 05/14/00Z 25 1007 LOW I am trying to create a nested dictionary that has a key holding the year and then the nested dictionary will hold the name and a tuple containing statistics. I would like the return value to look like this: {'2007': {'ANDREA': [(31.4, -71.9, '05/13/18Z', 25.0, 1007.0), (31.8, -69.4, '05/14/00Z', 25.0, 1007.0)] However when I run the code it returns only one set of statistics. It seems to be overwriting itself because I am getting that last line of statistics in the txt file returned: {'2007': {'ANDREA': [(31.8, -69.4, '05/14/00Z', 25.0, 1007.0)] Here is the code: def create_dictionary(fp): '''Remember to put a docstring here''' dict1 = {} f = [] for line in fp: a = line.split() f.append(a) for item in f: a = (float(item[3]), float(item[4]), item[5], float(item[6]), float(item[7])) dict1 = update_dictionary(dict1, item[0], item[1], a)) print(dict1) def update_dictionary(dictionary, year, hurricane_name, data): if year not in dictionary: dictionary[year] = {} if hurricane_name not in dictionary: dictionary[year][hurricane_name] = [data] else: dictionary[year][hurricane_name].append(data) else: if hurricane_name not in dictionary: dictionary[year][hurricane_name] = [data] else: dictionary[year][hurricane_name].append(data) return dictionary
upvote count: 1

http://stackoverflow.com/comment/82240284
score: 1
type: Comment
has text: @Lucubrator the dunder methods are really provided to override if you wish to, if you subclass the exception. I started exploring this myself but then realised that I was trying to make a self-handling exception by packaging the `if`/`elif` inside a custom exception, and that seems nonsensical (not to mention that I couldn't find a way to access the `args` string). Try `print(e.__cause__)`. No worries about waiting, I found the question interesting so I used it for my learning too :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47638448

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47622714
tags question: http://stackoverflow.com/q/47543696
tags question: http://stackoverflow.com/q/47627879
tags question: http://stackoverflow.com/q/47596831
tags question: http://stackoverflow.com/q/47621972
tags question: http://stackoverflow.com/q/47679599
tags question: http://stackoverflow.com/q/47544669
tags question: http://stackoverflow.com/q/47572366
tags question: http://stackoverflow.com/q/47583630
tags question: http://stackoverflow.com/q/47621042
tags question: http://stackoverflow.com/q/47562537
tags question: http://stackoverflow.com/q/47623063
tags question: http://stackoverflow.com/q/47657817
tags question: http://stackoverflow.com/q/47560399
tags question: http://stackoverflow.com/q/47654665
tags question: http://stackoverflow.com/q/47690770
tags question: http://stackoverflow.com/q/47557240
tags question: http://stackoverflow.com/q/47685405
tags question: http://stackoverflow.com/q/47575981
tags question: http://stackoverflow.com/q/47588182
tags question: http://stackoverflow.com/q/47689778
tags question: http://stackoverflow.com/q/47600238
tags question: http://stackoverflow.com/q/47620300
tags question: http://stackoverflow.com/q/47545128
tags question: http://stackoverflow.com/q/47604561
tags question: http://stackoverflow.com/q/47621360
tags question: http://stackoverflow.com/q/47690514
tags question: http://stackoverflow.com/q/47637351
tags question: http://stackoverflow.com/q/47663812
tags question: http://stackoverflow.com/q/47656073
tags question: http://stackoverflow.com/q/47611871
tags question: http://stackoverflow.com/q/47546742
tag name: pyqt
tags question: http://stackoverflow.com/q/47545513
tags question: http://stackoverflow.com/q/47654327
tags question: http://stackoverflow.com/q/47666922
tags question: http://stackoverflow.com/q/47599170
tags question: http://stackoverflow.com/q/47661681
tags question: http://stackoverflow.com/q/47544411
tags question: http://stackoverflow.com/q/47676660
tags question: http://stackoverflow.com/q/47546162
tags question: http://stackoverflow.com/q/47562740
tags question: http://stackoverflow.com/q/47647857
tags question: http://stackoverflow.com/q/47556122
tags question: http://stackoverflow.com/q/47621525

http://stackoverflow.com/comment/82278107
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47659215
has text: I made the rotation changes to my code and removed the redundant call from update(). However, now my paddle is flying off the screen, which is weird because I already put the restrictions on boundaries. I think this may have something to do with my self.rect. Please see the edits to my code.
type: Comment

http://stackoverflow.com/q/47666466
type: UnansweredQuestion
has title: How do you prevent duplicates from entering list using setdefault in python
tagged with: python
tagged with: dictionary
score: 0
has body: Suppose you have a dictionary: dict1 = {'a':[1,2], 'b':[1,2]} And suppose the next item is {b:2}. I don't want there to be any repeats in the values of my dictionary for all keys. So {b:2} would not update the dictionary, but {b:3} would update it as: {'a':[1,2], 'b':[1,2,3]} I would like to make some alteration to the setdefault method to accomplish this.
answer count: 1
has answer: http://stackoverflow.com/a/47666527
type: Question

http://stackoverflow.com/comment/82348437
type: Comment
type: QuestionComment
has text: Environmental variable finds the first file on a line. See `assoc /?`, `ftype /?`, and set up python files to open. Then see `Set PATHEXT=%pathext%;.py`. Now just type the filename with or without the extension.
comment on: http://stackoverflow.com/q/47693984
score: 0

http://stackoverflow.com/q/47588182
tagged with: pyqt
answer count: 1
has title: Trying to copy text from other threads using a button
has body: I am trying to figure out a way to make a decent copy to clipboard button function where I can copy text values from other threads inside a QTextEdit widget. I pull the values from other threads and display them in a QTextEdit widget and have been trying to successfully copy to clipboard the contents of QTextEdit with a button but the only way I have been able to is my code below. What I don't like is that the copy button makes a second call in order to copy the contents. Is there some way that the values can be stored from the first request using the get_button button and be available to copy with the copy button without having to make the same call all over again? Thanks. from PyQt4 import QtCore, QtGui import sys class WorkerThread(QtCore.QThread): get_String = QtCore.pyqtSignal(str) def __init__(self): super(WorkerThread, self).__init__() def run(self): self.get_String.emit('Some text.') class GUI(QtGui.QWidget): def __init__(self): super(GUI, self).__init__() self.get_Button = QtGui.QPushButton('Get') self.c_Button = QtGui.QPushButton('Copy') self.text_Box = QtGui.QTextEdit(self) vbox = QtGui.QVBoxLayout(self) vbox.addWidget(self.get_Button) vbox.addWidget(self.c_Button) vbox.addWidget(self.text_Box) vbox.addStretch() self.setGeometry(300, 300, 300, 300) self.show() self._thread = WorkerThread() self.get_Button.clicked.connect(self.doIt) self._thread.get_String.connect(self.text_Box.append) self.c_Button.clicked.connect(self.copy_Stuff) def copy_Stuff(self): self.clipboard = QtGui.QApplication.clipboard() self._thread.get_String.connect(self.clipboard.setText) self._thread.start() def doIt(self): self.text_Box.clear() self.text_Box.setText('') self._thread.start() def main(): app = QtGui.QApplication(sys.argv) gui = GUI() sys.exit(app.exec_()) if __name__ == '__main__': main()
type: Question
accepted answer: http://stackoverflow.com/a/47591628
tagged with: clipboard
tagged with: signals
tagged with: multithreading
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47591628

http://stackoverflow.com/comment/82312532
has text: `j in i` when `i` and `j` are strings checks if `j` is a substring of `i`. I guess you don't actually want that.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47676792
type: QuestionComment

http://stackoverflow.com/q/47661476
has comment: http://stackoverflow.com/comment/82282320
has answer: http://stackoverflow.com/a/47661564
linked to: http://stackoverflow.com/q/8628152
tagged with: python
has comment: http://stackoverflow.com/comment/82282049
score: 0
has comment: http://stackoverflow.com/comment/82282727
has comment: http://stackoverflow.com/comment/82282407
type: UnansweredQuestion
answer count: 1
tagged with: python-requests
has body: I try to using request.get with '@' in params, but in output I have '%40' How I can decode this dict? Using Python3 import requests payload = {'OPERATION-NAME': 'findItemsByProduct','productId.@type':'ReferenceID'} req = requests.post(url, params=payload) print(req.url) The output is - 'url?productId.%40type=ReferenceID'
has comment: http://stackoverflow.com/comment/82282952
type: Question
has title: python requests @ params
has comment: http://stackoverflow.com/comment/82282776
has comment: http://stackoverflow.com/comment/82283246

http://stackoverflow.com/a/47572977
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/47572695
score: 9
answers question: http://stackoverflow.com/q/47572695
type: AcceptedAnswer
downvote count: 0
has body: Python already does this: def foo(): print ("foo") return True def bar(): print ("bar") return False print (foo() or bar()) print ("") print (bar() or foo()) Returns: foo True bar foo True There is no need for AndAlso or OrElse in Python, it evaluates boolean conditions lazily (docs).

http://stackoverflow.com/comment/82201231
comment on: http://stackoverflow.com/q/47621607
has text: @MeC Please see my answer then as it will include multiple occurrences in a single word.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47668564
has comment: http://stackoverflow.com/comment/82295886
has body: I have a variable named email in view. I want to access this in ManageSerializer. How can I pass this argument in serializer and get there? views.py email = 'xyz@gmail.com' interviewData = Manage.objects. filter(catcher_id = userCheck['id'], acceptation = '1'). filter(invitation_date__gte = dateToday)[:5]; serializer = ManageSerializers(interviewData, many = True)
possible better answer: http://stackoverflow.com/a/47668655
has answer: http://stackoverflow.com/a/47668631
linked to: http://stackoverflow.com/q/32825236
answer count: 2
downvote count: 0
tagged with: django
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47668655
tagged with: serialization
has comment: http://stackoverflow.com/comment/82296177
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82295916
score: 1
accepted answer: http://stackoverflow.com/a/47668631
has title: Django Rest Framework: How to pass extra argument to django serializer?
tagged with: python

http://stackoverflow.com/comment/82325369
type: QuestionComment
comment on: http://stackoverflow.com/q/47682698
score: 0
has text: In your solution ```x[0] - x[1] >= 0```, what's wrong?
type: Comment

http://stackoverflow.com/q/47563682
downvote count: 0
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/47563970
has title: Plot data stored in list of dicts using list comprehension
type: Question
has answer: http://stackoverflow.com/a/47563782
tagged with: python
tagged with: dictionary
score: 4
upvote count: 4
tagged with: list
has answer: http://stackoverflow.com/a/47563970
possible better answer: http://stackoverflow.com/a/47563782
type: AnsweredQuestion
has body: I have a netCDF file containing monthly average temperatures around the globe dating back to 1948. For an assignment, I have to select any one provided datapoint, extract its mean temperature values for the months of December, January, February, and March, and then display it. I've already unpacked the data and I have it collected in a list of dictionaries, as shown here: For December: decemberMeans = [ {'year': 1948, 'temp': 271.24}, {'year': 1949, 'temp': 271.28}, {'year': 1950, 'temp': 268.52}, {'year': 1951, 'temp': 269.63}, ..., {'year': 2015, 'temp': 277.23}, {'year': 2016, 'temp': 271.25} ] Data corresponding to January, February, and March is structured in the same manner. My next step is to plot it. I have to plot one line on the same graph for each set of data, and I'm using list comprehensions to do it. Right now my plotting code looks like this: import matplotlib.pyplot as plt plt.figure(1) plt.hold(True) plt.plot([data['years'] for data in decemberMeans], \ [data['temp'] for data in decemberMeans], 'k-') plt.plot([data['years'] for data in januaryMeans], \ [data['temp'] for data in januaryMeans], 'r-') plt.plot([data['years'] for data in februaryMeans], \ [data['temp'] for data in februaryMeans], 'b-') plt.plot([data['years'] for data in marchMeans], \ [data['temp'] for data in marchMeans], 'y-') plt.grid(True) plt.show() plt.close() It plots just fine, but I can see that all of my list comprehensions are really redundant. Would there be a way that I could unpack the dictionary values in one fowl swoop so that I don't have to write data['...'] for data in list twice for each set? P.S. - As I'm writing this I've started to realize that I could write a function to do the plotting (which would probably take even less time than writing out this post), but I'm still curious to know. Thanks to all in advance!
answer count: 2

http://stackoverflow.com/q/47542493
score: 5
has comment: http://stackoverflow.com/comment/82043399
upvote count: 5
linked to: http://stackoverflow.com/q/46744968
type: UnansweredQuestion
has title: How to turn off command line logging in Selenium using Chrome in Python
tagged with: python
has comment: http://stackoverflow.com/comment/82931877
has comment: http://stackoverflow.com/comment/82931854
has comment: http://stackoverflow.com/comment/82136467
has answer: http://stackoverflow.com/a/64479066
linked to: http://stackoverflow.com/q/9226519
tagged with: windows
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82042143
has body: I'm trying to run a Python script using Selenium, and while everything runs fine, my personal print() to console lines get hidden between a ton of Selenium/Chromedriver outputs like this: 1128/150256.806:INFO:CONSOLE(0)] "The SSL certificate used to load resources from [some-link.com] will be distrusted in the future. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/symantecpkicerts for more information.", source: [current-page.com] (0) I checked what these links are, and they're just the ads on the pages I'm looking at, so it's completely useless. Also, since the ads are randomly generated every time a page loads/is reloaded, the links are different so the outputs are never-ending. This is incredibly annoying and makes it very hard to see what is actually happening within my program. Is there any way to turn this off with some Selenium options or something? The strange thing is, running the program in Eclipse Oxygen with PyDev doesn't show any of Selenium's output at all, only if I run it using command line. EDIT: following the instructions from the possible duplicate mentioned didn't help. I tried setting the logging level to the highest, CRITICAL, and the output mentioned above still went through and flooded the console.
has answer: http://stackoverflow.com/a/55371526
favorite count: 0
tagged with: command-line
type: Question
answer count: 2

http://stackoverflow.com/q/47581681
tagged with: python
tagged with: rdd
tagged with: apache-spark
score: 0
answer count: 1
has body: I am trying to access the dependencies of an RDD. In Scala it is a pretty simple code: scala&gt; val myRdd = sc.parallelize(0 to 9).groupBy(_ % 2) myRdd: org.apache.spark.rdd.RDD[(Int, Iterable[Int])] = ShuffledRDD[2] at groupBy at &lt;console&gt;:24 scala&gt; myRdd.dependencies res0: Seq[org.apache.spark.Dependency[_]] = List(org.apache.spark.ShuffleDependency@6c427386) But dependencies is not available in PySpark. Any pointers on how I can access them? &gt;&gt;&gt; myRdd.dependencies Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'PipelinedRDD' object has no attribute 'dependencies'
type: Question
has title: Access dependencies available in Scala but no PySpark
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47581869

http://stackoverflow.com/a/47634665
has comment: http://stackoverflow.com/comment/82228421
has comment: http://stackoverflow.com/comment/82227114
has comment: http://stackoverflow.com/comment/82228529
downvote count: 0
has comment: http://stackoverflow.com/comment/82228214
has comment: http://stackoverflow.com/comment/82227068
has comment: http://stackoverflow.com/comment/82228419
has comment: http://stackoverflow.com/comment/82227385
has comment: http://stackoverflow.com/comment/82227042
has comment: http://stackoverflow.com/comment/82228384
has comment: http://stackoverflow.com/comment/82228582
has comment: http://stackoverflow.com/comment/82227674
accepted answer of: http://stackoverflow.com/q/47634525
has comment: http://stackoverflow.com/comment/82228641
has comment: http://stackoverflow.com/comment/82227469
score: 5
has body: You should assign the slice to an iterable of the same length as the number of odds: bar[1::2] = [0]*(len(bar)//2) print(bar) # [2, 0, 4, 0, 6, 0, 8, 0, 10] To extend this for even indices, you need to take into consideration lists with odd-lengths (not relevant for the above case) by adding the modulo 2 value of the list length: bar[::2] = [0]*(len(bar)//2 + len(bar)%2) Which is same as: bar[::2] = [0]*sum(divmod(len(bar), 2))
has comment: http://stackoverflow.com/comment/82228656
has comment: http://stackoverflow.com/comment/82228321
type: AcceptedAnswer
upvote count: 5
answers question: http://stackoverflow.com/q/47634525
has comment: http://stackoverflow.com/comment/82228274
type: Answer
has comment: http://stackoverflow.com/comment/82227428
has comment: http://stackoverflow.com/comment/82228471

pytest
tags question: http://stackoverflow.com/q/47635577
tags question: http://stackoverflow.com/q/47575472
tags question: http://stackoverflow.com/q/47575615
tag name: pytest
tags question: http://stackoverflow.com/q/47594138
tags question: http://stackoverflow.com/q/47574413
tags question: http://stackoverflow.com/q/47544192
tags question: http://stackoverflow.com/q/47688389
tags question: http://stackoverflow.com/q/47570623
tags question: http://stackoverflow.com/q/47696002
tags question: http://stackoverflow.com/q/47674185
tags question: http://stackoverflow.com/q/47559524
tags question: http://stackoverflow.com/q/47549935
tags question: http://stackoverflow.com/q/47590564
tags question: http://stackoverflow.com/q/47560638
tags question: http://stackoverflow.com/q/47690250
tags question: http://stackoverflow.com/q/47568739
type: Tag
tags question: http://stackoverflow.com/q/47691512

http://stackoverflow.com/comment/82300655
type: AnswerComment
comment on: http://stackoverflow.com/a/47658202
has text: I used this before, but then in Jupyter the output always disappears/immedeatly reappears with the new plot and its not nice to look at this.
score: 0
type: Comment

http://stackoverflow.com/comment/82506383
type: AnswerComment
score: 0
has text: Thanks Max, This may be relevant (Normally I would ack all messages, but it takes time to ack them so library may consider them as unacked.) I couldn't find documentation to where I can control batch size, or ack all batch at once
type: Comment
comment on: http://stackoverflow.com/a/47761097

http://stackoverflow.com/a/47554749
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82066716
accepted answer of: http://stackoverflow.com/q/47554689
upvote count: 1
has comment: http://stackoverflow.com/comment/82066944
downvote count: 0
type: Answer
has body: Try the following: import sys sys.path.append("..") from .. import file1
answers question: http://stackoverflow.com/q/47554689

http://stackoverflow.com/comment/82306334
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47673592
type: AnswerComment
has text: Did you format your list like I did? Because it is a dictionary not a list. Try using the my `arr` declaration.

http://stackoverflow.com/q/47638633
has comment: http://stackoverflow.com/comment/82356184
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/47700800
has answer: http://stackoverflow.com/a/47667164
has answer: http://stackoverflow.com/a/47700800
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82351278
tagged with: neural-network
has body: I have a deep CNN that predicts a label between "0" and "2" for every pixel in a 3d image. I have trained the model on an image where every pixel is labeled "1". Therefore, when testing the model, I believe every prediction should be "1". Instead the model only predicts "0". Here is the repository for the whole model: https://github.com/dhasl002/Research-DeepLearning. Since the code is almost 300 lines, I will include only the relevant code below. x = tf.placeholder(tf.float32, shape=[None, 7168]) y_ = tf.placeholder(tf.float32, shape=[None, 7168, 3]) W_final = weight_variable([7168,7168,3]) b_final = bias_variable([7168,3]) #"final" is the result of the many convolutions final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=final_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(final_conv, 2), tf.argmax(y_, 2)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #a is a threshold associate with each pixel, b is the label of each pixel a = np.zeros((1,7168),dtype = float) b = np.zeros((1,7168, 3), dtype = float) #this is a little simplified for clarity of reader #TRAINING for line in inputFile: thresh, label = line.strip().split(",") a[0][it] = thresh b[0][it][label] = 1 train_step.run(feed_dict={x: a, y_: b, keep_prob: .5}) #TESTING for line in inputFile: thresh, label = line.strip().split(",") a[0][it] = thresh b[0][it][label] = 1 temp = sess.run(tf.argmax(final_conv,2), feed_dict={x: a}) I believe that "temp" from the last line should hold the correct predictions (7168 labels - one per pixel). Why does "temp" always result in all "0" labels when it is actually trained on images only with "1" labels?
tagged with: python
has title: Tensorflow neural network prediction is always the same
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47667164
tagged with: conv-neural-network

http://stackoverflow.com/comment/82258875
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47650268
has text: Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code!

http://stackoverflow.com/comment/82130899
score: 0
has text: I cannot read the entire dataset, it is 20GB and I do not have this time.@SandeepKadapa
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47586614

http://stackoverflow.com/a/47682449
has comment: http://stackoverflow.com/comment/82324189
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82324640
has body: I ran you code in IDLE and the indentation were off, also as user2357112 mentioned, global should go inside a function but I dont see why you are using it. Also you should have a condition for your while loop to end. Right now the loop will not end. def start(): invalid=True global invalid x = input('Type the correct key:') if ("m" == x) or ("M"==x): print('Correct!') else: print('Invalid Input.') invalid=False while invalid: start() print('Next Question') This might help def startm(): valid = True while(valid): x = input('Type the correct key:') if ("m" == x) or ("M"==x): print('Correct!') else: print('Invalid Input.') valid=False You can start the while loop with condition True and as long as its valid the loop will continue to run. Once the loop becomes False. It will break out.
answers question: http://stackoverflow.com/q/47682356
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82347763
score: 1
type: Comment
type: AnswerComment
has text: And if state is very large, then you can always save the pickles to disk.
comment on: http://stackoverflow.com/a/47693987

http://stackoverflow.com/comment/103251614
score: 0
has text: Adding `unsigned int reconnect;` to `typedef struct st_mysql {}` totally worked for me.
type: Comment
comment on: http://stackoverflow.com/a/49040494
type: AnswerComment

http://stackoverflow.com/comment/82498620
type: QuestionComment
comment on: http://stackoverflow.com/q/47694736
has text: @tripleee I have already done that and the issue is that logs are stored to both `nohup.out` and `python log file`; when it should be stored in only python log file.
score: 1
type: Comment

http://stackoverflow.com/q/47589721
tagged with: pdfminer
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has answer: http://stackoverflow.com/a/47589947
score: 0
tagged with: extract
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3984003
answer count: 1
has title: Reading data inside textbox of a pdf using python
duplicate of: http://stackoverflow.com/q/3984003
type: Question
has body: I have a pdf file which contains textboxes, radio buttons, check boxes etc. How do I extract all the data from the pdf using python? When i try using pdfminer or pypdf2, I am not able to scrape the data in textboxes. Refer attached image. For example: When i use pdfminer, I am able to scrae the "1) Program:" but not the value filled for it (i.e "EPIC_AFCS_AB139_7APD")

http://stackoverflow.com/comment/82256044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47648886
score: 3
has text: `str(dict)` does not produce valid JSON.

http://stackoverflow.com/a/55799548
has body: To deserialize the bytes you need np.frombuffer(). tobytes() serializes the array into bytes and the np.frombuffer() deserializes them. Bear in mind that once serialized, the shape info is lost, which means that after deserialization, it is required to reshape it back to its original shape. Below is a complete example: import numpy as np x = np.array([[0, 1], [2, 3]], np.int8) bytes = x.tobytes() # bytes is a raw array, which means it contains no info regarding the shape of x # let's make sure: we have 4 values with datatype=int8 (one byte per array's item), therefore the length of bytes should be 4bytes assert len(bytes) == 4, "Ha??? Weird machine..." deserialized_bytes = np.frombuffer(bytes, dtype=np.int8) deserialized_x = np.reshape(deserialized_bytes, newshape=(2, 2)) assert np.array_equal(x, deserialized_x), "Deserialization failed..."
score: 25
downvote count: 0
answers question: http://stackoverflow.com/q/47637758
upvote count: 25
type: Answer

http://stackoverflow.com/a/47660052
answers question: http://stackoverflow.com/q/47659757
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82280324
accepted answer of: http://stackoverflow.com/q/47659757
upvote count: 8
type: Answer
has body: You can use regex with extract: df'product','room'= df.Product.str.extract('(.)\s\((.\d+)', expand=True) Output (lower case product new column): Product Price product room 0 A (E10) 12 A E10 1 B (C12) 34 B C12 2 C (D30) 56 C D30 Or use regex '|' with split: df'product','room' = df.Product.str.split('\(|\)', expand=True).iloc[:,[0,1]] Output: Product Price product room 0 A (E10) 12 A E10 1 B (C12) 34 B C12 2 C (D30) 56 C D30
has comment: http://stackoverflow.com/comment/82279422
score: 8

http://stackoverflow.com/a/47645623
has comment: http://stackoverflow.com/comment/82713839
has comment: http://stackoverflow.com/comment/82710624
accepted answer of: http://stackoverflow.com/q/47596202
upvote count: 1
has comment: http://stackoverflow.com/comment/82758715
answers question: http://stackoverflow.com/q/47596202
type: AcceptedAnswer
has body: There are restrictions on how many requests you can make a day with a free API key, but this is the way I would suggest. As a note, anything date and/or time related I almost always use the arrow package. Something along these lines should work for you. import arrow # learn more: https://python.org/pypi/arrow from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather api_key = '' extractor = weather.Extract(api_key) zip = '96345' # get 20170101 00:00 begin_date = arrow.get("2017","YYYY") # get 20171231 23:00 end_date = arrow.get("2018","YYYY").shift(hours=-1) for date in arrow.Arrow.range('hour',begin_date,end_date): # get date object for feature # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date date_weather = extractor.date(zip,date.format('YYYYMMDD')) # use shortcut to get observations and data # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation for observation in date_weather.observations: print("Date:",observation.date_pretty) print("Temp:",observation.temp_f)
has comment: http://stackoverflow.com/comment/82269500
downvote count: 0
has comment: http://stackoverflow.com/comment/82272993
score: 1
has comment: http://stackoverflow.com/comment/82287806
type: Answer

record
type: Tag
tag name: record
tags question: http://stackoverflow.com/q/47587747

http://stackoverflow.com/q/47682919
has body: I am querying the Google Analytic API in Python 2.7. Below are two examples of code. The first one works, but does not involve the filtering I want to do. The second chunk of code does not work, but represents my attempt to filter my results based on the content of a custom GA dimension, which in this case is whether pages contain a custom GA tag. This is how I query the GA API, which works, but does not involve the filtering I need: import datetime import time from datetime import timedelta # get start and end dates in correct format start_date = d1.strftime('%Y-%m-%d') end_date = d2.strftime('%Y-%m-%d') # Create ReportRequest object response = service.reports().batchGet( body={ 'reportRequests': [ { 'viewId': 'ga:32981293', 'dateRanges': [{'startDate': start_date, 'endDate': end_date}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:pageviews'}, {'expression': 'ga:users'}, {'expression': 'ga:exits'}, {'expression': 'ga:avgSessionDuration'}, {'expression': 'ga:avgTimeonPage'}, {'expression': 'ga:sessionsPerUser'}, {'expression': 'ga:percentNewSessions'}, {'expression': 'ga:bounceRate'}], 'dimensions': [{"name": "ga:pagePath"}], 'orderBys': [{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}], 'pageSize': 500 }] } ).execute() So, the above could gives me an object where my Page Paths are sorted based on pageviews, and I'm getting the associated metrics that I asked for. What I want to do is add a filter so that I only get this information for Page Paths that contain a certain tag. In this case, I have a custom GA dimension called "News Page Tags" and I want to get information only for Page Paths that have specific News Page Tags. Here's one attempt at this, which does not work. I'm hoping there is some kind of syntax issue that someone can help me clear up. import datetime import time from datetime import timedelta # get start and end dates in correct format start_date = d1.strftime('%Y-%m-%d') end_date = d2.strftime('%Y-%m-%d') cur_tag = 'examp…
tagged with: google-analytics-api
type: AnsweredQuestion
tagged with: api
has title: Regexp filtering by custom dimensions in Google Analytics API in Python
accepted answer: http://stackoverflow.com/a/47683806
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47683806
upvote count: 1
favorite count: 0
type: Question
tagged with: google-analytics
score: 1
tagged with: python

http://stackoverflow.com/q/47676270
upvote count: 2
has answer: http://stackoverflow.com/a/47676417
has comment: http://stackoverflow.com/comment/82311406
downvote count: 0
has comment: http://stackoverflow.com/comment/82311459
has comment: http://stackoverflow.com/comment/82311346
has answer: http://stackoverflow.com/a/47676363
tagged with: string
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47676364
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47676411
possible better answer: http://stackoverflow.com/a/47676363
has comment: http://stackoverflow.com/comment/82311508
has comment: http://stackoverflow.com/comment/82311391
tagged with: python
has body: Let's say I have a string like this: s = '(X_xy09 and X_foobar or (X_abc123 and X_something))' and I want to turn it into '(xy09 and foobar or (abc123 and something))' then - in this particular case - I could simply do s.replace('X_', "") which gives the desired output. However, in my actual data there might be not only X_ but also other prefixes, so the above replace statement does not work. What I would need instead is a replacement of a capital letter followed by an underscore and an arbitrary sequence of letters and numbers by everything after the first underscore. So, to extract the desired elements I could use: import re print(re.findall('[A-Z]{1}_[a-zA-Z0-9]+', s)) which prints ['X_xy09', 'X_foobar', 'X_abc123', 'X_something'] how can I now replace those elements so that I obtain '(xy09 and foobar or (abc123 and something))' ?
tagged with: regex
answer count: 4
has title: Replace strings in a string by a substring of those strings
tagged with: replace
has answer: http://stackoverflow.com/a/47676364
score: 2

http://stackoverflow.com/comment/82212810
has text: @CDspace in that case, assuming `f()` is your function: `ret = set(f(x) for x in q)`
comment on: http://stackoverflow.com/a/47627569
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47695212
tagged with: design-patterns
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47756769
has title: What would be the robust design pattern for multiple class forms render/process (create, update) on single page in django
has comment: http://stackoverflow.com/comment/82350730
score: 0
has comment: http://stackoverflow.com/comment/82376340
answer count: 2
type: UnansweredQuestion
has body: I am working on a django project in which I have to design a sales order page for order processing,now as per requirement I have to create multiple information forms on single page with different fields (formset does not helpful in this case) which I achieved by creating specific form class and then render them in template through class view function def get_context_data(self, **kwargs): context = super(CreateOrderView, self).get_context_data(**kwargs) context['ord_info_form'] = OrderInformationForm() context['billing_form'] = BillingInformationForm(prefix='billing') context['shipping_form'] = ShipingInformationForm(prefix='shipping') context['payment_form'] = PaymentInfoForm() context['summary_form'] = OrderProductsForm() return context My template look like this: Now, I have to save data for all forms which belongs to multiple models like billing, contact and shipping information. So for save information I created another form class for create order and set it in form_class variable in Createview class, and I override the save function in form class in which I manipulate the data for all model forms. For update order (put operation) I did the same I create another form class for update like create one in form class. As per my understanding I implement this strategy, but this seems to me repetitive design. How can I design it better for multiple forms with different fields. Please let me know what kind of design pattern I can apply for this. P.S: If require I'll post more code and assets for clear understanding. Thanks in advance.
tagged with: django
has answer: http://stackoverflow.com/a/47995975

http://stackoverflow.com/comment/82210272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47625868
has text: I run this file from statsmodel master github repository, git://github.com/statsmodels/statsmodels.git .
score: 0

http://stackoverflow.com/a/47563415
has body: You can slice the dataframe based on the conditions, then change the name. df2 = df[df.Location.eq('london') &amp; df.Amount.gt(2000)].reset_index(drop=True) df2.Name = 'EEE'
score: 0
has comment: http://stackoverflow.com/comment/82084999
answers question: http://stackoverflow.com/q/47563313
has comment: http://stackoverflow.com/comment/82086102
type: Answer

http://stackoverflow.com/q/47673996
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82306926
tagged with: python
tagged with: php
tagged with: laravel
has comment: http://stackoverflow.com/comment/82307971
tagged with: azure
has answer: http://stackoverflow.com/a/47675796
has comment: http://stackoverflow.com/comment/82307314
score: 0
has body: I am connecting my two apps (laravel with python) using curl command. It is working absolutely fine on my local server without changing a single line but when it gives me following error when on azure server POST https://myweb.com/searchJobs 500 () my code is $ch = curl_init(); //URL to send the request to curl_setopt($ch, CURLOPT_URL, 'http://python-scrapper-python001.azurewebsites.net/myfunction'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); //We are doing a post request curl_setopt($ch, CURLOPT_POST, 1); //adding the post data to request curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); //Return instead of outputting directly curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); is there any security protocol that I need to update on azure or what can be possible issue?
has comment: http://stackoverflow.com/comment/82306915
has comment: http://stackoverflow.com/comment/82307069
has answer: http://stackoverflow.com/a/47677168
has comment: http://stackoverflow.com/comment/82307091
has title: laravel curl not working on azure
tagged with: curl
has comment: http://stackoverflow.com/comment/82307858
type: Question

http://stackoverflow.com/q/47554592
downvote count: 0
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/47554821
tagged with: python
has answer: http://stackoverflow.com/a/47554821
has body: x_d = np.linspace(-4, 8, 30) print('x_d shape: ',x_d.shape) print('x shape: ',x.shape) density = sum((abs(xi - x_d) &lt; 0.5) for xi in x)---------&gt; difficulty in understanding statement output: x_d shape: (30,) x shape: (20,) I am having difficulty in understanding above statement for each value of x we are substracting x_d from it, and we will get single value. But we are density as (30,) How we got density dimension as (30,)
has title: usage of sum function in python
tagged with: numpy
type: AnsweredQuestion
tagged with: pandas
upvote count: 3
answer count: 1

google-cloud-dataflow
tags question: http://stackoverflow.com/q/47678013
tags question: http://stackoverflow.com/q/47600263
tag name: google-cloud-dataflow
tags question: http://stackoverflow.com/q/47641063
tags question: http://stackoverflow.com/q/47546068
tags question: http://stackoverflow.com/q/47572389
tags question: http://stackoverflow.com/q/47617158
type: Tag

http://stackoverflow.com/comment/82371111
comment on: http://stackoverflow.com/a/47576896
type: Comment
type: AnswerComment
has text: @Gemini if this solution helped yo would you consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work?answertab=votes#tab-top) it.
score: 0

http://stackoverflow.com/q/47644826
has comment: http://stackoverflow.com/comment/82248334
has comment: http://stackoverflow.com/comment/82248342
tagged with: typeerror
has answer: http://stackoverflow.com/a/47644871
has answer: http://stackoverflow.com/a/47645140
has title: data consistency check : TypeError: argument of type 'NoneType' is not iterable
type: Question
has body: so basically i am writing a some codes to cross check if my data is consistent. I have written the below code but it has been showing TypeError: argument of type 'NoneType' is not iterable, i have tried changing the code quite a few times but still the same error comes out. Many thanks. def checkdata(sex,school): if (sex == 'F') and ('boys school' in school) : return 'inconsistent' if (sex == 'M') and ('girls school' in school): return 'inconsistent' return def Dif() : with arcpy.da.UpdateCursor(DATA_SET, [sex, school]) as Cursor : for Cols in Cursor : Data = checkdata(Cols[0], Cols[1]) if Data is not None: print (Data, " ",Cols)
has comment: http://stackoverflow.com/comment/82248379
score: 0
answer count: 2
tagged with: nonetype
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82512886
type: Comment
has text: Also I found that when I did print(process('a2')) I got negative scores for all 3 categories. Then I added a new category called "Id" where i added values like a1,a2,b1,b2 . Then i did print(process('a2')) and print(process('c2')) and i got high score for "id" category in both cases. So the code above is it learning meaning of new values under the hood? Since i added a new category called Id it is somehow able to figure out that values like a1,b2,c3 are closely related.
comment on: http://stackoverflow.com/a/47758616
score: 0
type: AnswerComment

http://stackoverflow.com/q/47591501
has answer: http://stackoverflow.com/a/47592174
has comment: http://stackoverflow.com/comment/82141794
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/82140142
upvote count: 0
has body: I am not able to run jupyter notebook even after trying for 2 days ! please help I am using windows 8.1 Please click on this for the screen shot of the error while trying to run jupyter notebook on windows command promt this is the error showing : Error executing Jupyter command 'notebook': [Errno 'jupyter-notebook' not found] 2
has title: Even after trying all commands found on stackoverflow , it is still showing the following error
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82140656
has comment: http://stackoverflow.com/comment/82140198
tagged with: anaconda
downvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82141583
score: -3

http://stackoverflow.com/a/47624869
has comment: http://stackoverflow.com/comment/82207741
type: Answer
has body: You just need to add the Endpoint instance to the Endpoint_list which you use for the collision detection. Also, don't use the same name for the instance and the class, otherwise you're overriding the class and can't create new instances anymore. endpoint = Endpoint(400, 590, 50, 15) # Just use a lowercase name for the instance. all_sprite_list.add(endpoint) Endpoint_list.add(endpoint) Alternatively, you could use the pygame.sprite.collide_rect() function. if pygame.sprite.collide_rect(player, endpoint): print('exit reached') Or just the colliderect method of the rects: if player.rect.colliderect(endpoint):
score: 0
has comment: http://stackoverflow.com/comment/82207700
accepted answer of: http://stackoverflow.com/q/47624765
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82207833
answers question: http://stackoverflow.com/q/47624765
has comment: http://stackoverflow.com/comment/82207809

http://stackoverflow.com/q/47646478
score: 0
has comment: http://stackoverflow.com/comment/82254632
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/82251535
has body: I want to track changes in the model, basically log every function in views.py.. so that whatever changes are made to the model are reflected in the log file. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) print("Inside wrapper. Calling method %s now..."%(func.__name__)) r = func(*args, **kwargs) logging.getLogger(__name__) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def update(self, request, pk=None): users = get_object_or_404(Mytable, name=pk) serializer = CheckSerializer(users, data=request.data) if serializer.is_valid(): serializer.save() logging.info("Updated required data") return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) **models.py** class Mytable(DjangoCassandraModel): name = columns.Text(primary_key=True) email = columns.Text() password = columns.Text() creation_date = columns.DateTime(default=datetime.datetime.today()) modified_on = columns.DateTime(default=datetime.datetime.now) In Views.py: I want to do something like this: def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) if func.__name__ == 'list': print("This is all the list of objects created by you") elif func.__name__ == 'create': print("New user added in %s.%s" %(table.__name__, field.__name__)) elif func.__name__ == 'retrieve': print("Tried retrieving pk %s" %(pk)) elif func.__name__ == 'update': print("Updated model fields %s from table %s" %(field.__name__, table.__name__)) elif func.__name__ == 'partial_update': print("Updated partial data from table %s in fields %s" %(table.__name__, field.__name__)…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82254126
tagged with: django
has title: Django: Track changes in models
tagged with: logging
type: Question
tagged with: cassandra

http://stackoverflow.com/comment/83187724
comment on: http://stackoverflow.com/q/47581672
type: QuestionComment
has text: I use tsplot regularly... I sure hope they replace it rather than just nuking it. Maybe they can hide it from people and leave it there...
score: 1
type: Comment

http://stackoverflow.com/comment/82227494
has text: can you add a sample data set?
type: QuestionComment
comment on: http://stackoverflow.com/q/47634751
type: Comment
score: 0

http://stackoverflow.com/comment/82430923
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47563101
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160866/discussion-between-thomas-and-xaav).

http://stackoverflow.com/q/47546510
tagged with: shell
has comment: http://stackoverflow.com/comment/82049856
has comment: http://stackoverflow.com/comment/82049982
type: Question
tagged with: python
type: UnansweredQuestion
has body: I came across query today on data comparison question today and I was wondering if 2 excel can be compared based on column name using shell/python script. File 2 is primary and need to have all columns . Null Columns from File 1 can be ignore. I know we can compare 2 text files using below method but not sure about the excel. file1=/var/tmp/foo.txt file2=/var/tmp/bar.txt sort ${file1} | grep -v '^$' &gt; ${file1}.tmp sort ${file2} | grep -v '^$' &gt; ${file2}.tmp sdiff ${file1} ${file2} Any suggestions on this ?
has comment: http://stackoverflow.com/comment/82052327
has comment: http://stackoverflow.com/comment/82050103
has comment: http://stackoverflow.com/comment/82049819
has comment: http://stackoverflow.com/comment/82049712
has title: Compare 2 Files based on Column name Using Shell/python Script
score: 0
answer count: 0

http://stackoverflow.com/comment/82242842
has text: I'll take a look at it. Could you maybe provide a very simple runnable example?
type: QuestionComment
comment on: http://stackoverflow.com/q/47639826
score: 0
type: Comment

http://stackoverflow.com/a/47575741
accepted answer of: http://stackoverflow.com/q/47575681
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82108586
has comment: http://stackoverflow.com/comment/82108535
has comment: http://stackoverflow.com/comment/82108856
has body: Your condition should be len(x) &gt;= 2. x will have two elements if there's data on the row.
answers question: http://stackoverflow.com/q/47575681
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82109175
score: 2

http://stackoverflow.com/comment/82129875
score: 1
has text: This is really not a good idea. Sure, you can use `globals()`, but then you need to keep using `globals()` to access your new variables. So you might as well just create your own `list` or `dict` to hold your objects. Using a `list` lets you access them by an index number. A `dict` gives you more options: you can give each object a name if you want.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47585899

http://stackoverflow.com/comment/82072178
type: Comment
type: QuestionComment
has text: What you have done till now?
comment on: http://stackoverflow.com/q/47557311
score: 1

http://stackoverflow.com/comment/82268457
type: AnswerComment
score: 0
type: Comment
has text: @Dark, that is interesting - thank you! I didn't know this way
comment on: http://stackoverflow.com/a/47650623

http://stackoverflow.com/q/47602364
has title: Updating canvas in Tkinter
accepted answer: http://stackoverflow.com/a/47602682
downvote count: 0
has answer: http://stackoverflow.com/a/47602682
has comment: http://stackoverflow.com/comment/82163680
possible better answer: http://stackoverflow.com/a/47602782
favorite count: 0
has comment: http://stackoverflow.com/comment/82163723
type: Question
has comment: http://stackoverflow.com/comment/82163525
has body: Does anybody know how to modify the following code so that the graph is updated every time I change a goniometric function? The plotting is done in function plot(). There are some related threads on stackoverflow, but I was not able to apply them on my example code... Many thx, Macky import numpy as np import Tkinter as tk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class App: def __init__(self, window): self.window = window # set up pi pi = 3.141592654 # create the frame and pack to the object frame = tk.Frame(window) frame.pack() def callback(func, *pargs): print(func.get()) func.set(func.get()) self.plot() self.window.update() self.func = tk.StringVar() self.func.set("sin") # default value self.func.trace('w', lambda *pargs: callback(self.func, *pargs)) self.button = tk.OptionMenu(window, self.func, "sin", "cos", "tan") self.button.pack(side = tk.TOP) self.min_value = tk.Entry(window, justify = tk.RIGHT) self.min_value.pack() self.min_value.delete(0, tk.END) self.min_value.insert(0, -pi) self.max_value = tk.Entry(window, justify = tk.RIGHT) self.max_value.pack() self.max_value.delete(0, tk.END) self.max_value.insert(0, pi) self.button = tk.Button(frame, text = "QUIT", foreground = "red", command = frame.quit) self.button.pack(side = tk.BOTTOM) self.draw = tk.Button(frame, text = "DRAW", command = self.plot()) self.draw.pack(side = tk.LEFT) def plot(self): # generate numbers for the plot x = np.array(np.arange(np.float64(self.min_value.get()), np.float64(self.max_value.get()), 0.001)) if self.func.get() == 'sin': print('plotting sin()') y = np.sin(x) elif self.func.get() == 'cos': print('plotting cos()') y = np.cos(x) else: print('plotting tan()') y = np.tan(x) # create the plot fig = Figure(figsize = (6, 6)) a = fig.add_subplot(1,1,1) a.plot(x, y, color = 'blue') a.set_title ("Goniometric Functions", fontsize = 12) a.set_ylabel(self.func.get() + '(x)', fontsize = 8) a.set_xlabel('x', fontsize = 8) # canvas …
tagged with: python
has comment: http://stackoverflow.com/comment/82163716
score: 2
has answer: http://stackoverflow.com/a/47602782
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82163676
answer count: 2
tagged with: tkinter
tagged with: canvas
upvote count: 2

http://stackoverflow.com/q/47638780
tagged with: python
has body: I have log data in 7 separate files which I need to merge into one file before I can conduct any page analysis on it. Below I have provided an example of a line within one of the log data files 207.46.13.124 - - [01/Jun/2015:00:00:04 +0000] "GET /maritime/collections/hmsconway/hiscock/index.aspx HTTP/1.0" 200 "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)" The names of the files are u_ex150601, u_ex150602, u_ex150603, u_ex1506014, u_ex150605, u_ex150606, and u_ex150607. How do I merge all of these together using just Python?
score: 0
has answer: http://stackoverflow.com/a/47639178
answer count: 1
has title: Merging log data in python
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47600263
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
has title: Weird pickling error running Apache Beam Python on Dataflow
has comment: http://stackoverflow.com/comment/82243595
has comment: http://stackoverflow.com/comment/82165242
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47642605
has body: We're running a fairly simple job which reads JSON, does some processing and outputs JSON. For some reason, this always fails with a very weird "pickling" error: PicklingError: Can't pickle &lt;type 'generator'&gt;: attribute lookup __builtin__.generator failed [while running 'map to user_activity'] It fails almost immediately on processing the first line of data. The preceding stage emits a tuple of (String, []). When the 'map to user_activity' stage runs, it will fail if it tries to iterate the []. There are no lambdas, which seem to be a common source of these pickling errors. We've narrowed it down to iterating over the [] in the input tuple. If we don't iterate, then the job will "work". As soon as we do: for entry in input_tuple: pass The job fails immediately. **** Update **** It turns out, iterating over the input tuple isn't the key. ANY for loop in the Map function will cause a crash, even something like this: q=[1,2,3,4,5,6] for a in q: pass Here's the full stack trace for the error: An exception was raised when trying to execute the workitem 4985068250752295797 : Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 582, in do_work work_executor.execute() File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 166, in execute op.start() File "dataflow_worker/native_operations.py", line 38, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3175) def start(self): File "dataflow_worker/native_operations.py", line 39, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:3079) with self.scoped_start_state: File "dataflow_worker/native_operations.py", line 44, in dataflow_worker.native_operations.NativeReadOperation.start (dataflow_worker/native_operations.c:2994) with self.spec.source.reader() as reader: File "dataflow_worker/native_operations.py", line 54, in dataflow_worker.n…
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/122412453
score: 6
has text: migrations are supposed to be shipped, why would you ignore these?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54693364

http://stackoverflow.com/q/47624390
has comment: http://stackoverflow.com/comment/82208204
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
has title: Groupby with condition
accepted answer: http://stackoverflow.com/a/47624607
has answer: http://stackoverflow.com/a/47625180
possible better answer: http://stackoverflow.com/a/47625180
upvote count: 1
tagged with: python
downvote count: 1
has body: I am trying to create a new variable which performs the SALES_AMOUNT difference between years-month on the following dataframe. I think my code should be think with this groupby but i dont know how to add the condition [df2 df.Control - df.Control.shift(1) == 12] after the groupby so as to perform a correct difference between years df['LY'] = df.groupby(['month']).SALES_AMOUNT.shift(1) Dataframe: SALES_AMOUNT Store Control year month 0 16793.14 A 3 2013 3 1 42901.61 A 5 2013 5 2 63059.72 A 6 2013 6 3 168471.43 A 10 2013 10 4 58570.72 A 11 2013 11 5 67526.71 A 12 2013 12 6 50649.07 A 14 2014 2 7 48819.97 A 18 2014 6 8 97100.77 A 19 2014 7 9 67778.40 A 21 2014 9 10 90327.52 A 22 2014 10 11 75703.12 A 23 2014 11 12 26098.50 A 24 2014 12 13 81429.36 A 25 2015 1 14 19539.85 A 26 2015 2 15 71727.66 A 27 2015 3 16 20117.79 A 28 2015 4 17 44252.19 A 29 2015 6 18 68578.82 A 30 2015 7 19 91483.39 A 31 2015 8 20 39220.87 A 32 2015 10 21 12224.11 A 33 2015 11 result should look like this: SALES_AMOUNT Store Control year month year_diff 0 16793.14 A 3 2013 3 Nan 1 42901.61 A 5 2013 5 Nan 2 63059.72 A 6 2013 6 Nan 3 168471.43 A 10 2013 10 Nan 4 58570.72 A 11 2013 11 Nan 5 67526.71 A 12 2013 12 Nan 6 50649.07 A 14 2014 2 Nan 7 48819.97 A 18 2014 6 -14239.75 8 97100.77 A 19 2014 7 Nan 9 67778.40 A 21 2014 9 Nan 10 90327.52 A 22 2014 10 -78143.91 11 75703.12 A 23 2014 11 17132.4 12 26098.50 A 24 2014 12 -41428.21 13 81429.36 A 25 2015 1 Nan 14 19539.85 A 26 2015 2 -31109.22 15 71727.66 A 27 2015 3 Nan 16 20117.79 A 28 2015 4 Nan 17 44252.19 A 29 2015 6 -4567.78 18 68578.82 A 30 2015 7 -28521.95 19 91483.39 A 31 2015 8 Nan 20 39220.87 A 32 2015 10 -51106.65 21 12224.11 A 33 2015 11 -63479.01
has comment: http://stackoverflow.com/comment/82207007
type: AnsweredQuestion
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47624607

http://stackoverflow.com/comment/82039195
type: QuestionComment
comment on: http://stackoverflow.com/q/47540944
score: 0
type: Comment
has text: Try updating your pandas?

http://stackoverflow.com/q/47681818
type: UnansweredQuestion
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82323999
favorite count: 0
tagged with: yield
has answer: http://stackoverflow.com/a/47682068
has comment: http://stackoverflow.com/comment/82322913
has comment: http://stackoverflow.com/comment/82322918
has comment: http://stackoverflow.com/comment/82323042
has comment: http://stackoverflow.com/comment/82322832
tagged with: python
tagged with: generator
type: Question
has body: A bar shop has a ten-day promotion. During this period, the price of an beer drops 10 percent each day. For example, a beer that costs 10$ on the first day costs $9 on the second day and $8.1 on the third day. I want to write a python function that uses yield keyword to calculate beer price each day. For instance if we give input 10, My expected output is: Price is discounted to : 9 Price is discounted to : 8.1 ..etc class DiscountCalc: def get_item_price(self): return input('Input a starting price (0 to quit): ') def discount(self, current_price, days): yield (current_price - (current_price*10)//100) def run(self): initial = self.get_item_price() for price in self.discount(initial, 10): print "Price is discounted to : " + str(price) DiscountCalc().run()
score: 0
has title: Python "yield" keyword to calculate
has comment: http://stackoverflow.com/comment/82322728

error-handling
tags question: http://stackoverflow.com/q/47676319
tags question: http://stackoverflow.com/q/47552417
tags question: http://stackoverflow.com/q/47637955
tags question: http://stackoverflow.com/q/47603405
tags question: http://stackoverflow.com/q/47574261
tags question: http://stackoverflow.com/q/47586618
tags question: http://stackoverflow.com/q/47562685
tags question: http://stackoverflow.com/q/47660050
tag name: error-handling
tags question: http://stackoverflow.com/q/47642021
tags question: http://stackoverflow.com/q/47663911
type: Tag
tags question: http://stackoverflow.com/q/47623450

http://stackoverflow.com/q/47569017
type: Question
upvote count: 2
type: UnansweredQuestion
has title: Miniconda + PyGObject: Gtk.Spinner not visible/ how to use system application appearance
tagged with: python
tagged with: miniconda
has body: I am writing an GUI application using PyGObject with GTK+ 3.16.6 in a miniconda virtual environment (Python 3.6.3). Within my application I want to use a Gtk.Spinner, but this widget is not shown when I start my program within the miniconda environment. If I start the application outside of the virtual environment (using Python and the libraries that are installed on my system), the widget is shown as expected. In addition the 'venv-version' does not use the application appearance that is configured in the system which makes sense to me, but the missing Gtk.Spinner does really bother me. Here is how the application looks like (the spinner is in the bottom right corner): Started in the virtual environment Started 'natively' I guess that I need to set some environment variable, but I have no clue what to add and how to do that permanent in the virtual environment. I would like to get that spinner visible, the rest of the appearance is not that important. Can you help me? Thank you in advance! For completeness, here is the output of conda list -e for the virtual environment: # This file may be used to create an environment using: # $ conda create --name &lt;env&gt; --file &lt;this file&gt; # platform: linux-64 at-spi2-atk=2.16.0=1 at-spi2-core=2.16.0=1 atk=2.16.0=2 bleach=2.0.0=py36h688b259_0 ca-certificates=2017.11.5=0 cairo=1.14.8=0 certifi=2017.11.5=py36_0 dbus=1.8.20=1 dbus-glib=0.104=1 decorator=4.1.2=py36hd076ac8_0 entrypoints=0.2.3=py36h1aec115_2 expat=2.1.0=0 fontconfig=2.12.1=3 freetype=2.5.5=2 gdk-pixbuf=2.30.8=3 gettext=0.19.7=1 glib=2.51.4=0 gmp=6.1.2=h6c8ec71_1 gobject-introspection=1.51.3=py36_0 gst-plugins-base=1.8.0=0 gstreamer=1.8.0=0 gtk=3.16.6=2 harfbuzz=1.0.1=3 html5lib=0.999999999=py36h2cfc398_0 icu=54.1=0 intel-openmp=2018.0.0=h15fc484_7 ipykernel=4.6.1=py36hbf841aa_0 ipython=6.1.0=py36hc72a948_1 ipython_genutils=0.2.0=py36hb52b0d5_0 ipywidgets=7.0.0=py36h7b55c3a_0 jedi=0.10.2=py36h552def0_0 jinja2=2.9.6=py36h489bce4_1 jpeg=9b=h024ee3a_2 jsonschem…
answer count: 0
score: 2
tagged with: pygobject
downvote count: 0
tagged with: gtk3
tagged with: spinner
favorite count: 0

http://stackoverflow.com/a/47590920
has comment: http://stackoverflow.com/comment/82139851
score: 0
has comment: http://stackoverflow.com/comment/82139918
has comment: http://stackoverflow.com/comment/82139014
has comment: http://stackoverflow.com/comment/82143610
type: Answer
has body: I am assuming you are storing the information in User object. usr = User.objects.get(username = whateveristheusername) if usr is not None: #User Exist. Click to join chat else: #Create User or any other viable functionality
has comment: http://stackoverflow.com/comment/82142106
answers question: http://stackoverflow.com/q/47590724

http://stackoverflow.com/q/47542073
possible better answer: http://stackoverflow.com/a/47542133
answer count: 2
has comment: http://stackoverflow.com/comment/82041355
tagged with: python
has answer: http://stackoverflow.com/a/47542133
linked to: http://stackoverflow.com/q/18689512
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47542120
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47542120
favorite count: 0
has body: Using python and panda: For a given data set how does one find the total number of missing attributes? I have found the number for each column, but I need to sum the columns using python to find the total. Below is the code I have currently used. def num_missing(x): return sum(x.isnull()) print("Missing Values per Column:") print(data_file1.apply(num_missing))
has title: Total Number of Missing Attributes
type: Question

http://stackoverflow.com/comment/82392670
has text: Hi @Kirill, I tried to do what you suggested, but I don't seem to make it work - would you mind helping out? See more details in the question.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47681199

http://stackoverflow.com/comment/82174704
type: QuestionComment
has text: There might be spaces in column names so do `main.columns = main.columns.str.strip()` and `items.columns=items.columns.str.strip()`
comment on: http://stackoverflow.com/q/47608112
type: Comment
score: 0

http://stackoverflow.com/q/47656153
has answer: http://stackoverflow.com/a/47656391
has title: Take the mean of values in a list if a duplicate is found
has comment: http://stackoverflow.com/comment/82270417
tagged with: arrays
has comment: http://stackoverflow.com/comment/82270584
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47656498
has comment: http://stackoverflow.com/comment/82270865
favorite count: 0
has answer: http://stackoverflow.com/a/47656498
type: Question
has answer: http://stackoverflow.com/a/47656850
possible better answer: http://stackoverflow.com/a/47656391
has answer: http://stackoverflow.com/a/47656561
answer count: 5
has comment: http://stackoverflow.com/comment/82270400
tagged with: python
has comment: http://stackoverflow.com/comment/82270726
has comment: http://stackoverflow.com/comment/82270539
has body: I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on: l1 = ['John', 'Bob', 'Stew', 'John'] l2 = [1, 4, 7, 3] My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be: l1 = ['John', 'Bob', 'Stew'] l2 = [2, 4, 7] I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this. Thank you
linked to: http://stackoverflow.com/q/47615401
tagged with: append
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47656787
tagged with: list
tagged with: for-loop
score: 1

http://stackoverflow.com/comment/82234251
has text: That's because you're calling ` C:/Users/boy/PycharmProjects/REAL` which appears to be a directory or command and not a `.xls` file. The example I gave above will work if you run it how it is.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47637482

python-multithreading
tags question: http://stackoverflow.com/q/47686853
tags question: http://stackoverflow.com/q/47675124
tags question: http://stackoverflow.com/q/47557340
tags question: http://stackoverflow.com/q/47588655
tags question: http://stackoverflow.com/q/47665944
tags question: http://stackoverflow.com/q/47611770
tag name: python-multithreading
tags question: http://stackoverflow.com/q/47672076
tags question: http://stackoverflow.com/q/47569811
tags question: http://stackoverflow.com/q/47624674
type: Tag

http://stackoverflow.com/q/47562012
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47573741
has title: Unable to access Python Pulp solver on AWS Lambda instance
score: 0
has body: I'm trying to run an optimisation on AWS Lambda using Pulp in Python. I have packaged pulp (zipping the contents not the directory) along with my lambda_function and uploaded the zip. The error I'm stuck on is: File "/var/task/pulp/pulp.py", line 1664, in solve status = solver.actualSolve(self, **kwargs) AttributeError: 'NoneType' object has no attribute 'actualSolve' I've tried the fixes here: Importing Python Module "Pulp" on Amazon AWS Lambda in particular trying to specify the solver directly, and placing the solver (cbc) into the parent directory of the script to no avail. When I do try to specify the solver directly I get a different error: Pulp: cannot execute cbc cwd: /var/task: PulpSolverError Traceback (most recent call last): File "/var/task/lambda_function.py", line 14, in lambda_handler result = ip_optimise(recipes, settings) File "/var/task/ip_optimise.py", line 102, in ip_optimise prob.solve(COIN_CMD()) I've also tried putting in the path directly, eg: prob.solve(COIN_CMD("/var/task/cbc")) with the same error (cannot execute)
answer count: 1
tagged with: pulp
tagged with: aws-lambda
type: Question
linked to: http://stackoverflow.com/q/45431487

http://stackoverflow.com/a/47587409
answers question: http://stackoverflow.com/q/47580074
has comment: http://stackoverflow.com/comment/82269652
type: Answer
has body: You are looking at it wrong. This has nothing to do with GridSearchCV. But with svm. You see, you are trying to use predict_proba() on the SVC, which is known to have confusing outputs and these outputs may not match the actual output from the predict() function. I ran your code with one small change: print(balanced.predict(pred_mat)) print(unbalanced.predict(pred_mat)) And the output is: [0 0 0 1 0 1] [0 0 0 1 1 1] So as you see, its not much different for the two cases. The only source of difference I can think of in these two outputs is that you have 1 extra data about the second class in the second case, which helps in recognizing it better than first case. This you can verify by changing the samples of classes. Now as to the explanation of why predict_proba is giving such results please look at: Scikit-learn clarification about it in documentation This answer on StackOverflow by one of the scikit developers This excellent explanation of the differences by another scikit developer. (Do read the comments)
score: 0

http://stackoverflow.com/q/47638964
has comment: http://stackoverflow.com/comment/82236973
tagged with: file
accepted answer: http://stackoverflow.com/a/47639309
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/23064549
has comment: http://stackoverflow.com/comment/82238180
has answer: http://stackoverflow.com/a/47639309
has body: I ran into an issue when trying to extract file creation date via Python. I am using Python3.6 on 64bit Windows7. I have a number of pictures (jpeg) that were taken [I should use "created" instead] in the past and uploaded to an on-line album on the same day. [Note: These JPEGs are not 'fresh' off the camera, some of them have been processed by other software and then "saved as"; Some of them are actually cellphone screenshots. So the EXIF Info may not be available] For example one of them were taken [or a better example cellphone screenshot created] and uploaded on 1/1/2016. I downloaded it from the on-line album on 11/1/2017. When this jpeg file is listed in Win7 file explorer’s “details” view, under “date” column it is showing 1/1/2016. When I try to use Python to extract the creation date info, all three ways (st_atime, st_mtime, st_ctime) gave me 11/1/2017. I then right click the file and view its property, there “created”, “modified”, and “accessed” all pointed to 11/1/2017. I am wondering if there is still a Python way to get the original creation date, i.e. 1/1/2016, from this file? On my windows screen I clearly see that date "1/1/2016" Why I could not retrieve it? That's thing really drives me to ask this question Thank you!
has title: Extract file creation date via Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82236424
tagged with: python
tagged with: creation
tagged with: date
favorite count: 0
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82236367

http://stackoverflow.com/comment/82055236
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47548957
has text: @ArthurSpoon Not duplicate. I had already checked that question. I get an memory error on the line where we dump the array. Besides my problem branches from having a low RAM.

http://stackoverflow.com/comment/82176216
score: 1
type: QuestionComment
type: Comment
has text: `reader.read()` doesn't take a filename. From the documentation it takes a *queue*: *queue: A Queue or a mutable string Tensor representing a handle to a Queue, with string work items.*
comment on: http://stackoverflow.com/q/47608909

http://stackoverflow.com/a/47645488
score: 0
answers question: http://stackoverflow.com/q/47644919
has body: Maybe introduce some javascript to make an ajax call to another view which adds to the Movie model (I'm making an assumption you are just adding a record). If I were you, I'd change that model to: class MovieLinkClick(models.Model): movie_id = models.IntegerField() def __str__(self): return self.movie_id Change the link to: &lt;a href="{{ movie_details }}" data-movieid={{id}} class="movielink"&gt;&lt;img src="{{ poster }}" alt=""&gt;&lt;/a&gt; then add some javascript in the template to watch for those clicks. If you've got jQuery loaded you can use the data attributes to easily get something like the movieid set in the a tag. (see https://api.jquery.com/data/). You'll likely also need a csrf_token if you are using a post method. $(document).ready(function() { $('.movielink').on("click", function(e) { e.preventDefault(); var link = $(this).attr("href"); var id = $(this).data('movieid'); $.ajax({ url: "{% url 'movies:log_click' %}", type: "POST", data: {movie_id: id, csrfmiddlewaretoken: "{{ csrf_token }}" }); window.location.href = link; //redirect to the href }); }); You'd need to create a suitable urls entry to handle the movies:log_click which accepts a post method. See https://docs.djangoproject.com/en/1.11/topics/http/urls/ for a refresher on that.
has comment: http://stackoverflow.com/comment/82249687
type: Answer

http://stackoverflow.com/a/47574048
has body: If you use the splat operator on your values iterable, then I guess it should work fine? plt.plot(x, y, label='best fit curve $y={0:.2f}x+{1:.2f}$'.format(*values))
answers question: http://stackoverflow.com/q/47573925
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/47652312
type: Question
has comment: http://stackoverflow.com/comment/82263148
downvote count: 3
has body: I'm trying to split an email address under the format jim.smith-royal@smth.edu or jim.smith@smth.edu into a name and a surname, so jim and smith, or jim and smith royal (with a space in between). (I am a beginner so I may not be doing it in the simplest way, but still). for row in votants: mail = row[1] full_name = mail.split('@')[0] prenom = full_name.split('.')[0] #The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim' pre_name = full_name.split('.') nom = pre_name[1] #The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me try: nom = nom.split('-')[0] + " " + nom.split('-')[1] except Exception: pass row.append(prenom) row.append(nom) Instead of giving me nom as 'smith', I get "IndexError: list index out of range".
has answer: http://stackoverflow.com/a/47652544
tagged with: email
tagged with: python
score: -1
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82262859
has comment: http://stackoverflow.com/comment/82262795
has comment: http://stackoverflow.com/comment/82262979
accepted answer: http://stackoverflow.com/a/47652544
answer count: 1
has title: Why doesn't Python want to access the second item of my 2-items list?
has comment: http://stackoverflow.com/comment/82262845
favorite count: 0

http://stackoverflow.com/comment/82158763
type: AnswerComment
has text: This goes like this: "Nana" is a employee that takes care of a baby, but can also cook, clean, etc. So "Nana" may have a lot of abilities ("habilidades"), as well as specialities ("especialidades") like "Spanish food", "See food", etc. Talking to a coworker to confirm this, he told me: A "Nana" can have multiple "habilidades" (abilities), and 1 "habilidades" can have a lot of "Nana" objects asociated. Thank you for your time.
comment on: http://stackoverflow.com/a/47599901
score: 0
type: Comment

http://stackoverflow.com/a/47943827
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/106136609
type: Answer
answers question: http://stackoverflow.com/q/47612822
accepted answer of: http://stackoverflow.com/q/47612822
has body: I will share a more generic solution that I came up with, as I was working with the Twitter API. Let's say you have the ID's of tweets that you want to fetch in a list called my_ids : # Fetch tweets from the twitter API using the following loop: list_of_tweets = [] # Tweets that can't be found are saved in the list below: cant_find_tweets_for_those_ids = [] for each_id in my_ids: try: list_of_tweets.append(api.get_status(each_id)) except Exception as e: cant_find_tweets_for_those_ids.append(each_id) Then in this code block we isolate the json part of each tweepy status object that we have downloaded and we add them all into a list.... my_list_of_dicts = [] for each_json_tweet in list_of_tweets: my_list_of_dicts.append(each_json_tweet._json) ...and we write this list into a txt file: with open('tweet_json.txt', 'w') as file: file.write(json.dumps(my_list_of_dicts, indent=4)) Now we are going to create a DataFrame from the tweet_json.txt file (I have added some keys that were relevant to my use case that I was working on, but you can add your specific keys instead): my_demo_list = [] with open('tweet_json.txt', encoding='utf-8') as json_file: all_data = json.load(json_file) for each_dictionary in all_data: tweet_id = each_dictionary['id'] whole_tweet = each_dictionary['text'] only_url = whole_tweet[whole_tweet.find('https'):] favorite_count = each_dictionary['favorite_count'] retweet_count = each_dictionary['retweet_count'] created_at = each_dictionary['created_at'] whole_source = each_dictionary['source'] only_device = whole_source[whole_source.find('rel="nofollow"&gt;') + 15:-4] source = only_device retweeted_status = each_dictionary['retweeted_status'] = each_dictionary.get('retweeted_status', 'Original tweet') if retweeted_status == 'Original tweet': url = only_url else: retweeted_status = 'This is a retweet' url = 'This is a retweet' my_demo_list.append({'tweet_id': str(tweet_id), 'favorite_count': int(favorite_count), 'retweet_count': int(retweet_count), 'url': …
downvote count: 0
upvote count: 1

numpy
tags question: http://stackoverflow.com/q/47661872
tags question: http://stackoverflow.com/q/47668971
tags question: http://stackoverflow.com/q/47544099
tags question: http://stackoverflow.com/q/47680897
tags question: http://stackoverflow.com/q/47586996
tags question: http://stackoverflow.com/q/47665432
tags question: http://stackoverflow.com/q/47541888
tags question: http://stackoverflow.com/q/47557810
tags question: http://stackoverflow.com/q/47609817
tags question: http://stackoverflow.com/q/47548611
tags question: http://stackoverflow.com/q/47641058
tags question: http://stackoverflow.com/q/47666359
tags question: http://stackoverflow.com/q/47637758
tags question: http://stackoverflow.com/q/47644660
tags question: http://stackoverflow.com/q/47670462
tags question: http://stackoverflow.com/q/47601377
tags question: http://stackoverflow.com/q/47572640
tags question: http://stackoverflow.com/q/47588696
tags question: http://stackoverflow.com/q/47600049
tags question: http://stackoverflow.com/q/47581672
tags question: http://stackoverflow.com/q/47627934
tags question: http://stackoverflow.com/q/47591481
tags question: http://stackoverflow.com/q/47678507
tags question: http://stackoverflow.com/q/47571896
tags question: http://stackoverflow.com/q/47658095
tags question: http://stackoverflow.com/q/47637241
tags question: http://stackoverflow.com/q/47593210
tags question: http://stackoverflow.com/q/47551733
tags question: http://stackoverflow.com/q/47610951
tags question: http://stackoverflow.com/q/47577060
tags question: http://stackoverflow.com/q/47598605
tags question: http://stackoverflow.com/q/47579297
tags question: http://stackoverflow.com/q/47559084
tags question: http://stackoverflow.com/q/47580701
tags question: http://stackoverflow.com/q/47577395
tags question: http://stackoverflow.com/q/47563638
tags question: http://stackoverflow.com/q/47663553
tags question: http://stackoverflow.com/q/47681620
tags question: http://stackoverflow.com/q/47553339
tags question: http://stackoverflow.com/q/47652820
tags question: http://stackoverflow.com/q/47561718
tags question: http://stackoverflow.com/q/47675434
tags question: http://stackoverflow.com/q/47566072
tags question: http://stackoverflow.com/q/47640385
tags question: http://stackoverflow.com/q/47602655
tags question: http://stackoverflow.com/q/47621997
tags question: http://stackoverflow.com/q/47569596
tags question: http://stackoverflow.com/q/47686824
tags question: http://stackoverflow.com/q/47577783
tags question: http://stackoverflow.com/q/47649108
tags question: http://stackoverflow.com/q/47678252
tags question: http://stackoverflow.com/q/47652962
tags question: http://stackoverflow.com/q/47644261
tags question: http://stackoverflow.com/q/47613376
tags question: http://stackoverflow.com/q/47610110
tags question: http://stackoverflow.com/q/47552894
tags question: http://stackoverflow.com/q/47592755
tags question: http://stackoverflow.com/q/47683120
tags question: http://stackoverflow.com/q/47596434
tags question: http://stackoverflow.com/q/47613953
tags question: http://stackoverflow.com/q/47562634
tags question: http://stackoverflow.com/q/47591056
tags question: http://stackoverflow.com/q/47630350
tags question: http://stackoverflow.com/q/47605244
tags question: http://stackoverflow.com/q/47551069
tags question: http://stackoverflow.com/q/47644890
tags question: http://stackoverflow.com/q/47554592
tags question: http://stackoverflow.com/q/47581877
tags question: http://stackoverflow.com/q/47661395
tags question: http://stackoverflow.com/q/47571343
tags question: http://stackoverflow.com/q/47596390
tags question: http://stackoverflow.com/q/47692155
tags question: http://stackoverflow.com/q/47666539
tags question: http://stackoverflow.com/q/47563379
tags question: http://stackoverflow.com/q/47552767
tags question: http://stackoverflow.com/q/47655958
tags question: http://stackoverflow.com/q/47548002
tags question: http://stackoverflow.com/q/47545489
tags question: http://stackoverflow.com/q/47642570
type: Tag

http://stackoverflow.com/q/47671284
has comment: http://stackoverflow.com/comment/82301357
tagged with: django
tagged with: javascript
tagged with: python
type: AnsweredQuestion
has title: error while filtering data as per columns in django template
score: 1
has body: I am using Django template to display a table and I wish to filter data based on columns In order to do so, I have taken two var q and r in my javascript function go(){ // alert("hellonikhar"); var q = document.getElementById("search").value; var r=document.getElementById("columnName").value; window.open("/?q="+q+"&r="+r,"_self"); } In my home.html I have made a text-field and a drop-down menu Customer Name Status Product OS Type Server Type L3 Version PM CDM I have defined a function in my views.py to check the value of r from the drop-down and q when the go button is clicked but the data is not filtered based on those columns def user_profile(request): q = request.GET.get('q','') custom = Customer.objects.all() r= request.GET.get('r','') if q and r=="Status": custom1=custom.filter(name__contains=q) currently, I'm just testing when the value in the drop-down is status
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47681434
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47681434

http://stackoverflow.com/comment/82232908
comment on: http://stackoverflow.com/a/47636062
score: 0
type: Comment
has text: Correct. ImageMagick is written in C, and ships with a C-API library called `MagickWand`. The python package `wand` integrates with `MagickWand` through `ctypes` module.
type: AnswerComment

http://stackoverflow.com/comment/82271739
has text: Sorry for double-checking: does the folder /home/joyvan/work exists on the remote server where you are working or on your local machine? Do you know about any limitations on the server? Is this a public server? (Application may run chrooted so you don't have access to everything) Can you also try with something like `/tmp/abc.h5` ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47568569

pandas
tags question: http://stackoverflow.com/q/47574775
tags question: http://stackoverflow.com/q/47584642
tags question: http://stackoverflow.com/q/47571209
tags question: http://stackoverflow.com/q/47569284
tags question: http://stackoverflow.com/q/47579844
tags question: http://stackoverflow.com/q/47569496
tags question: http://stackoverflow.com/q/47619836
tags question: http://stackoverflow.com/q/47591848
tags question: http://stackoverflow.com/q/47675072
tags question: http://stackoverflow.com/q/47687432
tags question: http://stackoverflow.com/q/47556243
tags question: http://stackoverflow.com/q/47542073
tags question: http://stackoverflow.com/q/47603274
tags question: http://stackoverflow.com/q/47675185
tags question: http://stackoverflow.com/q/47689825
tags question: http://stackoverflow.com/q/47633005
tags question: http://stackoverflow.com/q/47673363
tags question: http://stackoverflow.com/q/47581808
tags question: http://stackoverflow.com/q/47696009
tags question: http://stackoverflow.com/q/47676299
tags question: http://stackoverflow.com/q/47574028
tags question: http://stackoverflow.com/q/47616756
tags question: http://stackoverflow.com/q/47557563
tags question: http://stackoverflow.com/q/47635838
tags question: http://stackoverflow.com/q/47618888
tags question: http://stackoverflow.com/q/47603430
tags question: http://stackoverflow.com/q/47592386
tags question: http://stackoverflow.com/q/47543392
tags question: http://stackoverflow.com/q/47664952
tags question: http://stackoverflow.com/q/47684051
tags question: http://stackoverflow.com/q/47626579
tags question: http://stackoverflow.com/q/47693070
tags question: http://stackoverflow.com/q/47661149
tags question: http://stackoverflow.com/q/47579250
tags question: http://stackoverflow.com/q/47627965
tags question: http://stackoverflow.com/q/47681184
tags question: http://stackoverflow.com/q/47622290
tags question: http://stackoverflow.com/q/47643594
tags question: http://stackoverflow.com/q/47547688
tags question: http://stackoverflow.com/q/47595268
tags question: http://stackoverflow.com/q/47563638
tags question: http://stackoverflow.com/q/47641698
tags question: http://stackoverflow.com/q/47581738
tags question: http://stackoverflow.com/q/47646185
tags question: http://stackoverflow.com/q/47655866
tags question: http://stackoverflow.com/q/47694550
tags question: http://stackoverflow.com/q/47677446
tags question: http://stackoverflow.com/q/47574551
tags question: http://stackoverflow.com/q/47552875
tags question: http://stackoverflow.com/q/47584876
tags question: http://stackoverflow.com/q/47651708
tags question: http://stackoverflow.com/q/47691724
tags question: http://stackoverflow.com/q/47695453
tags question: http://stackoverflow.com/q/47602234
tags question: http://stackoverflow.com/q/47619540
tags question: http://stackoverflow.com/q/47617499
tags question: http://stackoverflow.com/q/47560533
tags question: http://stackoverflow.com/q/47681401
tags question: http://stackoverflow.com/q/47549652
tags question: http://stackoverflow.com/q/47634751
tags question: http://stackoverflow.com/q/47635136
tags question: http://stackoverflow.com/q/47604657
tags question: http://stackoverflow.com/q/47562604
tags question: http://stackoverflow.com/q/47647198
tags question: http://stackoverflow.com/q/47611492
tags question: http://stackoverflow.com/q/47684606
tags question: http://stackoverflow.com/q/47681020
tags question: http://stackoverflow.com/q/47604151
tags question: http://stackoverflow.com/q/47654580
tags question: http://stackoverflow.com/q/47597914
tags question: http://stackoverflow.com/q/47594945
tags question: http://stackoverflow.com/q/47550613
tags question: http://stackoverflow.com/q/47612684
tags question: http://stackoverflow.com/q/47557601
tags question: http://stackoverflow.com/q/47665176
tags question: http://stackoverflow.com/q/47584961
tags question: http://stackoverflow.com/q/47617111
tags question: http://stackoverflow.com/q/47623233
tags question: http://stackoverflow.com/q/47618569
tags question: http://stackoverflow.com/q/47598236

numba
tags question: http://stackoverflow.com/q/47597264
tags question: http://stackoverflow.com/q/47635040
tags question: http://stackoverflow.com/q/47578965
tags question: http://stackoverflow.com/q/47585444
type: Tag
tags question: http://stackoverflow.com/q/47667879
tags question: http://stackoverflow.com/q/47667906
tags question: http://stackoverflow.com/q/47662621
tags question: http://stackoverflow.com/q/47569389
tags question: http://stackoverflow.com/q/47683436
tags question: http://stackoverflow.com/q/47662076
tag name: numba
tags question: http://stackoverflow.com/q/47682094
tags question: http://stackoverflow.com/q/47560627

http://stackoverflow.com/comment/82284339
has text: There are many, *many* ways to format strings, `f` strings, `.format`, `%`, `str(i)`. This information is widely available.
score: 0
comment on: http://stackoverflow.com/q/47662607
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82044859
has text: Note: A mutating slice assignment could be used to make it work (it would just be less efficient, since it would involve making a potentially huge temporary `list` just to remove one item), via `x[:] = x[:-1]`, because that's reassigning the range of values, not rebinding `x`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47543827
score: 0
type: Comment

http://stackoverflow.com/comment/82219782
score: 0
has text: @AlexRiley thanks. So would it be better (more performant) to use a different function for values, which are not complex?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47630946

http://stackoverflow.com/comment/82196408
comment on: http://stackoverflow.com/a/47619072
score: 1
type: Comment
has text: This is clearly not what the OP is after. The first sentence explains "the order does not matter", and neither of your outputs match the OP's expectations.
type: AnswerComment

http://stackoverflow.com/comment/82331150
comment on: http://stackoverflow.com/a/47685526
score: 0
type: Comment
has text: @pshep123 You must be using something on Server B to return the response. Python's built-in HTTP server, or something else? There must be something that's *listening* for the incoming requests?
type: AnswerComment

http://stackoverflow.com/comment/82262877
score: 0
comment on: http://stackoverflow.com/q/47650158
type: Comment
has text: @totyped see my answer below, it has this functionality.
type: QuestionComment

http://stackoverflow.com/comment/82070498
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [StaleElementReference Exception in PageFactory](https://stackoverflow.com/questions/44838538/staleelementreference-exception-in-pagefactory)
comment on: http://stackoverflow.com/q/47551317

http://stackoverflow.com/a/47636167
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47636126
accepted answer of: http://stackoverflow.com/q/47636126
score: 1
type: Answer
has body: To use np.hstack, we need to convert V1 to 2D such that the lengths along the first axis for the three input arrays are the same - np.hstack((V1[:,None],V2,V3)) As alternatives, we can use np.column_stack or np.concatenate along the second axis on 2D converted V1 alongwith others or np.c_ - np.column_stack((V1,V2,V3)) np.concatenate([V1[:,None],V2,V3],axis=1) np.c_[V1,V2,V3]

http://stackoverflow.com/q/47690140
duplicate of: http://stackoverflow.com/q/15233340
has answer: http://stackoverflow.com/a/47690271
downvote count: 1
favorite count: 0
type: Question
tagged with: readlines
tagged with: backspace
has title: How to readlines without having the \n at the end? (python)
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47690271
has answer: http://stackoverflow.com/a/47690300
possible better answer: http://stackoverflow.com/a/47690300
type: AnsweredQuestion
answer count: 2
has body: As I was finishing off a game I made, I made a save button that saves to a file. When the game opens, it will then read the file and save those lines as variables. I do so, but then I see that it needs to be an integer, so I use int(). But then it does not work, because the variable is "0\n" instead of "0". I have checked many other questions, but they do not ask or answer the same question. So I am wondering, is there a way to readlines() without the \n at the end? Or is there a way that I can backspace the variable automatically? Here is my code: import tkinter as tk from PIL import Image, ImageTk # --- functions --- def eggvalue_change(): global eggvalue, eggvalueupgrade, money, eggz if money &gt; int(round(eggvalueupgrade)): eggz -= eggvalueupgrade / eggvalue eggvalue+=0.2 eggvalueupgrade += int(round(eggvalueupgrade + (eggvalueupgrade / 7))) def moar_eggz(): global eggzps, chookz chookz += 1 def saving(): savedfile.write(money) savedfile.write(eggvalueupgrade) savedfile.write(eggzps) savedfile.write(chookz) savedfile.write(eggvalue) savedfile.write(eggz) def main_loop(): global eggz, eggzps, money eggzps = chookz / 100.0 money = eggz * eggvalue try: openbutton2.config( text="Egg Value: " + str(eggvalue) + " --&gt; " + str(eggvalue+0.2) + " ($" + str(eggvalueupgrade) + ")", command=eggvalue_change) label2.config(text="Money: $" + str(int(round(money))), font=("Terminal", 50), borderwidth=5, relief="ridge", bg="black", foreground="white",pady=10, padx=498) if eggzps &gt;= 10: label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(int(round(eggzps)))+" | Egg Value: $" + str(eggvalue) + " |", font=("Terminal", 20), borderwidth=4, relief="ridge", bg="black", foreground="red",pady=10, padx=498) elif eggzps &lt; 10: label1.config(text="| Chickens: " + str(chookz)+" | Eggs: " + str(int(round(eggz)))+" | Eggs Per Second: " + str(eggzps)+" | Egg Value: $" + str(eggvalue)+ " |", font=("Terminal", 20), borderwidth=4…
upvote count: 0

http://stackoverflow.com/a/47559901
score: 0
has body: Update2: As @schwobaseggl has pointed out there's no reason to use the function states_dict() here. Just do def main(): states_dict = { "Alabama": ["montgomery", "kay ivey"], "Alaska": ["Juneau", "Bill Wallker"], } question_list = ["What is the capital of","Who is the governor of"] choose_question = random.choice(question_list) if choose_question == "What is the capital of": choose_state = random.choice(list(states_dict.keys())) # this will give you a random key from the dict. Also, you should study the PEP8 style guide and incorporate it in your muscle memory now. Update: def state_dict(): states={"Alabama":["montgomery","kay ivey"],"Alaska":["Juneau","Bill Wallker"]} return states # returned states dict. def main(): question_list=["What is the capital of","Who is the governor of"] choose_question=random.choice(question_list) if choose_question=="What is the capital of": choose_state= random.choice(states_dict()) # added () print("What is the capital of",choose_state) Original: You indentation is incorrect. def state_dict(): states={"Alabama":["montgomery","kay ivey"],"Alaska":["Juneau","Bill Wallker"]} states is outside the function state_dict(). Make it: def state_dict(): states={"Alabama":["montgomery","kay ivey"],"Alaska":["Juneau","Bill Wallker"]} Additionally, you haven't followed the PEP8 style guidelines, maybe you did and compacted the code for SO. For those reading, this is a better way to format the code: def state_dict(): states = { "Alabama": ["montgomery", "kay ivey"], "Alaska": ["Juneau", "Bill Wallker"], }
has comment: http://stackoverflow.com/comment/82077540
answers question: http://stackoverflow.com/q/47559845
type: Answer

http://stackoverflow.com/q/47591341
tagged with: matplotlib
tagged with: python
tagged with: label
has body: I creat a plot with major and minor y ticks. I set evry 5'th minor ticks invisible to avoid intereference of the major and minor ticks. It works fine when I creat my plot but after I zoom in it gets broken. I use python 2.7.11 with Canopy 1.7.4.3348 as IDE. I creat ticks for the y axis as next: major ticks are set for y = n +- 0.5 where n is element of Z, where Z labels integers minor ticks are set for y = n +- 0.1 where n is element of Z, where Z labels integers to avoid interferenc with the major ticks evry 5'th element of the minor ticks are set invisible The code which implement this is the next: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['text.usetex'] = True x = np.linspace(0,2*np.pi,200) y = np.sin(x) majorLocatorX = MultipleLocator(0.5) majorFormatterX = FormatStrFormatter('%.1f') majorLocatorY = MultipleLocator(0.5) minorLocatorY = MultipleLocator(0.1) majorFormatterY = FormatStrFormatter('%.1f') minorFormatterY = FormatStrFormatter('%.1f') fig1 = plt.figure(figsize=(12,12)) ax1 = fig1.add_subplot(1,1,1) ax1.set_xlabel(r'$x$') ax1.set_ylabel(r'$\sin(x)$') ax1.set_xlim([-0.03,2*np.pi+0.03]) ax1.set_ylim([-1.03,1.03]) ax1.xaxis.set_major_locator(majorLocatorX) ax1.xaxis.set_major_formatter(majorFormatterX) ax1.xaxis.set_minor_locator(minorLocatorX) ax1.yaxis.set_major_locator(majorLocatorY) ax1.yaxis.set_major_formatter(majorFormatterY) ax1.yaxis.set_minor_locator(minorLocatorY) ax1.yaxis.set_minor_formatter(minorFormatterY) for label in ax1_1.yaxis.get_ticklabels('minor')[1::5]: label.set_visible(False) ax1.plot(x,y,label=r'$\sin(x)$') ax1.legend(loc='best',fontsize=12.0) plt.show() Before I zoom in I have the plot: The "original" plot.. After I zoom in I get the plot: The zoomed in plot.. Any help is highly appreciated!
has comment: http://stackoverflow.com/comment/82152212
has comment: http://stackoverflow.com/comment/82296523
has comment: http://stackoverflow.com/comment/82179876
score: 0
has comment: http://stackoverflow.com/comment/82152402
answer count: 0
has comment: http://stackoverflow.com/comment/82186362
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/82140020
has title: In matplotlib setting minor ylabel invisible fails after zoom in
type: UnansweredQuestion

http://stackoverflow.com/comment/82047591
has text: I agree @PM2Ring with `__future__` is the way to go if you do packages, but if someone just started with Python, i like your first idea more..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47545242
type: Comment

http://stackoverflow.com/comment/82195040
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47618470
type: Comment
has text: Thank you. I like the straight forward method, as it doesn't confuses me that much. Thank you, @timgeb!

http://stackoverflow.com/comment/82240707
score: 0
type: QuestionComment
type: Comment
has text: BTW: I think there should be module to work directly with `VLC` without `os.system` or `subprocess`. If I run `pip search vlc` then it shows some modules with word `vlc`.
comment on: http://stackoverflow.com/q/47637675

scikit-learn
tags question: http://stackoverflow.com/q/47610026
tags question: http://stackoverflow.com/q/47665432
tags question: http://stackoverflow.com/q/47550754
tags question: http://stackoverflow.com/q/47624000
tags question: http://stackoverflow.com/q/47646093
tags question: http://stackoverflow.com/q/47635838
tags question: http://stackoverflow.com/q/47622946
tag name: scikit-learn
tags question: http://stackoverflow.com/q/47570307
tags question: http://stackoverflow.com/q/47563870
tags question: http://stackoverflow.com/q/47664604
tags question: http://stackoverflow.com/q/47598480
tags question: http://stackoverflow.com/q/47572380
tags question: http://stackoverflow.com/q/47675520
tags question: http://stackoverflow.com/q/47650917
tags question: http://stackoverflow.com/q/47565963
tags question: http://stackoverflow.com/q/47618414
tags question: http://stackoverflow.com/q/47580074
tags question: http://stackoverflow.com/q/47681099
tags question: http://stackoverflow.com/q/47684660
tags question: http://stackoverflow.com/q/47679627
type: Tag
tags question: http://stackoverflow.com/q/47656674
tags question: http://stackoverflow.com/q/47569394
tags question: http://stackoverflow.com/q/47632671
tags question: http://stackoverflow.com/q/47605271
tags question: http://stackoverflow.com/q/47577754
tags question: http://stackoverflow.com/q/47568428
tags question: http://stackoverflow.com/q/47578414
tags question: http://stackoverflow.com/q/47621847
tags question: http://stackoverflow.com/q/47554554
tags question: http://stackoverflow.com/q/47619836
tags question: http://stackoverflow.com/q/47689825
tags question: http://stackoverflow.com/q/47637070
tags question: http://stackoverflow.com/q/47625821
tags question: http://stackoverflow.com/q/47604826
tags question: http://stackoverflow.com/q/47575265
tags question: http://stackoverflow.com/q/47610529
tags question: http://stackoverflow.com/q/47663569
tags question: http://stackoverflow.com/q/47664709
tags question: http://stackoverflow.com/q/47551596
tags question: http://stackoverflow.com/q/47633587
tags question: http://stackoverflow.com/q/47596948
tags question: http://stackoverflow.com/q/47593729
tags question: http://stackoverflow.com/q/47592516
tags question: http://stackoverflow.com/q/47587081
tags question: http://stackoverflow.com/q/47627478
tags question: http://stackoverflow.com/q/47548178
tags question: http://stackoverflow.com/q/47564504
tags question: http://stackoverflow.com/q/47665530
tags question: http://stackoverflow.com/q/47551850
tags question: http://stackoverflow.com/q/47659998
tags question: http://stackoverflow.com/q/47664061
tags question: http://stackoverflow.com/q/47692386
tags question: http://stackoverflow.com/q/47557417
tags question: http://stackoverflow.com/q/47637005
tags question: http://stackoverflow.com/q/47640889
tags question: http://stackoverflow.com/q/47599425
tags question: http://stackoverflow.com/q/47680954
tags question: http://stackoverflow.com/q/47577168

http://stackoverflow.com/q/47624974
has title: multiple values for one key in python
type: Question
has body: I've got a dictionary of unique id's (strings), and values for each of these id's (also strings). The problem is that some of the keys have multiple values separated by commas. I can't think of how to use string manipulation to split them based on commas and still have them assigned to their key. for example... 'abcde': 'abc,def' and I would like it to be: 'abcde': 'abc' 'abcde': 'def' any insight would be greatly appreciated
has comment: http://stackoverflow.com/comment/82207936
favorite count: 0
tagged with: keyvaluepair
tagged with: split
downvote count: 4
has answer: http://stackoverflow.com/a/47624995
upvote count: 0
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/82207825

http://stackoverflow.com/q/47566351
linked to: http://stackoverflow.com/q/47564997
score: 1
upvote count: 1
downvote count: 0
has body: I am trying to cross-compile Python for a Raspberry Pi 3, but I've been having a lot of issues. For one, it doesn't come with pip nor setuptools and if I try to install pip via python3.6 get-pip.py I get a zipimport.ZipImportError: can't decompress data; zlib not available error. Now, I tried to configure it using the --with-zlib option but the configure script shows a warning that reads configure: WARNING: unrecognized options: --with-zlib I read A LOT of questions regarding this issue and I double-checked that ALL necessary files are present, I'm on Fedora, and I have installed both zlib and zlib-devel. I also have just ran a simple installation (excluding the options and envvars to cross-compile, and using a prefix for the output, so it doesn't mess with my existing installation from the repos) and it also doesn't work, pip and setuptools are not present in site-packages in the output and configure also can't recognize the --with- options What am I doing wrong? I'm on Fedora 26 which has python3.6 in the repos, if that matters for some reason. Edit: Apparently, I also can't build other packages as well: Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _sqlite3 _ssl _tkinter readline zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. I have checked in setup.py, specifically for the zlib case and it is apparently ignoring my system's dirs when looking for header files: zlib_inc = find_file('zlib.h', [], inc_dirs) As you can see the arg that should be filled with my system's "standard" paths is empty, If this is a generated file, how can I instruct it to fill it with the beforementioned paths? --with-zlib-dir=/path and --with-zlib=/path yielded the same results, the configure script didn't recognize them. What is wrong with the process? How can I have Python find and build those packages? This is a follow-up question for my ques…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88720267
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88713446
tagged with: compilation
tagged with: python
tagged with: python-3.6
has title: Cannot compile Python 3.6 with Zlib support
answer count: 0

http://stackoverflow.com/comment/82271489
type: QuestionComment
type: Comment
has text: You're welcome :)
comment on: http://stackoverflow.com/q/47656127
score: 1

http://stackoverflow.com/a/60701462
type: Answer
has body: You can just write this, you no need to mention sep='\n' n = 5 print('\n'.join(['*'*i for i in range(1,n+1)])) Note: You should always start your range from 1 to n+1, otherwise it will skip your first iteration.
answers question: http://stackoverflow.com/q/47603665
score: 0

http://stackoverflow.com/comment/82289257
has text: (Aside: there is no need to add "please comment if you need more help" - readers will know this. As per my trimming signatures etc., we like succinct here).
score: 0
comment on: http://stackoverflow.com/a/47624121
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82254822
type: QuestionComment
comment on: http://stackoverflow.com/q/47647365
has text: I see but I have the question about its function just post in the article, that copy from documation
type: Comment
score: 0

http://stackoverflow.com/comment/82302657
has text: did not get your last comment "...calling as a web-service"
type: AnswerComment
comment on: http://stackoverflow.com/a/47671283
score: 0
type: Comment

http://stackoverflow.com/comment/82233810
type: Comment
comment on: http://stackoverflow.com/q/47637770
score: 1
type: QuestionComment
has text: You specified `shell=True` but passed a list of args.

http://stackoverflow.com/comment/82083564
type: Comment
type: QuestionComment
has text: This is probably a duplicate of https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory.
comment on: http://stackoverflow.com/q/47562769
score: 0

http://stackoverflow.com/comment/82163422
type: Comment
has text: better find tutorial for Python. `else: self.parse_data(response)`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47602043

http://stackoverflow.com/a/47541866
score: 1
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82042360
answers question: http://stackoverflow.com/q/47541623
has body: You can use more-itertools' sliced() method to slice an iterable into equal chunks: import more_itertools contacts = [] class Contact: def __init__(self, surname, name, number, addr): self.surname = surname self.name = name self.number = number self.addr = addr with open('file.txt', 'r') as f: content = f.read().split('\n') for x in more_itertools.sliced(content, 4): c = Contact(*x) contacts.append(c)
has comment: http://stackoverflow.com/comment/82126933

http://stackoverflow.com/a/47623031
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47622831
has body: you can refer this python tutorial for input document def prompt(n): value = int(input("Please enter integer #" + str(n) + ": ")) # Error in this line return value print("This program adds together two integers.") value1 = prompt(1) # Call the function value2 = prompt(2) # Call the function again sum = value1 + value2 print(value1, "+", value2, "=", sum)

scipy
tags question: http://stackoverflow.com/q/47675913
tags question: http://stackoverflow.com/q/47649694
tags question: http://stackoverflow.com/q/47575063
tags question: http://stackoverflow.com/q/47635965
tags question: http://stackoverflow.com/q/47551885
tags question: http://stackoverflow.com/q/47667906
tags question: http://stackoverflow.com/q/47641235
tags question: http://stackoverflow.com/q/47625864
tags question: http://stackoverflow.com/q/47611064
tags question: http://stackoverflow.com/q/47673762
tags question: http://stackoverflow.com/q/47541888
tags question: http://stackoverflow.com/q/47659126
tags question: http://stackoverflow.com/q/47651192
tags question: http://stackoverflow.com/q/47559644
tags question: http://stackoverflow.com/q/47612243
tags question: http://stackoverflow.com/q/47658095
tags question: http://stackoverflow.com/q/47551733
tags question: http://stackoverflow.com/q/47552255
tags question: http://stackoverflow.com/q/47615473
tags question: http://stackoverflow.com/q/47542694
tags question: http://stackoverflow.com/q/47590721
tags question: http://stackoverflow.com/q/47587246
tags question: http://stackoverflow.com/q/47665176
tags question: http://stackoverflow.com/q/47692119
tags question: http://stackoverflow.com/q/47602514
tags question: http://stackoverflow.com/q/47594932
tags question: http://stackoverflow.com/q/47654491
type: Tag
tags question: http://stackoverflow.com/q/47545489
tags question: http://stackoverflow.com/q/47605529
tags question: http://stackoverflow.com/q/47678700
tags question: http://stackoverflow.com/q/47647135
tags question: http://stackoverflow.com/q/47583186
tag name: scipy
tags question: http://stackoverflow.com/q/47602925
tags question: http://stackoverflow.com/q/47613772
tags question: http://stackoverflow.com/q/47597203
tags question: http://stackoverflow.com/q/47677065
tags question: http://stackoverflow.com/q/47562695
tags question: http://stackoverflow.com/q/47665889
tags question: http://stackoverflow.com/q/47550615
tags question: http://stackoverflow.com/q/47661872
tags question: http://stackoverflow.com/q/47625973
tags question: http://stackoverflow.com/q/47635210
tags question: http://stackoverflow.com/q/47559623
tags question: http://stackoverflow.com/q/47562490
tags question: http://stackoverflow.com/q/47641223
tags question: http://stackoverflow.com/q/47548611
tags question: http://stackoverflow.com/q/47664360
tags question: http://stackoverflow.com/q/47607685
tags question: http://stackoverflow.com/q/47658848
tags question: http://stackoverflow.com/q/47562775
tags question: http://stackoverflow.com/q/47579819
tags question: http://stackoverflow.com/q/47613378
tags question: http://stackoverflow.com/q/47552392
tags question: http://stackoverflow.com/q/47620826
tags question: http://stackoverflow.com/q/47682698
tags question: http://stackoverflow.com/q/47625963
tags question: http://stackoverflow.com/q/47623582
tags question: http://stackoverflow.com/q/47595801

http://stackoverflow.com/a/76425066
score: 0
answers question: http://stackoverflow.com/q/47687307
type: Answer
has body: I fixed the problem by adding SECRET_KEY = 'mysecret' in the config.py file and then made sure to add the config when I call create_app() like that env = os.environ.get('FLASK_ENV', 'dev') app = create_app('app.config.%sConfig' % env.capitalize())

http://stackoverflow.com/q/47693399
downvote count: 0
has answer: http://stackoverflow.com/a/47694395
has title: Plot one stacked bar from more different dataframes in python Pandas
answer count: 1
tagged with: plot
favorite count: 0
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has body: I need to plot data like this: df1 id value ba1 4 ba2 5 ba3 5 df2 id value ba1, ba3 4 ba2 3 ba2, ba3 2 ba3 5 df3 id value ba1, ba3 3 ba1, ba3, ba4 1 ba2 3 ba2, ba3 2 ba3 4 ba3, ba4 1 Every df has the same sum of value, 14. I think that would be a stacked bar plot good solution, with one bar per df, where values would be presented in percent. But I have no idea how to do from three different data frames. Everything I found there it was for the more numeric-value column from one df. Any help is welcomed. Thanks in advance. The desired output would be something like this: example but in X would be name of dataframe
score: 2
upvote count: 2

http://stackoverflow.com/q/47690708
linked to: http://stackoverflow.com/q/18195322
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/47690865
answer count: 4
has title: AND/OR operator between numbers in Python
has answer: http://stackoverflow.com/a/47690789
has answer: http://stackoverflow.com/a/47690865
has answer: http://stackoverflow.com/a/47691013
has comment: http://stackoverflow.com/comment/82340463
duplicate of: http://stackoverflow.com/q/18195322
possible better answer: http://stackoverflow.com/a/47691111
downvote count: 0
has comment: http://stackoverflow.com/comment/82340392
score: 6
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82340601
type: AnsweredQuestion
has body: How do and/or operators work between numbers (or even strings)? 5 and 7 # this returns 7 7 and 5 # this returns 5 21 and 4 # this returns 4 4 and 21 # this returns 21 How does the and operator work in such cases?
has answer: http://stackoverflow.com/a/47691111

http://stackoverflow.com/a/47557743
has comment: http://stackoverflow.com/comment/82107184
answers question: http://stackoverflow.com/q/47555417
has comment: http://stackoverflow.com/comment/82107405
type: Answer
has body: You are actually not using Celery in your code example. Celery tasks can be called directly like any other function. Only if you use the special celery methods like delay(), the tasks are send asynchronously to celery. In your example, your code is executed in the server threads and therefore depend on the thread that is calling the function. Even though I have never done this, you would probably need to send the task to celery and then wait for the result to be returned. The following code could work, though I did not test it: views.py def send_to_celery(log_array, is_protection): from polls.tasks import add async_result = add.delay(log_array, is_protection) index_save = async_result.get() return index_save def get_from_celery(is_protection, index): from polls.tasks import get async_result = get.delay(is_protection, index) log_array = async_result.get() return log_array
has comment: http://stackoverflow.com/comment/82107668
has comment: http://stackoverflow.com/comment/82097332
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82102715
has comment: http://stackoverflow.com/comment/82104673
has comment: http://stackoverflow.com/comment/82105653

http://stackoverflow.com/comment/82163973
type: AnswerComment
has text: thanks and I have actually fixed circula dependency by using this implementation, but with returning instances directly. calling `__new__` wrong I guess might be my real problem; I am going to try it and update it later.. peculiar that you didn't get the same error.
score: 0
comment on: http://stackoverflow.com/a/47602346
type: Comment

http://stackoverflow.com/q/47585554
type: Question
tagged with: pandas
has title: How to separate out nested json values in pandas dataframe column?
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I have data in Pandas dataframe where certain fields have nested JSONs in them: As visible in the sample data, the post_likes field has nested JSON and is sometimes blank as well. post_shares has JSON format, but just one value and it is sometimes 0. How can I grab data out of JSON objects inside the fields? In the case of post_likes, I want to create a separate field for each object in JSON nest. I tried using pd.series() but getting Key and Runtime errors.
upvote count: 2
tagged with: python-3.x
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
favorite count: 0

http://stackoverflow.com/a/47620735
has body: You could use a descriptor for the attribute. In the descriptor's __set__ method, add an attribute to its value that can be inspected inside the function. from weakref import WeakKeyDictionary class A: def __init__(self): self.a = 1 class X: """A descriptor that knows where it was defined""" def __init__(self, default): self.default = default self.data = WeakKeyDictionary() def __get__(self, instance, owner): # we get here when someone calls x.d, and d is an X instance # instance = x # owner = type(x) return self.data.get(instance, self.default) def __set__(self, instance, value): # we get here when someone calls x.d = val, and d is an X instance # add an attribute to the value and assign the instance #value.defining_class = instance value.defining_class = instance.__class__ self.data[instance] = value class B: b = X(None) def __init__(self): self.b = A() def getClassOfVariable(abc): print(f'abc: {abc}') print(f'defining_class: {abc.defining_class}') getClassOfVariable(B().b) Result: abc: &lt;__main__.A object at 0x.....&gt; defining_class: &lt;class '__main__.B'&gt; I adapted this descriptor from Python Descriptors Demystified which I always refer to when writing a descriptor. Caveat: Although this works, this feels like a hack and certainly hasn't been tested for pitfalls. In this example an instance of A has had an attribute added that says it was defined in B; if that instance gets passed around a bit it might lose its context and upon introspection that added attribute might seem strange indeed. -but for this simple example it seems OK. Maybe downvotes with comments, or even edits will elucidate. It seems too easy to just add an attribute and maybe there should be some protection involved. Or maybe value.defining_class should just be the string instance.__class__ - edited to that effect
score: 0
has comment: http://stackoverflow.com/comment/82204073
answers question: http://stackoverflow.com/q/47620179
type: Answer

http://stackoverflow.com/comment/82318165
has text: Regardless of the formatting, I don't understand what is actually being asked. E.g. it's unclear what the intended transformation of input to output actually is.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47678290
type: QuestionComment

http://stackoverflow.com/a/47577269
has body: This serializer sets ensure_ascii = True by default, so the output strings will always be in pure ASCII. For getting utf8 characters in result, You can simply add ensure_ascii = False to json.dumps().
score: 0
answers question: http://stackoverflow.com/q/47574690
type: Answer
accepted answer of: http://stackoverflow.com/q/47574690
type: AcceptedAnswer

http://stackoverflow.com/comment/82147319
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47592557
has text: Thank you so much, this is exactly what I was hoping for.

http://stackoverflow.com/comment/82067466
type: QuestionComment
has text: Declarative would be: `L = createList()`. They are both imperative to me! Your declarative example does explain it all step by step, like you imperative example does.
type: Comment
comment on: http://stackoverflow.com/q/47555196
score: 0

http://stackoverflow.com/comment/82093038
comment on: http://stackoverflow.com/a/47567344
has text: Should be possible without Docker swarm, if your local machine is accessible from the remote machine. It's probably a network issue...
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82343329
type: Comment
has text: I need to sum 7 days data from each 1st data to the 7th data.(weekly) (e.g. the first data set is : df.iloc[0:6].sum[ ] and the second data set is df.iloc[7:13].sum() and so on ). If the date time have a gap, the value of the sum will be wrong, and others are incorrect as well.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47691228

http://stackoverflow.com/q/47694736
favorite count: 0
has body: I have coded a flask application on server. I run it like below :- export FLASK_APP=mypyhthonfile nohup flask run --host=host-ip --port=port-number The python script has logger statements like: Logger.info("this is a log") The logger statements are printed in both the logger file and nohup.out What is the way to avoid printing logger statements in nohup.out ?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49971894
has comment: http://stackoverflow.com/comment/82392463
score: 6
has comment: http://stackoverflow.com/comment/82498620
has title: Donot keep logger.info() statement in nohup.out
tagged with: flask
downvote count: 1
tagged with: nohup
has comment: http://stackoverflow.com/comment/82348952
answer count: 1
has comment: http://stackoverflow.com/comment/82414056
tagged with: python
upvote count: 7

http://stackoverflow.com/q/47673868
has comment: http://stackoverflow.com/comment/82307072
accepted answer: http://stackoverflow.com/a/47674204
has answer: http://stackoverflow.com/a/47674204
type: Question
has comment: http://stackoverflow.com/comment/82307018
score: 0
answer count: 1
has body: I am kind of green at pandas and other scipy libraries, so I am not sure how to do this. I have a list of two-element tuples and I am counting the number of times the same tuple is found, or the reversed counterpart, hence the sorting: In [24]: tuples Out[24]: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (2, 1), (3, 1), (4, 1), (3, 2), (4, 2), (4, 3)] In [30]: count = Counter([tuple(sorted(t)) for t in tuples]) In [31]: count Out[31]: Counter({(1, 2): 2, (1, 3): 2, (1, 4): 2, (2, 3): 2, (2, 4): 2, (3, 4): 2}) I am trying to create a DataFrame that essentially produces this output: 1 2 3 4 1 0 2 2 2 2 2 0 2 2 3 2 2 0 2 4 2 2 2 0
has title: How to create DataFrame from a Counter of tuples
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas

http://stackoverflow.com/q/47659836
has answer: http://stackoverflow.com/a/47660239
has comment: http://stackoverflow.com/comment/82278469
tagged with: regex
accepted answer: http://stackoverflow.com/a/47660239
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82279337
answer count: 2
has comment: http://stackoverflow.com/comment/82278491
downvote count: 3
has title: regex ^ and $ are not working
upvote count: 1
has comment: http://stackoverflow.com/comment/82278730
has answer: http://stackoverflow.com/a/47659960
possible better answer: http://stackoverflow.com/a/47659960
favorite count: 0
type: Question
has body: I'm trying to write a regex that matches a number with commas for every three digits? It must match the following: '42' '1,234' '6,368,745' but not the following: '12,34,567' (which has only two digits between the commas) '1234' (which lacks commas) so I have tried the following ((^\d{1,3})((\,\d{3})*$)) ^\d{1,3}(,{3})*$ ^(\d{1,3}(,{3})*)$ but it didn't match anything. when I tried without ^ and $ then it is not matching the exact pattern.
score: -2
has comment: http://stackoverflow.com/comment/82278619
tagged with: python

http://stackoverflow.com/comment/82185026
has text: What if I wanted the output file to have the original expression + = + answer?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47613196

http://stackoverflow.com/q/47696236
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82353191
has comment: http://stackoverflow.com/comment/82353946
has comment: http://stackoverflow.com/comment/82622788
type: Question
tagged with: out-of-memory
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82354056
has title: Python: How to train a huge data for Regression (Machine Learning)?
has body: The raw data shape is (200000 * 15) but after pre-processing the data and applying OneHotEncoding the data dimension has got increased to (200000 * 300). The data needs to be trained with Linear Regression, XGBoost and RF for predictive modeling. Earlier LabelEncoder had been used and the results are not satisfactory. (200000 * 300) is consuming a whole lot of RAM and slapping MemoryError while training the data. Running on Jupyter Notebook AWS with 16 gb RAM Using sklearn for most of the ML part Data is in csv format (loaded as DataFrame in Python) Would appreciate any suggestion !
score: 0
tagged with: regression
linked to: http://stackoverflow.com/q/4285185
answer count: 0
has comment: http://stackoverflow.com/comment/82458968
tagged with: machine-learning

mysql-connector
tags question: http://stackoverflow.com/q/47588910
tag name: mysql-connector
tags question: http://stackoverflow.com/q/47581682
type: Tag

http://stackoverflow.com/comment/82276905
comment on: http://stackoverflow.com/q/47659071
has text: @srig: More like: Use the `csv` module correctly in the first place.
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/82187975
has text: What are the contents of your list?
score: 0
comment on: http://stackoverflow.com/q/47614753
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47664604
linked to: http://stackoverflow.com/q/46406720
has comment: http://stackoverflow.com/comment/82288655
score: 0
has title: TypeError: '<' not supported between instances of 'float' and 'str'
has comment: http://stackoverflow.com/comment/132838679
answer count: 1
tagged with: scikit-learn
has body: I have recently taken course on learning python and I have ran into this issue while trying to encode the data in my lesson. The action I typed in was # Encoding categorical data from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:, 0] = labelencoder_X.fit_transform(X[:, 0]) Once I enter this into the console, I get this message. `TypeError: '&lt;' not supported between instances of 'float' and 'str' I have read responses towards similar questions but I am still at a lost here. Any tips would be of service to me. Thank you in advance.
type: Question
has comment: http://stackoverflow.com/comment/82408892
tagged with: typeerror
has answer: http://stackoverflow.com/a/51859503
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82475887

ipopt
tags question: http://stackoverflow.com/q/47638934
tag name: ipopt
type: Tag

http://stackoverflow.com/comment/82146304
score: 0
comment on: http://stackoverflow.com/q/47594473
type: QuestionComment
has text: tobias_k okay but im wondering how i would make sure the password has some caps but not all caps, do you have any advice on how to do this? thanks
type: Comment

http://stackoverflow.com/q/47562201
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/47562884
tagged with: numpy
has answer: http://stackoverflow.com/a/47562621
has body: I have a list of coordinates like list_cor = [[4190091.4195999987, 7410226.618699998], [4190033.2124999985, 7410220.0823], [4190033.2124999985, 7410220.0823], [4190035.7005000003, 7410208.670500003], [4190033.2124999985, 7410220.0823], [4190022.768599998, 7410217.844300002]] I need to get only these values: [[4190091.4195999987, 7410226.618699998], [4190035.7005000003, 7410208.670500003], [4190022.768599998, 7410217.844300002]] Tried numpy.unique() but it adds this item [4190033.2124999985, 7410220.0823], which I don't need.
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/47562292
has answer: http://stackoverflow.com/a/53928532
upvote count: 7
has answer: http://stackoverflow.com/a/47562509
tagged with: unique
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82083140
answer count: 5
type: UnansweredQuestion
has title: Finding ONLY Unique Coordinates in List

http://stackoverflow.com/q/47622029
answer count: 2
downvote count: 0
has title: Why does a form not need an 'action' attribute? UserCreationForm
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47622169
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47622169
tagged with: django
tagged with: python
has body: I create a form using django auth forms UserCreationForm and it works without 'action' inside . Why it works? views.py def sign_up(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('contacts:index') else: form = UserCreationForm() return render(request, 'account/signup.html', {'form': form}) sgnup.html Sign up {% csrf_token %} {{ form.as_p }} Sign up!
has answer: http://stackoverflow.com/a/47622073
accepted answer: http://stackoverflow.com/a/47622073
type: AnsweredQuestion

http://stackoverflow.com/comment/82039093
has text: Btw your code doesn't work, or you didn't put the full source.\
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47540852
type: QuestionComment

http://stackoverflow.com/comment/129075460
comment on: http://stackoverflow.com/q/47559623
type: Comment
type: QuestionComment
score: 0
has text: I found that you can get good behaviour by softmaxing the Jacobian, _e.g._ `new_jac = np.tanh(jac*100)/100`

http://stackoverflow.com/q/47671664
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/58059380
type: Question
has body: When i install pillow in my machine, pillow install successfully, but when i use it like below: from PIL import Image Image.open(link) _imaging throws error like below: from . import _imaging as core ImportError: /home/users/xyz/.jumbo/lib/python2.7/site-packages/PIL/_imaging.so: undefined symbol: TIFFSetWarningHandlerExt in my machine, i only install pillow, i do not install PIL, pip list like below: imageio (2.2.0) itsdangerous (0.24) jieba (0.39) Jinja2 (2.9.6) MarkupSafe (1.0) meld3 (0.6.10) MySQL-python (1.2.5) numpy (1.12.1) olefile (0.44) Pillow (4.2.1) pip (9.0.1) pycurl (7.43.0) PyMysqlPool (0.9) setuptools (17.0) supervisor (3.0a12) Werkzeug (0.12.2) my pillow version is 4.2.1, Python 2.7.3 I search too many mathods, but I can not solve it, So I ask someone can help me , thank you!
answer count: 2
has comment: http://stackoverflow.com/comment/82302550
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50330736
tagged with: python
score: 0
has title: python pillow _imaging.so undefined symbol: TIFFSetWarningHandlerExt error

http://stackoverflow.com/q/47661866
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82282955
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82282871
accepted answer: http://stackoverflow.com/a/47664199
tagged with: list
has comment: http://stackoverflow.com/comment/82282828
answer count: 2
has title: Efficiently mapping unhashable objects to their index in a list
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: A Python list f = [x0, x1, x2] may be seen as an efficient representation of a mapping from [0, 1, ..., len(f) - 1] to the set of its elements. By "efficient" I mean that f[i] returns the element associated with i in O(1) time. The inverse mapping may be defined as follows: class Inverse: def __init__(self, f): self.f = f def __getitem__(self, x): return self.f.index(x) This works, but Inverse(f)[x] takes O(n) time on average. Alternatively, one may use a dict: f_inv = {x: i for i, x in enumerate(f)} This has O(1) average time complexity, but it requires the objects in the list to be hashable. Is there a way to define an inverse mapping that provides equality-based lookups, in O(1) average time, with unhashable objects? Edit: sample input and expected output: &gt;&gt;&gt; f = [x0, x1, x2] &gt;&gt;&gt; f_inv = Inverse(f) # this is to be defined &gt;&gt;&gt; f_inv[x0] # in O(1) time 0 &gt;&gt;&gt; f_inv[x2] # in O(1) time 2
tagged with: hashable
possible better answer: http://stackoverflow.com/a/47662447
has comment: http://stackoverflow.com/comment/82293588
has answer: http://stackoverflow.com/a/47664199
has comment: http://stackoverflow.com/comment/82283673
has answer: http://stackoverflow.com/a/47662447
has comment: http://stackoverflow.com/comment/82287767
tagged with: python

http://stackoverflow.com/q/47627575
has comment: http://stackoverflow.com/comment/82228895
upvote count: 1
has title: Problems with Sprites Appearing and Collision with Rotated Objects; Pygame object is not iterable
favorite count: 0
has comment: http://stackoverflow.com/comment/82229766
type: Question
tagged with: object
tagged with: rotation
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47629360
tagged with: collision
has comment: http://stackoverflow.com/comment/82230345
has comment: http://stackoverflow.com/comment/82229825
has comment: http://stackoverflow.com/comment/82230228
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82216072
has body: I'm currently trying to make pixel perfect collisions between my pong ball and my player's paddle using the mask and collide_rect functions. I made my own checkCollision function in the pong class which would check for pixel perfect collision. However, right now, I can't even get the Sprites to work or appear on the screen because my "Pong object is not iterable. Here is my pong class with the important features: (I will post additional code if needed) class Pong(pygame.sprite.Sprite): def __init__(self, screensize): pygame.sprite.Sprite.__init__(self) self.screensize = screensize self.centerx = screensize[0] // 2 self.centery = screensize[1] // 2 self.radius = 25 self.rect = pygame.Rect(self.centerx-self.radius, self.centery-self.radius, self.radius*2, self.radius*2) self.pokeimage = pygame.image.load("pokeball.png") self.pokeimage = pygame.transform.scale(self.pokeimage, (self.radius, self.radius)) #Create the mask self.mask = pygame.mask.from_surface(self.pokeimage) def checkCollision(self, player_paddle, ai_paddle): col = pygame.sprite.collide_rect(self, player_paddle) return col def collisionFormula(self, player_paddle, ai_paddle): if self.checkCollision(self, player_paddle): def collision_checks(self, player_paddle, ai_paddle): #if the ball hits the top or bottom of the screen, change the y direction if self.rect.top &lt;= 0 or self.rect.bottom &gt;= self.screensize[1] - 1: self.direction[1] *= -1 #if the pong hits the paddles, change how the pong ball moves if self.rect.colliderect(player_paddle.rect) or self.rect.colliderect(ai_paddle.rect): self.collisionFormula(player_paddle, ai_paddle) def update(self, player_paddle, ai_paddle): self.update_ball_position() self.reset_ball() self.collision_checks(player_paddle, ai_paddle) In my PlayerPaddle class, I do the same mask initialization. class PlayerPaddle(pygame.sprite.Sprite): def __init__(self, screensize): pygame.sprite.Sprite.__init__(self) self.screensize = screensize self.centerx = 50 self.centery = scree…

http://stackoverflow.com/comment/104155147
has text: Thanks for the help.
comment on: http://stackoverflow.com/q/47669910
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82370441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47597693
has text: What does `Hero()` object represent ? is it just pointing to a sprite ? Can one sprite be refer to many users ?
score: 0

http://stackoverflow.com/q/47630631
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has body: Given a dataframe, with Age as basis, I need to get the correspondence values from other columns (Sport, Mode). Could someone help with R/python code? . In fact, it will be helpful if I could get for age 15, 2 baseball with 2 play; age 19 1 golf and 1 play. the output should look like the below with Age as base variable Further on with Sport as base variable, the mode should have a similar summary. Thank you
downvote count: 4
accepted answer: http://stackoverflow.com/a/47633986
has title: Column wise correspondence values in data frame
has comment: http://stackoverflow.com/comment/82225385
answer count: 1
upvote count: 1
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/82220063
type: Question
has comment: http://stackoverflow.com/comment/82220481
has answer: http://stackoverflow.com/a/47633986
tagged with: python
score: -3

http://stackoverflow.com/a/48597955
type: Answer
answers question: http://stackoverflow.com/q/47643961
score: 0
has body: So you wont to create a function to check if any inputted string have been already used. There reason your code isnt working correctly is because you tried to check wherethere your counter is up to 3, while it isnt any loop, and thus it only ascends to 1. To re-arrange that to a correct way for example, you would do this: while answer not in possible_values: &lt;your code here&gt;

http://stackoverflow.com/q/47618336
has answer: http://stackoverflow.com/a/47618776
tagged with: python
has body: I am new to Python and I want to make a program that does the following: Use this list = [aapl,goog,jnj,msft] as input Go to the url "https://finance.google.com/finance/historical?q=goog&amp;output=csv" and replace "goog" with tickers from list above Finally save the CSV file onto the file system. The image contains the code i have been able to think of from urllib import request ticker_list = "aapl" response = request.urlretrieve("https://finance.google.com/finance/historical?q="+ticker_list+"&amp;output=csv",'D:/LatestStockFile.csv') #[aapl,goog,xom,ge,msft,bp,c,pg,wmt,pfe,tm,jnj] # I want tickers from this list to append instead of ticker_list # also if possible a different file name to save for each iteration of ticker # example : say ticker = "aaple" then this "aapl" should be appended to url and path: "D:/Apple.csv" def download_csv(ticker,path): response = request.urlretrieve(ticker,path) def user_input(): choice = input("enter choice: 1/2/3\n") if choice == 1: download_csv("aapl","D:/Apple.csv") elif choice == 2: download_csv=("goog","D:/Google.csv") elif choice == 3: download_csv("jnj","D:/Johnson.csv") user_input()
has title: download CSV file from a URL based on inputs from a ticker_list?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47618441
has comment: http://stackoverflow.com/comment/82195156
answer count: 3
has comment: http://stackoverflow.com/comment/82194922
has answer: http://stackoverflow.com/a/47674229
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47618441
type: Question
possible better answer: http://stackoverflow.com/a/47618776

http://stackoverflow.com/q/47612805
score: 0
has answer: http://stackoverflow.com/a/47612840
accepted answer: http://stackoverflow.com/a/47612840
has title: Recursive file walk only going one depth down
tagged with: python
type: Question
answer count: 1
has body: I am trying to create code for an assignment that can walk down a directory and return all files I am having trouble with multilevel folders, such as folder1 ---> folder2 ------->foo.txt I have the following code def find_larger(path, max_n_results=10): files = [] print(path) path_files = os.listdir(path) for file in path_files: if os.path.isdir(file): files += find_larger(os.path.join(path, file)) files.append(file) return files print(find_larger('.')) However, If I were to run that code I would get the following result [folder1, folder2] I have run through this is a debugger and the program is not detecting the second directory to actually be a directory. How can I get the program to walk all the way through the directory. Note, I am not allowed to user os.walk
type: AnsweredQuestion

http://stackoverflow.com/q/47650410
score: 0
answer count: 1
tagged with: selenium
type: Question
has title: Python Selenium checkbox
has comment: http://stackoverflow.com/comment/82259641
has comment: http://stackoverflow.com/comment/82259881
type: UnansweredQuestion
has body: i am using python 2.7+selenium chromdriver. I am trying to automatically check the last checkbox (terms of use) in this page : https://www.insuranceonline.nrma.com.au/oss/GTConnect/UnifiedAcceptor/Portal.Quote?product=Comprehensive&amp;brandId=nrma&amp;_ga=2.57549100.746604201.1512466470-1388355662.1512466470 . I tried several methods, but still can not get it working. the following method get it checked , but when i click on continue button , it asks me to agree on terms of use although it is checked . browser.execute_script('document.getElementsByName("f9_chkAgree")[0].checked=true') any help please ? Thanks.
has answer: http://stackoverflow.com/a/47650729
tagged with: python
tagged with: selenium-chromedriver

http://stackoverflow.com/q/47575564
favorite count: 0
type: Question
has title: How do I print certain parts of an array inside an array in python 3
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47576114
upvote count: 0
has body: How do I print certain parts of an array inside an array. For example: How do I print [0] of the [1] position of the following array: testarray = [[1, 2, 3], ["icecream", "person", "bird"], [4, 5, 6]] the result should be "icecream".
downvote count: 6
has answer: http://stackoverflow.com/a/47576296
tagged with: python
has comment: http://stackoverflow.com/comment/82107968
score: -6

pong
tag name: pong
type: Tag
tags question: http://stackoverflow.com/q/47665537

http://stackoverflow.com/q/47574624
has body: I am new to Spark and Python and I am trying to launch a Python script (through a bash run.sh command). When I run it on local mode, everything is fine. When I try to run it in the cluster(which has spark 2.1.2 without hadoop) then I receive the same error. I hope this info is enough. What should I do so that the script runs in yarn? from pyspark import SparkContext, SparkConf import sys import collections import os from subprocess import call, Popen import numpy import re import requests import json import math from bs4 import BeautifulSoup from bs4.element import Comment sc = SparkContext("yarn", "test") record_attribute = sys.argv[1] in_file = sys.argv[2] #Read warc file and split in WARC/1.0 rdd = sc.newAPIHadoopFile(in_file, "org.apache.hadoop.mapreduce.lib.input.TextInputFormat", "org.apache.hadoop.io.LongWritable", "org.apache.hadoop.io.Text", conf={"textinputformat.record.delimiter": "WARC/1.0"}) And this is the error 7/11/30 14:05:48 INFO spark.SparkContext: Created broadcast 1 from broadcast at PythonRDD.scala:553 Traceback (most recent call last): File "/home/test/script.py", line 51, in &lt;module&gt; ,conf={"textinputformat.record.delimiter": "WARC/1.0"}) File "/home/test/spark-2.1.2-bin-without-hadoop/python/lib/pyspark.zip/pyspark/context.py", line 651, in newAPIHadoopFile File "/home/test/spark-2.1.2-bin-without-hadoop/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/home/test/spark-2.1.2-bin-without-hadoop/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.newAPIHadoopFile. org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist
type: UnansweredQuestion
tagged with: hadoop-yarn
downvote count: 0
has comment: http://stackoverflow.com/comment/82173987
has answer: http://stackoverflow.com/a/48638704
score: 2
answer count: 3
tagged with: apache-spark
has title: PySpark - Input path does not exist on YARN. Works fine locally
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/48623454
has comment: http://stackoverflow.com/comment/82106037
has answer: http://stackoverflow.com/a/48638340
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/47586162
tagged with: web-scraping
has body: I'm wanting to scrape data to a text file instead of a csv. I feel like I am making this a lot more complicated than it should be and have always used csv's. As an example lets say I wanted to scrape .question-hyperlink off stackoverflow homepage Txt: (something like) With open('C:/dwadawd.txt', 'a', newline='', encoding="utf-8") as outfile: writer = csv.writer(outfile) for row in zip(gz_text, ga_href): writer.writerow(row) print(row) I have also tried the following: #Scrapes from website # EXTRACT elems = driver.find_elements_by_css_selector('.question-hyperlink') ag_href = [] for ag in elems: ag_href.append(elem.get_attribute("href")) Something like: f = open('helloworld.txt', 'a') w.write(str(ag_href)) f.write(' ') The output just appears to be blank. I have tried different methods but the results are the same. Any help?
has title: Scrape data to a text file
type: Question
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47586200
has comment: http://stackoverflow.com/comment/82146825
tagged with: python
has answer: http://stackoverflow.com/a/47586200
linked to: http://stackoverflow.com/q/18048728
tagged with: text
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82168431
tagged with: selenium

http://stackoverflow.com/q/47605387
tagged with: python
tagged with: css
has answer: http://stackoverflow.com/a/47605463
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47605463
has title: How to move paginator block to the footer?
answer count: 1
has body: I have developed a django application. I added a paginator block to a webpage. It is placed on the wrong position. Instead, i want it to be placed below the list which is being shown. Actually, I am displaying group list on the page. Per page, only 5 group names will be displayed. Using pagination, i did that. But the problem is i am unable to place it in a correct position. I am attaching an image of the page. The html page for this is: {% extends "groups/group_base.html" %} {% block pregroup %} &lt;div class="col-md-4"&gt; &lt;div class="content"&gt; {% if user.is_authenticated %} &lt;h2&gt; Welcome back &lt;a href="{% url 'posts:for_user' username=user.username %}"&gt;@{{user.username }}&lt;/a&gt; &lt;/h2&gt; {% endif %} &lt;h2&gt;Groups&lt;/h2&gt; &lt;p&gt;Welcome to the Groups Page! Select a Group with a shared interest!&lt;/p&gt; &lt;/div&gt; {% if user.is_authenticated %} &lt;a href="{% url 'groups:create' %}" class="btn btn-md btn-fill btn-warning"&gt;&lt;span class="glyphicon glyphicon-plus-sign"&gt;&lt;/span&gt; Create New Group!&lt;/a&gt; {% endif %} &lt;/div&gt; {% endblock %} {% block group_content %} &lt;div class="col-md-8"&gt; &lt;div class="list-group"&gt; {% for group in object_list %} &lt;a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}"&gt; &lt;h3 class="title list-group-item-heading"&gt;{{ group.name }}&lt;/h3&gt; &lt;div class="list-group-item-text container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;span class="badge"&gt;{{ group.members.count }}&lt;/span&gt; member &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;span class="badge"&gt;{{ group.posts.count }}&lt;/span&gt; post &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; {% block pagination %} {% if is_paginated %} &lt;ul class="pagination" style="display:inline-block"&gt; {% if page_obj.has_previous %} …
type: Question
tagged with: pagination
tagged with: http://stackoverflow.com/tag/html
tagged with: django

http://stackoverflow.com/q/47618170
type: Question
tagged with: raspbian
has answer: http://stackoverflow.com/a/47620140
tagged with: raspberry-pi
has body: I have a Kedei V6.3 touchscreen for a raspberry pi and I'm using raspbian 8 Jessie and a raspberry pi 1B. My touchscreen is running and I'm trying to install a UI from gitHub: https://github.com/garthvh/pitftmenu i have installed it, but when i try to run it it gives me an error: Traceback (most recent call last): File "/home/pi/Desktop/pitftmenu/menu_kali-1.py", line 11, in &lt;module&gt; pygame.display.init() pygame.error: Unable to open mouse I tried to run it regularly and as root.i have downloaded my OS from here: http://kedei.net/raspberry/raspberry.html and the software works, but if i try sudo apt-get upgrade, the touchscreen stops working, so i cannot update it and i would really like to run that UI
linked to: http://stackoverflow.com/q/24875682
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82197641
has comment: http://stackoverflow.com/comment/82197514
has title: Raspberry pi Pygame issues
answer count: 1
has comment: http://stackoverflow.com/comment/82197548
accepted answer: http://stackoverflow.com/a/47620140

http://stackoverflow.com/comment/82191064
score: 0
type: AnswerComment
has text: That code looks like it might work. I am testing it now, however, with this many data points, it is taking a long time. I will update once I get get a result. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/47616201

http://stackoverflow.com/comment/82291888
type: QuestionComment
score: 0
has text: I don't know - I use Linux. Normally you can run cmd.exe as admin and then run program as admin.
comment on: http://stackoverflow.com/q/47666124
type: Comment

http://stackoverflow.com/a/47682952
has body: Turns out it matters whether you use the CS from contour or from contourf. You want the one from contourf to get a filled colorbar. import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 4, 1000) y = np.linspace(-1, 1, 1000) xx, yy = np.meshgrid(x, y) z = np.sin(xx + yy**2) plt.figure() CS = plt.contour(x, y, z) CS = plt.contourf(x, y, z) plt.clabel(CS, fontsize=8, colors='black') cbar = plt.colorbar(CS) plt.savefig('test.png') Note how I swapped the contour and contourf lines. I don't know how to make a filled colorbar using just contour.
has comment: http://stackoverflow.com/comment/82341235
has comment: http://stackoverflow.com/comment/82332903
has comment: http://stackoverflow.com/comment/82403046
downvote count: 0
has comment: http://stackoverflow.com/comment/113310565
has comment: http://stackoverflow.com/comment/82328891
has comment: http://stackoverflow.com/comment/102828451
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47682951

http://stackoverflow.com/comment/82300501
comment on: http://stackoverflow.com/a/47670353
type: AnswerComment
has text: Great. ".xs" works now, I am currently trying the solution with my real dataframe, but I want to select/keep all columns instead of "a". Leaving only the comma results in " UnsortedIndexError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'"
type: Comment
score: 0

http://stackoverflow.com/comment/82270563
score: 0
comment on: http://stackoverflow.com/q/47645081
has text: @daveydave400 that was it! wow tough one. I had a bin script referenced in my scripts section, and in that script, there was no shebang at the top. If you post as an answer I will accept.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47618470
has comment: http://stackoverflow.com/comment/82195283
has comment: http://stackoverflow.com/comment/82195212
has comment: http://stackoverflow.com/comment/82195365
has comment: http://stackoverflow.com/comment/82195073
has comment: http://stackoverflow.com/comment/82195238
has body: Loop over all the stars in the given cluster. If a star's total mass exceeds 9.5, count the amount of planets that belong to that star to the amount of endangered planets. def planets_in_danger(self): in_danger = 0 for star in self.star_list: if star.total_mass &gt; 9.5: in_danger += len(star.orbiting_planets) return in_danger Or shorter: def planets_in_danger(self): return sum(len(star.orbiting_planets) for star in self.star_list if star.total_mass &gt; 9.5) edit: returning the count of endangered planets and the planets: def planets_in_danger(self): in_danger = [] for star in self.star_list: if star.total_mass &gt; 9.5: in_danger.extend(star.orbiting_planets) return (len(in_danger), in_danger)
accepted answer of: http://stackoverflow.com/q/47618438
has comment: http://stackoverflow.com/comment/82195568
has comment: http://stackoverflow.com/comment/82195256
has comment: http://stackoverflow.com/comment/82195225
has comment: http://stackoverflow.com/comment/82195698
has comment: http://stackoverflow.com/comment/82195669
type: Answer
has comment: http://stackoverflow.com/comment/82195040
has comment: http://stackoverflow.com/comment/82195351
has comment: http://stackoverflow.com/comment/82195292
has comment: http://stackoverflow.com/comment/82195598
score: 2
has comment: http://stackoverflow.com/comment/82195426
upvote count: 2
has comment: http://stackoverflow.com/comment/82195320
answers question: http://stackoverflow.com/q/47618438
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82195580
has comment: http://stackoverflow.com/comment/82195194

http://stackoverflow.com/a/47623649
type: Answer
has body: Dependencies pip install editdistance code (closest.py) import editdistance listA = ['apple', 'banana', 'coco', 'grape', 'pear'] listB = ['ba88tana', 'peeaar', 'apple', 'ggra))pe'] listC = [] for i in listB: res = None distance = len(i)+1 for j in listA: diff = editdistance.eval(i, j) if diff &lt; distance: distance = diff res = j listC.append(res) print listC
answers question: http://stackoverflow.com/q/47623474
has comment: http://stackoverflow.com/comment/82206279
has comment: http://stackoverflow.com/comment/82205172
has comment: http://stackoverflow.com/comment/82206643
score: 0

http://stackoverflow.com/comment/82285596
has text: @finnrayment that doesn't work either because as you said, it takes the output of the last command and feeds it into the next.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47662947

http://stackoverflow.com/a/74900395
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/132789915
answers question: http://stackoverflow.com/q/47564997
has body: Funny that by setting the PATH of the build system to include the natively build Python required for cross-compiling will not take care of fulfilling the --with-ensurepip=install flag by checking only the host Python and not the cross-compiled one. To get pip and setuptools added to site-packages/ you need to copy the cross-compiled Python on the targeted host machine and run: ./python3 -m ensurepip --default-pip
type: Answer

http://stackoverflow.com/q/47626518
score: -1
has body: I am wanting to search and extract unique numbers from a txt files. Every line contains a unique 10 digit number beginning with 33- (33XXXXXXXX). How do I print just the number so that i end up with a list of 33XXXXXXXX numbers that are in the file? (Python) I want to have all the number in a list separated by an "OR" statement? **They are located at [155-156]
tagged with: search
upvote count: 0
has title: Python search and character extarction
has answer: http://stackoverflow.com/a/47626873
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82710624
comment on: http://stackoverflow.com/a/47645623
type: AnswerComment
has text: Can you help with this other WU post question I have? The script above works awesome. https://stackoverflow.com/questions/47872635/weather-underground-api-python-3
score: 0
type: Comment

http://stackoverflow.com/comment/82187764
type: Comment
score: 1
type: AnswerComment
has text: Thanks, Bharath. That's quick and clean.
comment on: http://stackoverflow.com/a/47598732

http://stackoverflow.com/q/47610073
downvote count: 0
tagged with: twitter
upvote count: 1
has answer: http://stackoverflow.com/a/47610163
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
has body: I do not use requests library often so I do not know how to debug this error. I am using some code from github. https://github.com/ashleycoxley/twitter-analytics-export The error is with the .get function. tw_url = "https://twitter.com/" session = requests.session() first_req = session.get(tw_url) Error Message: requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",) It's probably simple, but any help would be appreciated. Thanks,
score: 1
accepted answer: http://stackoverflow.com/a/47610163
has title: Twitter.com requests Error
answer count: 1

http://stackoverflow.com/q/47570695
downvote count: 2
answer count: 1
tagged with: python
has title: re.sub with matched replacement
favorite count: 0
has answer: http://stackoverflow.com/a/47570773
has body: I'm trying to use Python and re.sub to replace strings by a previously matched string. Basic exemple : From this : Cat_A SomeStuff Cat_B SomeStuff Cat_C SomeStuff To this : Cat_A Cat_A Cat_B Cat_A Cat_C Cat_A But when I try to use re.sub for this, I'm having some kind of operand error. Thanks ! Edit : Ok so my question is really not precise so here is an example based on what I really what to achieve. I have an output like this : 6500_1#show ip arp vrf A Protocol Address Age (min) Internet 1.1.1.1 - Internet 1.1.1.2 0 Internet 1.1.1.3 0 Internet 1.1.1.4 - 6500_1#show ip arp vrf B Protocol Address Age (min) Internet 2.2.2.1 0 Internet 2.2.2.2 - I want to replace "Internet" word by the previous vrf name to get something like this : 6500_1#show ip arp vrf A Protocol Address Age (min) vrf A 1.1.1.1 - vrf A 1.1.1.2 0 vrf A 1.1.1.3 0 vrf A 1.1.1.4 - 6500_1#show ip arp vrf B Protocol Address Age (min) vrf B 2.2.2.1 0 vrf B 2.2.2.2 - I'm tying to use re.sub for this but I'm not able to push a regex for the replacement part.
has comment: http://stackoverflow.com/comment/82098599
has comment: http://stackoverflow.com/comment/82098627
tagged with: regex
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2

http://stackoverflow.com/a/47684446
answers question: http://stackoverflow.com/q/47684302
score: 2
has body: Using Counter definitely is the best option: In [ ]: from collections import Counter ...: d = Counter(map(len, s)) ...: d == {1:2, 6:2, 8:1, 2:1, 10:1} Out[ ]: True Without using "fancy stuff", we use generator expressions, something I consider to be equally fancy: Counter(len(i) for i in s) If by "ordinarily" you mean using for loops, we can do that like so: d = {} for i in s: if len(i) not in d: d[len(i)] = 1 else: d[len(i)] += 1
has comment: http://stackoverflow.com/comment/82329029
has comment: http://stackoverflow.com/comment/82329386
type: Answer
has comment: http://stackoverflow.com/comment/82329062
has comment: http://stackoverflow.com/comment/82328995
has comment: http://stackoverflow.com/comment/82328958
has comment: http://stackoverflow.com/comment/82329416
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/47607516
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/82173403
downvote count: 1
has body: os.chdir("D:\DOWNLOAD") # Change file direction first for file in glob.glob("*.mp3"): # search for the *.mp3 extension time.sleep(1) shutil.move("path/to/current/file", "path/to/new/destination/for/file") something like this, you have to add walk through os function to get all sub direction,
answers question: http://stackoverflow.com/q/47607278
type: Answer

http://stackoverflow.com/comment/82238983
has text: That you for your answer. By adding a block of code that completely solves the problem. i.e. `new_df = ....`
type: Comment
comment on: http://stackoverflow.com/a/47640157
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82105123
has text: how do i make loopme a non print command been trying for 30mins now and cant find a way to do it
comment on: http://stackoverflow.com/a/47572636
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47629957
has comment: http://stackoverflow.com/comment/82219848
has comment: http://stackoverflow.com/comment/82220339
has comment: http://stackoverflow.com/comment/82220329
type: Question
has comment: http://stackoverflow.com/comment/82219990
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82220664
has title: How to use function similar to vlookup pandas
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82218591
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82220287
has comment: http://stackoverflow.com/comment/82220348
has comment: http://stackoverflow.com/comment/82220073
has comment: http://stackoverflow.com/comment/82218435
downvote count: 1
has body: How do I use function similar to vlookup in pandas. df 1: AS G DA VV VV 0 potato this is spart today 1 potato surely not the day 2 you retire is it day df 2: V V VA ZD VE 0 a does potato even work 1 I am potato even today 2 O how potato mighty have 3 fallen O potato K R Data-frame I am desiring: V V VA ZD VE 0 a does potato even work 1 I am potato even today 2 O how NaN mighty have 3 fallen O NaN K R I've tried- df1.insert(2, 'VA', df1['AS'].map(df2.set_index('AS')['VA'])) #KeyError#####
has comment: http://stackoverflow.com/comment/82219900
favorite count: 0
has comment: http://stackoverflow.com/comment/82217763
tagged with: pandas
has comment: http://stackoverflow.com/comment/82219550
has comment: http://stackoverflow.com/comment/82219459
score: 1
has comment: http://stackoverflow.com/comment/82219116
tagged with: python
has comment: http://stackoverflow.com/comment/82219946
has comment: http://stackoverflow.com/comment/82219723

http://stackoverflow.com/a/47611821
score: 0
has comment: http://stackoverflow.com/comment/82235788
has comment: http://stackoverflow.com/comment/82211813
type: Answer
has body: 10% accuracy in a ten-category problem is random output; my guess is that your call to reshape is scrambling your input. For example, consider the following code: import tensorflow as tf initial = tf.constant([[1, 2, 3, 4],[5, 6, 7, 8]]) reshaped = tf.reshape(initial, [4, 2]) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) print(sess.run(initial)) print(sess.run(reshaped)) I'm turning a 2x4 tensor into a 4x2 tensor, which makes it sound like I'm transposing it, but in fact the output is [[1 2 3 4] [5 6 7 8]] [[1 2] [3 4] [5 6] [7 8]] I'd recommend using matplotlib to display a few of your examples to see if they still look like numbers. It would also be a good idea to output the labels to make sure they still match.
answers question: http://stackoverflow.com/q/47588786

http://stackoverflow.com/q/47619628
has comment: http://stackoverflow.com/comment/82197287
has answer: http://stackoverflow.com/a/47619709
type: AnsweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/82197310
has comment: http://stackoverflow.com/comment/82197393
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82197465
favorite count: 0
type: Question
tagged with: keyerror
accepted answer: http://stackoverflow.com/a/47619709
downvote count: 2
has body: I am trying to make something like FileSystem in python. My goal is to make files which can contain some data and Directories which can contain some files. Then I have some simple commands cd ls mk_dir mk_file So, now I have a problem with this: There's DirectoryBase class which is different from Directory, because it has no ParentDir (Directory in that is File/Directory saved). Then there's Directory class that extends DirectoryBase and overwrites path() method (method returning path to file/dir) and data dict has another default key: '..', but when I am trying to find it in data dict it raises KeyError. Another weird thing, about it is that I am testing if file/dir exists, and if not it will return, so I don't know how this is possible, that it got KeyError. This is my code: class AttributeDictionary(dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.__getattr__ = self.__getitem__ self.__setattr__ = self.__setitem__ self.__delattr__ = self.__delitem__ class FileManager(object): def __init__(self): self.disk_dir = DirectoryBase('__disk__') self.current_dir = self.disk_dir def _find(self, path): """ Gets file/dir object using path """ _cd = self.current_dir for part in path: _cd = _cd[part] return _cd def cmd_cd(self, path): """ Classic unix `cd` command """ f = self._find(path) if f is DirectoryBase: self.current_dir = f else: return FileSystemError('DirectoryNotFound') def cmd_ls(self): """ Classic unix `ls` command """ return ConsoleOutput(''.join([f'{i}\n' for i in self.current_dir.data])) def cmd_mkfile(self, name): """ file making command """ self.current_dir.__setitem__(name, File(name, self.current_dir)) def cmd_mkdir(self, name): """ file making command """ self.current_dir.__setitem__(name, Directory(name, self.current_dir)) class File(object): def __init__(self, name, pd): self.data = [0x00] self.name = name self.pd = pd def path(self): return [self.name] + self.pd.path() def __sizeof__(self): return len(self.data) class DirectoryBase(At…
has title: Weird KeyError || Python3.6.1
tagged with: dictionary

http://stackoverflow.com/q/47630440
linked to: http://stackoverflow.com/q/7281955
tagged with: python
has title: import pyodbc not working in eclipse
tagged with: eclipse
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47691608
has body: I am new to python.. I am not able to import pyodbc I am getting an error in eclipse (just for this import) i install pyodbc C:\Users\app_rahavm&gt;pip install pyodbc Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages python interpeter is also updated with the path: and still i am getting Unresolved import: pyodbc when i write this: import pyodbc i also see this package under packages click here to see any ideas? another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside see image here see content of lib here
has answer: http://stackoverflow.com/a/47631621
possible better answer: http://stackoverflow.com/a/47630524
has answer: http://stackoverflow.com/a/47630524
type: Question
accepted answer: http://stackoverflow.com/a/47691608

http://stackoverflow.com/q/47548360
tagged with: mezzanine
has title: Forbidden (403) CSRF verification failed. Request aborted when login to admin mezzanine
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82112211
has comment: http://stackoverflow.com/comment/82055762
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82055344
tagged with: django
tagged with: python
score: 0
has body: I deploy project web into server but when i login admin page it has an error Forbidden (403) CSRF verification failed. Request aborted. It's normal when I test in local. My project used mezzanine CMS and i use default login of mezzanine. Thanks you very much , i fixed it
answer count: 0
has comment: http://stackoverflow.com/comment/82057352
tagged with: web
upvote count: 1

http://stackoverflow.com/comment/82090863
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47566494
type: Comment
has text: `reversed` returns a reverse iterator, it doesn't make a new reversed `list` unless you `list`ify it. Try your code before posting!

http://stackoverflow.com/comment/82287506
type: AnswerComment
has text: Sorry. that's still not crystal clear. Please edit your question and show the desired output for each dictionary entry.
type: Comment
comment on: http://stackoverflow.com/a/47664029
score: 0

http://stackoverflow.com/a/47721398
answers question: http://stackoverflow.com/q/47687423
has body: This is known as the initial transient problem, and was first identified by Conway back in 1963. You can get very thorough discussions of a variety of options in any modern simulation text book&mdash;search Google, Amazon, or Barnes &amp; Noble for "discrete event simulation" and you'll get lots of hits. Alternatively, this paper gives a reasonable overview of the variety of methods that have been proposed in the intervening half-century. I recommend the MSER estimator by Pres White, which combines simplicity with analytical rigor.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47687423

http://stackoverflow.com/comment/82237367
score: 0
comment on: http://stackoverflow.com/q/47639432
type: QuestionComment
type: Comment
has text: @roganjosh oh that's true, just verified it.

http://stackoverflow.com/comment/82338958
has text: print out the len of Magnetosheath_data just to make sure it's not zero
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47688655

http://stackoverflow.com/q/47646690
type: Question
has answer: http://stackoverflow.com/a/47647026
tagged with: pyramid
tagged with: python
has title: Pyramid AuthTktAuthenticationPolicy callback never invoked
accepted answer: http://stackoverflow.com/a/47647026
type: AnsweredQuestion
score: 0
has body: Im trying to implement simple authentication in Pyramid by using AuthTktAuthenticationPolicy. I follow this - authentication and this - authorization. init.py from pyramid.config import Configurator from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from .security import groupfinder, Root def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ #config = Configurator(settings=settings) # ACL config = Configurator(settings=settings, root_factory=Root) authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.include('pyramid_jinja2') config.include('.models') config.include('.routes') config.scan() return config.make_wsgi_app() security.py GROUPS = {'admin': ['group:admin']} USERS = {'receptionist' : 'receptionist'} def groupfinder(userid, request): print("It's here") return ['group:admin'] from pyramid.security import Allow, Everyone class Root(object): def __acl__(self): return [(Allow, Everyone, 'view'), (Allow, 'group:admin', 'edit')] def __init__(self, request): pass my view default.py ... @view_config(route_name='login', renderer='../templates/login.jinja2') def login(request): try: if not ('user_name' in request.params and 'password' in request.params): return {} if request.params['user_name'] == '' or request.params['password'] == '': raise Exception('Ada inputan yang kosong dari form') match_ = request.dbsession.query(TblUser).filter_by(user_name=request.params['user_name'], user_password=request.params['password']).one() username = request.params['user_name'] if match_ is not None: headers = remember(request, username) request.response.headerlist.extend(headers) next_url = request.route_url('search-room') return HTTPFound(location=next_url) except Exception as e: log.exception(s…
answer count: 1

http://stackoverflow.com/comment/82210360
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47625924
has text: It returned an error inside `kswargs['id']`, I assume it must be `pk` so I change it and it returned `The view attendee.views.AttendeeDeleteView didn't return an HttpResponse object. It returned None instead.`

http://stackoverflow.com/comment/82041905
score: 1
comment on: http://stackoverflow.com/q/47542374
type: Comment
type: QuestionComment
has text: Why do you need this?

http://stackoverflow.com/q/47613624
score: 0
has title: Python coding for opening and saving data to a file
has body: I am having an issue getting the train function to work correctly in python. I can not modify the def function. I am at the point where I need to get the second file to read lines one at a time for PosList and i need to match the value of movieWordCount[z] in OpenPos. If the file is there, then I am good to incrment column 2 by one of t hat line (segmented by a space). If it is not, then I need the else to append it to the file end. It does not work. It does not append the values if it is missing and I am not sure if it will find the value if it is there. I have been stuck getting thsi to work for two days. Here is my code segment I am working with: with open("PosList") as OpenPos: lines = OpenPos.readlines() print lines if movieWordCount[z] in lines: print "found" #Now use tokenize to split it apart by space and set to new array for me to call column2 else: print "not found" lines.append(movieWordCount[z] + " 1" + "\n") Here is my full code: #!/usr/bin/python #Import Counter import collections from collections import Counter #Was already here but pickle is used for data input and export import math, os, pickle, re class Bayes_Classifier: def __init__(self, trainDirectory = "movie_reviews/"): #If file listing exists skip to train if os.path.isfile('iFileList'): print "file found" self.train() #self.classify() #If file listing does not exist skip to train if not os.path.isfile('iFileList'): print "no file" newfile = 'iFileList' tempList = set() subDir = './movie_reviews' for filenames in os.listdir(subDir): my_sub_path = os.path.join(os.sep,subDir,filenames) tempList.add(filenames) self.save("filenames", "try3") f = [] for fFileObj in os.walk("movie_reviews/"): f.extend(fFileObj) break pickle.dump(f, open( "save.p", "wb" )) self.save(f, "try4") with open(newfile, 'wb') as fi: pickle.dump(tempList, fi) #print tempList self.train() #self.classify() def train(self): '''Trains the Naive Bayes Sentiment Classifier.''' print "File ready for training" #Open iFileList to use…
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47613784
tagged with: python-2.7

http://stackoverflow.com/q/47660523
answer count: 5
has answer: http://stackoverflow.com/a/71959478
tagged with: python
has body: I'm using Selenium to enter information into search boxes on a search page. This website uses JavaScript and the id's and names for each search box change each time the website is loaded, but the class names remain consistent. Class names are frequently reused though, so my goal is to use find_elements_by_class_name(classname) and then index through that list. One box has the class name x-form-text x-form-field x-form-num-field x-form-empty-field, but Selenium considers it a compound class name and throws an error. If I use just a portion of it such as x-form-text, it can't find the element. My hope is to either find a way to allow the spaces, or search for all elements whose class name contain a section of text without spaces (such as x-form-text). I tried this code: quantminclass = 'x-form-text.x-form-field.x-form-num-field.x-form-empty-field' quantmin = '25' browser.find_elements_by_css_selector(quantminclass)[0].send_keys(quantmin) But got an error that the list index was out of range, implying that it can't find anything. I inspected the element and that is definitely its class name, so I'm not sure how to proceed.
type: AnsweredQuestion
score: 14
accepted answer: http://stackoverflow.com/a/47660610
has answer: http://stackoverflow.com/a/47660624
has title: Finding elements by class name with spaces
has answer: http://stackoverflow.com/a/74705654
tagged with: selenium
linked to: http://stackoverflow.com/q/32043877
has answer: http://stackoverflow.com/a/47660610
has comment: http://stackoverflow.com/comment/82280123
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/78630165
type: Question
upvote count: 15
possible better answer: http://stackoverflow.com/a/47660624

http://stackoverflow.com/q/47585386
type: Question
has answer: http://stackoverflow.com/a/47585437
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has title: Visual Studio Python: How do I build a connection string using passed in arguments?
tagged with: visual-studio
has body: Fellow techies, To make a long story short, I want to pass in configuration arguments from an SSIS package to a python program (script below). #app and sql server specific settings ssisTimespan = sys.argv[1] ssisIoTDatabase = sys.argv[2] ssisIoTserver = sys.argv[3] #[snippet] AuditTableConnString = '"' + "Driver={SQL Server};" + '"' + ' ' + '"' + "Server=" + ssisIoTserver + ';"' + ' ' + '"' + "Database=" + ssisIoTDatabase + ';"' + ' ' + '"' + "Trusted_Connection=yes;" + '"' + "autocommit=True;" + '"' LoadAuditconn = pyodbc.connect(AuditTableConnString) The line above errors out with: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') So rather than interpret the AuditTableConnString as is (screen shot), the value is taken to be the intended target server. I can see how that would happen. What do I need to do to keep the server and database names configurable when building out a flexible connection string?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82129924

http://stackoverflow.com/comment/82247352
type: Comment
type: QuestionComment
has text: use button `{}` to correctly format code
score: 0
comment on: http://stackoverflow.com/q/47644279

http://stackoverflow.com/a/47590870
score: 0
answers question: http://stackoverflow.com/q/47586587
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47586587
has comment: http://stackoverflow.com/comment/82138862
has body: Haar-cascades are a good method, however training them takes a lot of time as well as effort. You can get a lot of trained cascades file online. Second approach could be of getting the contours from the image and then proceeding forward. - Original image - Smooth the image so that you will get an image without edges. - (Original image- Smooth image) to get the edges - Get Contours from image
type: Answer
has comment: http://stackoverflow.com/comment/82151858
has comment: http://stackoverflow.com/comment/82138925

http://stackoverflow.com/q/47667869
has comment: http://stackoverflow.com/comment/82297058
tagged with: python
has comment: http://stackoverflow.com/comment/82338587
tagged with: google-drive-api
has comment: http://stackoverflow.com/comment/82298034
answer count: 0
has comment: http://stackoverflow.com/comment/82338741
score: 0
tagged with: google-api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82297993
has body: I am using python to upload or download files on Google Drive. This is the most important part of my code: from httplib2 import Http from oauth2client import file, client, tools from apiclient.http import MediaFileUpload from apiclient import errors import io from apiclient.http import MediaIoBaseDownload from apiclient import errors import os import csv ##################################### try : import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive.file' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: print("Create new data storage file ...") flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) flow.redirect_uri = client.OOB_CALLBACK_URN authorize_url = flow.step1_get_authorize_url() creds = tools.run_flow(flow, store, flags) \ if flags else tools.run(flow, store) print ("Storage") DRIVE = build('drive', 'v2', http=creds.authorize(Http())) The python-script worked fine for 2 month. But since yesterday I get this error if I start my script: 400. That’s an error. Error: admin_policy_enforced Company security policies do not allow this app to connect to your Company account data. Please contact your local helpdesk for any support. Request Details client_id=XXXYYYZZZ.apps.googleusercontent.com redirect_uri=urn:ietf:wg:oauth:2.0:oob scope=https://www.googleapis.com/auth/drive.file access_type=offline response_type=code My admin rights have not been changing till now. Do someone have an idea?
has title: Python Google Drive Authentification - Error: admin_policy_enforced
type: Question
has comment: http://stackoverflow.com/comment/82297082
has comment: http://stackoverflow.com/comment/82296514
tagged with: google-workspace

http://stackoverflow.com/a/47672311
type: Answer
score: 0
has body: Something as simple as this would work: def to_rec(lst): # base case, when list is empty if not lst: return 0 # recursive case return 1 + to_rec(lst[1:]) Base case: If the list has no elements, return 0. Recursive case: Otherwise return 1 + the length of the list, minus one element, which is why we use [1:] here, to disregard the head of the list. You could also explicitly set an accumulator with a helper function. If you've ever used a functional programming language, such as Haskell or Prolog, this technique is quite popular. Here is what it could look like: # main function def to_rec(lst): # calls helper function with starting accumulator of 0 return accum(lst, 0) def accum(lst, acc): # returns accumulator instead if not lst: return acc # increments accumulator, and looks at the tail of the list return accum(lst[1:], acc + 1) Both work as follows: &gt;&gt;&gt; print(to_rec(['a', 'b', 'c', 'd'])) 4 &gt;&gt;&gt; print(to_rec([])) 0 &gt;&gt;&gt; print(to_rec(['a'])) 1
answers question: http://stackoverflow.com/q/47671254

http://stackoverflow.com/comment/83035398
has text: @pshep123 Hi, it's been a while, but I just realized you can send the value of `color` itself in a header, instead of the number of bytes it has. I don't know why it slipped my mind then, but it is definitely a simpler solution. But I'm sure you must be done with your project by now, so I just wanted to let you know for future.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47685526
type: Comment

http://stackoverflow.com/comment/82075498
comment on: http://stackoverflow.com/q/47558723
type: Comment
has text: Try running the function in the developer tools console of your browser, if it returns the URL you need you can then proceed to execute it with selenium like this: `link = driver.execute_script('return los_mostrarficha(0)')`
score: 0
type: QuestionComment

http://stackoverflow.com/a/47588290
has comment: http://stackoverflow.com/comment/82134632
type: Answer
has body: You are using max(), but args in your function is a tuple (0.85 * (1115 - q)) + (0.87 * (1127 - q)), this is not right
answers question: http://stackoverflow.com/q/47588114
score: 0

http://stackoverflow.com/a/47670307
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
has body: I would definitely use ManyToManyField for your receive_user. You're going to find that keeping a CharField updated and sanitised with user_ids is going to be a nightmare that will involve re-implementing vast swathes of existing Django functionality. I'm not sure if I understand your potential issue to using ManyToManyField, users of the admin will be able to select which users are to be recipients of the message, it doesn't automatically a message for each user. e: Also, depending on which version of python you're using (2 or 3) you only need one of either __str__ or __unicode__ __unicode__ is the method to use for python2, __str__ for python3: See this answer for more details
answers question: http://stackoverflow.com/q/47670181
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47670181

image-processing
tags question: http://stackoverflow.com/q/47684660
tags question: http://stackoverflow.com/q/47550518
type: Tag
tags question: http://stackoverflow.com/q/47543754
tags question: http://stackoverflow.com/q/47553136
tags question: http://stackoverflow.com/q/47647512
tags question: http://stackoverflow.com/q/47654846
tags question: http://stackoverflow.com/q/47657701
tags question: http://stackoverflow.com/q/47582856
tags question: http://stackoverflow.com/q/47540926
tags question: http://stackoverflow.com/q/47597358
tags question: http://stackoverflow.com/q/47660094
tags question: http://stackoverflow.com/q/47586587
tags question: http://stackoverflow.com/q/47667728
tags question: http://stackoverflow.com/q/47630444
tags question: http://stackoverflow.com/q/47580887
tags question: http://stackoverflow.com/q/47614396
tag name: image-processing
tags question: http://stackoverflow.com/q/47678507
tags question: http://stackoverflow.com/q/47553339
tags question: http://stackoverflow.com/q/47585871
tags question: http://stackoverflow.com/q/47636816

http://stackoverflow.com/q/47656346
has comment: http://stackoverflow.com/comment/82271073
has answer: http://stackoverflow.com/a/47656537
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/47656537
tagged with: global
tagged with: loops
has answer: http://stackoverflow.com/a/47656624
accepted answer: http://stackoverflow.com/a/47656624
favorite count: 0
type: Question
has body: I want to set the values of matrix W in Wo. Then, I will go inside a loop and do operations with W. At the end of the loop, I want to restore it to Wo, but I am getting the opposite result, Wo is becoming Wo. How is that possible? How can I accomplish what I want? I have also tried defining Wo as a global but no result W = np.random.rand(5, 10) global Wo Wo = W # Back up for the initial values of W for k in range(0, K): for j in range(0, m): # For every hidden node for i in range(0, n): # For every connection # Operations (W get changed) W = Wo Then, if I check the value of Wo has been modified, in a way that Wo == W is always True. What am I missing? Thanks in advance
tagged with: python
has title: Python - Why backup variable inside loop is being updated if I don't change it value inside?

http://stackoverflow.com/comment/82286288
comment on: http://stackoverflow.com/q/47663406
score: 1
type: Comment
type: QuestionComment
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the links it contains. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.

http://stackoverflow.com/q/47661778
favorite count: 0
has comment: http://stackoverflow.com/comment/82283086
type: Question
has title: Multiple functions across columns of a dataframe in Python
type: UnansweredQuestion
tagged with: function
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82312982
has answer: http://stackoverflow.com/a/47662192
upvote count: 0
has comment: http://stackoverflow.com/comment/82283212
has comment: http://stackoverflow.com/comment/82309858
has body: How can i apply functions in the one line of code as below. I want to calculate mean,STD etc etc for the data set of which link has been shared below. In the given example i have already calculated "mean" and now i want to add some code and find other functions like STD etc. df1 = df.loc[(df.time&gt;=171) &amp; (df.time&lt;=174)'S08','S09','S41'.mean(axis=1) click here for the dataset (CSV file) i am referring to the column names In the image above i need the mean and STD (blue) but in different Dataframe not same.
linked to: http://stackoverflow.com/q/20109391
tagged with: pandas
answer count: 1
downvote count: 1

http://stackoverflow.com/q/47602884
type: Question
has answer: http://stackoverflow.com/a/47603111
has answer: http://stackoverflow.com/a/47605121
tagged with: python
has comment: http://stackoverflow.com/comment/82164607
has body: When I'd like to use train_generator.next() method for doing deep learning project, I found the mistake information: 'Could not import `PIL.Image`. The use of `array_to_img` requires PIL.' But I have already written the code import PIL from PIL import Image X,y=train_generator.next() How could I fix this problem? Thank you very much!
answer count: 2
type: UnansweredQuestion
score: 1
has title: Could not import PIL.Image
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47668723
has comment: http://stackoverflow.com/comment/82296099
score: 0
has comment: http://stackoverflow.com/comment/82307973
answer count: 1
has title: Django ImportError: No module named 'culqipy'
type: Question
has answer: http://stackoverflow.com/a/47668760
has body: I made a module for Python https://github.com/culqi/culqi-python but I don't know the reason why I cannot import it into my Django project. File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/willyaguirre/PycharmProjects/e-s/tienda/urls.py", line 4, in &lt;module&gt; from . import views File "/Users/willyaguirre/PycharmProjects/e-s/tienda/views.py", line 13, in &lt;module&gt; import culqipy as culqi ImportError: No module named culqipy Maybe my module is not correct.
tagged with: django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82306947
linked to: http://stackoverflow.com/q/31235376

http://stackoverflow.com/comment/82321825
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47680849
score: 0
has text: I like that solution. Out of curiosity what advantage does it have over class encapsulation?

http://stackoverflow.com/q/47677006
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/106366333
type: Question
downvote count: 0
tagged with: confluent-platform
type: UnansweredQuestion
answer count: 1
favorite count: 0
tagged with: apache-kafka
has answer: http://stackoverflow.com/a/47677517
has body: I have a topic with 40 partitions. Settings are such: def on_assign (c,ps): for p in ps: p.offset=0 print ps c.assign(ps) conf = {'bootstrap.servers': 'localhost:9092' 'enable.auto.commit' : False, 'group.id' : 'confluent_consumer', 'default.topic.config': {'auto.offset.reset': 'earliest'} } consumer = Consumer(**conf) consumer.subscribe(['topic.source'], on_assign=on_assign) msg = consumer.poll(timeout=100000) print "Topic is %s: | Partition is %d: | Offset is : %d | key is :%s " % (msg.topic(), msg.partition(), msg.offset(), msg.key()) I want to read from offset 0 for all partitions of the topic topic.source. But I don't see it happening for all partitions. For some partitions it reads from a specific offset which I'm assuming is the committed offset, changing the group.id every time doesn't help either. How can I read from beginning for all partitions of this topic irrespective of the committed offsets? I printed ps in on_assign() and it printed something like this for all 40 partitions: [TopicPartition{topic=topic.source,partition=0,offset=0,error=None},TopicPartition{topic=topic.source,partition=1,offset=0,error=None}....] and so on
has title: Confluent Kafka: Consumer does not read from beginning for all partitions in a topic
tagged with: python
tagged with: kafka-consumer-api

http://stackoverflow.com/q/47673839
type: UnansweredQuestion
has body: Here is my error : File "C:\Program Files\Python36\lib\site-packages\object_detection-0.1-py3.6.egg\object_detection\models\faster_rcnn_inception_resnet_v2_feature_extractor.py", line 28, in &lt;module&gt; ModuleNotFoundError: No module named 'nets' screenshot I have already change the python path but it doesn't change anything
has answer: http://stackoverflow.com/a/52305046
has answer: http://stackoverflow.com/a/62399096
tagged with: python
has answer: http://stackoverflow.com/a/53246648
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/53442032
linked to: http://stackoverflow.com/q/49724650
downvote count: 1
favorite count: 0
type: Question
has title: ModuleNotFoundError: No module named 'nets' (TensorFlow)
has answer: http://stackoverflow.com/a/54860891
answer count: 5

http://stackoverflow.com/q/47603473
has answer: http://stackoverflow.com/a/48300244
type: AnsweredQuestion
tagged with: stackdriver
has body: I am having a RPC issue with logging an error to GCP StackDriver. Following is the error message: grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED, Deadline Exceeded)&gt; Here is the python code for logging: import logging import logging.handlers import os import config import google.cloud.logging as gcp_logging from google.oauth2 import service_account logger = logging.getLogger('my_logger') ## using Google Stackdriver logging #client = gcp_logging.Client(project=config.project, credentials=config.credentials_gcp_ml) #client = gcp_logging.Client.from_service_account_json('./cred.json') cred = service_account.Credentials.from_service_account_file('./cred.json') client = gcp_logging.Client(project = config.project, credentials=cred) hdlr = client.get_default_handler() logger = logging.getLogger('cloudLogger') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) I run this code in my local computer connecting to my GCP account. google-auth 1.2.0; google-cloud-logging 1.4.0
tagged with: python
has comment: http://stackoverflow.com/comment/83541402
score: 1
has title: Stackdriver python log RPC error
favorite count: 0
type: Question
tagged with: google-cloud-platform
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83540762
answer count: 1
accepted answer: http://stackoverflow.com/a/48300244
tagged with: google-cloud-stackdriver

http://stackoverflow.com/comment/82218149
type: Comment
type: QuestionComment
has text: No, it's instantaneous.
score: 0
comment on: http://stackoverflow.com/q/47629161

http://stackoverflow.com/a/47627569
has comment: http://stackoverflow.com/comment/82212919
has comment: http://stackoverflow.com/comment/82212853
has comment: http://stackoverflow.com/comment/82212884
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82212854
has body: Two expressions yet, it's a one-liner which is not long: q = { 1, 2, 3, 4 } # given def f(x): return x * x ret = q | set(f(x) for x in q) In case f(x) returns a set: reduce(lambda a, b: a | b, map(lambda a: f(a), q))
has comment: http://stackoverflow.com/comment/82212791
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82212965
has comment: http://stackoverflow.com/comment/82212810
has comment: http://stackoverflow.com/comment/82212863
accepted answer of: http://stackoverflow.com/q/47627505
answers question: http://stackoverflow.com/q/47627505
type: Answer
has comment: http://stackoverflow.com/comment/82212948

http://stackoverflow.com/q/47641228
has body: I'm pulling from an xml file using etree where I've extracted the following from a tag called dc as text: &lt;dc&gt;[{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]&lt;/dc&gt; so I have dc = [{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}] I want to parse this out to have names and affiliations as lists: names = Smith, Doe affiliations = UofHawaii, UW Is there a simple way to do this? I can see that it's similar to a dictionary but not quite. The number of names and affiliations does vary in the tree from 1 to 4. Thanks.
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/5946236
accepted answer: http://stackoverflow.com/a/47641555
has title: Extracting from key value pairs where each is in curly brackets
has comment: http://stackoverflow.com/comment/82240928
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47641555
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82241107
tagged with: python

http://stackoverflow.com/q/47643499
type: UnansweredQuestion
has title: How do I make a function with an array output?
answer count: 1
tagged with: arrays
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82245803
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82245793
favorite count: 0
has comment: http://stackoverflow.com/comment/82247084
type: Question
has answer: http://stackoverflow.com/a/47644575
has body: Let X be an array of shape (100,200,3) When a 3-dimensional vector y is given, I want to define a function f such that f(y) is an array of shape (100,200) such that f(y)[i][j] is the l2 distance between X[i][j] and y. Here is how I tried: import numpy as np def norm(n): return np.linalg.norm(n) def sdistance(y,i,j): return norm(np.asarray(y)-X[i][j] def distance(y): return ??? I want to define the last function distance(y) so that distance(y) is an array of shape (100,200) such that distance(y)[i][j]=sdistance(y,i,j). How do I properly define the function distance(y)?

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

http://stackoverflow.com/q/47555829
accepted answer: http://stackoverflow.com/a/47556342
has answer: http://stackoverflow.com/a/54491485
possible better answer: http://stackoverflow.com/a/54491485
has title: preprocess_input() method in keras
upvote count: 56
tagged with: python
has body: I am trying out some sample keras code from this keras documentation page What does the preprocess_input(x) function of keras module do in the code below? Why do we have to do expand_dims(x, axis=0) before that is passed to the preprocess_input() method? from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input import numpy as np model = ResNet50(weights='imagenet') img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) Is there any documentation with a good explanation of these functions? Thanks!
has comment: http://stackoverflow.com/comment/82069710
has answer: http://stackoverflow.com/a/58250681
answer count: 4
has comment: http://stackoverflow.com/comment/82068834
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69641927
score: 56
downvote count: 0
has comment: http://stackoverflow.com/comment/95106476
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/95127677
type: Question
has comment: http://stackoverflow.com/comment/95121065
has answer: http://stackoverflow.com/a/47556342

http://stackoverflow.com/comment/82183651
type: Comment
has text: In layman terms, the pip is for the first python version you install. Next time you install a separate version, the new one becomes pip2 or pip3 correspondingly.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47612640

http://stackoverflow.com/comment/82163923
score: 0
type: Comment
type: QuestionComment
has text: Compile *what* with MKL? What are you currently using that MKL would replace? Even with this information, there's probably not much to say other than you'll have to try it and see if you get any speedups.
comment on: http://stackoverflow.com/q/47591056

http://stackoverflow.com/a/47560057
score: 1
upvote count: 1
has body: In a case like this, would I usually do, is something like this: if input == "": roll_dice() I'm not sure if thats what you are looking for, though :3
answers question: http://stackoverflow.com/q/47560026
type: Answer
downvote count: 0

http://stackoverflow.com/a/47665267
has comment: http://stackoverflow.com/comment/82290993
has comment: http://stackoverflow.com/comment/82290496
accepted answer of: http://stackoverflow.com/q/47664945
has comment: http://stackoverflow.com/comment/82291220
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82290528
has comment: http://stackoverflow.com/comment/82290917
has comment: http://stackoverflow.com/comment/82290991
has comment: http://stackoverflow.com/comment/82291329
has comment: http://stackoverflow.com/comment/82291098
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/82291312
type: Answer
answers question: http://stackoverflow.com/q/47664945
has comment: http://stackoverflow.com/comment/82291113
has body: I just had a go at recreating this, and I see a few ways to fix it. Firstly, JSON will not be able to parse either the Page object, nor the QuerySet underlying the page.object_list property. It will say "Object of type 'Employee' is not JSON serialisable". So to solve this, I'd try: employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values().order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(list(employees) ,status=status.HTTP_200_OK) Firstly, we use .values() on the employees queryset because the resulting ValuesQuerySet of this call can be parsed with list(employees). Inside the Page class, they evaluate the object list inside the instance this way before returning any results. Lastly, because JSON can't serialise the Page class, we simply call list(Page) to return a list. This works because Page implements __getitem__ and returns the underlying object_list. Also, you may find that some datatypes will throw JSON serialization errors (values() will return DateTime objects for DateTime fields). In my testing I had an issue with Object of type 'datetime' is not JSON serializable. If this happens, you need to use a different JSON Encoder or extend your own. The DjangoJSONEncoder can be found in django.core.serializers.json.DjangoJSONEncoder and handles datetimes, uuids, decimals, and other common datatypes in django. Edit:: You've mentioned your model code as: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) email = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, bla…

http://stackoverflow.com/comment/82047380
score: 0
comment on: http://stackoverflow.com/q/47545128
type: Comment
type: QuestionComment
has text: It is a QTableWidget

http://stackoverflow.com/a/50784503
type: Answer
has body: Hmmm. This is a complicated question to answer. Answer now: not sure. If you look at autobahn-python it specifies that its for twisted/asyncio, didn't find a mention of uvloop. Although I might add I think swopping uvloop for asyncio should be possible if you look at this discussion with a colleague of mine talking about it in crossbar.io: https://github.com/crossbario/autobahn-python/issues/925. According to the above mentioned issue 925 you need to create a new event loop var to tap into uvloop. Haven't tried it myself so hope it helps.
score: 0
answers question: http://stackoverflow.com/q/47620582

http://stackoverflow.com/comment/83027029
comment on: http://stackoverflow.com/a/47685469
score: 1
type: Comment
type: AnswerComment
has text: Both [numpy.linalg.qr](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.linalg.qr.html) and [scipy.linalg.qr](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.qr.html) interface to the same LAPACK routines, so I'm not sure why there would be a difference. But if the numpy function is working better for you, I'll update the answer to use this instead.

http://stackoverflow.com/comment/82270954
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47639325
has text: I was trying to solve a path problem through a list. Rakshith was right, but thanks a lot for helping!

http://stackoverflow.com/comment/82129752
comment on: http://stackoverflow.com/a/47585772
type: Comment
has text: From the sudo manual: `-E, --preserve-env`. Try running your original script with this flag.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82387108
comment on: http://stackoverflow.com/q/47618622
score: 0
type: QuestionComment
has text: @ekhumoro I implemented your suggestion, it works fine but there is small problem. Please read the above description. I have mentioned my problem in the code. Can you please suggest me what I should do for making my GUI process to know that signal has been received? Thank you!
type: Comment

http://stackoverflow.com/comment/82167612
comment on: http://stackoverflow.com/q/47603105
score: 0
type: Comment
type: QuestionComment
has text: @ThomasJungblut Tried with `dropout_prob = 0.9` and a smaller learning rate of 0.005, but not much improvement. Now the accuracy is around 20%, but almost constant. I tried plotting the `costs` vs `epochs`, and [this](https://i.imgur.com/pF2cCGI.png) is what I see. (When I set `dropout_prob = 1`, it works the same as without dropout, and accuracy rises as expected.)

http://stackoverflow.com/comment/82274043
has text: Are you trying to drop `my_df_Group['Group_Value']>16` or `my_df1['Value'] >16`?
comment on: http://stackoverflow.com/q/47657153
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47544154
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47543824
has comment: http://stackoverflow.com/comment/82086430
has body: Is there any reason you want to save them all as global variables? That seems like it would be a real pain to recover them again. I'd change df_list to instead hold the data frames def csv_to_df(csv_list): '''Takes a list of input csv files as strings. Converts the file names to pandas dataframes. The data frames are assigned names df1, df2, df3...dfn''' # make a dictionary of dataframes df_dict = {} for i, df in enumerate(csv_list): df_dict['df' + str(i+1)] = pd.read_csv(y, header=None,names=['Time', 'Temp'], delimiter='\t') files = ['../data/something', '../data/something else', '../data/something else here', '../data/something for sure', '../data/something sometimes'] csv_to_df(files) Then instead of getting df1, you'd get df_dict['df1']. You could even just put them straight in a list and get them by index. def csv_to_df(csv_list): '''Takes a list of input csv files as strings. Converts the file names to pandas dataframes. The data frames are assigned names df1, df2, df3...dfn''' # make a list of dataframes df_list = [] for df in csv_list: df_list.append(pd.read_csv(y, header=None,names=['Time', 'Temp'], delimiter='\t')) files = ['../data/something', '../data/something else', '../data/something else here', '../data/something for sure', '../data/something sometimes'] csv_to_df(files) Then instead of df1, you'd get df_list[0].
downvote count: 0
has comment: http://stackoverflow.com/comment/82087849
type: Answer
accepted answer of: http://stackoverflow.com/q/47543824
upvote count: 1

http://stackoverflow.com/a/47687312
has comment: http://stackoverflow.com/comment/82337498
answers question: http://stackoverflow.com/q/47686827
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82765909
score: 4
has comment: http://stackoverflow.com/comment/82798379
has comment: http://stackoverflow.com/comment/82765077
has body: There's no built-in way to parse a raw HTTP response like this and handle compression properly. I would use urllib3: import urllib3 from io import BytesIO from http.client import HTTPResponse class BytesIOSocket: def __init__(self, content): self.handle = BytesIO(content) def makefile(self, mode): return self.handle def response_from_bytes(data): sock = BytesIOSocket(data) response = HTTPResponse(sock) response.begin() return urllib3.HTTPResponse.from_httplib(response) if __name__ == '__main__': import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('httpbin.org', 80)) sock.send(b'GET /gzip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n') raw_response = sock.recv(8192) response = response_from_bytes(raw_response) print(response.headers) print(response.data)
type: Answer
has comment: http://stackoverflow.com/comment/82765046
accepted answer of: http://stackoverflow.com/q/47686827
upvote count: 4

http://stackoverflow.com/comment/82248215
has text: @scriptboy and georgexsh You are right! I know from [this answer](https://stackoverflow.com/a/18947948/3552975) that "when you create a pool the workers are created by forking the current process".
score: 0
comment on: http://stackoverflow.com/q/47636699
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47566494
downvote count: 1
has comment: http://stackoverflow.com/comment/82090863
answers question: http://stackoverflow.com/q/47566434
type: Answer
has comment: http://stackoverflow.com/comment/82101983
score: -1
has body: You can use reversed() function as well. l = list(reversed(n)) print(l)
upvote count: 0

http://stackoverflow.com/q/47615359
score: -1
has body: I would like to use Python to rename the files in a directory called myShow from a .txt file that contains the "target" names: realNameForEpisode1 realNameForEpisode2 realNameForEpisode3 The hierarchy looks like: episodetitles.txt myShow ├── ep1.m4v ├── ep2.m4v └── ep3.m4v I tried the following: import os with open('episodetitles.txt', 'r') as txt: for dir, subdirs, files in os.walk('myShow'): for f, line in zip(sorted(files), txt): originalName = os.path.abspath(os.path.join(dir, f)) newName = os.path.abspath(os.path.join(dir, line + '.m4v')) os.rename(originalName, newName) but I don't know why I get a ? at the end of the filename before the extension: realNameForEpisode1?.m4v realNameForEpisode2?.m4v realNameForEpisode3?.m4v
has comment: http://stackoverflow.com/comment/82189122
answer count: 2
tagged with: file-io
has title: Replacing file names in directory from text file
has answer: http://stackoverflow.com/a/47615638
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82189780
tagged with: os.path
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47615978
tagged with: python

http://stackoverflow.com/q/47594537
tagged with: surface
type: AnsweredQuestion
has body: I'm getting used to python and now wanna make a 3D surface plot. I have three variables x,y,z and an Intensity function I=I(x,y,z). I want to pick out a particular slice z=250 and plot the dsitribution for the x and y direction. The Problem is, I dont know how to pick a slice for a z-value. All Versions I tried ended iin some error Here is what i have import pandas as pd import numpy as np #NumPy import scipy as sp #SciPy import matplotlib as mpl #Matplotlib(2D/3D) import matplotlib.pyplot as plt #Matplotlib's pyplot from pylab import * #Matplotlib's pylab from mpl_toolkits.mplot3d import Axes3D %matplotlib inline x = linspace(-4,4,50) # units mm y = linspace(-4,4,50) # units mm # define beam parameters I_0 = 1e0 # intensity lambda_1 = 800e-9 # wavelength w_0 = 1.5 # beam waist z_r = pi*w_0**2*1e-6/lambda_1 # Rayleigh length in units mm z = linspace(-4,4,500)*z_r # calculate intensity profile X,Y,Z = meshgrid(x,y,z) w = w_0 *sqrt(1+(Z/z_r)**2) I = I_0*((w_0/w)**2)*exp(-2*(X**2+Y**2)/(w**2)) fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(X, Y, I[:,:,250], cmap=cm.coolwarm,linewidth=0,antialiased=False) show() I get an error: ValueError: shape mismatch: objects cannot be broadcast to a single shape How do I do it correctly? Edit: I'm using python 3.6 with jupyter notebook
score: 0
linked to: http://stackoverflow.com/q/35445424
answer count: 1
has comment: http://stackoverflow.com/comment/82146534
has comment: http://stackoverflow.com/comment/82146438
accepted answer: http://stackoverflow.com/a/47594834
type: Question
has answer: http://stackoverflow.com/a/47594834
has title: Python surface plot Value error
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/82146501

http://stackoverflow.com/comment/82201275
type: AnswerComment
comment on: http://stackoverflow.com/a/47621643
type: Comment
has text: This code seems to work. Its difficult to interpret what the OP actually wants.
score: 0

http://stackoverflow.com/a/47697832
answers question: http://stackoverflow.com/q/47697749
has comment: http://stackoverflow.com/comment/82356915
score: 1
has comment: http://stackoverflow.com/comment/82356773
has comment: http://stackoverflow.com/comment/82356383
upvote count: 2
has comment: http://stackoverflow.com/comment/82356876
type: Answer
has comment: http://stackoverflow.com/comment/82356508
downvote count: 1
has comment: http://stackoverflow.com/comment/82356107
has body: As simple as: listx, listy = [x for x in listx if x != None], [y for y in listy if y != None]

http://stackoverflow.com/comment/82048196
has text: It's as though you are passing 3 different arguments into `print`: 1, 000 (which is 0), and 000 (0, again)
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47545711

http://stackoverflow.com/comment/82057769
score: 0
has text: now i am getting following erro:: raise MultiValueDictKeyError(repr(key)) MultiValueDictKeyError: "u'third_value'"
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47548545

http://stackoverflow.com/q/47663809
has comment: http://stackoverflow.com/comment/82293068
has comment: http://stackoverflow.com/comment/82287012
type: Question
downvote count: 2
linked to: http://stackoverflow.com/q/988228
has title: Python Convert string to dict
type: UnansweredQuestion
score: 16
tagged with: string
has answer: http://stackoverflow.com/a/49938770
has answer: http://stackoverflow.com/a/47667558
has comment: http://stackoverflow.com/comment/82286967
favorite count: 0
has body: I have a string : '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}' and would like to convert it to { "tomatoes" : "5" , "livestock" :"{"cow" : "5" , "sheep" :"2" }" } Any ideas ?
has comment: http://stackoverflow.com/comment/82288789
has answer: http://stackoverflow.com/a/47667031
has answer: http://stackoverflow.com/a/47664694
upvote count: 18
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82310284
answer count: 4

http://stackoverflow.com/q/47697497
type: UnansweredQuestion
tagged with: python
tagged with: settings
tagged with: mezzanine
score: 0
has title: django project, mezzanine of "from mezzanine.conf import settings"
has body: Using Mezzanine Resource, I find some files are missing in source folder, but project is not except error, i really want know why! i want know this file in where? look: ./mezzanine-master/mezzanine/blog/views.py #this file import this line "from mezzanine.conf import settings" when i goto this ./mezzanine-master/mezzanine/conf folder and list files: total 96 drwxr-xr-x@ 13 Elone staff 416B Nov 12 15:28 . drwxr-xr-x@ 19 Elone staff 608B Nov 12 15:28 .. -rwxr-xr-x@ 1 Elone staff 10K Nov 12 15:28 __init__.py -rwxr-xr-x@ 1 Elone staff 2.2K Nov 12 15:28 admin.py -rwxr-xr-x@ 1 Elone staff 2.3K Nov 12 15:28 context_processors.py -rwxr-xr-x@ 1 Elone staff 5.3K Nov 12 15:28 forms.py drwxr-xr-x@ 40 Elone staff 1.3K Nov 12 15:28 locale drwxr-xr-x@ 4 Elone staff 128B Nov 12 15:28 migrations -rwxr-xr-x@ 1 Elone staff 646B Nov 12 15:28 models.py drwxr-xr-x@ 3 Elone staff 96B Nov 12 15:28 static drwxr-xr-x@ 3 Elone staff 96B Nov 12 15:28 templates -rwxr-xr-x@ 1 Elone staff 8.6K Nov 12 15:28 tests.py -rwxr-xr-x@ 1 Elone staff 233B Nov 12 15:28 translation.py not found settings.py file in this conf folder, i do not find this settings in where, this settings is not project settings, i know project settings in project root folder, but this settings in conf folder, who can tellde me this is what means? thinks
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47729945

http://stackoverflow.com/comment/82165007
comment on: http://stackoverflow.com/q/47602962
score: 0
type: Comment
type: QuestionComment
has text: @Ryan Better make it an answer,

http://stackoverflow.com/comment/82201961
type: AnswerComment
comment on: http://stackoverflow.com/a/47622038
has text: and where should my main program be located in this situation?
type: Comment
score: 0

http://stackoverflow.com/q/47606406
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47606477
score: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: I have a form that involves uploading a profile picture. I have it working so that I can upload images in the /admin/ interface and display them correctly, but I cannot get my Modelform to save the image. Here is what I have: models.py class Candidate(models.Model): UserID = models.ForeignKey(User, on_delete=models.CASCADE) ElectionID = models.ForeignKey(Election, on_delete=models.CASCADE) Bio = models.CharField(max_length=500, blank=True) ProfilePicture = models.ImageField(upload_to="profilepics/", null=True, blank=True) forms.py class AddCandidateForm(forms.ModelForm): class Meta: model = Candidate fields = ['ElectionID', 'Bio', 'ProfilePicture'] cand_reg.html (Template) {% block content %} Register as a candidate {% csrf_token %} Select an election: {{form.ElectionID}} Enter your bio: {{form.Bio}} Upload a profile picture: {{form.ProfilePicture}} Register {% endblock %} When I try the view function like so I get the error: MultiValueDictKeyError at /register/ "'ProfilePicture'" views.py def add_candidate(request): if request.method == 'POST': form = AddCandidateForm(request.POST, request.FILES) if form.is_valid(): candidate = form.save(commit=False) candidate = request.FILES['ProfilePicture'] candidate.UserID = request.user candidate.save() return redirect('/home/') else: form = AddCandidateForm() return render(request, 'cand_reg.html', { "form": form }) views.py When I remove the offending line, the error goes away. def add_candidate(request): if request.method == 'POST': form = AddCandidateForm(request.POST, request.FILES) if form.is_valid(): candidate = form.save(commit=False) # candidate = request.FILES['ProfilePicture'] candidate.UserID = request.user candidate.save() return redirect('/home/') else: form = AddCandidateForm() return render(request, 'cand_reg.html', { "form": form }) However, this doesn't actually save the image, so when I try to render it in a separate template, I get an error then. Can anyone help me understand why the image isn't uploading?…
upvote count: 1
tagged with: django-forms
favorite count: 0
type: Question
has title: Django image form isn't saving the image
has answer: http://stackoverflow.com/a/47606477
downvote count: 0
tagged with: django

http://stackoverflow.com/a/47543718
answers question: http://stackoverflow.com/q/47543696
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47543696
has body: You just have to call the parent's method: class QLabelFontAutoResize(QLabel): [...] def setText(self, text): [...] self.setFont(_font) QLabel.setText(self, text) # super(QLabelFontAutoResize, self).setText(text) # super().setText(text)

http://stackoverflow.com/q/47621435
has comment: http://stackoverflow.com/comment/82200806
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47621551
has answer: http://stackoverflow.com/a/47621628
tagged with: for-loop
upvote count: 0
downvote count: 3
has title: From for loop to while loop
has answer: http://stackoverflow.com/a/47621645
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47621628
tagged with: while-loop
score: -3
has answer: http://stackoverflow.com/a/47621941
tagged with: python
accepted answer: http://stackoverflow.com/a/47621551
answer count: 4
has body: I am trying to transform it to while loop. def function(n, step): s = 0 for i in range(1, n, step): s += i return s Any ideas? def function(n, step): s = 0 i = 1 while i&lt;n: so i don't know what to do after this. edit: so the solution is def function(n, step): s = 0 i = 1 while(i&lt;n): s += i i += step return s

http://stackoverflow.com/comment/82302152
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47669536
type: QuestionComment
has text: So try it out. `i` is one of the keys (a title). Split it and see if `book_search` is in the resulting list.

http://stackoverflow.com/q/47573735
has comment: http://stackoverflow.com/comment/82105112
score: 4
has comment: http://stackoverflow.com/comment/82135837
has answer: http://stackoverflow.com/a/47573829
has comment: http://stackoverflow.com/comment/82136062
answer count: 3
has comment: http://stackoverflow.com/comment/82104997
has comment: http://stackoverflow.com/comment/82140517
tagged with: types
downvote count: 1
has comment: http://stackoverflow.com/comment/82192111
has comment: http://stackoverflow.com/comment/82104738
has comment: http://stackoverflow.com/comment/82104415
tagged with: floating-point
has body: I need to store a float variable with 12 bits precision in Python I know that to convert a variable in float there is a float function but how can I specify the size of the float in bits? e.g. (12, 16, ...)
tagged with: floating-accuracy
linked to: http://stackoverflow.com/q/9062562
tagged with: precision
favorite count: 0
type: Question
has title: How to convert a number to 12 bits precision in python?
has answer: http://stackoverflow.com/a/47573898
linked to: http://stackoverflow.com/q/18536820
has comment: http://stackoverflow.com/comment/82104723
upvote count: 5
has comment: http://stackoverflow.com/comment/82123281
has answer: http://stackoverflow.com/a/47583005
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47545300
tagged with: django
has body: django 1.11 python 3.x I have been trying to breakout models, views and forms into folders. I started out with models and it seemed to work. Changing views.py to views/index.py is stumping me. I have seen posts on this and I think that I am setting the __init__.py files correctly but makemigrations still yells at me about views/Profile.py. File "/home/me/AppBase/MyApp/Members/urls.py", line 3, in &lt;module&gt; from . import views File "/home/me/AppBase/MyApp/Members/views/__init__.py", line 1, in &lt;module&gt; from .Profile import * File "/home/me/AppBase/MyApp/Members/views/Profile.py", line 7, in &lt;module&gt; from MyApp.Members.models.Profile import * ImportError: No module named 'MyApp.Members' the file structure MyApp |-- Members | |-- __init__.py | |-- account_adapter.py | |-- admin.py | |-- apps.py | |-- forms | | |-- ProfileForm.py | | |-- __init__.py | |-- models | | |-- Profile.py | | |-- __init__.py | |-- tests.py | |-- urls.py | `-- views | |-- Profile.py | |-- __init__.py views/__init__.py is: from .Profile import * views/Profile.py is: from django.contrib import messages from django.core.exceptions import * from django.shortcuts import redirect from django.shortcuts import render from MyApp.Members.models.Profile import * def create_profile(user): pass def profile(request): if not request.user.is_authenticated: return redirect('/account/login') try: profile = Profile.objects.get(user=request.user) messages.add_message(request, 1, "have profile") except ObjectDoesNotExist: messages.add_message(request, 1, "create profile") create_profile(request.user) return render(request, 'Members/index.html') urls.py is: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.Profile, name='profile'), ] I am using PyCharm as the IDE and it claims all the paths are ok. I am not sure what I am missing.
has answer: http://stackoverflow.com/a/47545521
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82047517
accepted answer: http://stackoverflow.com/a/47545521
tagged with: python
has comment: http://stackoverflow.com/comment/82060247
type: Question
score: 0
has title: python django: views, models and forms in directories
answer count: 1

http://stackoverflow.com/q/47641184
has comment: http://stackoverflow.com/comment/82243671
duplicate of: http://stackoverflow.com/q/22219004
has comment: http://stackoverflow.com/comment/82240751
score: 0
linked to: http://stackoverflow.com/q/22219004
tagged with: pandas
tagged with: python
has title: converting pandas dataframe to contain a list
type: Question
has body: state Year Month count 0 alabama 2017.0 10.0 31 1 alabama 2017.0 11.0 30 2 alabama 2017.0 12.0 31 3 alabama 2018.0 1.0 31 4 alabama 2018.0 2.0 28 5 alabama 2018.0 3.0 31 6 alabama 2018.0 4.0 30 7 alabama 2018.0 5.0 31 8 alabama 2018.0 6.0 30 9 alabama 2018.0 7.0 14 10 arkansas 2017.0 10.0 31 11 arkansas 2017.0 11.0 30 12 arkansas 2017.0 12.0 31 Can I convert dataframe above to: Month state alabama [10.0, 11.0, 12.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] arkansas [10.0, 11.0, 12.0] I tried using unstack but that does not work
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47659654
answer count: 1
has body: My code for an alarm in tkinter won't open on double click. It runs in idle just fine and all my other tkinter programs open on double click too. What in the code is causing this? from tkinter import * import datetime import time from time import strftime import winsound master = Tk() master.geometry('300x300') master.title('Alarm Time') label = Label(master, text = 'What time would you like to wake up?') label.pack() EnteredAlarm = Entry(master) EnteredAlarm.pack(ipady=8) def callback(): Alarm = EnteredAlarm.get() while True: Time = strftime('%H:%M') if str(Time) == str(Alarm): print('Wake up Mister West') winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME) break else: print('Zzz...') time.sleep(5) b = Button(master, text="OK", command=callback) b.pack() The code doesn't return any errors, all that happens is cmd opens for half a second then closes. Any help is appreciated, thanks in advance.
accepted answer: http://stackoverflow.com/a/47659673
has title: One single tkinter program wont open on double click. I get no error message
has answer: http://stackoverflow.com/a/47659673
type: Question
type: AnsweredQuestion
tagged with: user-interface
score: 1
has comment: http://stackoverflow.com/comment/82278059
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82410165
type: Comment
comment on: http://stackoverflow.com/a/47722881
score: 0
type: AnswerComment
has text: intresting, how could i make it faster? @skrx

http://stackoverflow.com/comment/82131098
score: 0
has text: @ChapmanAtwell I also didn't get, how redirection loop is related to sessions, directly. It just happened so, that, in my case, `session` is involved in triggering (or not triggering) the redirect — there are, probably, other ways to do it, with the same result. Am I missing something?
comment on: http://stackoverflow.com/q/47567263
type: Comment
type: QuestionComment

jupyter-notebook
tags question: http://stackoverflow.com/q/47587329
tags question: http://stackoverflow.com/q/47642801
tags question: http://stackoverflow.com/q/47604151
tags question: http://stackoverflow.com/q/47571007
tags question: http://stackoverflow.com/q/47643925
tags question: http://stackoverflow.com/q/47633153
tags question: http://stackoverflow.com/q/47541643
tags question: http://stackoverflow.com/q/47654317
tags question: http://stackoverflow.com/q/47564103
tags question: http://stackoverflow.com/q/47679938
tags question: http://stackoverflow.com/q/47672982
tags question: http://stackoverflow.com/q/47637739
tags question: http://stackoverflow.com/q/47642683
tags question: http://stackoverflow.com/q/47545420
tags question: http://stackoverflow.com/q/47591501
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/47663860
tags question: http://stackoverflow.com/q/47612157
tags question: http://stackoverflow.com/q/47648203
tags question: http://stackoverflow.com/q/47610875
tags question: http://stackoverflow.com/q/47554722
tags question: http://stackoverflow.com/q/47660483
type: Tag
tags question: http://stackoverflow.com/q/47564423
tags question: http://stackoverflow.com/q/47557385
tags question: http://stackoverflow.com/q/47644152
tags question: http://stackoverflow.com/q/47555345
tags question: http://stackoverflow.com/q/47619249
tags question: http://stackoverflow.com/q/47600569
tags question: http://stackoverflow.com/q/47598627
tags question: http://stackoverflow.com/q/47586606
tags question: http://stackoverflow.com/q/47658456
tags question: http://stackoverflow.com/q/47644753
tags question: http://stackoverflow.com/q/47630296
tags question: http://stackoverflow.com/q/47570793
tags question: http://stackoverflow.com/q/47662692
tags question: http://stackoverflow.com/q/47603274

http://stackoverflow.com/q/47586269
type: UnansweredQuestion
tagged with: subset
tagged with: python
has title: Get the subset with maximum diverse without compute all distance
tagged with: distance
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: graph
has body: I read slide about top-k algorithms which are Fagin Algorithm (FA), Threshold Algorithm (TA) and No random access algorithm (NRA). Those algorithms are good because we do not need to see all values, we just need to set a threshold or compute lower bound and upper bound. Slide = http://alumni.cs.ucr.edu/~skulhari/Top-k-Query.pdf Now, I have large of data points and I want to get the top-k points (subset) which diversity maximum, means that the distances among points in the top-k (subset) are maximum. I know that this problem is NP-Hard. The algorithm such as Brute force is not feasible for this case due to the dataset is large. In here, I just want to know, is it possible to get subset/top-k points without computing all distances among all pair points like in FA/TA/NRA algorithm?
tagged with: algorithm

http://stackoverflow.com/a/47615732
answers question: http://stackoverflow.com/q/47615652
type: Answer
has comment: http://stackoverflow.com/comment/82769551
score: 0
has comment: http://stackoverflow.com/comment/82190050
has body: Modules can have submodules and/or functions, variables, etc. What gets imported by from &lt;module&gt; import * depends on how the module was implemented. Most modules will not automatically import submodules. In this case, tkinter is the main module, and font is a submodule, and tkinter was not designed to import all submodules automatically. So when you do from tkinter import *, you are grabbing all the functions and variables, but not the submodules. The submodules must be explicitly imported to be used. You can enter: from tkinter import * from tkinter import font Or you could also enter: import tkinter # actually not needed since the below "does both" import tkinter.font The difference would be whether you want to use font.Font(... or tkinter.font.Font(...
has comment: http://stackoverflow.com/comment/82190156

http://stackoverflow.com/q/47670928
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has body: I have done with the web scraping with following code: Number = soup.find('th',text = "Number of samples").find_next_sibling("td").text for x in range(1,int(Number)+1): #loop of function to parse the data format I want item = item_text.split('tooltip')[x].split("class")[0].replace('"','').replace(',','').replace(':','').replace("&lt;br&gt;"," ").replace("/","").replace("\\","") #print(item) TESTDATA=StringIO(item) df = pd.read_csv(TESTDATA, sep=" ",header=None) print(df) Now the result is in the following: 0 1 2 3 4 5 6 7 8 9 \ 0 TCGA-KK-A7B3-01A Male NaN Stage not reported NaN Alive FPKM 5.5 10 11 12 13 14 0 Living days 899 (2.5 years) 0 1 2 3 4 5 6 7 8 9 \ 0 TCGA-G9-6347-01A Male NaN Stage not reported NaN Alive FPKM 14.2 10 11 12 13 14 0 Living days 2089 (5.7 years) ... Now the problem is how to combine those separate dataframes into one dataframe so that it's easier to save to a whole csv file? Thanks
has title: How to combine the dataframes in a for loop
score: 0
answer count: 1
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/47671079
type: UnansweredQuestion

http://stackoverflow.com/q/47579844
upvote count: 1
favorite count: 0
type: Question
tagged with: dataframe
tagged with: python
has title: Change Color of Header Row
accepted answer: http://stackoverflow.com/a/47579889
has answer: http://stackoverflow.com/a/47579889
type: AnsweredQuestion
has body: Okay, so I've scoured the net for this but no dice. I am trying to change the background color of my header row in my dataframe to blue. My code: def color_blue(val): color = 'blue' return['background-color: blue'] s = wci_fmo.iloc[:0].style.apply(color_blue) s But I get the following error: ValueError: Function &lt;function color_blue at 0x000000000BD0F730&gt; returned the wrong shape. Result has shape: (7,) Expected shape: (0, 7) Please help! I have numpy, pandas, and seaborn imported.
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/82163952
downvote count: 0
answer count: 1

http://stackoverflow.com/a/47608777
type: Answer
has body: There might be spaces in column names so do main.columns = main.columns.str.strip() #and items.columns=items.columns.str.strip() You are now good to merge the dataframes
accepted answer of: http://stackoverflow.com/q/47608112
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47608112

http://stackoverflow.com/q/47587278
tagged with: pandas
duplicate of: http://stackoverflow.com/q/14941097
answer count: 1
type: Question
type: UnansweredQuestion
has title: Pandas 0.20.3 "KeyError: '[1 2] not in index'" When Trying to Select Columns to Display in DataFrame
has answer: http://stackoverflow.com/a/47587578
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/14941097
has body: I'm working through the book Mastering Pandas for Finance and I created the following DataFrame for the S&amp;P 500: sp500 = pd.read_csv("sp500.csv", index='Symbol', usecols=[0, 2, 3, 7]) Returns the following DataFrame: S&amp;P 500 DataFrame A part of the exercise is to then display the dataframe with only select columns using the following code: $ sp500[[1, 2]].head(3) Which should produce the following DataFrame: S&amp;P 500 DataFrame with Indexed Columns Only When I run the code I get the following error: KeyError: '[1 2] not in index' Traceback --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-67-9993ec8d3122&gt; in &lt;module&gt;() ----&gt; 1 sp500[[1, 2]].head(3) ~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key) 1956 if isinstance(key, (Series, np.ndarray, Index, list)): 1957 # either boolean or fancy integer index -&gt; 1958 return self._getitem_array(key) 1959 elif isinstance(key, DataFrame): 1960 return self._getitem_frame(key) ~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_array(self, key) 2000 return self.take(indexer, axis=0, convert=False) 2001 else: -&gt; 2002 indexer = self.loc._convert_to_indexer(key, axis=1) 2003 return self.take(indexer, axis=1, convert=True) 2004 ~/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter) 1229 mask = check == -1 1230 if mask.any(): -&gt; 1231 raise KeyError('%s not in index' % objarr[mask]) 1232 1233 return _values_from_object(indexer) KeyError: '[1 2] not in index'
tagged with: indexing
score: 0

http://stackoverflow.com/comment/82161032
score: 0
type: Comment
type: QuestionComment
has text: @RNar: I'm learning pandas and I'd like to know how to do this within pandas @ayhan: Yes the column is sorted. But how can I specify complex conditions using `np.searchsorted`? For example, how to find the first even number?
comment on: http://stackoverflow.com/q/47601118

http://stackoverflow.com/comment/82315598
score: 0
comment on: http://stackoverflow.com/a/47678066
has text: Is there a way to Modify the Numpy Array flags.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47666026
answers question: http://stackoverflow.com/q/47665984
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You're out of range, because j is taking the values of the elements of the N array, not the index. So, j is not 0, 1, 2, 3 but rather 20, 40, 60, 80. So, when you get to for i in range((0, N[j]), you're asking for N[20], which is well beyond the length of the N list. You could do: N = [20,40,60,80] for j in range(len(N)): # ^^^^^^^^^^^^^ print(j) for i in range(0,N[j]): print(i)
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82291268
accepted answer of: http://stackoverflow.com/q/47665984

http://stackoverflow.com/a/47696944
type: AcceptedAnswer
downvote count: 0
has body: There are no backslashes in the variable, they are just in the printed output. The shell does not print the variable directly, but calls repr() on it. This function makes an attempt to return a string that would yield an object with the same value when passed to eval() Usually, repr just wraps strings in quotes: &gt;&gt;&gt; "abc" # actually calls repr("abc") 'abc' If your string contains one kind of quotes, it uses the other kind: &gt;&gt;&gt; "ab'c" "ab'c" &gt;&gt;&gt; 'ab"c' 'ab"c' But your string contains both kinds of quotes. If you would want to specify that in your code, you could either join string literals which each only have one kind (like you did), or escape one kind: &gt;&gt;&gt; "a\"b'c" 'a"b\'c' &gt;&gt;&gt; 'a"b\'c' 'a"b\'c' This escaping is exactly what repr does when you output a string representation of the variable to the command line. One side note: You are building a SQL query by concatenating fixed parts and (user supplied?) variables. Please don't do that. Please use at least prepared statements, or better a wrapper library like SQLAlchemy. This does not only make it easier to handle database connections, but also much more secure.
has comment: http://stackoverflow.com/comment/82354389
score: 5
has comment: http://stackoverflow.com/comment/82354225
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47696911
answers question: http://stackoverflow.com/q/47696911

http://stackoverflow.com/comment/82315372
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47670568
has text: Hi @Shengbao Shui. Thanks for the prompt reply. **app.run(host='0.0.0.0',port=5000) could you modify your port** _Oh yeah. Thanks for the solution. So I just have to allocate the right port to replace port 80 right?_ **If you want to execute it 24/7 on linux. You could execute it as a background tasks. Using nohup python <file> &** _Thank you. Yes. It works_
type: Comment

http://stackoverflow.com/comment/82266859
score: 0
has text: cool, thanks. I'll have a look at the example, I believe it should not be too much effort/too tough to create a little Python wrapper.
comment on: http://stackoverflow.com/a/47654331
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82163086
type: Comment
has text: Use the boolean `and`, not the bitwise `&`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47602153
score: 3

http://stackoverflow.com/comment/82354377
type: Comment
has text: get_target() won’t accept that path because it doesn’t end with `.lnk`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47682435

http://stackoverflow.com/a/47596373
type: Answer
answers question: http://stackoverflow.com/q/47596256
has comment: http://stackoverflow.com/comment/82153048
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47596256
upvote count: 1
has comment: http://stackoverflow.com/comment/82151939
has comment: http://stackoverflow.com/comment/82158427
has body: According to the source code, keras creates this in theano: variable = theano.shared(value=np.zeros(shape), name='somename', strict=False) variable._keras_shape = value.shape variable._uses_learning_phase = False It's often better to use keras objects. They've got shapes and other features for keras models.

http://stackoverflow.com/a/71959478
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47660523
has body: If you have class name (or another attrs) with spaces, for example: Test 123 This will work: driver.find_element_by_xpath("//div[@class='target with space or maybe another-long-text']")

http://stackoverflow.com/q/47663923
has comment: http://stackoverflow.com/comment/82287416
has comment: http://stackoverflow.com/comment/82287157
has comment: http://stackoverflow.com/comment/82293886
has comment: http://stackoverflow.com/comment/83112806
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has title: 64 bit and 32 bit Python Modules
has comment: http://stackoverflow.com/comment/82287400
favorite count: 0
type: Question
has body: Will 64 bit Python Modules work with a 32 bit Python 3.6.3? I am trying to make a keylogger and I need some modules, I have a 3.6.3 32 bit python and should I get 32 or 64 bit modules?
has comment: http://stackoverflow.com/comment/82287329
type: UnansweredQuestion
tagged with: python
tagged with: module

http://stackoverflow.com/comment/82208209
type: QuestionComment
has text: Okay, would it be possible to dump the `model.wv` and inspect what is the contents?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47624644

http://stackoverflow.com/comment/82079826
comment on: http://stackoverflow.com/q/47561032
type: QuestionComment
has text: Please include the *full traceback* of the exception, not just the last line. That way we can see where Python got into trouble, and how it got there. Just the exception is pretty useless to us.
score: 0
type: Comment

http://stackoverflow.com/a/47590965
has comment: http://stackoverflow.com/comment/82148637
accepted answer of: http://stackoverflow.com/q/47578807
downvote count: 0
score: 1
has body: Alternative way to create the repository archive is to use the git archive command which supports zip and tar formats: import git import tempfile import os tempdir = tempfile.mkdtemp() temppath = os.path.join(tempdir) print(temppath) repo = git.Repo.clone_from( 'https://github.com/serebrov/nodejs-typescript.git', to_path=temppath) with open("archive.zip", "wb") as zipfile: repo.archive(zipfile, format='zip') The resulting archive.zip contains the repository files: (venv) $ unzip -l archive.zip Archive: archive.zip c55ff81ef2934670cb273b5fadd555d932081f2e Length Date Time Name --------- ---------- ----- ---- 18 2017-11-10 22:57 .gitignore 552 2017-11-10 22:57 README.md 0 2017-11-10 22:57 client/ 305 2017-11-10 22:57 client/client.ts 146 2017-11-10 22:57 client/tsconfig.json 586 2017-11-10 22:57 package.json 0 2017-11-10 22:57 server/ 488 2017-11-10 22:57 server/app.ts 195 2017-11-10 22:57 server/tsconfig.json 0 2017-11-10 22:57 views/ 169 2017-11-10 22:57 views/index.html --------- ------- 2459 11 files
has comment: http://stackoverflow.com/comment/82171956
answers question: http://stackoverflow.com/q/47578807
has comment: http://stackoverflow.com/comment/82172337
has comment: http://stackoverflow.com/comment/82171782
has comment: http://stackoverflow.com/comment/82172022
has comment: http://stackoverflow.com/comment/82140230
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82172503
has comment: http://stackoverflow.com/comment/82139834
type: Answer
has comment: http://stackoverflow.com/comment/82143084
has comment: http://stackoverflow.com/comment/82172183
has comment: http://stackoverflow.com/comment/82141491
has comment: http://stackoverflow.com/comment/82140583
has comment: http://stackoverflow.com/comment/82171980
has comment: http://stackoverflow.com/comment/82171904

http://stackoverflow.com/a/47655912
type: Answer
answers question: http://stackoverflow.com/q/47655842
has body: You can try this: import re s = ["Level production data TD Index", "Total Agriculture\Production data TS Index"] new_s = [re.findall('[\w\s\W]{1,}(?=\s\w+\s\w+$)', i)[0] for i in s] Output: ['Level production data', 'Total Agriculture\\Production data']
score: 0

http://stackoverflow.com/q/47681110
answer count: 1
linked to: http://stackoverflow.com/q/22392497
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82321625
has comment: http://stackoverflow.com/comment/82321770
tagged with: python
duplicate of: http://stackoverflow.com/q/22392497
has comment: http://stackoverflow.com/comment/82321730
accepted answer: http://stackoverflow.com/a/47683176
favorite count: 0
has comment: http://stackoverflow.com/comment/82321466
has comment: http://stackoverflow.com/comment/82321885
tagged with: numpy
has comment: http://stackoverflow.com/comment/82321742
has answer: http://stackoverflow.com/a/47683176
has body: I need to create an empty numpy array of a shape (?, 10, 10, 3). ? means I don't know how many elements will be inserted. Then I have many numpy arrays of a shape (1, 10, 10, 3) which I want to be inserted to the prepared array one by one, so the ? mark will be increasing with inserted elements. I'm trying all variations of numpy array methods like empty, insert, concatenate, append... but I'm not able to achieve this. Could you please give me a hand with this?
has title: Inserting values to an empty multidim. numpy array
type: Question
upvote count: 2
score: 2
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/82325336

http://stackoverflow.com/comment/82354455
has text: Yes maybe its a bug which I was not aware of. I am trying to use geckodriver 0.18.0 instead of 0.16.0. But I learned this information in the last 2 minutes, so please forgive my ignorance on all these extremely complex things...
comment on: http://stackoverflow.com/q/47694922
score: 0
type: Comment
type: QuestionComment

pygame
tags question: http://stackoverflow.com/q/47563482
tags question: http://stackoverflow.com/q/47575662
tags question: http://stackoverflow.com/q/47597693
tags question: http://stackoverflow.com/q/47545910
tags question: http://stackoverflow.com/q/47688220
tags question: http://stackoverflow.com/q/47645155
tags question: http://stackoverflow.com/q/47666135
tag name: pygame
tags question: http://stackoverflow.com/q/47682103
tags question: http://stackoverflow.com/q/47603024
tags question: http://stackoverflow.com/q/47604195
tags question: http://stackoverflow.com/q/47658646
tags question: http://stackoverflow.com/q/47590429
tags question: http://stackoverflow.com/q/47631536
tags question: http://stackoverflow.com/q/47639826
tags question: http://stackoverflow.com/q/47682120
tags question: http://stackoverflow.com/q/47670635
tags question: http://stackoverflow.com/q/47644279
tags question: http://stackoverflow.com/q/47661930
tags question: http://stackoverflow.com/q/47609852
tags question: http://stackoverflow.com/q/47619007
tags question: http://stackoverflow.com/q/47605598
tags question: http://stackoverflow.com/q/47613121
tags question: http://stackoverflow.com/q/47624765
tags question: http://stackoverflow.com/q/47619954
tags question: http://stackoverflow.com/q/47685436
tags question: http://stackoverflow.com/q/47600141
tags question: http://stackoverflow.com/q/47664265
tags question: http://stackoverflow.com/q/47684661
tags question: http://stackoverflow.com/q/47641208
tags question: http://stackoverflow.com/q/47627575
tags question: http://stackoverflow.com/q/47555614
tags question: http://stackoverflow.com/q/47560867
tags question: http://stackoverflow.com/q/47623084
tags question: http://stackoverflow.com/q/47603286
tags question: http://stackoverflow.com/q/47644878
tags question: http://stackoverflow.com/q/47692151
tags question: http://stackoverflow.com/q/47566955
tags question: http://stackoverflow.com/q/47660370
tags question: http://stackoverflow.com/q/47682842
tags question: http://stackoverflow.com/q/47613823
tags question: http://stackoverflow.com/q/47585711
tags question: http://stackoverflow.com/q/47635765
tags question: http://stackoverflow.com/q/47680627
tags question: http://stackoverflow.com/q/47682662
tags question: http://stackoverflow.com/q/47614396
tags question: http://stackoverflow.com/q/47604219
tags question: http://stackoverflow.com/q/47665537
tags question: http://stackoverflow.com/q/47576735
tags question: http://stackoverflow.com/q/47573174
tags question: http://stackoverflow.com/q/47618170
tags question: http://stackoverflow.com/q/47686889
tags question: http://stackoverflow.com/q/47599792
tags question: http://stackoverflow.com/q/47598959
tags question: http://stackoverflow.com/q/47691823
tags question: http://stackoverflow.com/q/47578963
tags question: http://stackoverflow.com/q/47665777
tags question: http://stackoverflow.com/q/47644019
tags question: http://stackoverflow.com/q/47601460
tags question: http://stackoverflow.com/q/47614229
tags question: http://stackoverflow.com/q/47623439
tags question: http://stackoverflow.com/q/47577034
tags question: http://stackoverflow.com/q/47638477
tags question: http://stackoverflow.com/q/47618426
tags question: http://stackoverflow.com/q/47604678
tags question: http://stackoverflow.com/q/47685506
tags question: http://stackoverflow.com/q/47592252
tags question: http://stackoverflow.com/q/47630640
tags question: http://stackoverflow.com/q/47666220
type: Tag

http://stackoverflow.com/a/47620856
accepted answer of: http://stackoverflow.com/q/47620788
type: Answer
has body: self.request.GET holds variables from the querystring, e.g. if you did /bienbox/bucket/?bucket=mybucket. In your case, you can get the bucket name from self.kwargs. def get(self, request, *args, **kwargs): bucketName = self.kwargs['bucket'] return render(request,self.template_name,{'bucketName': bucketName}) Try to avoid overriding get or post when you use class based views. In this case you could do: class bucketPage(TemplateView): template_name = "project/bucket.html" def get_context_data(self, *args, **kwargs): context = super(bucketPage, self).get_context_data(**kwargs) context['bucketName'] = self.kwargs['bucket'] return context
has comment: http://stackoverflow.com/comment/82199804
answers question: http://stackoverflow.com/q/47620788
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/comment/82181148
has text: Yes, that's right. It is in fact better to not categorise them - the tree can then optimally choose where to 'cut' the distribution. E.g. suppose the right decision cut is whether a feature is less or more than 15. If you discretise prior to that into bins [0, 10), [10, 20), [20, 30) etc. you will lose that information.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47610920

http://stackoverflow.com/comment/82244719
type: Comment
type: AnswerComment
score: 0
has text: Nah. That leads to a result like [Severity CRITICAL 219.0 HIGH 306.0 LOW 32.0 MODERATE 339.0] This is the wrong output.
comment on: http://stackoverflow.com/a/47642734

http://stackoverflow.com/q/47647135
tagged with: scipy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47647595
has answer: http://stackoverflow.com/a/47647595
downvote count: 0
upvote count: 1
tagged with: plot
tagged with: statistics
type: AnsweredQuestion
has body: I'm trying to set an alpha value or some other way of making dots in a probability plot slightly translucent. This is the code I have. import numpy as np import pylab import scipy.stats as stats stats.probplot(x, dist=stats.gamma, sparams=(2.74,),plot=pylab) This is what the plot sort of looks like. Any tips on how to make the dots slightly translucent? I'd like to do this for aesthetic purposes.
tagged with: matplotlib
answer count: 1
tagged with: python
score: 1
has title: Set transparent dots in probability plot

http://stackoverflow.com/q/47619679
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/58217157
accepted answer: http://stackoverflow.com/a/58217157
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: Csvkit : use "in2csv" in python code
tagged with: csvkit
has body: I'd like to use in2csv to convert excel files into csv in my python code, but without running it as a separate process using exec. Instead, I'd like to directly import the function and use it, like in2csv("input.xls", "output.csv"), or still better, get directly the structure of the file in python without using the csv reader out the output file. Is it possible? Thank you!
favorite count: 0

vba
tags question: http://stackoverflow.com/q/47557057
tags question: http://stackoverflow.com/q/47649553
tag name: vba
tags question: http://stackoverflow.com/q/47678775
type: Tag
tags question: http://stackoverflow.com/q/47637111

http://stackoverflow.com/a/47623192
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82204288
accepted answer of: http://stackoverflow.com/q/47623084
has body: You haven't really said how the Player1 and Player2 classes are different, but assuming you have a good reason I would suggested creating a base class called PlayerBase and using that as the base class for these two other classes. This will make it very clear they share behavior and only differences will need to be implemented in the methods of each subclass. The reason I said "assuming you have a good reason" for having two classes, is because if the only difference between them is what data they contain, for example, you don't need to have two classes to do that—instead just define the __init__() method of a (single) class so it accepts arguments that provide this data and then store it if necessary as class instance data via the self argument which is passed by default to all regular methods. There's a section titled Objects and classes in Wikipedia's article on Object-oriented Programming (OOP) which discusses the difference between the two which might provide you more insight into when you should use one or the other to do things.
has comment: http://stackoverflow.com/comment/82217353
score: 3
answers question: http://stackoverflow.com/q/47623084
type: Answer
has comment: http://stackoverflow.com/comment/82204381

http://stackoverflow.com/comment/82348567
type: QuestionComment
has text: `assoc .py=PythonFile` then `ftype pythonfile=c:\python\python %1 %*` (%1 may need quotes)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47693984

merge
type: Tag
tags question: http://stackoverflow.com/q/47689407
tags question: http://stackoverflow.com/q/47612366
tags question: http://stackoverflow.com/q/47608112
tags question: http://stackoverflow.com/q/47563510
tags question: http://stackoverflow.com/q/47619920
tag name: merge
tags question: http://stackoverflow.com/q/47688909
tags question: http://stackoverflow.com/q/47546469
tags question: http://stackoverflow.com/q/47681517
tags question: http://stackoverflow.com/q/47638340
tags question: http://stackoverflow.com/q/47561694
tags question: http://stackoverflow.com/q/47678682
tags question: http://stackoverflow.com/q/47598343
tags question: http://stackoverflow.com/q/47689237
tags question: http://stackoverflow.com/q/47582893
tags question: http://stackoverflow.com/q/47614815
tags question: http://stackoverflow.com/q/47575489

http://stackoverflow.com/q/47614940
answer count: 1
tagged with: python
downvote count: 2
has answer: http://stackoverflow.com/a/47615499
has comment: http://stackoverflow.com/comment/82189089
has comment: http://stackoverflow.com/comment/82189143
favorite count: 0
type: Question
upvote count: 0
has body: Right now I'm doing a easy videogame in Python using the libraty Turtle but this error appeared and I don't know how to solve it. My code is here: pastebin.com/wu5jM0gT Error : Traceback (most recent call last): File "C:/Users/ricar/PycharmProjects/Juego/Juego.py", line 122, in &lt;module&gt; objetivo.movimiento() File "C:/Users/ricar/PycharmProjects/Juego/Juego.py", line 91, in movimiento self.forward(self.speed) File "C:\Python27\lib\lib-tk\turtle.py", line 1553, in forward self._go(distance) File "C:\Python27\lib\lib-tk\turtle.py", line 1520, in _go ende = self._position + self._orient * distance File "C:\Python27\lib\lib-tk\turtle.py", line 277, in __mul__ return Vec2D(self[0]*other, self[1]*other) TypeError: unsupported operand type(s) for *: 'float' and 'instancemethod'` Any suggestions?
has title: I am getting an error in my Python code
type: UnansweredQuestion
score: -2

http://stackoverflow.com/q/47541623
score: 0
tagged with: instance
has answer: http://stackoverflow.com/a/47542411
has title: How to create class instances with attributes read from a textfile?
accepted answer: http://stackoverflow.com/a/47542411
tagged with: file
has comment: http://stackoverflow.com/comment/82040908
linked to: http://stackoverflow.com/q/8290397
has comment: http://stackoverflow.com/comment/82040718
has comment: http://stackoverflow.com/comment/82040982
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82040679
has answer: http://stackoverflow.com/a/47541866
has body: I currently have a textfile with saved data just as: surname1 name1 number1 address1 surname2 name2 number2 address2 ... I want to use this textfile to create instances in my class: class Contact(object): def __init__(self, surname, name, number, address): self.surname = surname self.name = name self.number = number self.address = address I need a function that can read from the textfile, use 4 rows as attributes for a new instance, append that instance to a list &amp; then do it again for the next 4 rows and so on...how can this be done?
tagged with: python
has comment: http://stackoverflow.com/comment/82040575
possible better answer: http://stackoverflow.com/a/47541866
tagged with: class
tagged with: object
type: AnsweredQuestion

http://stackoverflow.com/q/47644000
tagged with: pyspark
tagged with: python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47644334
accepted answer: http://stackoverflow.com/a/47655289
has answer: http://stackoverflow.com/a/47655289
has body: I have to calculate the number of times a user has tweeted, with data being in a JSON file. I tried groupByKey and reduceByKey but the output is user id and the tweet itself, not the count of tweets. Code: from pyspark import SparkContext from pyspark.sql import SQLContext sc = SparkContext("local", "Twitter") sqlc = SQLContext(sc) df = sqlc.read.json("file.json") tweets = df.select("user.id","text") users = tweets.rdd.reduceByKey(lambda x,y:x+y) How do I get the count of tweets by their respective users as key?
has title: Spark calculate number of times a user has tweeted
type: Question
score: 0
tagged with: apache-spark
has answer: http://stackoverflow.com/a/47644334

http://stackoverflow.com/a/47571620
has body: You're close, you just need to modify the return statements elif numbers[-1] % m == 0 and numbers[-1] &gt; mx: mx = numbers[-1] numbers = find_max_modulo(numbers[:-1], m) return mx to: elif numbers[-1] % m == 0 and numbers[-1] &gt; mx: return numbers[-1] return find_max_modulo(numbers[:-1], m)
answers question: http://stackoverflow.com/q/47571407
type: Answer
score: 0

http://stackoverflow.com/q/47612285
has answer: http://stackoverflow.com/a/47612646
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82185652
tagged with: text
upvote count: 0
tagged with: tkinter
tagged with: notepad
tagged with: fonts
has comment: http://stackoverflow.com/comment/82183286
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82182842
type: Question
has comment: http://stackoverflow.com/comment/82182941
has title: Change the font proprietes of a piece of text
has body: I'm making a notepad and I've created tools for fonts, but this changes the font of all the text, not just the selected piece or the part where you are The code for all the tools looks like this: def ng(): global fn #the font global b #Bold variable b=not b if b==True: fn.configure(weight="bold") if b==False: fn.configure(weight="normal") scroll.config(font=fn) How I do this?
type: UnansweredQuestion

http://stackoverflow.com/a/47633626
has comment: http://stackoverflow.com/comment/82225064
score: 0
has body: As Paulie_D said, there is no such "level" of color. You can't use floats in the color string. The Documentation states: RGB functions, given as rgb(red, green, blue) where the color values are integers in the range 0 to 255. Alternatively, the color values can be given as three percentages (0% to 100%). For example, rgb(255,0,0) and rgb(100%,0%,0%) both specify pure red. So these are the only options you can use.
answers question: http://stackoverflow.com/q/47633181
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47633181
has comment: http://stackoverflow.com/comment/82229323
type: Answer
has comment: http://stackoverflow.com/comment/82224892
has comment: http://stackoverflow.com/comment/82224977

http://stackoverflow.com/comment/82178863
has text: That did it! Your explanation sounds right, I am on very restricted network. Thank You!
score: 0
comment on: http://stackoverflow.com/a/47610163
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82127191
type: QuestionComment
has text: @juanpa.arrivillaga: Yes, that appears to work and do what I originally wanted. I think it would be a good official answer for this question, with the addition of a disclaimer stating it is better to add `my_var` as an attribute to the passed in `func` in `my_decorator`.
score: 0
comment on: http://stackoverflow.com/q/47584427
type: Comment

http://stackoverflow.com/q/47615963
tagged with: selenium
type: Question
tagged with: python-3.x
has body: I have noticed selenium keeps printing the current url even when it changes pages when I click the next button. Am I missing something? It seems to loop through all the pages correctly, yet the driver.current url is the same each time. How is that possible? Did I forget to have my morning coffee.. I have also noticed that it quite often glitches and instead of clicking next it just displays a little icon like so. Are these two issues linked perhaps? driver = webdriver.Chrome() driver.maximize_window() driver.get('https://github.com/scrapy/scrapy/issues?page=1&amp;q=is%3Aissue+is%3Aopen') elements = driver.find_elements_by_css_selector("div &gt; div.float-left.col-9.p-2.lh-condensed &gt; a") elem_href1 = [element.get_attribute("href") for element in elements] for link in elem_href1: try: directory = 'C:\\Users\\fefs.csv' with open(directory, 'a', newline='', encoding="utf-8") as outfile: writer = csv.writer(outfile) time.sleep(2) langs_text = driver.current_url print(langs_text) writer.writerow(langs_text) SCROLL_PAUSE_TIME = 0.5 last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(SCROLL_PAUSE_TIME) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height time.sleep(2) wait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ("#js-repo-pjax-container &gt; div.container.new-discussion-timeline.experiment-repo-nav &gt; div.repository-content &gt; div &gt; div.paginate-container &gt; div &gt; a.next_page")))).click()
has comment: http://stackoverflow.com/comment/82190212
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82190240
tagged with: python
has title: printing same url if new page and gets stuck at click next every so often
tagged with: selenium-webdriver
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82215380

http://stackoverflow.com/a/75610463
score: 1
type: Answer
has body: Building on ChaimG's answer, one might use a dummy breakpoint statement instead: for i in range(100): breakpoint # &lt;--- toggle breakpoint here, note there is no parenthesis
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47625526

http://stackoverflow.com/comment/82200470
score: 0
type: Comment
type: QuestionComment
has text: What is nbr_sims?
comment on: http://stackoverflow.com/q/47620895

http://stackoverflow.com/comment/107411545
has text: Great Solution. Do you know how i can use this code for a password protected website?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/58068662

http://stackoverflow.com/comment/82271508
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47654613
has text: Then perhaps you want to split all this up into several classes. One class that takes some initial values, and which has a `calculate` method, and returns a new object with the results, which you can reuse.

http://stackoverflow.com/comment/82131751
type: Comment
type: QuestionComment
has text: ok i added a sample of the df data frame. my goal is to get that first true after all the false.
score: 0
comment on: http://stackoverflow.com/q/47586996

http://stackoverflow.com/comment/82201300
comment on: http://stackoverflow.com/q/47621397
score: 0
type: Comment
type: QuestionComment
has text: eitherway, I get the redirected url.. so I still need to figure out how to download the link

http://stackoverflow.com/q/47694103
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82347450
downvote count: 0
upvote count: 1
tagged with: python
has title: PermissionError Python - os.rename
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82349673
has body: I am just trying to get a number from a file and rename it to another directory. Can you help me? My code below: path_txt = 'temp' name_files1 = os.listdir(path_txt) for TXT in name_files1: with open(os.path.join(path_txt,TXT), "r") as content: search = re.search(r'(\d{21,30})|' r'(\d{7})\-\s*(\d{2})\.(\d{4})\.(\d)\.(\d{2})\.(\d{4})|' r'(\d{7})\.?(\d{2})\/?(\d{4})\.?(\d)\.?(\d{2})\.?(\d{4})|' r'(\d{7})\-(\d{2})\-(\d{4})\.(\d)\.(\d{2})\.(\d{4})|' r'(\d{7})\-(\d{2})\.(\d{4})\.(\d)\.(\d{2})\-(\d{4})', content.read()) text = content.read() if search is not None: name1 = search.group(0) name1 = re.sub(r"\D", "", name1) fp = os.path.join("20_digitos", name1 + "_%d.txt") postfix = 0 while os.path.exists(fp % postfix): # Verifica se o arquivo já existe na pasta, se existir incrementa +1 em %d de fp postfix += 1 os.rename( os.path.join(path_txt, TXT), fp % postfix ) It's giving me the following error: Traceback (most recent call last): File "---", line 30, in &lt;module&gt; fp % postfix PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'temp\\Processo ID 1000000.pdf .txt' -&gt; '20_digitos\\00025087420135020003_0.txt'
tagged with: regex
has comment: http://stackoverflow.com/comment/82347647
tagged with: permissions
favorite count: 0

http://stackoverflow.com/q/47598323
has comment: http://stackoverflow.com/comment/82154838
tagged with: python
has answer: http://stackoverflow.com/a/47598466
has answer: http://stackoverflow.com/a/47598574
answer count: 4
type: Question
accepted answer: http://stackoverflow.com/a/47598428
score: 0
has answer: http://stackoverflow.com/a/47598428
has body: &gt;&gt;&gt; itms="""banana cookie cream soda lime limes apples desert plate cake orange milk beans juice apple pie""" I'm wondering how do you count items in a certain row from a multi lined string? Example: The first row would return 7 The Second would return 6 and the last one would return 2 (due to "apple pie" only containing 1 white-space in-between it).
has comment: http://stackoverflow.com/comment/82154811
has answer: http://stackoverflow.com/a/47598778
possible better answer: http://stackoverflow.com/a/47598466
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has title: How to count items in a specific row from a multi lined string

http://stackoverflow.com/comment/82115280
score: 1
comment on: http://stackoverflow.com/a/47579020
has text: If you are using a virtual environment, make sure to install it in that as well as globally.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82293464
has text: unable to locate input id="email-file-upload"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47616455
type: Comment

http://stackoverflow.com/q/47613376
tagged with: python
has comment: http://stackoverflow.com/comment/82185314
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/82185211
answer count: 0
linked to: http://stackoverflow.com/q/23914697
has title: read matrix from file using Numpy
has comment: http://stackoverflow.com/comment/82185335
type: Question
has body: I am new in python. I want to read a multiple array from text file to a python array [ [ [1 1] [1 1] ] [ [2 2] [2 2] ] [ [3 3] [3 3] ] ... ... ... ] I have tried this but seems I am not really good with python dt = np.dtype(None, 2, 2) data = np.fromfile(fileName, dtype=dt) print(data) by the np.dtype I want to tell python that the type is an array of unknown size containing arrays that each contains two arrays of two integer
type: UnansweredQuestion

http://stackoverflow.com/a/47644316
upvote count: 4
answers question: http://stackoverflow.com/q/47644293
has comment: http://stackoverflow.com/comment/82247433
has comment: http://stackoverflow.com/comment/82247400
has comment: http://stackoverflow.com/comment/82247557
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47644293
has comment: http://stackoverflow.com/comment/82247508
has comment: http://stackoverflow.com/comment/82247498
type: Answer
has body: You can try this: import re s = '12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank' new_s = re.split('(?&lt;=[a-zA-Z])\s(?=\d)', s) Output: ['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank'] Or, just using re.findall: new_list = [i[:-1] if i.endswith(' ') else i for i in re.findall('[\d\/]+\s[a-zA-Z\s]+(?=\d)|[\d\/]+\s[a-zA-Z\s]+(?=$)', s)] Output: ['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']
score: 4
has comment: http://stackoverflow.com/comment/82247358

http://stackoverflow.com/a/47642379
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47642201
score: 7
has body: df.sort_values() returns sorted DF, but it doesn't sort in place. So either use: df = df.sort_values(by='date') or df.sort_values(by='date', inplace=True)
type: Answer
accepted answer of: http://stackoverflow.com/q/47642201
type: AcceptedAnswer

http://stackoverflow.com/q/47582179
has comment: http://stackoverflow.com/comment/82246171
has comment: http://stackoverflow.com/comment/82251678
has comment: http://stackoverflow.com/comment/101376617
linked to: http://stackoverflow.com/q/46026987
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82336187
has comment: http://stackoverflow.com/comment/83144011
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47655395
has title: Python: How to check off a checkbox with Browser splinter?
has comment: http://stackoverflow.com/comment/82245098
linked to: http://stackoverflow.com/q/27927964
favorite count: 0
has comment: http://stackoverflow.com/comment/83139848
type: Question
tagged with: splinter
has comment: http://stackoverflow.com/comment/82246310
has comment: http://stackoverflow.com/comment/85084928
type: UnansweredQuestion
score: 6
has body: Once I add the following item to cart: http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w and go to the check out page: https://www.supremenewyork.com/checkout, there is a terms and conditions checkbox that I’m attempting to check off with Browser’s splinter but I’m not able to do so: e.g. Tried the following but all encountered an error: from splinter import Browser browser = Browser("chrome") browser.find_by_id('order_terms').click() #Error: selenium.common.exceptions.WebDriverException: Message: unknown error browser.check('order[terms]').click() #Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible browser.find_by_name('order[terms]').click() #Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible What could I be doing wrong? And how can I go about checking the checkbox with the Browser splinter? Thank you in advance and will be sure to upvote/accept answer
upvote count: 6
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83148699
tagged with: python

http://stackoverflow.com/a/47650729
has body: I am not much familiar with python. But the selenium methods are almost same in all languages. First view the checkbox element. elem = driver.findElement(By.className("chkAgree")); jse = (JavascriptExecutor)driver; jse.executeScript("arguments[0].scrollIntoView(true);", elem); Then select the checkbox. checkBox = elem.findElement(By.cssSelector("input[type='checkbox']")); checkBox.click();
type: Answer
answers question: http://stackoverflow.com/q/47650410
has comment: http://stackoverflow.com/comment/82260400
score: 0

http://stackoverflow.com/q/47603286
downvote count: 0
has title: Creating a Group to add my Class to in Pygame
has comment: http://stackoverflow.com/comment/82166158
tagged with: sprite
has comment: http://stackoverflow.com/comment/82166520
favorite count: 0
type: Question
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/47603775
has body: I am currently making a game in Pygame, and would like to generate several platforms randomly throughout my screen. However, I can't seem to figure out how to create a group so that I can draw several sprites at once. I have tried using super.__init__(self) and also replacing self with (*Group) , yet it isn't working. I also have just tried to add it to a group. How should I make my group and how do I correctly add my sprite to it? Here is the code (the sprite I want to add in is created here but not drawn): ######## basic setup import pygame, sys, time, random, threading, tkinter, ctypes from threading import Timer from pygame.locals import * from tkinter import * pygame.init() WINDOWHEIGHT = 720 WINDOWWIDTH = 1280 windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32) pygame.display.set_caption('Hitman Grandma | vB1.0 (prealpha)') white = (255,255,255) red = (255,0,0) black = (0,0,0) green = (0,255,0) blue = (0,0,255) cyan = (0,255,255) lightgrey = (198,198,198) windowSurface.fill(lightgrey) pygame.display.update() mainClock = pygame.time.Clock() ########## variables level = 0 touching = False global x_speed x_speed = 0 y_speed = 0 leftallowed = True rightallowed = True hgturnright = True hgjumpallowed = True ########### the grandma d'awesome murder sorts hgimage = pygame.image.load('hgfinal.png') hgimage.convert_alpha() class HG(object): def __init__(self,x,y,image): self.image = image self.rect = self.image.get_rect() self.x = x self.y = y def draw(self): windowSurface.blit(self.image,(self.x,self.y)) def move(self): self.x += x_speed self.y += y_speed def topcollide(self,box): if not self.rect.colliderect(box.rect): global y_speed if y_speed &lt; 20: y_speed += 1 elif y_speed == 20: y_speed = 20 print('shhoooo') elif self.rect.colliderect(box.rect): y_speed = 0 print('flop') hg = HG(0,0,hgimage) ########### land and boundary lands = pygame.image.load('hgland1.png') floorland = pygame.transform.scale(lands,(1280,50)) sideedge = pygame.Rect(0…
has answer: http://stackoverflow.com/a/47603775
tagged with: class
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82165919
has comment: http://stackoverflow.com/comment/82166544
has comment: http://stackoverflow.com/comment/82165792
upvote count: 2
has comment: http://stackoverflow.com/comment/82166019
answer count: 1

http://stackoverflow.com/comment/82090249
type: AnswerComment
comment on: http://stackoverflow.com/a/47566118
score: 0
type: Comment
has text: Nice. This is actually faster than my recursive function with `reduce`.

http://stackoverflow.com/comment/82284778
type: QuestionComment
has text: do you have another jupyter notebook version outside of the one you got from anaconda?
comment on: http://stackoverflow.com/q/47662692
score: 0
type: Comment

http://stackoverflow.com/q/47637774
downvote count: 0
has answer: http://stackoverflow.com/a/47637854
accepted answer: http://stackoverflow.com/a/47637854
score: 30
upvote count: 30
favorite count: 0
type: Question
has title: Pandas groupby quantile values
has body: I tried to calculate specific quantile values from a data frame, as shown in the code below. There was no problem when calculate it in separate lines. When attempting to run last 2 lines, I get the following error: AttributeError: 'SeriesGroupBy' object has no attribute 'quantile(0.25)' How can I fix this? import pandas as pd df = pd.DataFrame( { 'x': [0, 1, 0, 1, 0, 1, 0, 1], 'y': [7, 6, 5, 4, 3, 2, 1, 0], 'number': [25000, 35000, 45000, 50000, 60000, 70000, 65000, 36000] } ) f = {'number': ['median', 'std', 'quantile']} df1 = df.groupby('x').agg(f) df.groupby('x').quantile(0.25) df.groupby('x').quantile(0.75) # code below with problem: f = {'number': ['median', 'std', 'quantile(0.25)', 'quantile(0.75)']} df1 = df.groupby('x').agg(f)
tagged with: python
has answer: http://stackoverflow.com/a/68553485
type: AnsweredQuestion
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/17578115
has comment: http://stackoverflow.com/comment/82234701
has answer: http://stackoverflow.com/a/58535752
possible better answer: http://stackoverflow.com/a/58535752

http://stackoverflow.com/q/47683500
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39458193
answer count: 1
score: 7
tagged with: python-typing
favorite count: 0
type: Question
has title: What is the benefit to using typing library classes vs. types in Python type hints?
upvote count: 8
has body: I'm starting to learn type hints in Python to ease the future porting of code from Python to C. I am wondering what the difference is, if any, between using types directly in type hints vs. using the classes defined in the typing module. For example, the difference between def somefn(a: list[int]) -&gt; tuple[str, int]: ... and from typing import List, Tuple def somefn(a: List[int]) -&gt; Tuple[str, int]: ... It seems like some classes like Union, Any, Callable, and Iterable would be useful, but the utility of classes for data types that already exist as keywords in python is unclear to me.
duplicate of: http://stackoverflow.com/q/39458193
accepted answer: http://stackoverflow.com/a/47683779
tagged with: python
has answer: http://stackoverflow.com/a/47683779
downvote count: 1

http://stackoverflow.com/comment/82255877
score: 0
comment on: http://stackoverflow.com/q/47648038
type: Comment
type: QuestionComment
has text: hi @BeyhanGül could you please explain with code. Because I think in my case, as I am not using findall, resultant will not have tuples.

http://stackoverflow.com/q/47639589
type: UnansweredQuestion
has title: Making John, john and JOHN mean the same variable in python lists?
tagged with: python
answer count: 4
score: 0
has answer: http://stackoverflow.com/a/47639784
has comment: http://stackoverflow.com/comment/82242514
has comment: http://stackoverflow.com/comment/82237794
has answer: http://stackoverflow.com/a/47639653
has body: My question is this. How do I make it so users can not make a new user_name John if JOHN or john are already in use. Can I make user_name.upper() = user_name.lower() or something like that. These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms. Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.
has comment: http://stackoverflow.com/comment/82237908
type: Question
has comment: http://stackoverflow.com/comment/82237593
has answer: http://stackoverflow.com/a/47639729
has answer: http://stackoverflow.com/a/47640054

python-3.x
tags question: http://stackoverflow.com/q/47668000
tags question: http://stackoverflow.com/q/47667149
tags question: http://stackoverflow.com/q/47623109
tags question: http://stackoverflow.com/q/47685575
tags question: http://stackoverflow.com/q/47667980
tags question: http://stackoverflow.com/q/47655232
tags question: http://stackoverflow.com/q/47660227
tags question: http://stackoverflow.com/q/47634751
tags question: http://stackoverflow.com/q/47609028
tags question: http://stackoverflow.com/q/47640554
tags question: http://stackoverflow.com/q/47638042
tags question: http://stackoverflow.com/q/47547771
tags question: http://stackoverflow.com/q/47562604
tags question: http://stackoverflow.com/q/47622356
tags question: http://stackoverflow.com/q/47696911
tags question: http://stackoverflow.com/q/47681372
tags question: http://stackoverflow.com/q/47671372
tags question: http://stackoverflow.com/q/47644723
tags question: http://stackoverflow.com/q/47580444
tags question: http://stackoverflow.com/q/47645879
tags question: http://stackoverflow.com/q/47604151
tags question: http://stackoverflow.com/q/47557989
tags question: http://stackoverflow.com/q/47577643
tags question: http://stackoverflow.com/q/47560644
tags question: http://stackoverflow.com/q/47646371
tags question: http://stackoverflow.com/q/47586900
tags question: http://stackoverflow.com/q/47696515
tags question: http://stackoverflow.com/q/47659289
tags question: http://stackoverflow.com/q/47604044
tags question: http://stackoverflow.com/q/47584961
tags question: http://stackoverflow.com/q/47620840
tags question: http://stackoverflow.com/q/47656152
tags question: http://stackoverflow.com/q/47676660
tags question: http://stackoverflow.com/q/47601540
tags question: http://stackoverflow.com/q/47546162
tags question: http://stackoverflow.com/q/47640407
tags question: http://stackoverflow.com/q/47584787
tags question: http://stackoverflow.com/q/47545511
tags question: http://stackoverflow.com/q/47660194
tags question: http://stackoverflow.com/q/47604989
tags question: http://stackoverflow.com/q/47579944
tags question: http://stackoverflow.com/q/47575979
tags question: http://stackoverflow.com/q/47671753
tags question: http://stackoverflow.com/q/47573416
tags question: http://stackoverflow.com/q/47647365
tags question: http://stackoverflow.com/q/47605334
tags question: http://stackoverflow.com/q/47600298
tags question: http://stackoverflow.com/q/47580019
tags question: http://stackoverflow.com/q/47683257
tags question: http://stackoverflow.com/q/47693494
tags question: http://stackoverflow.com/q/47552154
tags question: http://stackoverflow.com/q/47637987
tags question: http://stackoverflow.com/q/47586275
tags question: http://stackoverflow.com/q/47571412
tags question: http://stackoverflow.com/q/47598953
tags question: http://stackoverflow.com/q/47624934
tags question: http://stackoverflow.com/q/47652495
tags question: http://stackoverflow.com/q/47552490
tags question: http://stackoverflow.com/q/47564702
tags question: http://stackoverflow.com/q/47661711
tags question: http://stackoverflow.com/q/47630655
tags question: http://stackoverflow.com/q/47581959
tags question: http://stackoverflow.com/q/47624578
tags question: http://stackoverflow.com/q/47656991
tags question: http://stackoverflow.com/q/47577450
tags question: http://stackoverflow.com/q/47557740
tags question: http://stackoverflow.com/q/47565541
tags question: http://stackoverflow.com/q/47578902
tags question: http://stackoverflow.com/q/47613582
tags question: http://stackoverflow.com/q/47683474
tags question: http://stackoverflow.com/q/47685845
tags question: http://stackoverflow.com/q/47558854
tags question: http://stackoverflow.com/q/47636993
tags question: http://stackoverflow.com/q/47584829
tags question: http://stackoverflow.com/q/47663110
tags question: http://stackoverflow.com/q/47697476
tags question: http://stackoverflow.com/q/47660676
tags question: http://stackoverflow.com/q/47589327
tags question: http://stackoverflow.com/q/47600448
tags question: http://stackoverflow.com/q/47589853

http://stackoverflow.com/comment/82048702
has text: that's typo, im sorry
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47545762
score: 0

http://stackoverflow.com/comment/82147108
has text: thanks, i have already set the index in my notebook but it still seems to return true for everything.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47594747
type: Comment

http://stackoverflow.com/comment/82172337
type: Comment
comment on: http://stackoverflow.com/a/47590965
type: AnswerComment
score: 0
has text: now, it's working with another small tweak, thanks for your help!

http://stackoverflow.com/comment/82278762
type: Comment
has text: So mintty creates a hidden console that bash inherits uselessly, and the standard handles are instead set to named pipes, which Python inherits, so we're forced to use `-i` and `PYTHONIOENCODING` to get around Python's default behavior when standard I/O is piped. Then of course Python no longer has the console's cooked read for input history and input editing. So we'll solve that with winpty and winpty-agent, which creates another hidden console for Python and depends on dubious polling of the screen buffer. Too convoluted. I'll stick to running MSYS bash as a normal console application.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47637584

recursion
type: Tag
tags question: http://stackoverflow.com/q/47591978
tags question: http://stackoverflow.com/q/47604564
tags question: http://stackoverflow.com/q/47546740
tags question: http://stackoverflow.com/q/47639215
tags question: http://stackoverflow.com/q/47686088
tags question: http://stackoverflow.com/q/47551468
tags question: http://stackoverflow.com/q/47640962
tags question: http://stackoverflow.com/q/47632044
tags question: http://stackoverflow.com/q/47647797
tag name: recursion
tags question: http://stackoverflow.com/q/47569579
tags question: http://stackoverflow.com/q/47618118
tags question: http://stackoverflow.com/q/47571407
tags question: http://stackoverflow.com/q/47600975
tags question: http://stackoverflow.com/q/47641332
tags question: http://stackoverflow.com/q/47671254
tags question: http://stackoverflow.com/q/47623788
tags question: http://stackoverflow.com/q/47666884
tags question: http://stackoverflow.com/q/47588114
tags question: http://stackoverflow.com/q/47579110
tags question: http://stackoverflow.com/q/47584854
tags question: http://stackoverflow.com/q/47564765
tags question: http://stackoverflow.com/q/47612693
tags question: http://stackoverflow.com/q/47603498

http://stackoverflow.com/a/47606305
has body: Try the following code from the tensorflow wiki tf.reset_default_graph() # Create some variables. v1 = tf.get_variable("v1", shape=[3], name="v1") v2 = tf.get_variable("v2", shape=[5], name="v2") saver = tf.train.Saver(var_list=[v1, v2]) # list of TF variables that are to be restored with tf.Session() as sess: # Restore variables from disk. saver.restore(sess, "./model.ckpt") print("Model restored.") # Check the values of the variables print("v1 : %s" % v1.eval()) print("v2 : %s" % v2.eval()) I hope this helps!
score: 0
answers question: http://stackoverflow.com/q/47605104
type: Answer
has comment: http://stackoverflow.com/comment/82179472

http://stackoverflow.com/comment/82066263
type: Comment
comment on: http://stackoverflow.com/a/47554164
has text: The noteworthy issue being: `(1)` is not a tuple, `(1,)` is.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82345166
type: Comment
comment on: http://stackoverflow.com/q/47693021
type: QuestionComment
score: 0
has text: Thanks jezrael - stupid me. Can you post as an answer and I can mark as solved?

http://stackoverflow.com/q/47583064
tagged with: plotly
tagged with: symbols
has comment: http://stackoverflow.com/comment/82226539
answer count: 1
tagged with: marker
favorite count: 0
type: Question
score: 5
has body: I'm trying to generate a scattermapbox using dash and plotly, when I specify a symbol (e.g. "square") inside the marker, it doesn't render when the map is generated. I'm using a callback function and I tried several symbols, none of which worked, but the circle marker. Is there something obvious that I'm missing? Here is a minimal example, to run it you will need a mapbox token. import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import datetime as dt app = dash.Dash() mapbox_access_token = 'YOUR_MAPBOX_TOKEN_HERE' app.layout = html.Div(children=[ html.H1('Dashboard'), dcc.DatePickerRange(id='fecha', start_date=dt.datetime.today() - dt.timedelta(days=30), end_date=dt.datetime.today() ), html.Center(dcc.Graph( id='mapa', figure={ 'data': [ go.Scattermapbox( lat=[], lon=[], ) ], 'layout': go.Layout( autosize=False, width=1300, height=800, hovermode='closest', showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=-32, lon=-70 ), pitch=0, zoom=5, ), ) }) ,) ]) @app.callback( dash.dependencies.Output('mapa', 'figure'), [dash.dependencies.Input('fecha', 'start_date'), dash.dependencies.Input('fecha', 'end_date') ]) def update_graph(inicio,fin): Data = [go.Scattermapbox( name='square', lat=[-31,-30], lon=[-71,-71], marker = dict( symbol='square', size = 8, opacity = 0.8, color='grey' ), text = np.array(['square1','square2'])), go.Scattermapbox( name='circle', lat=[-31,-30], lon=[-72,-72], marker = dict( symbol='circle', size = 8, opacity = 0.8, color='grey' ), text = ['circle1','circle2'])] figure={ 'data': Data, 'layout': go.Layout( title='Visitas', autosize=False, width=1300, height=800, hovermode='closest', showlegend=True, mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=-30.5, lon=-72 ), pitch=0, zoom=5, ), ) } return figure if __name__ == '__main__': app.run_server(host= '0.0.0.0',port=9999) I tried making the same mapbox without dash (i.e. jus…
upvote count: 5
tagged with: plotly-dash
accepted answer: http://stackoverflow.com/a/47662779
has comment: http://stackoverflow.com/comment/82166836
tagged with: python
has title: When I plot the markers in a trace with a symbol, it doesn't show up
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47662779
downvote count: 0
has comment: http://stackoverflow.com/comment/82124685

http://stackoverflow.com/comment/82122600
comment on: http://stackoverflow.com/q/47582312
score: 0
type: Comment
type: QuestionComment
has text: Are you using Python 3?

arguments
tags question: http://stackoverflow.com/q/47664319
tags question: http://stackoverflow.com/q/47613070
tag name: arguments
type: Tag
tags question: http://stackoverflow.com/q/47543262
tags question: http://stackoverflow.com/q/47672679

http://stackoverflow.com/q/47622065
upvote count: 1
has answer: http://stackoverflow.com/a/47622832
favorite count: 0
possible better answer: http://stackoverflow.com/a/47622372
type: AnsweredQuestion
tagged with: list
score: 1
tagged with: python
has title: Find surroundings numbers in lists in lists Python
has comment: http://stackoverflow.com/comment/82202226
has body: I am having trouble finding surrounding numbers in list in list environment. The idea is that the list underneath each other form a grid. grid= [[1, 5, 4, 1], [2, 5, 3, 2], [6, 3, **6**, 3], [1, 4, 2, 1]] The function I try to write has as given value the position of a number and the grid itself. The program should find the surrounding numbers. e.g. with this &gt;&gt;&gt; grid= [[1, 5, 4, 1], [2, 5, 3, 2], [6, 3, **6**, 3], [1, 4, 2, 1]] &gt;&gt;&gt; neighbours(2, 2, grid) {1, 2, 3, 4, 5} In this example the element of choice is the bold 6. I have no idea how to do this without constantly going out of indexes or making the code extremely difficult. Any help would be appreciated a lot
has answer: http://stackoverflow.com/a/47622246
answer count: 4
has answer: http://stackoverflow.com/a/47622415
type: Question
has answer: http://stackoverflow.com/a/47622372
accepted answer: http://stackoverflow.com/a/47622832
has comment: http://stackoverflow.com/comment/82202151
downvote count: 0
has comment: http://stackoverflow.com/comment/82202236

http://stackoverflow.com/comment/83034536
type: AnswerComment
comment on: http://stackoverflow.com/a/47987890
has text: Thanks for your interest and research. It's a good food for thought and further investigation. P.S.: after doing `from werkzeug import security` the `werkzeug.security.generate_password_hash()` results in `NameError: name 'werkzeug' is not defined` — I have checked =)
score: 1
type: Comment

http://stackoverflow.com/a/47615008
type: Answer
has body: Answering my own question: there is no backwards compatible max, but it is arguable that trying to find the max of None doesn't really make sense. The entries that I was comparing were timestamps, and I knew that they would never be negative. So I changed my code to return 0 instead of None, so the max turned to max([0,0,0]) which worked. If you can't make such guarantees about your data, you could return -sys.maxsize instead. In [7]: max([-sys.maxsize, -sys.maxsize, -sys.maxsize]) Out[7]: -9223372036854775807 Note sys.maxsize not sys.maxint, which is a documented change. What is sys.maxint in Python 3?
upvote count: 2
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47614961
score: 1
answers question: http://stackoverflow.com/q/47614961

topology
tags question: http://stackoverflow.com/q/47618710
tag name: topology
type: Tag

http://stackoverflow.com/comment/82165689
has text: You mean `[s[0]]`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47603402
type: AnswerComment

http://stackoverflow.com/a/47619140
has comment: http://stackoverflow.com/comment/82362321
has comment: http://stackoverflow.com/comment/91158118
has comment: http://stackoverflow.com/comment/82362230
has comment: http://stackoverflow.com/comment/82365169
has comment: http://stackoverflow.com/comment/82367435
answers question: http://stackoverflow.com/q/47602533
has comment: http://stackoverflow.com/comment/82269442
has comment: http://stackoverflow.com/comment/82232916
has comment: http://stackoverflow.com/comment/82365263
type: Answer
has comment: http://stackoverflow.com/comment/82232797
has comment: http://stackoverflow.com/comment/82362064
has comment: http://stackoverflow.com/comment/82362561
has comment: http://stackoverflow.com/comment/82362415
has comment: http://stackoverflow.com/comment/82380288
score: 2
has comment: http://stackoverflow.com/comment/82274864
upvote count: 2
has body: If you use openpyxl's utilities for dataframes then you should be able to do everything you need with the existing workbook, assuming this fits into memory. from openpyxl import load_workbook from openpyxl.utils.dataframe import dataframe_to_rows wb = load_workbook("C:\Andrea\master_file.xlsx") ws = wb[SHEETNAME] for row in dataframe_to_rows(dt_today): ws.append(row)
has comment: http://stackoverflow.com/comment/82362450
downvote count: 0

http://stackoverflow.com/comment/82202168
has text: Thank you for your feedback. I will try to implement this.
type: Comment
comment on: http://stackoverflow.com/a/47620937
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82051024
type: AnswerComment
comment on: http://stackoverflow.com/a/47546587
has text: I followed these steps:
type: Comment
score: 0

http://stackoverflow.com/a/47563130
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47563065
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47563065
type: Answer
has body: Your get_longest_name function is returning the key in the dictionary, rather than the attributes of the class. The following would fix it: def get_longest_name(people): return people[max(people, key=lambda word: (len(word), word))].name Edit to add a full working answer: &gt;&gt;&gt; class Person: ... def __init__(self, name, year_of_birth, degree): ... self.name = name ... self.year_of_birth = year_of_birth ... self.degree = degree ... self.mentor = None ... self.mentees = [] ... &gt;&gt;&gt; def get_longest_name(people): ... return people[max(people, key=lambda word: (len(word), word))].name ... &gt;&gt;&gt; people = {} &gt;&gt;&gt; people['martin'] = Person('Martin', 1991, 'phd') &gt;&gt;&gt; people['peter'] = Person('Peter', 1995, 'bc') &gt;&gt;&gt; get_longest_name(people) Martin
has comment: http://stackoverflow.com/comment/82084137

http://stackoverflow.com/comment/82218684
comment on: http://stackoverflow.com/a/47628408
score: 0
type: Comment
has text: First of all thanks for your help. Usually I use python2.7 and apparently this "@" stuff works only in python3.6. Isn't it? Nevertheless, I've got an error: np.shape(A) (1024, 1024, 1) np.shape(B) (1024, 1024, 2) np.add.at(C, n, np.moveaxis(A[:, :, (n - m)], -1, 0) @ np.moveaxis(B[:, :, m], -1, 0)) ValueError: array is not broadcastable to correct shape
type: AnswerComment

http://stackoverflow.com/q/47672056
type: Question
tagged with: urllib2
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/47678268
type: AnsweredQuestion
has body: Can we add the unix user credentials to SQS client? Situation : I have a user in Unix system (without 'sudo'/root privileges). And this Unix user's permissions does not allow me to connect to amazonaws.com. Can I pass the username and password of this Unix user to boto3 client (SQS) ? OR, can we pass boto3 client receive message object in urllib2/3? What I already tried : import boto3 # Create SQS client sqs = boto3.client('sqs',region_name='eu-west-1') queue_url='https://sqs.eu-west-1.amazonaws.com/XXXX' # Receive message from SQS queue response = sqs.receive_message( QueueUrl=queue_url, AttributeNames=[ 'SentTimestamp' ], MaxNumberOfMessages=10, MessageAttributeNames=[ 'All' ], VisibilityTimeout=0, WaitTimeSeconds=0 ) I can access any URL using urllib2 to scrape it. And I am able to pass Unix credentials while doing it. As a root user I am able to get messages from amazonSQS using boto3 as mentioned in the above code.
has answer: http://stackoverflow.com/a/47678268
tagged with: urllib3
has title: boto3 add unix credentials, urllib2/3
score: 0
answer count: 1

http://stackoverflow.com/comment/82126767
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47574005
has text: Cool example @CommonSense

http://stackoverflow.com/comment/82089897
has text: Try makemigrations command. Like the error says, there is no such table in your db now.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47546579
type: Comment

http://stackoverflow.com/comment/82301605
type: Comment
has text: That means, I need single quotes for character and no quotes for numeric. Or even singles quotes for all value also fine
comment on: http://stackoverflow.com/a/47671093
type: AnswerComment
score: 0

http://stackoverflow.com/q/47623233
linked to: http://stackoverflow.com/q/27905295
has body: I have a Series like so: &gt;&gt;&gt; s = pd.Series([1,0,0,3,0,5,0,0,0]) &gt;&gt;&gt; s[s==0] = pd.np.nan &gt;&gt;&gt; s 0 1.0 1 NaN 2 NaN 3 3.0 4 NaN 5 5.0 6 NaN 7 NaN 8 NaN dtype: float64 and I'd like to 'extend' the values, as illustrated here: &gt;&gt;&gt; t = s.shift() &gt;&gt;&gt; for _ in range(100000): ... s[s.isnull()] = t ... if not s.isnull().any(): ... break ... t = t.shift() ... &gt;&gt;&gt; s 0 1.0 1 1.0 2 1.0 3 3.0 4 3.0 5 5.0 6 5.0 7 5.0 8 5.0 dtype: float64 But I'd like something more vectorized and efficient. How do I do that?
has title: How to extend values to next non-null in pandas/numpy?
tagged with: pandas
has answer: http://stackoverflow.com/a/47623258
duplicate of: http://stackoverflow.com/q/27905295
tagged with: python
score: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/47623301
answer count: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47623301
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47623258
type: AnsweredQuestion

http://stackoverflow.com/q/47656071
score: 42
has answer: http://stackoverflow.com/a/62475265
tagged with: flask
has answer: http://stackoverflow.com/a/57485942
linked to: http://stackoverflow.com/q/57758213
has answer: http://stackoverflow.com/a/74039275
has comment: http://stackoverflow.com/comment/82300985
upvote count: 42
has comment: http://stackoverflow.com/comment/121610460
answer count: 12
has answer: http://stackoverflow.com/a/67015509
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56710322
has answer: http://stackoverflow.com/a/49525132
has title: CommandError: Can't locate revision identified by '...' when migrating using Flask-Migrate
has comment: http://stackoverflow.com/comment/82271288
downvote count: 0
has answer: http://stackoverflow.com/a/60632707
has body: I started using Flask-Migrate today and installed it on a test project. However i am getting following error: alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810' Steps to reproduce: run "python create_db.py" run "flask db init" add column "name" to Entry-model run "flask db migrate" EDIT: After removing migrations directory and repeating the process i am getting the same error after running "flask db migrate". I also tried using a manage.py file with flask-script --> same issue Error: (venv_mentz) H:\Flask-API-Test&gt;python manage.py db migrate INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. Traceback (most recent call last): File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 143, in _catch_revision_errors yield File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions return self.revision_map.get_revisions(id_) File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in get_revisions return sum([self.get_revisions(id_elem) for id_elem in id_], ()) File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in &lt;listcomp&gt; return sum([self.get_revisions(id_elem) for id_elem in id_], ()) File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in get_revisions for rev_id in resolved_id) File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in &lt;genexpr&gt; for rev_id in resolved_id) File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 362, in _revision_for_ident resolved_id) alembic.script.revision.ResolutionError: No such revision or branch 'e39d16e62810' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; man…
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
tagged with: flask-migrate
has comment: http://stackoverflow.com/comment/82292132
has answer: http://stackoverflow.com/a/71545511
has answer: http://stackoverflow.com/a/71974871
has answer: http://stackoverflow.com/a/58648805
has answer: http://stackoverflow.com/a/59226957
has answer: http://stackoverflow.com/a/62812162
has comment: http://stackoverflow.com/comment/82281832
tagged with: python

http://stackoverflow.com/comment/82193128
has text: You are using Python 3.x. I have updated the script accordingly.
type: AnswerComment
comment on: http://stackoverflow.com/a/47600366
score: 0
type: Comment

http://stackoverflow.com/a/47592880
score: 2
answers question: http://stackoverflow.com/q/47592732
downvote count: 0
upvote count: 2
type: Answer
has body: I believe your code is correct. (30.8^2 + 69^2 + 69^2)^0.5 = 102 (3 s.f.). This is more than your radius of 100 so it's outside of the sphere.

http://stackoverflow.com/a/47626225
score: 1
type: Answer
has body: One way is to think how many 3 x 3 x 3 cubes you may cut and grab from 6 x 6 x 3 rectangle prism. Also, let's make the question simpler. Let's say you have 2 x 2 input image patch and you want to do 2 x 2 convolution. How many ways you can fit 2 x 2 convolution to input image patch = 1 x 1 (1 in x direction, 1 in y direction) Let's extend it: 4 x 2 input image with 2 x 2 conv. Unique convolution count = 3 x 1 (3 in x direction, 1 in y direction etc.) Let's extend it: 4 x 4 input image with 2 x 2 conv. Unique convolution count = 3 x 3 Let's extend it: 4 x 4 x 2 input image with 2 x 2 x 2 conv. Unique convolution count = 3 x 3 x 1 Let's extend it: 6 x 6 x 3 input image with 3 x 3 x 3 conv. Unique convolution count = 4 x 4 x 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47616700
answers question: http://stackoverflow.com/q/47616700

http://stackoverflow.com/q/47623836
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: scrapy
score: 6
favorite count: 0
has body: It looks that I came to the dead end. Is there any way to run scrapy spider inside asyncio loop? For example in the code below: import asyncio from scrapy.crawler import CrawlerProcess from myscrapy import MySpider import scrapy async def do_some_work(): process = CrawlerProcess() await process.crawl(MySpider) loop = asyncio.get_even_loop() loop.run_until_complete(do_some_work()) Which leads me to the error: raise TypeError('A Future, a coroutine or an awaitable is required') TypeError: A Future, a coroutine or an awaitable is required I do understand that after await there should be another coroutine. Is there any way to bypass it and still make it work asynchronous? Thank you
has answer: http://stackoverflow.com/a/48483003
has comment: http://stackoverflow.com/comment/82206515
tagged with: python
has answer: http://stackoverflow.com/a/54458883
upvote count: 6
has title: How to run scrapy spider inside asyncio even loop?
type: Question

http://stackoverflow.com/comment/82072972
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47555196
score: 0
has text: @CharlesDuffy Yes, I do agree with you! I did provide the example to show to OP what declarative would look like (no steps at all, I just want a list).

http://stackoverflow.com/q/47631832
score: 0
answer count: 0
tagged with: null
type: UnansweredQuestion
tagged with: columnsorting
tagged with: sparse-matrix
type: Question
has comment: http://stackoverflow.com/comment/82775512
has comment: http://stackoverflow.com/comment/82788962
has comment: http://stackoverflow.com/comment/82227757
tagged with: python
has title: Blocks of non-contradicting n-tupels
has body: I would like to efficiently compute a boolean matrix that stores all non-contradicting pairings over a large set of n-tupels with possible empty fields, for example: (1,None,44,22,44,None,33,) (1,24,None,None,None,23,33,) These two tupels do not contradict each other. Ultimately, I am looking for python code, but this is more about the general idea and I have a feeling there should be some matrix operations that enable this - or a simple tree structure. The tricky part is that an empty value None is not contradicting any given value.
tagged with: numpy
has comment: http://stackoverflow.com/comment/82226900

http://stackoverflow.com/comment/82411692
score: 0
comment on: http://stackoverflow.com/q/47678702
has text: Got a hint and will try tf.where(): In tensorflow > v1.0 tf.select replaced with tf.where and logical operations can be accessed directly like tf.equal. A sample loss function can be: def loss(y_true, y_pred): import tensorflow as tf pt = tf.where(tf.equal(y_true, 1), y_pred, 1 - y_pred) return -K.sum(alpha * K.pow(1. - pt, gamma) * K.log(pt))
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47658467
tagged with: matplotlib
has body: I installed matplotlib 2.1 from version 2.0.2 and my simple 2D x-y plots are now showing the y-axis with a log scale, when before the scale was linear. I am not sure how this is happening. import matplotlib import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import matplotlib.gridspec as gridspec from numpy import sqrt, pi, exp, linspace, loadtxt from lmfit import Model path=r'C:\users\test.mca' f=open(path,'r') lines=f.readlines()[14:2060] x=[] for i in range(0,2046): x.append(i) plt.figure(figsize=(10,6)) plt.xlim(0,600) plt.ylim(0,1000) plt.grid(True) plt.xlabel('Channels') plt.ylabel('Counts') def gaussian(x, amp, cen, wid): "1-d gaussian: gaussian(x, amp, cen, wid)" return (amp/(sqrt(2*pi)*wid)) * exp(-(x-cen)**2 /(2*wid**2)) gmod = Model(gaussian) pars = gmod.make_params(amp=15000, wid=14, cen=380) result = gmod.fit(lines, pars, x=x) print(result.fit_report()) fwhm=result.params['wid'].value*2.35 ER=100*fwhm/result.params['cen'].value center=result.params['cen'] plt.title('Gaussian fit\n Center=%.1f FWHM=%.1f ER=%.1f%%' % (center, fwhm, ER)) plt.plot(x, lines,'bo', markersize=4) plt.plot(x, result.best_fit, 'r-') plt.show() Version 2.1: Version 2.0.2: The top figure is plotted using 2.1 and the bottom figure is using 2.0.2. Having some trouble understanding why this is.
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47658745
has title: Matplotlib 2.1 issue with log scale
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47658745
score: 0

http://stackoverflow.com/comment/82298881
type: Comment
has text: yes i'm sorry, i edited, the solution is "a do red" And i have not need a correct sentence. It's just word list no real english sentence
type: QuestionComment
comment on: http://stackoverflow.com/q/47669999
score: 0

http://stackoverflow.com/comment/82218130
has text: One question, do you need replace from first `True`s of mask to end of DataFrame?
comment on: http://stackoverflow.com/a/47629629
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47652962
has comment: http://stackoverflow.com/comment/82314922
has comment: http://stackoverflow.com/comment/82264327
score: 0
answer count: 0
tagged with: arrays
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82281641
tagged with: python
linked to: http://stackoverflow.com/q/2709821
has title: imported module and current file don't work together
has comment: http://stackoverflow.com/comment/82315407
tagged with: numpy
has comment: http://stackoverflow.com/comment/82295362
has body: First and foremost, I'm not a native english speaker (just to make that clear) I have written a script for my numeric class in which i computed all necessary functions to pass my class. Now I want to implement everything into a GUI to make things easier. For the whole testing I worked with a 'test' file to see what types the outputs are and so on. The file is called Numerik_Funktionen1 and is imported to every file im working on. Now here is the problem: This is a class and function i've written: class LR: def LR_zerlegung(self, A, b = 0.): ''' splits Matrix A in L and R L = lower triangular matrix -&gt; linke untere Dreiecksmatrix R = upper triangular matrix -&gt; rechte obere Dreiecksmatrix returns (L, R) as tupel ''' self.A = np.copy(A) * 1. self.ALr = A * 1. self.n = len(self.A[0]) self.b = b self.L = np.eye(self.n) for k in range(self.n-1): for i in range(self.n)[k+1:self.n]: self.L[i, k] = self.ALr[i, k] / self.ALr[k, k] self.ALr[i, k] = 0 for j in range(self.n)[k+1:self.n]: self.ALr[i, j] = self.ALr[i, j] - self.L[i, k] * self.ALr[k, j] self.R = self.ALr print('Ax = b') print('A', '\n', self.A,"\n") print('b', '\n', self.b,"\n") print('L', '\n', self.L,"\n") print('R', '\n', self.R,"\n") return self.L, self.R The problem I run into is best described with code (I now it's neither well written nor good looking code, sorry) import Numerik_Funktionen1 a = input("a eingeben: ") b = input("b eingeben: ") array_from_string = [s.split(',') for s in a.split(';')] array_from_string2 = [s.split(',') for s in b.split(';')] c = np.asarray(array_from_string) d = np.asarray(array_from_string2) A = c.astype(int) b = d.astype(int) The input for a looks like this: 2,3;5,4 and for b 2;4 After the proceeding A is an array (array([[2, 3], [5, 4]])) and b as well (array([[2], [2]])) The call of the function looks like this: Numerik_Funktionen1.LR.LR_zerlegung(A, b) So far so good, but if I want to take the previously described function LR_zerlegung, it returns this: 'numpy.ndarray…
type: Question

http://stackoverflow.com/q/47685791
type: UnansweredQuestion
score: -3
tagged with: python
downvote count: 4
tagged with: python-2.7
answer count: 2
tagged with: tkinter
upvote count: 1
has answer: http://stackoverflow.com/a/47685830
has title: What does the enteredPassword = passwordEntry.get() command do?
has comment: http://stackoverflow.com/comment/82331421
has body: What does the enteredPassword = passwordEntry.get() command do in this context: import Tkinter as tk window = tk.Tk() def checkPassword(): password = "Oranges" enteredPassword = passwordEntry.get() if password == enteredPassword: confirmLabel.config(text="Correct") else: confirmLabel.config(text="Incorrect") passwordLabel = tk.Label(window, text="Password:") passwordEntry = tk.Entry(window, show="*") button = tk.Button(window, text="Enter", command=checkPassword) confirmLabel = tk.Label(window) passwordLabel.pack() passwordEntry.pack() button.pack() confirmLabel.pack() window.mainloop() Thank you!
has answer: http://stackoverflow.com/a/47686991
favorite count: 0
type: Question

http://stackoverflow.com/a/47629290
answers question: http://stackoverflow.com/q/47628807
score: 0
has body: If you have only two elements 1982 &amp; 2007 then you can try below function , or you can add your condition in elif case : def ListBreak(alist): flist,slist =[],[] for each in alist: if each[0] == 1982: flist.append(each) else: slist.append(each) return flist,slist Here function will return two list that you can simply unpack using : f,s = ListBreak(yourList) Hope this helps :)
type: Answer

http://stackoverflow.com/comment/82273883
comment on: http://stackoverflow.com/a/47644295
has text: My assumption is that I will bring in both the xls and the csv. Create a list of lists of the csv.... and then??
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82196811
score: 0
type: Comment
has text: uhm... that's what this answer is about
comment on: http://stackoverflow.com/a/47618441
type: AnswerComment

http://stackoverflow.com/q/47599128
tagged with: perceptron
tagged with: python
has title: Perceptron not training correctly - error in loop?
has answer: http://stackoverflow.com/a/47600262
tagged with: for-loop
has body: I'm trying to implement a simple perceptron in python that will be able to classify logical functions like OR, or AND. I have the following code in python: The bias is the third entry in each input vector. There is a row vector, 'targets', which contains the 'correct' values, the labels: The problem is that the weights do not update properly. They remain random, which tells me that nothing is really being trained. inputs = np.array([ [0,0,1], [0,1,1], [1,0,1], [1,1,1], ]) targets = np.array([0,0,0,1]) def step_function(x): return 1 * (x&gt;=0) def train(x,y): rate = 0.1 trials = 10 errors = [] w = np.random.rand(len(inputs[0])) for t in range(trials): for i, x in enumerate(inputs): actual = np.dot(inputs[i], w) desired = targets[i] error = desired - step_function(actual) if error != 0: errors.append(error) w += rate * error * inputs[i] return w w = train(inputs, targets) print(w)
type: UnansweredQuestion
tagged with: arrays
answer count: 1
type: Question
tagged with: enumerate
score: 0

http://stackoverflow.com/a/47618345
has body: Try this: for obj in ques: print obj.slug_field Can access the object fields by iterating through the list generated. I can see that you are trying to shuffle the queryset randomly. Maybe you can do this: ques = Upload.objects.filter(unique_id=tdetail).order_by('?') which in turn will be a queryset and you can use it as usual. Or maybe you can use shuffle from random, and do it using python: Assuming ques is a list: from random import shuffle shuffle(ques) For the error, Instead of this: slugs = platform.list do this: import json slugs = json.loads(platform.list) which will return a list of slugs, after that instead of the loop: ques = Upload.objects.filter(slug__in=slugs)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82194925
has comment: http://stackoverflow.com/comment/82194945
accepted answer of: http://stackoverflow.com/q/47618289
has comment: http://stackoverflow.com/comment/82195185
has comment: http://stackoverflow.com/comment/82194966
has comment: http://stackoverflow.com/comment/82195136
has comment: http://stackoverflow.com/comment/82195038
answers question: http://stackoverflow.com/q/47618289
has comment: http://stackoverflow.com/comment/82195216
has comment: http://stackoverflow.com/comment/82195237
type: Answer
has comment: http://stackoverflow.com/comment/82195069
score: 2
has comment: http://stackoverflow.com/comment/82195102
has comment: http://stackoverflow.com/comment/97993301
has comment: http://stackoverflow.com/comment/82195414
has comment: http://stackoverflow.com/comment/98494420
upvote count: 2
has comment: http://stackoverflow.com/comment/82195170

http://stackoverflow.com/comment/82249981
type: Comment
type: QuestionComment
has text: So only sublists of length 2 you want to remain?
comment on: http://stackoverflow.com/q/47645501
score: 0

http://stackoverflow.com/q/47613242
type: Question
score: 0
has body: I have the following code cmd = raw_input("&gt; ") if cmd[0] == "/": if " " in cmd: cmd = cmd.split(" ") { '/help': help, '/cf': cf(f = cmd[1]), '/rf': rf(f = cmd[1]), '/md': md(f = cmd[1]), '/rd': rd(f = cmd[1]), '/dir': dir(f = cmd[1]), '/tree': tree(f = cmd[1]), '/date': date, '/time': time_, '/clear': clear, '/echo': echo(f = cmd[1]), }.get(cmd[0])() For some reason, if I call, say, /md, it runs it as if I called /cf, can anyone offer any insight? My whole code can be found here: https://pastebin.com/ukwY6LfV
tagged with: python
accepted answer: http://stackoverflow.com/a/47613648
has comment: http://stackoverflow.com/comment/82185542
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47613648
has title: Pass parameters through function with .get() python
answer count: 1

http://stackoverflow.com/q/47611770
downvote count: 0
has title: Sikuli script slowing down - MouseDown: extended delay
tagged with: python
score: 2
tagged with: sikuli
has comment: http://stackoverflow.com/comment/82185761
tagged with: mouseevent
favorite count: 0
type: Question
has body: I am using sikuli for automating a game. The full code is pretty long but the part that moves / clicks mouse is as follows:- class click_thread(threading.Thread): def __init__(self, reg_to_click): threading.Thread.__init__(self) self.reg_to_click = reg_to_click def run(self): click_lock.acquire() click_func(self.reg_to_click) click_lock.release() def click_func(reg_to_click): while True: if auto_mouse == 'go': #this is global variable to 'pause' the mouse actions if need be by reassigning it somewhere else Settings.MoveMouseDelay = 0.1 Settings.DelayBeforeMouseDown = 0.1 Settings.ClickDelay = 0.1 click(reg_to_click.getCenter()) mouseMove(0,50) break else: print((time.asctime(time.localtime(time.time()))),"click func recd call - waiting 1s") wait(1) click_lock = threading.Lock() I am using threading to take care of mouse actions. Other functions in the code create a thread instance whenever they need the mouse to click something on the screen in the following way:- click_thread_instance = click_thread(reg_to_click) click_thread_instance.start() click_thread_instance.join() The program slows down as it runs, resulting in a lot of 'timeouts' in the game i use it on. When i check logs, the most frequent entry seems to be 'MouseDown: extended delay'. I have tried running it both from IDE and the command line. It appears to make no difference to this problem. Any idea what might be causing this and what can be done to rectify it? My env:- OS:- Microsoft Windows 10 Home, 64-bit Java:- Version 8, Update 151, build 1.8.0_151-b12 Sikuli: 1.1.1 Thanks in Advance. Some additional info:- I tried to carry out the clicks via a function instead of using multi threading to see if it makes any difference:- def click_func(reg_to_click): while True: if auto_mouse == 'go': Settings.MoveMouseDelay = 0.1 Settings.DelayBeforeMouseDown = 0.1 Settings.ClickDelay = 0.1 click(reg_to_click.getCenter()) mouseMove(0,50) break else: print((time.asctime(time.localtime(time.time()))),"click func rec…
answer count: 0
upvote count: 2
tagged with: python-multithreading
type: UnansweredQuestion

http://stackoverflow.com/a/55265666
has body: Try this: yum install python-devel
answers question: http://stackoverflow.com/q/47542282
has comment: http://stackoverflow.com/comment/97263824
type: Answer
score: 0

http://stackoverflow.com/comment/82098626
type: Comment
comment on: http://stackoverflow.com/q/47543720
type: QuestionComment
score: 0
has text: PDF documents can contain not only text but also lines, arcs, and Bezier curves. Which are editable in Illustrator. Have a look at the Python libraryfrom www.reportlab.com

http://stackoverflow.com/q/47657542
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
score: 2
has comment: http://stackoverflow.com/comment/82290997
downvote count: 0
has body: Now that twitter has increased the number of characters from 140 to 280 how can I use my tweetpy api in order to get the whole tweet? This is how my code is right now: for search in Search.objects.all(): if search.is_enabled: for keyword in search.keywords.all(): results = api.search(q=keyword.name, count=100, include_entities=True) for result in results: print ("results", dir(result)) print " ID: %s" % result.id print " From: %s" % result.user.name.encode('utf-8') print " Created : %s" % result.created_at print " %s" % result.text.encode('utf-8') self.loadtweet(search, result) I tried to add this: tweet_mode='extended' in the: results = api.search(q=keyword.name, count=100, include_entities=True) but it returns an error of missing text attribute in Status object.
has title: How to get the whole tweet with tweetpy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82296997
linked to: http://stackoverflow.com/q/47211501
has comment: http://stackoverflow.com/comment/91111390
answer count: 0

http://stackoverflow.com/comment/82230109
has text: Are you still trying to do `Coper.objects.get...` within the tag?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47635726
type: Comment

http://stackoverflow.com/q/47678708
tagged with: python
linked to: http://stackoverflow.com/q/38346018
accepted answer: http://stackoverflow.com/a/47678824
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47678824
upvote count: 3
answer count: 1
has body: I am trying to detect objects from an mp4 video file using OpenCV in Python. I am able to detect the objects in the video. I would like to get the timestamp of the position at which the object was detected in the video file and write it to a text file. Here is my code so far: import cv2 my_cascade = cv2.CascadeClassifier('toy.xml') def detect(gray, frame): toys= my_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in toys: cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) #Logic to write time stamp to file goes here return frame video_capture = cv2.VideoCapture('home.mp4') cv2.startWindowThread() while True: _, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) canvas = detect(gray, frame) cv2.imshow('Video', canvas) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows() I tried to use VideoCapture's method get() using property identifier like this: video_capture.get(CV_CAP_PROP_POS_MSEC) but get an error name 'CV_CAP_PROP_POS_MSEC' is not defined Seems like cv2 does not have this method or property identifier implemented. Is there any other way in cv2 to implement what I want? Please help. SOLVED This will print timestamp of the position of object everytime it is detected in the video. Here is the working code: import cv2 my_cascade = cv2.CascadeClassifier('toy.xml') def detect(gray, frame): toys= my_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in toys: cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) print("Toy Detected at: "+str(video_capture.get(cv2.CAP_PROP_POS_MSEC))) return frame video_capture = cv2.VideoCapture('home.mp4') cv2.startWindowThread() while True: _, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) canvas = detect(gray, frame) cv2.imshow('Video', canvas) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
downvote count: 1
favorite count: 0
has title: Detect timestamp of position of object detected from an mp4 video using OpenCV in Python
type: Question
tagged with: opencv

http://stackoverflow.com/comment/82167694
type: Comment
score: 0
type: AnswerComment
has text: Your first question is unclear. As for your second question: `soup.select` works like how css selectors does. You might wanna go through this documentation [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors). And as for your last question: No this `#` is not referring to a. That is the symbol of `ID` so it is referring to `id="listAlbum"`. Be sure to mark this as an answer. Thanks.
comment on: http://stackoverflow.com/a/47587376

http://stackoverflow.com/q/47571489
answer count: 3
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/82100184
has comment: http://stackoverflow.com/comment/82100129
upvote count: 5
has comment: http://stackoverflow.com/comment/82100573
tagged with: python
has answer: http://stackoverflow.com/a/47575705
favorite count: 0
type: Question
has body: I'm getting into Tkinter and I'm trying to put images into the windows it makes, but wherever I search the internet all I find is that I need a module called ImageTk. I've tried installing this module and it doesn't work, I've got PIL and Pillow installed but ImageTk just won't install and I have no idea why. I'm relatively new to Tkinter and my understanding of it is limited, so I'm sorry if it's an obvious problem. Whenever I try to install I get the following: Selecting previously unselected package python3-pil.imagetk:armhf. dpkg: unrecoverable fatal error, aborting: files list file for package 'qdbus' is missing final newline E: Sub-process /usr/bin/dpkg returned an error code (2)
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71935833
score: 5
downvote count: 0
has title: why cant i install ImageTk
has comment: http://stackoverflow.com/comment/82100215
has answer: http://stackoverflow.com/a/79420099

http://stackoverflow.com/comment/82299955
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47668052
has text: What is the difficulty you're having about that there? What is the variable name for keyword?
type: Comment

http://stackoverflow.com/q/47602925
has comment: http://stackoverflow.com/comment/82165026
has answer: http://stackoverflow.com/a/47603062
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82164958
has comment: http://stackoverflow.com/comment/82164710
has comment: http://stackoverflow.com/comment/82164818
has title: Why does summing a sparse matrix leave an empty dimension?
tagged with: scipy
tagged with: sparse-matrix
favorite count: 0
has body: When summing a numpy.ndarray, it reduces the dimensionality of the array, unless we set keepdims=True. However, this doesn't seem to be true for Scipy's sparse matrices: import scipy.sparse matrix = scipy.sparse.coo_matrix([[0, 1], [2, 1]]) print(matrix.shape) # (2, 2) as expected. print(matrix.sum().shape) # () as expected. print(matrix.sum(axis=0).shape) # (1, 2) but expected (2,). print(matrix.sum(axis=0)[0].shape) # (1, 2) but expected (2,). As shown from the last line in the example, I cannot even select the resulting vector. Further, trying to cast the result of the sum to a dense Numpy array fails: matrix.toarray() # This works. matrix.sum(axis=0).toarray() # AttributeError: 'matrix' has no 'toarray'. How can I compute the sum of a sparse matrix along one dimension and obtain the result as a dense array?
type: Question
linked to: http://stackoverflow.com/q/47591481
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82164693
has comment: http://stackoverflow.com/comment/82181834
tagged with: python
has comment: http://stackoverflow.com/comment/82165134
has comment: http://stackoverflow.com/comment/82164772
has comment: http://stackoverflow.com/comment/82164797
has comment: http://stackoverflow.com/comment/82164704

http://stackoverflow.com/comment/82078840
type: Comment
score: 0
has text: There are two packages: 'pycrypto' and 'crypto'. The 'pycrypto' package has module `Crypto` and the `crypto` package has module `crypto`. I believe this causes problems with case insensitivity. Try uninstalling both and installing only the one you need.
type: QuestionComment
comment on: http://stackoverflow.com/q/47559877

http://stackoverflow.com/comment/82127714
type: QuestionComment
score: 0
has text: Your quotes are weirdly placed, this could explain your error. Use a full example that reproduces your error
comment on: http://stackoverflow.com/q/47585007
type: Comment

http://stackoverflow.com/q/47664545
has answer: http://stackoverflow.com/a/47664650
favorite count: 0
has comment: http://stackoverflow.com/comment/82288380
has title: Simple python script is not printing output
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82288412
tagged with: python
downvote count: 6
answer count: 2
has comment: http://stackoverflow.com/comment/82288469
type: Question
upvote count: 0
has body: This code doesn't print an output: x = 1500000 y = 0 while (x&gt;0): x=(x * 1.1) - 20000 y = y+1 else: print (y) How would one fix this problem?
has answer: http://stackoverflow.com/a/47664627
score: -6

http://stackoverflow.com/comment/82268908
has text: I currently have that installed already and the whitelist includes "localhost:8100"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47654886
score: 0

http://stackoverflow.com/a/47542769
score: 0
has comment: http://stackoverflow.com/comment/82045631
has comment: http://stackoverflow.com/comment/82045238
type: Answer
has comment: http://stackoverflow.com/comment/82042812
has body: If you add an extra empty list, you can append to that list for item1 in pat: if item1.find("name"): name = item1.find("name").text date = item1.find("date").text data.append((name, date, [])) for item2 in app: if item2.find("country"): country = item2.find("country") data[-1][-1].append(country) It may be easier to follow if you name the list though. Any reason not to do the second loop first?
has comment: http://stackoverflow.com/comment/82046330
has comment: http://stackoverflow.com/comment/82043412
has comment: http://stackoverflow.com/comment/82044991
answers question: http://stackoverflow.com/q/47542251

http://stackoverflow.com/comment/82204300
comment on: http://stackoverflow.com/a/47623133
type: AnswerComment
score: 0
has text: yes, doubly less performant: 1) changes string and 2) no `set`. Good answer.
type: Comment

http://stackoverflow.com/comment/82309858
type: Comment
has text: Please read [how to make good reproducible pandas examples](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and edit your post correspondingly.
score: 0
comment on: http://stackoverflow.com/q/47661778
type: QuestionComment

http://stackoverflow.com/comment/82041981
type: Comment
type: QuestionComment
has text: Possible duplicate of [I have Python on my Ubuntu system, but gcc can't find Python.h](https://stackoverflow.com/questions/8282231/i-have-python-on-my-ubuntu-system-but-gcc-cant-find-python-h)
score: 2
comment on: http://stackoverflow.com/q/47542282

http://stackoverflow.com/comment/82283657
type: QuestionComment
comment on: http://stackoverflow.com/q/47623439
has text: Thank you this is very helpful. Yet before going any further my pyzo now starts returning `'pygame' is not defined` even though it starts the black window and all. (I still use `from pygame import *` but it looked like the only way which actually worked out). Any idea ?
score: 0
type: Comment

http://stackoverflow.com/comment/82264327
type: QuestionComment
has text: [What is the purpose of self?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self) should help you.
comment on: http://stackoverflow.com/q/47652962
score: 0
type: Comment

http://stackoverflow.com/q/47597942
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47598254
score: -1
has body: I have a text file that i'm trying to convert to a Excel file in python 3. The text files have a series of accounts - one text file looks like: example - PRODUCE_NAME: abc PRODUCE_NUMBER: 12345 DATE: 12/1/13 PRODUCE_NAME: efg PRODUCE_NUMBER: 987 DATE: 2/16/16 TIME: 12:54:00 PRODUCE_NAME: xyz PRODUCE_NUMBER: 0046 DATE: 7/15/10 COLOR: blue. I would like the excel file to look like this. enter image description here some code: ` # open text file op_file = open("Comp_file_1.txt", "r", encoding='windows-1252') text_file = op_file.read() ############################################################## # location of CAP WORD: and group them for mj in re.finditer(r"[A-Z]\w+(:)", text_file): col_list_start.append(mj.start(0)) col_list_end.append(mj.end(0)) col_list_group.append(mj.group()) ############################################################# # Location of the end of file and delete index 0 of start while True: # Advance location by 1. location = text_file.find(".", location + 1) # Break if not found. if location == -1: break # Display result. endline = location col_list_start.append(int(endline)) del col_list_start[0] ############################################################## # cut out the index of the rows - abc , 12345, 12/1/13 for m in range(len(col_list_end)): index4.append(file_data2[col_list_end[m]:col_list_start[m]]) ############################################################## # makes a data frame # and groups the data frame group_excel_list = {} for k,v in zip(col_list_group, index4): group_excel_list.setdefault(k, []).append(v)` dataframe looks like this key value {"PRODUCE_NAME:": [abc, efg, xyz]} {"PRODUCE_NUMBER:" : [12345, 987, 0046]} {"DATE:" : [12/1/13, 2/16/16, 7/15/10]} {"TIME:" : [12:54:00]} {"COLOR:" [blue]} df = pd.DataFrame(data=[group_excel_list], columns = col_list_group) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter("Comp_file_1" + '.xlsx', engine='xlsxwriter') # Convert the dataframe to an XlsxWri…
tagged with: text
upvote count: 0
linked to: http://stackoverflow.com/q/19677104
answer count: 2
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/47598041
tagged with: excel
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82154458
has title: converting text file to excel python 3

http://stackoverflow.com/comment/82068904
score: 0
type: Comment
type: QuestionComment
has text: Response.write is just to test with, i wont be using it in my markup when I can see that the ID can be returned through the SELECT command
comment on: http://stackoverflow.com/q/47555711

http://stackoverflow.com/q/47571774
tagged with: python
type: Question
upvote count: 2
has body: I tried to append an element to a list in a function call, which accepts a list as argument, def print_options(title, option_list): print('\n' + title) for index, elem in enumerate(option_list): print(index, '-', elem) options = ['A', 'B', 'C'] print_options('Title', options.append('D')) but this failed with TypeError: 'NoneType' object is not iterable have to do options.append('D') print_options('Title', options) to resolve the above issue. Wondering why it has to be this way.
score: 0
tagged with: list
answer count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/16641119
has title: 'NoneType' object is not iterable when list append elements in function call argument list
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/11205254
has answer: http://stackoverflow.com/a/47571850
has answer: http://stackoverflow.com/a/47572201
possible better answer: http://stackoverflow.com/a/47572201
accepted answer: http://stackoverflow.com/a/47571850

http://stackoverflow.com/q/47628735
type: Question
has answer: http://stackoverflow.com/a/47629340
accepted answer: http://stackoverflow.com/a/47629340
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has body: I have 4 forms that the user submits by clicking one Submit button. The forms are: Person Form - Will Save to Person Model Address Form - Will Save to Address Model Email Form - Will save to Email Model Phone Form - Will save to Phone Model. So, a Person can have multiple Addresses, Emails and Phone Numbers. So, I did this in the Person Model: class Person(models.Model): first_name = models.CharField(max_length=99) middle_name = models.CharField(max_length=99, blank=True, null=True) last_name = models.CharField(max_length=99, blank=True, null=True) address = GenericRelation('Address') phone = GenericRelation('Phone') email = GenericRelation('Email') I have these 3 lines along with their respective model fields for Address, Phone and Email content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Now, how do I save data to these models properly in my views when I receive the form from the user? This what I have so far. if request.method == 'POST': if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \ and phone_form.is_valid(): address = address_form.save() email = email_form.save() phone = phone_form.save() person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone person.address = (address) #This is where I need help. Am I thinking right? Is this the right way to save?
type: AnsweredQuestion
score: 1
has title: How do I set django generic foreign key from my views?
tagged with: forms
favorite count: 0

http://stackoverflow.com/comment/82223302
type: QuestionComment
has text: without imshow, does it crash? how did you install OpenCV? have you tried the latest version?
comment on: http://stackoverflow.com/q/47632758
score: 0
type: Comment

http://stackoverflow.com/q/47667708
has comment: http://stackoverflow.com/comment/82297414
has body: This is my first post so please be gentle, im trying to write two text files generated from some user input, the file "hostname - VLAN_config" is fine, i use that file elsewhere in my code, what i do need however is another file (in this case "hostname - Trunk_config" to be formatted in a certain manner in order to use it for another part of my code. The below code produces a file that looks like this; ", 1, 2, 3" but i need it to generate a text file that looks like; 1, 2, 3 print ('VLANS') print('-----------------------------------------------') print(' ') condition = True while (condition == True): vlan = raw_input('Specify a VLAN id: ') name = raw_input('What name for this VLAN: ') print(' ') with open(hostname + ' - VLAN_config', "ab") as f: f.write('vlan ' + vlan) f.write('\n') f.write('name ' + name) f.write('\n') with open(hostname + ' - Trunk_config', "ab") as f: f.write(', ' + vlan) test = raw_input('Would you like to add another? [Y] ') if test == (''): condition = True elif test == ('n'): condition = False else: test = raw_input('Invalid input, more?') if test == ('y'): condition = True elif test == ('n'): condition = False any help will be much appreciated!
has answer: http://stackoverflow.com/a/47667820
has comment: http://stackoverflow.com/comment/82297307
accepted answer: http://stackoverflow.com/a/47667820
tagged with: python
has comment: http://stackoverflow.com/comment/82294925
has title: Python output file formatting - text
type: AnsweredQuestion
score: 0
answer count: 1
type: Question

http://stackoverflow.com/comment/82343711
comment on: http://stackoverflow.com/a/47692086
score: 0
has text: So 1 case for each? Because i would like to check every command, action, monitor, max-threshold, zero-failcount, etc.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82062528
score: 0
comment on: http://stackoverflow.com/q/47552767
type: Comment
type: QuestionComment
has text: You want `np.random.rand(k, 2) * [300, 100]`?

http://stackoverflow.com/q/47605244
answer count: 1
has comment: http://stackoverflow.com/comment/82171894
tagged with: python
tagged with: slice
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/82169132
has comment: http://stackoverflow.com/comment/82169712
has comment: http://stackoverflow.com/comment/82169434
downvote count: 0
has answer: http://stackoverflow.com/a/47605511
has comment: http://stackoverflow.com/comment/82169234
accepted answer: http://stackoverflow.com/a/47605511
score: 4
type: AnsweredQuestion
has title: Compact notation for multidimensional slicing
has body: Let's say I have 3 (or more) dimensional array A and two arrays with minimum and maximum edges left, right for slicing it. Is there a more compact notation than this to select the view delimited by my edges? V = A[left[0]:right[0], left[1]:right[1], left[2]:right[2]) Probably something like this is already better view = [ slice(a, b) for a,b in zip(left, right) ] V = A[view] but I feel there's a more numpythonic way I'm not seeing... don't know, something with np.s_? EDIT: an example of the expected result A = np.arange(1000).reshape(10,10,10) left = np.array([0, 0, 0]) right = np.array([2, 4, 3]) view = [ slice(a, b) for a,b in zip(left, right) ] In [32]: A[view] Out[32]: array([[[ 0, 1, 2], [ 10, 11, 12], [ 20, 21, 22], [ 30, 31, 32]], [[100, 101, 102], [110, 111, 112], [120, 121, 122], [130, 131, 132]]])

http://stackoverflow.com/q/47655155
linked to: http://stackoverflow.com/q/47223944
favorite count: 0
type: Question
tagged with: cx-freeze
duplicate of: http://stackoverflow.com/q/47223944
has body: What's wrong in my application? Fatal Python error: Py_Initialize: unable to load the file system codec Traceback (most recent call last): File "C:\ ~~~~~ \ Python36\lib\encodings\__init__.py", line 31, in &lt;module&gt; ModuleNotFoundError: No module named 'codecs'
type: UnansweredQuestion
score: -4
has title: I got python cx freeze issue
tagged with: python
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/48123451
linked to: http://stackoverflow.com/q/42961944
answer count: 1

http://stackoverflow.com/q/47561198
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82080359
tagged with: fiddler
has comment: http://stackoverflow.com/comment/82080682
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82080227
has comment: http://stackoverflow.com/comment/82080295
linked to: http://stackoverflow.com/q/34113005
has comment: http://stackoverflow.com/comment/82080743
tagged with: python
has comment: http://stackoverflow.com/comment/82080444
has title: Cookie selectively not sent with Requests
score: 2
has comment: http://stackoverflow.com/comment/82080523
has body: Using the requests module with Python 3.6 (also happens with 3.5), here's the essence of my code: sess=requests.Session() login_to_stackexchange(sess) # logs in to SE print(sess.cookies) # see below sess.post("chat.stackexchange.com/something",data=data) # data={"index":stuff} The cookies at line 3 are: &lt;Cookie acct=t=[key here]&amp;s=[key here] for .stackexchange.com/&gt; &lt;Cookie prov=[key here] for .stackexchange.com/&gt; However when looking at the sent request using Fiddler, only the first cookie (prov) is sent. I need both cookies for my requests to work. Why is requests only sending one cookie ? How can I fix that ? "Full" cookie returned by line 3: &lt;Cookie uauth=true for .chemistry.stackexchange.com/&gt; &lt;Cookie acct=t=[key here]&amp;s=[key here] for .stackexchange.com/&gt; &lt;Cookie prov=[key here] for .stackexchange.com/&gt; &lt;Cookie sechatusr=t=[key here] for chat.stackexchange.com/&gt; &lt;Cookie anon=[key here] for openid.stackexchange.com/&gt;
answer count: 0
has comment: http://stackoverflow.com/comment/82080585
upvote count: 2
tagged with: cookies
downvote count: 0
tagged with: python-requests
favorite count: 0
has comment: http://stackoverflow.com/comment/82080117

http://stackoverflow.com/comment/82279743
type: QuestionComment
has text: if you think that there is problem with `raise` then did you check in Python 3 documentation how to use `raise` ?
score: 0
comment on: http://stackoverflow.com/q/47660370
type: Comment

http://stackoverflow.com/comment/82319651
type: QuestionComment
has text: Oh, I see what you mean, for debugging purposes. Well, you just partly solved the mystery, I think. I won't post the output now, but it does print the correct URL, AND, when I output the crawled content (shove it out to the console from the parser) it has indeed fetched it. There is a strange delay before it prints out those initial dozen lines, but in fact it was fetching them. However that is bad because I don't think it's respecting the `download_delay`. Maybe I could resolve that by adding a 'time.sleep(self.delay)' before each `yield Request ()`, seems a bit of a kludge though...
comment on: http://stackoverflow.com/q/47673406
score: 0
type: Comment

http://stackoverflow.com/a/47696461
has body: There are multiple solutions to your problem. First thing is that the file variable here is local to the index()-function. If you want to use a variable you defined outside of the function (and it's not imported like request and session) you need to start the function with the line global file. I would store the filename in session, then read the file again when you need the data. That way it will be local to the user, and you're not storing large amounts data in memory. Plus, if you use session.permanent = True it will be the stored for month for that "user" regardless of server and browser restarts. Edit: This answer originally stated that you can use the Flask g-object to store the global. However, the g-object is local to a request even though it lives in the application context. (i.e. data stored on the g-object is not accessible across requests, it's only accessible within the same request)
accepted answer of: http://stackoverflow.com/q/47693197
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47693197
has comment: http://stackoverflow.com/comment/82387387
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82386237

http://stackoverflow.com/q/47694802
answer count: 1
downvote count: 0
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/47695492
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47695492
has title: OpenCV length of matches in BFMatcher
type: Question
upvote count: 4
has body: I am trying to use SIFT on two images and match the keypoints using BFMatcher in OpenCV. However, the number of matches is not equal to the number of query descriptors. Can someone explain why they are not equal? According to docs match() function "Finds the best match for each descriptor from a query set." import cv2 import numpy as np im1 = cv2.imread("trex1.png", cv2.IMREAD_GRAYSCALE) im2 = cv2.imread("trex2.png", cv2.IMREAD_GRAYSCALE) sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(im1, None) kp2, des2 = sift.detectAndCompute(im2, None) im_kp1 = np.zeros(im1.shape, dtype=np.uint8) im_kp2 = np.zeros(im1.shape, dtype=np.uint8) im_kp1 = cv2.drawKeypoints(im1,kp1,None) im_kp2 = cv2.drawKeypoints(im2,kp2,None) bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) matches = bf.match(des1,des2) print len(des1) # Result : 78 print len(des2) # Result : 71 print len(matches) # Result : 55

http://stackoverflow.com/comment/82052724
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47548113
has text: You mean you want the result of the majority?
type: Comment

http://stackoverflow.com/q/47633016
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/47634573
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/82223890
type: Question
has title: How to display user input variables in single quotes in Python
has answer: http://stackoverflow.com/a/47633066
downvote count: 1
tagged with: python
score: -1
has body: I am trying to display user input data in single quotes, but something seems to be going wrong. Can you please help. For eg: name1 = raw_input() print "[{0}]". format ("'"+ "','".join (str(i) for i in [name1] + "'") However it's working as below: Input- Jan, Feb Actual output- ['Jan,Feb'] Expected output- ['Jan','Feb'] Can anyone please help

http://stackoverflow.com/a/47575205
score: 1
has body: You could just transpose the dataframe data, like this: import pandas as pd # Create a Pandas dataframe from some data. df1 = pd.DataFrame({'Data': [10, 20, 30, 40]}) df2 = df1.T # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') # Write the data in column and transposed (row) directions. df1.to_excel(writer, sheet_name='Sheet1', startrow=1, startcol=1, header=False, index=False) df2.to_excel(writer, sheet_name='Sheet1', startrow=1, startcol=3, header=False, index=False) # Close the Pandas Excel writer and output the Excel file. writer.save() Output:
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47569973
type: Answer
answers question: http://stackoverflow.com/q/47569973
has comment: http://stackoverflow.com/comment/82110598

http://stackoverflow.com/q/47589268
tagged with: arrays
upvote count: 1
has comment: http://stackoverflow.com/comment/82135812
favorite count: 0
has body: Array_1 = [{'name': 'Anna','rank': 'first', 'roll_no': 'R1111','id': '1000'},{'name': 'Anna','rank': 'first', 'roll_no': 'R1111','id': '1000'},{'name': 'Anna','rank': 'second', 'roll_no': 'R1111','id': '1000'},{'name': 'Bob','rank': 'first', 'roll_no': 'R1112','id': '1001'},{'name': 'Charles','rank': 'third', 'roll_no': 'R1113','id': '1002'},{'name': 'Charles','rank': 'second', 'roll_no': 'R1113','id': '1002'},{'name': 'Darwin','rank': 'fourth', 'roll_no': 'R1114','id': '1003'},{'name': 'Darwin','rank': 'second', 'roll_no': 'R1114','id': '1003'},{'name': 'Darwin','rank': 'second', 'roll_no': 'R1114','id': '1003'},{'name': 'Eve','rank': 'fifth', 'roll_no': 'R1115','id': '1004'}] I have an array with multiple dictionaries which have some duplicates. I want to remove duplicates and also keep only values based on priority. My priority is rank: 'first' then 'second' then 'third' then 'fourth' then 'fifth' ranks are fixed upto fifth {'id': '1000', 'rank': 'first', 'roll_no': 'R1111', 'name': 'Anna'} {'id': '1000', 'rank': 'first', 'roll_no': 'R1111', 'name': 'Anna'} {'id': '1000', 'rank': 'second', 'roll_no': 'R1111', 'name': 'Anna'} {'id': '1001', 'rank': 'first', 'roll_no': 'R1112', 'name': 'Bob'} {'id': '1002', 'rank': 'third', 'roll_no': 'R1113', 'name': 'Charles'} {'id': '1002', 'rank': 'second', 'roll_no': 'R1113', 'name': 'Charles'} {'id': '1003', 'rank': 'fourth', 'roll_no': 'R1114', 'name': 'Darwin'} {'id': '1003', 'rank': 'second', 'roll_no': 'R1114', 'name': 'Darwin'} {'id': '1003', 'rank': 'second', 'roll_no': 'R1114', 'name': 'Darwin'} {'id': '1004', 'rank': 'fifth', 'roll_no': 'R1115', 'name': 'Eve'} I want like this {'id': '1000', 'rank': 'first', 'roll_no': 'R1111', 'name': 'Anna'} {'id': '1001', 'rank': 'first', 'roll_no': 'R1112', 'name': 'Bob'} {'id': '1002', 'rank': 'second', 'roll_no': 'R1113', 'name': 'Charles'} {'id': '1003', 'rank': 'second', 'roll_no': 'R1114', 'name': 'Darwin'} {'id': '1004', 'rank': 'fifth', 'roll_no': 'R1115', 'name': 'Eve'} Un…
type: Question
has title: Keep values(or items) based on priority in an array(or list) which has multiple dictionaries and remove duplicates too
has comment: http://stackoverflow.com/comment/82143354
tagged with: duplicates
tagged with: python
has comment: http://stackoverflow.com/comment/82137787
tagged with: dictionary
score: -1
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47589419
accepted answer: http://stackoverflow.com/a/47589419
has answer: http://stackoverflow.com/a/47591112
possible better answer: http://stackoverflow.com/a/47591112
downvote count: 2

http://stackoverflow.com/comment/82281472
type: Comment
type: AnswerComment
has text: Okay, that sounds good. Can the `W` be generalized in second snippet as well? (Value of `idx0`)
comment on: http://stackoverflow.com/a/47660287
score: 0

http://stackoverflow.com/a/47585287
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47585184
type: Answer
has body: LA=[[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]] new_dict = {} for (key, value) in LA: if key in new_dict: new_dict[key].append(value) else: new_dict[key] = [value] for key, value in new_dict.items(): new_dict[key] = (sum(value)) dictlist = [] for key, value in new_dict.items(): temp = [key,value] dictlist.append(temp) print(dictlist) will do the job too
score: 2

http://stackoverflow.com/comment/82225779
score: 1
type: Comment
type: AnswerComment
has text: And also please note that a good answer worthy some upvote should contain some description what was changed and why. If @IanH's answer helped you significantly, you should accept it or upvote it. See the [tour] for more.
comment on: http://stackoverflow.com/a/47628869

http://stackoverflow.com/q/47618888
has answer: http://stackoverflow.com/a/58001216
has answer: http://stackoverflow.com/a/47619261
has answer: http://stackoverflow.com/a/47619176
has comment: http://stackoverflow.com/comment/82196072
downvote count: 1
favorite count: 0
tagged with: combinations
linked to: http://stackoverflow.com/q/43800390
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
has comment: http://stackoverflow.com/comment/82195851
possible better answer: http://stackoverflow.com/a/47619645
tagged with: python
has answer: http://stackoverflow.com/a/47619645
answer count: 4
upvote count: 13
has comment: http://stackoverflow.com/comment/82196117
score: 12
type: Question
has title: How generate all pairs of values, from the result of a groupby, in a pandas dataframe
has comment: http://stackoverflow.com/comment/82196012
has body: I have a pandas dataframe df: ID words 1 word1 1 word2 1 word3 2 word4 2 word5 3 word6 3 word7 3 word8 3 word9 I want to produce another dataframe that would generate all pairs of words in each group. So the result for the above would be: ID wordA wordB 1 word1 word2 1 word1 word3 1 word2 word3 2 word4 word5 3 word6 word7 3 word6 word8 3 word6 word9 3 word7 word8 3 word7 word9 3 word8 word9 I know that I can used df.groupby['words'] to get the words within each ID. I also know that I can use iterable = ['word1','word2','word3'] list(itertools.combinations(iterable, 2)) to get all possible pairwise combinations. However, I'm a little lost as to the best way to generate a resulting dataframe as shown above.
accepted answer: http://stackoverflow.com/a/47619176

http://stackoverflow.com/q/47615103
tagged with: python
has body: mydict = {'Papa': {12:{45: {'AG'}}}} mydict.append{'Papa':{21:{54:{'GA'}}}} print(mydict) {'Papa': {12:{45: {'AG'}}}, {21:{54:{'GA'}}}} How can I append a value into my dictionary so that one key can hold more than one value? In this case, I want the 'Papa' key to hold both nested dictionaries as values. And is there a way to do this without using update function or e? I don't know how to use them. I just wanna do it manually.
has title: Holding more than one value for a key in nested dictionary
score: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82188604
tagged with: key
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47615274
has comment: http://stackoverflow.com/comment/82188830

http://stackoverflow.com/q/47562155
has comment: http://stackoverflow.com/comment/82082233
favorite count: 0
has answer: http://stackoverflow.com/a/50070778
type: Question
tagged with: numpy
tagged with: adafruit
has comment: http://stackoverflow.com/comment/82082128
has title: Way to pipe or stream Array in Numpy/Scipy
accepted answer: http://stackoverflow.com/a/50070778
tagged with: python
type: AnsweredQuestion
has body: This is my specific use case to better explain the problem, but I'm looking for a generalized solution. I am using a Raspberry Pi with the adafruit LED display that displays an RGB matrix (this code is in Python 2). I have a python script that generates RGB data every 1/n seconds. Is there a package or library that allows me to continuously generate RGB data in the form of an np.ndarray in one process and have it be polled by the the matrix script so that it does near-real time interprocess communication of numpy arrays.
score: 1
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/82275587
type: QuestionComment
has text: What is your question? What is `j`? What you intend to do?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47657841

http://stackoverflow.com/comment/82325081
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47680073
score: 0
has text: Possible duplicate of [How do you remove duplicates from a list in whilst preserving order?](https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order)

http://stackoverflow.com/q/47585871
has comment: http://stackoverflow.com/comment/82130759
linked to: http://stackoverflow.com/q/29731726
has comment: http://stackoverflow.com/comment/82129728
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: blur
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49925278
has comment: http://stackoverflow.com/comment/82130406
has comment: http://stackoverflow.com/comment/82129660
has comment: http://stackoverflow.com/comment/82130028
score: 1
has answer: http://stackoverflow.com/a/49925278
has title: PSF (point spread function) for an image (2D)
has comment: http://stackoverflow.com/comment/82130913
tagged with: image-processing
has body: I'm new in image analysis (with Python) and I would like to apply the richardson_lucy deconvolution (from skimage) on my data (CT scans). For this reason, I estimated the PSF in "number of voxels" by means of a specific software. Its value is roughly 6.73 voxels, but I don't know how to use it as a paramter in the function. The function uses the PSF parameter as a ndarray, so I tried in this way: from skimage import io from pylab import array img = io.imread ("Slice1.tif") import skimage.restoration as rst PSF = array (6.7) img_dbl = rst.richardson_lucy (img, PSF, iterations=10) It shows me this error: IndexError: too many indices for array In CT scans, blurring between two different materials can be linked to a Gaussian PSF. If you have more tips for deblurring (maybe better than RL) just write them. Can any one please help me.
has comment: http://stackoverflow.com/comment/82130692
type: Question
tagged with: deconvolution
has comment: http://stackoverflow.com/comment/82129441

http://stackoverflow.com/comment/82280982
comment on: http://stackoverflow.com/q/47660954
has text: presumably used to generate this doc page https://www.tensorflow.org/api_guides/python/contrib.rnn#Base_interface_for_all_RNN_Cells
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82081630
has text: Can you please show more of the output, and the exact command that you typed?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47561804

http://stackoverflow.com/comment/82196442
has text: Have you tried commenting out code until you find the line that cause the problem?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47619145

http://stackoverflow.com/comment/82281452
comment on: http://stackoverflow.com/q/47661136
score: 0
type: Comment
type: QuestionComment
has text: From the suggested duplicate - `peopleList = sorted(peopleList, key=lambda x: x.firstname)` for example.

http://stackoverflow.com/a/47629506
type: AcceptedAnswer
has body: obs = {i+1: str(i*by+1)+':'+str((i+1)*by) for i in range(sessions)} Edited, Kyle: For the odd models it would seem wrapping a ceil the division will ensure we we do not go over the 'total_models' total_models=1000326 sessions=5 by=math.ceil(total_models/sessions) obs = {i+1: str(i*by+1)+':'+str(min((i+1)*by,total_models)) for i in range(sessions)}
accepted answer of: http://stackoverflow.com/q/47629406
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47629406
has comment: http://stackoverflow.com/comment/82217188
score: 5
downvote count: 0

http://stackoverflow.com/comment/82047644
type: AnswerComment
comment on: http://stackoverflow.com/a/47545241
type: Comment
has text: For sure, but is there an easier way to take the Cartesian product of two Series and turn it into a DataFrame with a custom function? Or is there a better method to approach this? Like I said, this was my "good-enough" approach, but I'd love to see a more refined answer.
score: 0

http://stackoverflow.com/q/47639165
type: Question
tagged with: replace
answer count: 2
has title: Removing items in list not corresponding to max value in another list
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47639246
downvote count: 0
has answer: http://stackoverflow.com/a/47639185
score: 3
tagged with: list
upvote count: 3
tagged with: python
has body: model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10'] As an example, models = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3] The maximum of the list is 0.3, which corresponds to model names 'im1' and 'im10'. I'd like the function dominant_model(models) to return ['im1', 'im10'] i.e, the most 'dominant' model(s). Here's my code which does the job, but I'd like to know if there's a shorter way of doing the same thing rather than all of the conditionals: def dominant_model(models): m = max(models) dom_models = [i for i,j in enumerate(models) if j==m] for i in range(len(dom_models)): if dom_models[i]==0: dom_models[i]=model_names[0] elif dom_models[i]==1: dom_models[i]=model_names[1] elif dom_models[i]==2: dom_models[i]=model_names[2] elif dom_models[i]==3: dom_models[i]=model_names[3] elif dom_models[i]==4: dom_models[i]=model_names[4] elif dom_models[i]==5: dom_models[i]=model_names[5] return dom_models
favorite count: 0

http://stackoverflow.com/a/47563670
downvote count: 0
upvote count: 1
has body: You could try waiting for a few ms to ensure the page has rendered and the expected element is visible with: time.sleep(1) Alternatively, try using IDs or custom data attributes to target the elements instead of xpath. Something like find_by_css_selector('.my_class') may work better.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47563515

http://stackoverflow.com/comment/82267378
type: Comment
has text: One is glad to be of service, sire.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47640849

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/47648747
tags question: http://stackoverflow.com/q/47571786
tags question: http://stackoverflow.com/q/47605387
tags question: http://stackoverflow.com/q/47541363
tags question: http://stackoverflow.com/q/47598442
tags question: http://stackoverflow.com/q/47573423
tags question: http://stackoverflow.com/q/47606406
tags question: http://stackoverflow.com/q/47559245
tags question: http://stackoverflow.com/q/47599637
tags question: http://stackoverflow.com/q/47674081
tags question: http://stackoverflow.com/q/47620498
tags question: http://stackoverflow.com/q/47667379
tags question: http://stackoverflow.com/q/47693595
tags question: http://stackoverflow.com/q/47663378
tags question: http://stackoverflow.com/q/47684182
tags question: http://stackoverflow.com/q/47679729
tags question: http://stackoverflow.com/q/47621619
tags question: http://stackoverflow.com/q/47647938
tags question: http://stackoverflow.com/q/47606002
tags question: http://stackoverflow.com/q/47574384
tags question: http://stackoverflow.com/q/47567325
tags question: http://stackoverflow.com/q/47549856
tags question: http://stackoverflow.com/q/47541295
tags question: http://stackoverflow.com/q/47557947
tags question: http://stackoverflow.com/q/47626696
tags question: http://stackoverflow.com/q/47560004
tags question: http://stackoverflow.com/q/47659675
tags question: http://stackoverflow.com/q/47573155
tags question: http://stackoverflow.com/q/47634093
tags question: http://stackoverflow.com/q/47673088
tags question: http://stackoverflow.com/q/47668709
tags question: http://stackoverflow.com/q/47548863
tags question: http://stackoverflow.com/q/47627918
tags question: http://stackoverflow.com/q/47646254
tags question: http://stackoverflow.com/q/47557040
tags question: http://stackoverflow.com/q/47558723
tags question: http://stackoverflow.com/q/47636968
tags question: http://stackoverflow.com/q/47584343
tags question: http://stackoverflow.com/q/47611721
tags question: http://stackoverflow.com/q/47614897
tags question: http://stackoverflow.com/q/47541320
tags question: http://stackoverflow.com/q/47542255
tags question: http://stackoverflow.com/q/47597866
tags question: http://stackoverflow.com/q/47653309
tags question: http://stackoverflow.com/q/47558176
tags question: http://stackoverflow.com/q/47601943
type: Tag
tags question: http://stackoverflow.com/q/47641197
tags question: http://stackoverflow.com/q/47650575
tag name: html
tags question: http://stackoverflow.com/q/47614973
tags question: http://stackoverflow.com/q/47554840
tags question: http://stackoverflow.com/q/47689160
tags question: http://stackoverflow.com/q/47596782
tags question: http://stackoverflow.com/q/47567666
tags question: http://stackoverflow.com/q/47550523
tags question: http://stackoverflow.com/q/47622029
tags question: http://stackoverflow.com/q/47639238
tags question: http://stackoverflow.com/q/47681102
tags question: http://stackoverflow.com/q/47561251
tags question: http://stackoverflow.com/q/47552417
tags question: http://stackoverflow.com/q/47646097
tags question: http://stackoverflow.com/q/47640441
tags question: http://stackoverflow.com/q/47679938
tags question: http://stackoverflow.com/q/47546923
tags question: http://stackoverflow.com/q/47648276
tags question: http://stackoverflow.com/q/47665289
tags question: http://stackoverflow.com/q/47565913
tags question: http://stackoverflow.com/q/47631081
tags question: http://stackoverflow.com/q/47606765
tags question: http://stackoverflow.com/q/47544194
tags question: http://stackoverflow.com/q/47605073
tags question: http://stackoverflow.com/q/47635162
tags question: http://stackoverflow.com/q/47612658

http://stackoverflow.com/comment/82351914
has text: Thanks. Hope I could have found it in documentation of python. :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47696111
score: 0
type: Comment

http://stackoverflow.com/a/47561321
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47558723
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47558723
has body: You will have to perform the click event in this case because the HTML does not contain the URL linked to the image -- it calls a script. What can be done is to use Selenium to click the element that contains the onclick event. from selenium.webdriver.chrome.options import Options from selenium import webdriver options = Options() options.add_argument('--disable-infobars') driver = webdriver.Chrome(chrome_options=options) div = find_element_by_id('cel_lisimg_18755') div.click() # Then wait for the page to load # Get the URL url = driver.current_url print(url) # Assumes v3 python
score: 1
type: Answer

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

http://stackoverflow.com/q/47550523
tagged with: cgi
tagged with: wordpress
score: 1
has title: wordpress on apache2 running python as cgi
has answer: http://stackoverflow.com/a/47554546
has answer: http://stackoverflow.com/a/71941053
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
has body: So here is what I want to do: On my Raspi a python program is running. On a wordpress site the current state of the program should be displayed and some configurations should be changeable. Here is the problem: Whenever I want to execute the python script, I get a 500 error code. It doesn't matter if I just want to display the value or change it. I'm new to html, cgi and apache, tried a lot but now I have no clue how to continue. I'd appreciate it a lot if someone could point me in the right direction. Here are my configurations: Apache: Edited the file /etc/apache2/apache2.conf: Options +ExecCGI +Indexes +FollowSymLinks AddHandler cgi-script .cgi .py AllowOverride None Require all granted AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Require all granted Options All I also ran sudo a2enmod cgi The webserver directory (/var/www/) looks like this: . ├── cgi-bin └── html ├── pma │ └── ... └── wordpress └── ... Wordpress: On a wordpress site, I go into the "text" mode and have the following html code: Curent Value: True (do automatic scan) False (do manual scan) Python files: The apfautostartval.py should just get the value from the config.ini and post it: #!/usr/bin/python3 import configparser import os import cgi, cgitb cgitb.enable() # Create config parser config = configparser.ConfigParser() configFilePath = os.path.join(os.path.sep,"home","pi",..., "config.ini") config.read(configFilePath) print("Content-type: text/html") print() print(" ") print(" ") print(" ") print(str(config['SETTINGS']["autoTest"])) print(" ") print(" ") And finally the apfcgi.py should receive the submitted new value and write it to the config.ini: #!/usr/bin/python3 import configparser import os import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() cgitb.enable() # Create config parser config = configparser.ConfigParser() configFilePath = os.path.join(os.path.sep,"home","pi",..., "config.ini") print("Content-type: text/html") print() print(" ")…
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/47586900
accepted answer: http://stackoverflow.com/a/47587061
favorite count: 0
has body: I am currently writing a script to read two columns of float numbers in a CSV file and find the average of each column. I do not understand why my code is giving me a ValueError I/O operation on closed file. My code has two open statements since to my understanding you must close the file and reopen it before adding and finding the average to a second column. My code is below, I appreciate any feedback I can get on this, It is not making sense to me. Thank you. Language: Python 3.6 def main(): import csv file = input("What is the name of the file, dont forget the .csv: ") INFILE = open(file,"r") totalCol1 = 0 countCol1 = 0 totalCol2 = 0 countCol2 = 0 read = csv.reader(INFILE,lineterminator=",") # Loop through column 1 for row in read: totalCol1 += float(row[0]) countCol1 += 1 averageCol1 = totalCol1 / countCol1 INFILE.close() INFILE = open(file,"r") for row in read: totalCol2 += float(row[1]) countCol2 += 1 averageCol2 = totalCol2 / countCol2 print('Average for Column One:%5.2f' % averageCol1) print('Average for Column Two:%5.2f' % averageCol2) INFILE.close() main()
type: AnsweredQuestion
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/82131709
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47587061
tagged with: valueerror
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82131453
upvote count: 1
has title: operation on closed csv file ValueError, Python Code

http://stackoverflow.com/q/47594244
has comment: http://stackoverflow.com/comment/82147383
has answer: http://stackoverflow.com/a/47595446
type: AnsweredQuestion
tagged with: plotly
tagged with: matplotlib
answer count: 1
downvote count: 3
linked to: http://stackoverflow.com/q/21654635
has comment: http://stackoverflow.com/comment/82145725
has body: I have a dataset having frequencies of observations. I am doing exploratory data analysis. Following is the sample. x1 x2 x3 x4 label 15 10 1 2 0 3 2 15 10 1 0 1 10 11 1 9 7 1 1 0 I want to plot a single plot using python that uses x1,x2....xn at x-axis and frequencies for every record at y axis but color codes the plot based on labels i.e blue for label 0 and red for label 1. Objective is to visualize if there is a relation between class label and values of variables. How to do that in python? Something like this. But it uses one variable on x-axis and another on y-axis. I want to use all variables on x-axis and their frequencies on Y-axis.
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/21654635
has comment: http://stackoverflow.com/comment/82147958
upvote count: 1
tagged with: python
has title: Color a plot of n variables based on class label
score: -2
accepted answer: http://stackoverflow.com/a/47595446

http://stackoverflow.com/comment/82179428
comment on: http://stackoverflow.com/a/47610451
score: 0
type: AnswerComment
has text: @JoeIddon My mistake, I made a typo.
type: Comment

http://stackoverflow.com/q/47561507
has title: How to fix this error: Could not convert string to float error with csv file
type: Question
has comment: http://stackoverflow.com/comment/82080736
has comment: http://stackoverflow.com/comment/82080714
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I am using a csv file and trying to take information to make a graph. Everything looks right until I try to plot the scatter plot and it gives me the error that it couldn't convert string to float. matrix=[] doors= [] import csv with open('9car.data.csv') as csvfile: M=csv.reader(csvfile, delimiter=',') for row in M: rowlist= [x for x in row] matrix.append(rowlist) for index in range(len(matrix)): if (index==0): pass else: doors.append((matrix[index][2])) import matplotlib.pyplot as plt from math import * import numpy as np from numpy import * n=1 a=np.arange(0,len(doors),n) y=[doors[int(x)] for x in a ] plt.scatter(a,y) plt.show()
tagged with: plot
has answer: http://stackoverflow.com/a/47561557
has comment: http://stackoverflow.com/comment/82080847
tagged with: http://stackoverflow.com/tag/csv
score: 0

http://stackoverflow.com/comment/82429034
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47563101
has text: Personally, I would figure out where the .lib file is located. Which linker are you using?
score: 0

http://stackoverflow.com/comment/82156530
has text: It loads it in the first time it is shown with the scroll, if you have a large number of images it would be advisable not to save it since it would cost a lot of ram, in this case I gave an intermediate solution
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47594740

http://stackoverflow.com/q/47623723
tagged with: python
has comment: http://stackoverflow.com/comment/82206097
has title: Numpy Problems with Arrays of poly1d Objects
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47624840
accepted answer: http://stackoverflow.com/a/47624840
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82206061
answer count: 1
tagged with: polynomials
favorite count: 0
type: Question
tagged with: numpy
has body: I'd like to first start this out with the fact that it is possible, in numpy, to create an array of poly1d objects: random_poly = np.frompyfunc(lambda i, j: np.poly1d(np.random.randint(1, 4, 3)), 2, 1) def random_poly_array(shape): return np.fromfunction(random_poly, shape) a1 = random_poly_array((3,3)) This works just fine, and we can even multiply matrices made from this form using np.dot: a2 = random_poly_array((3,3)) a1_x_a2 = np.dot(a1, a2) However, most other methods fail to work. For example, you can't take a list of certain poly1d objects and convert it into an array: np.array([np.poly1d([1,2,3]), np.poly1d([1,2,3])]) As that will raise ValueError: cannot copy sequence with size 2 to array axis with dimension 3. To add to the confusion, np.array([np.poly1d([1,2]), np.poly1d([1,2])]) will not raise an error, but instead create a 2x2 array of just 2's. Adding dtype=object has no affect, and numpy will still try to convert the poly1d objects to arrays. The reason why this is problematic is that one cannot take an array of dimension d and convert it to an array of poly1d objects of dimension d-1. I would have expected arr = np.arange(1, 10).reshape(3,3) np.apply_along_axis(np.poly1d, 0, arr) To return an array of poly1d objects, but instead it returns an unalterated array. Even worse, if arr=np.arange(9).reshape(3,3), it will throw an error, as the first poly1d object created will have a length of 2 instead of 3 due to the zero coefficient. Thus, my question is this: is there a feasible method to create poly1d arrays in numpy? If not, why not?
has comment: http://stackoverflow.com/comment/82206258
has comment: http://stackoverflow.com/comment/82207581
tagged with: arrays

http://stackoverflow.com/comment/82275780
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47658522
has text: @lPlant yes, car and rac should be 3 as well

http://stackoverflow.com/a/47672855
has comment: http://stackoverflow.com/comment/82305205
has comment: http://stackoverflow.com/comment/82304929
has comment: http://stackoverflow.com/comment/82305443
accepted answer of: http://stackoverflow.com/q/47672534
type: Answer
answers question: http://stackoverflow.com/q/47672534
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Remove the first plt.show() # plt.show() # remove this plt.plot([-6,2],[-6,4],"k-") plt.plot([5,0],[-6,4],"k-") plt.legend() plt.title('LDA of WINE dataset') plt.show() As soon as you call plt.show(), the plot is generated and all your code below this line will be ignored. Furthermore, change [0, 1, 2] to [1, 2, 3]: for c, i, target_name in zip("rgb", [1, 2, 3], target_names): plt.scatter(X_lda[y == i, 0], X_lda[y == i, 1], c=c, label=target_name) Now you get your desired output.

http://stackoverflow.com/comment/82189783
score: 2
type: Comment
has text: There's never a chance for one to be True and the other to be False, based on your code...
type: QuestionComment
comment on: http://stackoverflow.com/q/47615747

http://stackoverflow.com/comment/82165308
comment on: http://stackoverflow.com/q/47602922
type: Comment
score: 1
has text: Thanks a lot guys I've figured it out finally
type: QuestionComment

http://stackoverflow.com/q/47628122
has comment: http://stackoverflow.com/comment/82214171
score: 1
has title: Is it possible to read the data exchange between my computer and a usb device in python?
has comment: http://stackoverflow.com/comment/82214042
tagged with: usb
tagged with: python
has comment: http://stackoverflow.com/comment/82213807
tagged with: python-3.x
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82213949
type: UnansweredQuestion
has body: Hi there I'm new to python I am tasked to write a python program to read the data that is sending from my computer to USB devices like a flash drive. import win32com.client wmi = win32com.client.GetObject ("winmgmts:") for usb in wmi.InstancesOf ("Win32_USBHub"): print (usb.DeviceID) However other than identifying the devices that are connected. I can't read what is going out of the USB port. I understand it is possible to read it using a USB listener, is there any python library that is able to act as a USB listener?
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82283389
type: QuestionComment
has text: You might find some help in this thread: https://stackoverflow.com/q/30677241/3670871
comment on: http://stackoverflow.com/q/47661872
score: 0
type: Comment

http://stackoverflow.com/q/47558531
score: 0
has answer: http://stackoverflow.com/a/47563798
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82082257
has comment: http://stackoverflow.com/comment/82085605
tagged with: pywinauto
favorite count: 0
type: Question
answer count: 2
has body: When i use below pywinauto code, i am getting error saying from pywinauto.controls.win32_controls import ButtonWrapper checkbox = ButtonWrapper(app.Dialog.child_window(title='Has Balance',auto_id='HasBalanceCheckEdit',control_type='CheckBox').TCheckBox.WrapperObject()) print(checkbox.GetCheckState()) Error: raise MatchError(items = name_control_map.keys(), tofind = search_text) pywinauto.findbestmatch.MatchError: Could not find 'TCheckBox' in 'dict_keys(['Has Balance', 'Has BalanceStatic', 'Static'])'
has title: Get checkbox state and click accordingly using pywinauto
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82085580
has answer: http://stackoverflow.com/a/47677333
tagged with: python
has comment: http://stackoverflow.com/comment/82083487

object-detection
tags question: http://stackoverflow.com/q/47550498
tags question: http://stackoverflow.com/q/47627395
type: Tag
tag name: object-detection

http://stackoverflow.com/comment/82073399
type: Comment
type: QuestionComment
has text: Let me guess, 32bit build of Python?
score: 0
comment on: http://stackoverflow.com/q/47557810

http://stackoverflow.com/a/47661488
type: Answer
has comment: http://stackoverflow.com/comment/82287889
has comment: http://stackoverflow.com/comment/82282736
score: 1
accepted answer of: http://stackoverflow.com/q/47661149
type: AcceptedAnswer
upvote count: 1
has body: The problem is with this part: X = zoodatabase_v2.loc[1:101,'hair':'catsize'] Y = zoodatabase_v2.loc[0:6,'Class_Type':'Animal_Names'] X is a DataFrame with length 100 (1:101), and Y is a Series with length 6. To train a model (supervised learning), you need to give target labels for ALL input records. Also, you need to give a single target label, whereas currently it looks as if you are giving 2 ('Animal_Names' and 'Class_Type'). If you remove the subsetting, it should work. i.e. X = zoodatabase_v2.loc[:, 'hair':'catsize'] Y = zoodatabase_v2.loc[:, 'Class_Type'] should work fine.
answers question: http://stackoverflow.com/q/47661149
has comment: http://stackoverflow.com/comment/82283272
has comment: http://stackoverflow.com/comment/82282412
has comment: http://stackoverflow.com/comment/82286222
downvote count: 0

http://stackoverflow.com/q/47655898
duplicate of: http://stackoverflow.com/q/37771604
has answer: http://stackoverflow.com/a/47656007
has title: Selenium - compound class names not permitted
has body: I am trying to get all elements with a certain class name: theButtons = browser.find_elements_by_class_name("Icon Icon--medium Icon--reply"); However I get the error: Compound class names not permitted I understand that spaces are not allowed in the class name to get it, but then what should I do? Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82270153
tagged with: python
score: 0
answer count: 1
tagged with: selenium
linked to: http://stackoverflow.com/q/37771604
type: Question

http://stackoverflow.com/comment/82350466
has text: @AvikAggarwal Either you are doing something wrong or you think that it "refuses" to work (since it's obvious that it's working as my answer shows). Either way you will need to update your question with your exact code. Keep in mind that `map` **returns a new list (map object in Python 3)** and does **not** modify the provided iterable in-place.
score: 1
comment on: http://stackoverflow.com/a/47695093
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47551485
has comment: http://stackoverflow.com/comment/82061504
has comment: http://stackoverflow.com/comment/82061264
type: Answer
has comment: http://stackoverflow.com/comment/82062136
score: 0
answers question: http://stackoverflow.com/q/47551406
has comment: http://stackoverflow.com/comment/82062493
has comment: http://stackoverflow.com/comment/82063034
has body: Try running this: def fetch_skills(cleaned_resume=None): with open('skillsdata.csv', 'r') as skills: skill_set=[] for skill in skills: if skill in cleaned_resume: skill_set.append(skill) # Stripping newlines and tabs skill_set = [s.rstrip() for s in skill_set] return skill_set if __name__ == '__main__': inputfile = open('inputfile.txt', 'r') cleaned_resume = inputfile.read() skills = fetch_skills(cleaned_resume=cleaned_resume) print(skills)
has comment: http://stackoverflow.com/comment/82060132
has comment: http://stackoverflow.com/comment/82061293
has comment: http://stackoverflow.com/comment/82061028
has comment: http://stackoverflow.com/comment/82060696
has comment: http://stackoverflow.com/comment/82060489
has comment: http://stackoverflow.com/comment/82062235

http://stackoverflow.com/q/47653321
answer count: 2
linked to: http://stackoverflow.com/q/46431660
downvote count: 0
has comment: http://stackoverflow.com/comment/82265895
has answer: http://stackoverflow.com/a/47654154
favorite count: 0
has comment: http://stackoverflow.com/comment/82265950
accepted answer: http://stackoverflow.com/a/47654314
type: Question
possible better answer: http://stackoverflow.com/a/47654154
has answer: http://stackoverflow.com/a/47654314
tagged with: python
has title: Replace all None's in a Pandas data frame with a tuple of None's
has body: So I am working on some code for an NLP application. An interesting solution on Stackoverflow creates a dataframe from lists of unequal lengths. Taking the code from that solution with tuples in the input: import pandas as pd import itertools aa = [('aa1',4), ('aa2',3), ('aa3',2), ('aa4',2), ('aa5',1)] bb = [('bb1',8), ('bb2',6), ('bb3',4), ('bb4',4)] cc = [('cc1',3), ('cc2',2), ('cc3',1)] nest = [aa, bb, cc] df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc']) df you get a dataframe which looks like this: A subsequent step requires all elements in the data frame to be tuples. I have tried this: df.replace({None : (None,None)}) While it seems to run without error, it does not carry out any replacement. Any ideas how to accomplish this?
upvote count: 2
tagged with: pandas
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/82297544
comment on: http://stackoverflow.com/q/47669073
score: 0
type: Comment
type: QuestionComment
has text: That's a good idea ;)

http://stackoverflow.com/comment/82126263
has text: In pandas, dataframes rows all have the same number of columns. What you are describing here is not possible. Do some of the columns on some rows have NaN values?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47584263
type: QuestionComment

http://stackoverflow.com/a/47568438
answers question: http://stackoverflow.com/q/47568356
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: json.dumps automatically turn interger indexes to string indexes &gt;&gt;&gt; import json &gt;&gt;&gt; a = {'income': {'deciles': [10198.0, 25269.4, 31325.800000000003, 37857.0, 43721.8, 52880.0, 63996.0, 72526.9, 82388.2, 89765.90000000001, 99783.0], 'min': 10198.0, 'std': 24846.911384024643, 'quartiles': [35088.5, 78687.25], 'median': 52880.0, 'decile_event_rate': [0.6666666666666666, 0.6, 0.5333333333333333, 0.5666666666666667, 0.5, 0.6451612903225806, 0.4827586206896552, 0.5, 0.5666666666666667, 0.5], 'max': 99783.0, 'mean': 55621.78666666667}, 'age': {1: 25.0, 2: 50.25, 3: 50.0, 4: 75.0, 5: 14.580906789680968, 6: [25.0, 30.0, 34.800000000000004, 40.0, 46.60000000000001, 50.0, 56.0, 61.0, 65.0, 69.0, 75.0], 'quartiles': [38.0, 64.0], 'decile_event_rate': [0.8125, 0.7142857142857143, 0.65625, 0.42857142857142855, 0.45161290322580644, 0.4857142857142857, 0.5925925925925926, 0.5, 0.5142857142857142, 0.375]}, 'edu_yrs': {'deciles': [0.0, 2.0, 4.0, 7.0, 9.600000000000009, 13.0, 16.0, 18.0, 21.200000000000017, 23.0, 25.0], 'min': 0.0, 'std': 7.86234623342895, 'quartiles': [6.0, 20.0], 'median': 13.0, 'decile_event_rate': [0.5384615384615384, 0.6521739130434783, 0.5151515151515151, 0.48, 0.6111111111111112, 0.5, 0.5, 0.6071428571428571, 0.5151515151515151, 0.6666666666666666], 'max': 25.0, 'mean': 12.73}, 'security_label': {'var_type': 'categorical', 'freq': {'C': 100, 'A': 100, 'B': 100}, 'event_rate': {'C': {'0.0': 0.5, '1.0': 0.5}, 'A': {'0.0': 0.4, '1.0': 0.6}, 'B': {'0.0': 0.43, '1.0': 0.57}}}, 'yrs_since_exercise': {'deciles': [0.0, 3.0, 5.0, 8.0, 12.0, 16.0, 20.0, 25.0, 31.0, 41.0, 60.0], 'min': 0.0, 'std': 14.417527732194037, 'quartiles': [6.0, 27.0], 'median': 16.0, 'decile_event_rate': [1.0, 1.0, 1.0, 0.9629629629629629, 0.75, 0.4857142857142857, 0.15384615384615385, 0.06666666666666667, 0.0, 0.0], 'max': 60.0, 'mean': 18.566666666666666}} &gt;&gt;&gt; new = json.dumps(a) # as a json string &gt;&gt;&gt; new '{"income": {"deciles": [10198.0, 25269.4, 31325.800…

http://stackoverflow.com/comment/82085880
type: QuestionComment
comment on: http://stackoverflow.com/q/47559154
score: 3
type: Comment
has text: `parent`'s *columns* haven't been modified, but its *relationships* have, i.e. `parent.parent` [sic] now contains `child`, when you added `child` to the session.

raspberry-pi
tags question: http://stackoverflow.com/q/47662978
tags question: http://stackoverflow.com/q/47613459
tags question: http://stackoverflow.com/q/47643872
tags question: http://stackoverflow.com/q/47564997
tags question: http://stackoverflow.com/q/47607115
tags question: http://stackoverflow.com/q/47600597
tags question: http://stackoverflow.com/q/47601411
type: Tag
tags question: http://stackoverflow.com/q/47585704
tags question: http://stackoverflow.com/q/47692049
tags question: http://stackoverflow.com/q/47549294
tags question: http://stackoverflow.com/q/47681307
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/47677025
tags question: http://stackoverflow.com/q/47551383
tags question: http://stackoverflow.com/q/47543111
tags question: http://stackoverflow.com/q/47555482
tags question: http://stackoverflow.com/q/47560552
tags question: http://stackoverflow.com/q/47659325
tags question: http://stackoverflow.com/q/47660136
tags question: http://stackoverflow.com/q/47618170
tags question: http://stackoverflow.com/q/47659592
tags question: http://stackoverflow.com/q/47602086
tags question: http://stackoverflow.com/q/47549851

dictionary
tags question: http://stackoverflow.com/q/47645828
tags question: http://stackoverflow.com/q/47550585
tags question: http://stackoverflow.com/q/47632128
tags question: http://stackoverflow.com/q/47653484
tags question: http://stackoverflow.com/q/47637639
tags question: http://stackoverflow.com/q/47648886
tags question: http://stackoverflow.com/q/47649044
tags question: http://stackoverflow.com/q/47667885
tags question: http://stackoverflow.com/q/47603564
tags question: http://stackoverflow.com/q/47632044
tags question: http://stackoverflow.com/q/47661711
tags question: http://stackoverflow.com/q/47635507
tags question: http://stackoverflow.com/q/47683531
tags question: http://stackoverflow.com/q/47614580
tags question: http://stackoverflow.com/q/47687055
tags question: http://stackoverflow.com/q/47557740
tags question: http://stackoverflow.com/q/47561108
tags question: http://stackoverflow.com/q/47655958
tags question: http://stackoverflow.com/q/47634921
tags question: http://stackoverflow.com/q/47688909
tags question: http://stackoverflow.com/q/47559191
tags question: http://stackoverflow.com/q/47544993
tags question: http://stackoverflow.com/q/47582940
tags question: http://stackoverflow.com/q/47666466
tags question: http://stackoverflow.com/q/47642398
tags question: http://stackoverflow.com/q/47626542
tags question: http://stackoverflow.com/q/47588649
tags question: http://stackoverflow.com/q/47560685
tags question: http://stackoverflow.com/q/47676919
tags question: http://stackoverflow.com/q/47663285
tags question: http://stackoverflow.com/q/47553778
tags question: http://stackoverflow.com/q/47684009
tags question: http://stackoverflow.com/q/47564712
tags question: http://stackoverflow.com/q/47678665
tags question: http://stackoverflow.com/q/47616188
tags question: http://stackoverflow.com/q/47603880
tags question: http://stackoverflow.com/q/47554060
tags question: http://stackoverflow.com/q/47568197
tags question: http://stackoverflow.com/q/47685573
tags question: http://stackoverflow.com/q/47678389
tags question: http://stackoverflow.com/q/47585705
tags question: http://stackoverflow.com/q/47669151
tags question: http://stackoverflow.com/q/47629406
tags question: http://stackoverflow.com/q/47679770
tags question: http://stackoverflow.com/q/47565417
tags question: http://stackoverflow.com/q/47606995
tags question: http://stackoverflow.com/q/47581791
tags question: http://stackoverflow.com/q/47604132
tags question: http://stackoverflow.com/q/47568211
tags question: http://stackoverflow.com/q/47585007
tags question: http://stackoverflow.com/q/47674708
tags question: http://stackoverflow.com/q/47620588
tags question: http://stackoverflow.com/q/47641332
tags question: http://stackoverflow.com/q/47662610
tags question: http://stackoverflow.com/q/47629640
tags question: http://stackoverflow.com/q/47563682
tags question: http://stackoverflow.com/q/47616191
tags question: http://stackoverflow.com/q/47622665
tags question: http://stackoverflow.com/q/47663809
tags question: http://stackoverflow.com/q/47581188
tags question: http://stackoverflow.com/q/47587713
tags question: http://stackoverflow.com/q/47544804
tags question: http://stackoverflow.com/q/47585566
tags question: http://stackoverflow.com/q/47565786
tags question: http://stackoverflow.com/q/47610423
tags question: http://stackoverflow.com/q/47638583
tags question: http://stackoverflow.com/q/47568356
tags question: http://stackoverflow.com/q/47612928
tags question: http://stackoverflow.com/q/47651925
tags question: http://stackoverflow.com/q/47557594
tags question: http://stackoverflow.com/q/47623398
tags question: http://stackoverflow.com/q/47638952
tags question: http://stackoverflow.com/q/47627477
tags question: http://stackoverflow.com/q/47582475
tags question: http://stackoverflow.com/q/47598311
tags question: http://stackoverflow.com/q/47659483
tags question: http://stackoverflow.com/q/47683349
tags question: http://stackoverflow.com/q/47619946
tags question: http://stackoverflow.com/q/47645484
tags question: http://stackoverflow.com/q/47566201

http://stackoverflow.com/comment/82063630
has text: Yep, I also think so.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47553322
type: Comment

django-templates
tags question: http://stackoverflow.com/q/47581167
tags question: http://stackoverflow.com/q/47671389
tags question: http://stackoverflow.com/q/47644824
tags question: http://stackoverflow.com/q/47570493
tags question: http://stackoverflow.com/q/47561693
tags question: http://stackoverflow.com/q/47578556
tag name: django-templates
tags question: http://stackoverflow.com/q/47630449
tags question: http://stackoverflow.com/q/47693834
tags question: http://stackoverflow.com/q/47597866
type: Tag
tags question: http://stackoverflow.com/q/47650575

http://stackoverflow.com/comment/82048287
type: AnswerComment
comment on: http://stackoverflow.com/a/47545662
score: 0
has text: thank you :) I've got now to learn about parameterised queries :p as I want the proper and recommended solution. and the second solution with %s gave me a weird .decode socket error
type: Comment

http://stackoverflow.com/comment/82318984
type: QuestionComment
score: 0
has text: sounds like the sql is bad. The error you're getting is usually associated with the parser not finding the end of the file where it expected. In this case it sounds like the SQL is indicating that the last command was reached but python is detecting that there are more commands in the file.
type: Comment
comment on: http://stackoverflow.com/q/47679719

http://stackoverflow.com/q/47695549
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47700737
has body: So, before anyone tells me about the flat structure of S3, I already know, but the fact is you can create 'folders' in S3. My objective with this Python code is to create a new folder named using the date of running and appending the user's input to this (which is the createS3Folder function) - I then want to sync a folder in a local directory to this folder. The problem is that my upload_files function creates a new folder in S3 that exactly emulates the folder structure of my local set up. Can anyone suggest how I would just sync the folder into the newly created one without changing names? import sys import boto3 import datetime import os teamName = raw_input("Please enter the name of your project: ") bucketFolderName = "" def createS3Folder(): date = datetime.date.today().strftime("%Y") + "." + datetime.date.today().strftime("%B") + "." + datetime.date.today().strftime("%d") date1 = datetime.date.today() date = str(date1) + "/" #In order to generate a file, you must put "/" at the end of key bucketFolderName = date + teamName + "/" client = boto3.client('s3') client.put_object(Bucket='MY_BUCKET',Key=bucketFolderName) upload_files('/Users/local/directory/to/sync') def upload_files(path): session = boto3.Session() s3 = session.resource('s3') bucket = s3.Bucket('MY_BUCKET') for subdir, dirs, files in os.walk(path): for file in files: full_path = os.path.join(subdir, file) with open(full_path, 'rb') as data: bucket.put_object(Key=bucketFolderName, Body=data) def main(): createS3Folder() if __name__ == "__main__": main()
answer count: 2
tagged with: amazon-s3
score: 1
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/47700737
favorite count: 0
type: Question
has title: Boto3 folder sync under new S3 'folder'
accepted answer: http://stackoverflow.com/a/47705466
has answer: http://stackoverflow.com/a/47705466

http://stackoverflow.com/comment/82220143
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47630462
type: Comment
has text: HI @PicoutputCls, thanks for your reply. I've added the details to my initial post.

http://stackoverflow.com/comment/82162177
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47601376
has text: Thank you. Rolling is what I needed indeed. I shall look up documentation more before posting next time.

http://stackoverflow.com/q/47566955
score: 0
tagged with: installation
has comment: http://stackoverflow.com/comment/82096918
answer count: 1
accepted answer: http://stackoverflow.com/a/48032142
type: Question
has comment: http://stackoverflow.com/comment/83034386
has answer: http://stackoverflow.com/a/48032142
has body: I want to install 'pygame' library in Ubuntu 14.04 with Anaconda Python 3.6 environment. Anyone can do this? I have tried these methods: conda install -c cogsci pygame conda install -c tlatorre pygame=1.9.2 sudo apt-get install pygame
tagged with: python
tagged with: pygame
tagged with: ubuntu
has title: How to install pygame in Ubuntu 14.04 64bit with Anaconda Python 3.6
has comment: http://stackoverflow.com/comment/82091690
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82097119

http://stackoverflow.com/q/47616586
accepted answer: http://stackoverflow.com/a/47616922
tagged with: python
tagged with: deployment
answer count: 4
upvote count: 8
score: 8
tagged with: gunicorn
has answer: http://stackoverflow.com/a/53691005
downvote count: 0
has title: Gunicorn/Django, ImportError: No module named application.wsgi
tagged with: django
has answer: http://stackoverflow.com/a/75252259
favorite count: 0
type: Question
has body: I'm trying to deploy a Django app using Heroku, but I'm running into the following error: "ImportError: No module named myproject.wsgi". My project is configured as such: my-project │ Procfile │ requirements.txt │ runtime.txt │ README.md │ ├───myproject │ │ db.sqlite3 │ │ django │ │ django._file_ │ │ import │ │ manage.py | | │ ├───myproject | | | wsgi.py | | | settings.py | | | urls.py | | | _init_.py | | | | | ├───_pycache_ | | │ ├───venv ... My wgsi.py file is configured as such: import os import signal import sys import traceback import time from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) My Procfile contains the following: web: gunicorn myproject.wsgi:application --log-file - Why is this producing an error?
has answer: http://stackoverflow.com/a/61736064
possible better answer: http://stackoverflow.com/a/61736064
tagged with: heroku
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47616922

http://stackoverflow.com/q/47650139
has body: I have multiple instances of a services. This service access a collection of unprocessed document. We are using MongoDB. The role of service is : Fetch the first unprocessed document from collection A. Make a Rest call using uuid. Get the response and store the response in another collection B. Multiple service may access the same document leading to duplicate. The steps which I can think to deal with this situation: FindandModify() along with progress field. So we will call this function with query of progress field to be "0". We will update the value to 1 so other services can not access it. On getting the success from Rest call we can delete the record. On getting the failure we will again call the FindandModify() with update value to be "0" so other service can access at later time. We we call Find() function which will give us one document. We get the "_id" of the document and store it into another collection. If another service also gets the same document and that document "_id" is already present. Then it will not be insert again and that service again call Find() function. What would be the performance and bottleneck of these approaches. Also do we have any other better approach which will enhance the performance.
answer count: 1
has comment: http://stackoverflow.com/comment/82259363
tagged with: mongodb
has title: Prevent multiple service access same document in MongoDB till processing is done
type: Question
tagged with: microservices
has answer: http://stackoverflow.com/a/47653516
tagged with: python
type: UnansweredQuestion
tagged with: mongodb-query
tagged with: nosql
score: 0

http://stackoverflow.com/q/47583175
has title: Python Curve_Fit with Bars
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/82130172
has body: We are given Ic values that are mA range and of the order of magnitude .1~2 mA and there is a Gaussian distribution among them as the Magnetic Field is swept from -1500 t0 1500. I found this Curve_Fitting code through Python documentation that does the fit, but was wondering if it is possible to do curve fitting for Bars in Python? def func(x, I, CorrectedBitSize, Lambda, M): return I * abs( 2 * sp.jv(1, ( (float(CorrectedBitSize) * ( 2 * abs(Lambda) + 2 * dN + dF) * (x + M)) / (phi0 * math.pow(10, 10)))) / ( (float(CorrectedBitSize) * ( 2 * Lambda + 2 * dN + dF) * (x + M)) / (phi0 * math.pow(10, 10)) ) ) dF = 2 * math.pow(10, -9) # thickness dN = 5 * math.pow(10, -9) # thickness mu0 = 4 * math.pi * math.pow(10, -7) # constant phi0 = 6.62607 * math.pow(10, -34) / (2 * 1.6 * math.pow(10, -19)) Ic_Bins_pos = np.array(random); Ic_Bins_Field_Pos = np.array(-1500, 1500) Lambda = (0.00000009) best_vals, covar = curve_fit(func, Ic_Bins_Field_pos, Ic_Bins_pos, sigma=.2) # popt, pcov = leastsq(func, Ic_Bins_Field_pos, Ic_Bins_pos) y = func(Ic_Bins_Field_pos, *best_vals) x = np.linspace(-1500, 1500, len(y)) y_noise = 0.2 * x yfit = y_noise + y plt.plot(Ic_Bins_Field_pos, yfit, c='g') # plt.show()
score: 0
has comment: http://stackoverflow.com/comment/82124364

http://stackoverflow.com/comment/122127463
comment on: http://stackoverflow.com/a/47576699
type: AnswerComment
score: 0
has text: you have to ensure that you use the statement "import matplotlib.pyplot as plt" in your cell for this to work. if you are calling a function that will plot the graph, then ensure that you use the statement inside the function's definition
type: Comment

http://stackoverflow.com/q/47572165
tagged with: python
has answer: http://stackoverflow.com/a/47572225
tagged with: pathlib
upvote count: 24
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47572467
possible better answer: http://stackoverflow.com/a/47572467
score: 23
downvote count: 1
favorite count: 0
type: Question
has title: What's the best way to add a trailing slash to a pathlib directory?
has answer: http://stackoverflow.com/a/47572715
accepted answer: http://stackoverflow.com/a/47572715
has body: I have a directory I'd like to print out with a trailing slash: my_path = pathlib.Path('abc/def') Is there a nicer way of doing this than os.path.join(str(my_path), '')?

http://stackoverflow.com/a/47658597
downvote count: 1
score: 16
upvote count: 17
has body: One workaround to this issue is to explicitly launch LLDB with only the system Python installation on the PATH, e.g. PATH=/usr/bin /usr/bin/lldb It appears as though LLDB queries the PATH for the 'active' Python installation; if you have a Homebrew installation of Python available on the PATH then you can run into this sort of cross-talk when LLDB attempts to launch Python.
has comment: http://stackoverflow.com/comment/82290170
type: Answer
has comment: http://stackoverflow.com/comment/95581260
has comment: http://stackoverflow.com/comment/89515391
answers question: http://stackoverflow.com/q/47658596

http://stackoverflow.com/comment/82154583
comment on: http://stackoverflow.com/q/47587081
has text: @mkaran - ok I will try with the suggestions. Shall update. Thanks
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82185862
comment on: http://stackoverflow.com/q/47613053
score: 0
type: Comment
type: QuestionComment
has text: (1) You should (almost) never inverse sparse-matrices. Always try to use the Ax=b approach (2) Without specifying the matrix, it's hard too chose a library (indefinite?, psd? symmetric? square?) (3) There is more than mumps. scipy's superlu is in many many cases a viable candidate, much easier to use and tested by many people. The differences in regards to mumps and superlu are mostly based on point 2.

http://stackoverflow.com/a/47695485
type: Answer
answers question: http://stackoverflow.com/q/47695453
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82350443
has comment: http://stackoverflow.com/comment/82351327
has comment: http://stackoverflow.com/comment/82351168
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82351572
has comment: http://stackoverflow.com/comment/82350485
has body: You need split: df'value_left','value_right' = df['value_1'].str.split(';', expand=True) print (df) value_1 value_left \ 0 over 1 - 42 -&gt; take this ; over 3 - 4 over 1 - 42 -&gt; take this 1 over 3 - 26 -&gt; take this ; over 3 - 45 over 3 - 26 -&gt; take this 2 over 5 - 25 -&gt; take this ; over 2 - 80 over 5 - 25 -&gt; take this value_right 0 over 3 - 4 1 over 3 - 45 2 over 2 - 80 Sample for multiple ; - is possible specify which ; is used for split: df = pd.DataFrame({ 'value_1': ['a;r;e','b;r','c;g;t;e'] }) print (df) value_1 0 a;r;e 1 b;r 2 c;g;t;e df'value_left','value_right' = df['value_1'].str.split(';', expand=True, n=1) print (df) value_1 value_left value_right 0 a;r;e a r;e 1 b;r b r 2 c;g;t;e c g;t;e
accepted answer of: http://stackoverflow.com/q/47695453

attributes
tags question: http://stackoverflow.com/q/47654548
tags question: http://stackoverflow.com/q/47645024
tags question: http://stackoverflow.com/q/47695462
tag name: attributes
tags question: http://stackoverflow.com/q/47657089
tags question: http://stackoverflow.com/q/47583986
tags question: http://stackoverflow.com/q/47608523
tags question: http://stackoverflow.com/q/47581331
tags question: http://stackoverflow.com/q/47560837
tags question: http://stackoverflow.com/q/47677241
type: Tag
tags question: http://stackoverflow.com/q/47634894

http://stackoverflow.com/comment/82118588
has text: Hi, I find the 191 line the same as you said in another convert_matrix.py.(I don't know why I have 2 files named convert_matrix.py). And I changed it as you said but it still not works......
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47569594
type: Comment

http://stackoverflow.com/a/47846712
has body: This is the code after fixing the error import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential column_names = ['Date', 'Time', 'Open', 'High', 'Low','Close', 'Volume'] df = pd.read_csv(r"E:\Tutorial\EURUSD60.csv", header=None, names=column_names) df['DateTime'] = pd.to_datetime(df.Date + ' ' + df.Time) del df['Date'] del df['Time'] df.rename(columns={'DateTime': 'timestamp', 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume'}, inplace=True) df['timestamp'] = pd.to_datetime(df['timestamp'], infer_datetime_format=True) df.set_index('timestamp', inplace=True) df = df.astype(float) df['hour'] = df.index.hour df['day'] = df.index.weekday df['week'] = df.index.week sequence_length = 21 n_features = len(df.columns) val_ratio = 0.1 n_epochs = 300 batch_size = 512 data = df.as_matrix() data_processed = [] for index in range(len(data) - sequence_length): data_processed.append(data[index: index + sequence_length]) data_processed = np.array(data_processed) val_split = round((1 - val_ratio) * data_processed.shape[0]) train = data_processed[: int(val_split), :] val = data_processed[int(val_split):, :] print('Training data: {}'.format(train.shape)) print('Validation data: {}'.format(val.shape)) train_samples, train_nx, train_ny = train.shape val_samples, val_nx, val_ny = val.shape train = train.reshape((train_samples, train_nx * train_ny)) val = val.reshape((val_samples, val_nx * val_ny)) preprocessor = MinMaxScaler().fit(train) train = preprocessor.transform(train) val = preprocessor.transform(val) train = train.reshape((train_samples, train_nx, train_ny)) val = val.reshape((val_samples, val_nx, val_ny)) X_train = train[:, : -1] y_train = train[:, -1][:, -1] X_val = val[:, : -1] y_val = val[:, -1][:, -1] X_train = np.reshape(X_train, (X_train.shape[0], X_t…
accepted answer of: http://stackoverflow.com/q/47617920
type: Answer
answers question: http://stackoverflow.com/q/47617920
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82341235
type: Comment
has text: Sorry, what I mean is because the question above seems so trivial (of course `x = 3; x=4; print x` prints 4 not 3; same with `CS=...; CS=...; colorbar(CS)`) I was thinking that the real question was "how to make a filled colorbar from contour" which would be misplaced in an answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47682952

http://stackoverflow.com/comment/82116641
has text: Sure - but I'm looking for a way to do this in a single statement.
type: Comment
comment on: http://stackoverflow.com/a/47579532
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82187230
type: Comment
comment on: http://stackoverflow.com/q/47614316
score: 0
type: QuestionComment
has text: @AK47 Yes, that's a good method, worth an upvote (I never even thought about `eval()`! Ususally I avoid it like the plague, but this might be a real application for it!)

http://stackoverflow.com/a/47552674
has comment: http://stackoverflow.com/comment/82063141
answers question: http://stackoverflow.com/q/47550831
has comment: http://stackoverflow.com/comment/82062928
has comment: http://stackoverflow.com/comment/82062516
has body: Not a one-liner, because you have to identify the shorter list first. If you always know, that note has less elements than mag, then you can skip this test. a = [note, mag][len(mag) &gt; len(note)] #more list elements b = [note, mag][mag != a] #less list elements print(all([a.count(item) &gt;= b.count(item) for item in set(b)])) Output mag =['two', 'times', 'three', 'is', 'not', 'four', 'two'] note =['two', 'times', 'two', 'is', 'four'] &gt;&gt;&gt;True mag =['two', 'times', 'three', 'is', 'not', 'five'] note =['two', 'times', 'two', 'is', 'four'] &gt;&gt;&gt;False
score: 0
has comment: http://stackoverflow.com/comment/82062186
type: Answer

http://stackoverflow.com/q/47658365
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82279420
favorite count: 0
type: Question
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82281642
has title: Camera Pose Estimation With OpenCV and Python
tagged with: python
tagged with: computer-vision
has body: I'm trying to use OpenCV with python to track camera pose in a video stream. I have a sample of code that determines the pose between two images as a test environment. The overall flow here is this: Read in the images and convert to gray/resize. Extract features with cv2 goodfeaturestotrack from both images. Use cv2 calcOpticalFlowPyrLK to find matching points. Convert the p1 points (starting image) to (x,y,z) with z for all points set as 0. Resolve cv2 PnPRansac to get the rotation and translation vectors. Convert angles from radians to degrees. def function(mtx,dist): #feature dictionary feature_params = dict( maxCorners = 1000, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) lk_params = dict( winSize = (15,15), maxLevel = 2, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) #image 1 image_1=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg") image_1=cv2.resize(image_1,(640,480)) gray_1=cv2.cvtColor(image_1,cv2.COLOR_BGR2GRAY) p1=cv2.goodFeaturesToTrack(gray, mask = None, **feature_params) #image read in image_2=cv2.imread("/Users/user/Desktop/Test_images/Test_image.jpg") image_2=cv2.resize(image_2,(640,480)) gray_2 = cv2.cvtColor(image_2,cv2.COLOR_BGR2GRAY) p2, st, err = cv2.calcOpticalFlowPyrLK(gray_1, gray_2, p1, None, **lk_params) #convert the old points to 3d zeros=np.zeros([len(p1),1],dtype=np.float) old_3d=np.dstack((p1, zeros)) #get rotational and translation vector blank,rvecs, tvecs, inliers = cv2.solvePnPRansac(old_3d, p2, mtx, dist) rad=180/math.pi roll=rvecs[0]*rad pitch=rvecs[1]*rad yaw=rvecs[2]*rad print(roll) print(pitch) print(yaw) print(tvecs) function(mtx,dist) rvec (roll, pitch and yaw) [ 0.35305807] [ 2.95965708] [ 0.10954427] tvec (x,y,x ???) [[ -668.42397254] [ -387.32180857] [ 1180.94652875]] Given the fact that I am using exactly the same image to run this sample calculation I was expecting rotation and translation vectors to be very close to zero. However they are quite high, take a look at the sample o…
has answer: http://stackoverflow.com/a/47667684
tagged with: opticalflow

http://stackoverflow.com/comment/82080358
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47560859
type: Comment
has text: You should try looking in your SLOWLOG for identifying slow-running commands. Also, consider upgrading your Redis version - later versions pack optimizations in the List domain. That said, none of the operations you've mentioned should cause so much stress on the CPU.

http://stackoverflow.com/comment/82194898
has text: so how i'll extract the slug values of this `<Upload: 33-bb6f5d9a98604450>`....here Upload is model name and ` 33-bb6f5d9a98604450` is slug ......kindly help me
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47618329

http://stackoverflow.com/q/47638644
has answer: http://stackoverflow.com/a/47640235
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: Whenever I run this code I get an error saying "Error %s % e INSERT has more target columns than expressions" with a ^ showing under fthg. Any idea what the issue is here, considering fthg is already defined? Many thanks! cur.execute("CREATE TABLE IF NOT EXISTS soccerleague.games (gameId SERIAL PRIMARY KEY, homeTeamId INTEGER, FOREIGN KEY (homeTeamId) REFERENCES soccerleague.teams(id),awayTeamId INTEGER, FOREIGN KEY (awayTeamId) REFERENCES soccerleague.teams(id), fthg INTEGER, athg INTEGER, ftr VARCHAR, refereeId INTEGER, FOREIGN KEY (refereeId) REFERENCES soccerleague.referees(id), HY INTEGER, AY INTEGER)") data3 = (teamsDict[homeTeam], teamsDict[awayTeam], fthg, athg, ftr, refereesDict[refereeName], hy, ay) query3 = "INSERT INTO soccerleague.games (homeTeamId, awayTeamId, fthg, athg, ftr, refereeId, hy, ay) VALUES" query3 += "('" + str(data3) + "', '" + x + "')," query3 = query3[:-1] + ";"
has title: Postgres error “ERROR: INSERT has more target columns than expressions”
favorite count: 0
type: Question
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/47640235
tagged with: python

http://stackoverflow.com/a/47681316
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47663883
has comment: http://stackoverflow.com/comment/82322954
answers question: http://stackoverflow.com/q/47663883
score: 1
type: Answer
has body: I was doing tips = sns.load_dataset("df") as per the documentation, but this is nothing more than a Seaborn way of pulling data from csv on their server. Simply stating data=df inside barplot() extracts data from my DF.. The apply function I added is for unique counts instead of just count. df=df.groupby(['channel'])['Id'].apply(lambda x:len(x.unique())).reset_index() print(df) sns.set(style='darkgrid') sns.barplot(x='channel', y='Id', data=df, palette='Set2') plt.show() --Edit to order by count desc, I suggest doing something like this: result = df.sort_values('Id',ascending=False) sns.barplot(x='channel', y='id', data=result, palette='Set2')
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47622849
has body: You should define the function before using it. You are calling functions before they are defined. Also the calls to them (e.g. level1()) after them is not needed. You may also move the imports at the begging of the file, and remove them from each function. You may also use an IDE, for example PyCharm. def level1(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(1, 10) num_b = random.randint(1, 10) op = random.choice(tuple(ops.keys())) print('{}{}{}=?'.format(num_a, op, num_b)) expected_answer = ops[op](num_a, num_b) user_answer = int(input()) if user_answer == expected_answer: print('Correct') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) else: print('Wrong') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) while user_answer == expected_answer: level1() else: exit() def level2(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(10, 50) num_b = random.randint(10, 50) op = random.choice(tuple(ops.keys())) print('{}{}{}=?'.format(num_a, op, num_b)) expected_answer = ops[op](num_a, num_b) user_answer = int(input()) if user_answer == expected_answer: print('Correct') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) else: print('Wrong') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) while user_answer == expected_answer: level2() else: exit() def level3(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(50, 100) num_b = random.randint(50, 100) op = random.choice(tuple(ops.keys())) print('{}{}{}=?'.format(num_a, op, num_b)) expected_answer = ops[op](num_a, num_b) user_answer = int(input()) if user_answer == expected_answer: print('Correct') print('It took you {0:0.1f} s…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82204215
type: Answer
accepted answer of: http://stackoverflow.com/q/47622186
has comment: http://stackoverflow.com/comment/82204021
answers question: http://stackoverflow.com/q/47622186
score: 0

http://stackoverflow.com/comment/82199859
type: AnswerComment
has text: All ones e.g. `[1, 1, 1]` returns `0` when `3` expected. Add `m = max(c, m)` after the loop
comment on: http://stackoverflow.com/a/47620646
type: Comment
score: 0

http://stackoverflow.com/comment/82244299
type: Comment
type: AnswerComment
has text: @LeonardShaw, please see UPDATE section
score: 0
comment on: http://stackoverflow.com/a/47641768

http://stackoverflow.com/comment/82319355
comment on: http://stackoverflow.com/q/47679139
has text: Python 3.5.3 Also is this echo being executed from a script or are you pasting this into command line?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47579855
type: Answer
accepted answer of: http://stackoverflow.com/q/47579701
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47579701
type: AcceptedAnswer
has body: Maybe you want .where() select([column['name']]).select_from(func.func_name(*vars)).where(column["colname"]=="val") Relevant docs here.

http://stackoverflow.com/a/47872706
score: 2
accepted answer of: http://stackoverflow.com/q/47651881
upvote count: 3
type: AcceptedAnswer
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47651881
has comment: http://stackoverflow.com/comment/96249410
has body: In the end I found multiple ways to solve this problem: Simply having adding /?token=77c1f767bc31859fee1ffe041343fa48&amp;allowcookies=ACCEPTEER+ALLE+COOKIES to the start url worked for this specific case I later switched to a CrawlSpider instead of a normal Spider, then I could add the xpath of the cookie button as the first rule. Clicking the button using the earlier mentioned Selenium also worked, but is a lot of hassle that is not really necessary...

http://stackoverflow.com/comment/82196109
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47619038
type: Comment
has text: This does not provide enough info to answer. What are you doing? Please provide some sample of your code...

list
tags question: http://stackoverflow.com/q/47604621
tags question: http://stackoverflow.com/q/47639983
tags question: http://stackoverflow.com/q/47622065
tags question: http://stackoverflow.com/q/47664102
type: Tag
tags question: http://stackoverflow.com/q/47562411
tags question: http://stackoverflow.com/q/47560859
tags question: http://stackoverflow.com/q/47627896
tags question: http://stackoverflow.com/q/47663040
tags question: http://stackoverflow.com/q/47562434
tags question: http://stackoverflow.com/q/47617045
tags question: http://stackoverflow.com/q/47585163
tags question: http://stackoverflow.com/q/47620972
tags question: http://stackoverflow.com/q/47608315
tags question: http://stackoverflow.com/q/47602645
tags question: http://stackoverflow.com/q/47695455
tags question: http://stackoverflow.com/q/47618379
tags question: http://stackoverflow.com/q/47672176
tags question: http://stackoverflow.com/q/47645501
tags question: http://stackoverflow.com/q/47673421
tags question: http://stackoverflow.com/q/47678665
tags question: http://stackoverflow.com/q/47616188
tags question: http://stackoverflow.com/q/47581700
tags question: http://stackoverflow.com/q/47686473
tags question: http://stackoverflow.com/q/47576775
tags question: http://stackoverflow.com/q/47675444
tags question: http://stackoverflow.com/q/47566910
tags question: http://stackoverflow.com/q/47602922
tags question: http://stackoverflow.com/q/47598760
tags question: http://stackoverflow.com/q/47634525
tags question: http://stackoverflow.com/q/47628807
tags question: http://stackoverflow.com/q/47642388
tags question: http://stackoverflow.com/q/47594300
tags question: http://stackoverflow.com/q/47681601
tags question: http://stackoverflow.com/q/47612733
tags question: http://stackoverflow.com/q/47559551
tags question: http://stackoverflow.com/q/47636305
tags question: http://stackoverflow.com/q/47685195
tags question: http://stackoverflow.com/q/47581791
tags question: http://stackoverflow.com/q/47604132
tags question: http://stackoverflow.com/q/47653632
tags question: http://stackoverflow.com/q/47621607
tags question: http://stackoverflow.com/q/47606495
tags question: http://stackoverflow.com/q/47643961
tags question: http://stackoverflow.com/q/47597058
tags question: http://stackoverflow.com/q/47660331
tags question: http://stackoverflow.com/q/47659017
tags question: http://stackoverflow.com/q/47565786
tags question: http://stackoverflow.com/q/47548749
tags question: http://stackoverflow.com/q/47617486
tags question: http://stackoverflow.com/q/47638583
tags question: http://stackoverflow.com/q/47663911
tags question: http://stackoverflow.com/q/47613403
tags question: http://stackoverflow.com/q/47678352
tags question: http://stackoverflow.com/q/47561204
tags question: http://stackoverflow.com/q/47666687
tags question: http://stackoverflow.com/q/47623398
tags question: http://stackoverflow.com/q/47598716
tags question: http://stackoverflow.com/q/47564206
tags question: http://stackoverflow.com/q/47584845
tags question: http://stackoverflow.com/q/47596837
tags question: http://stackoverflow.com/q/47605884
tags question: http://stackoverflow.com/q/47614316
tags question: http://stackoverflow.com/q/47575837
tags question: http://stackoverflow.com/q/47656153
tags question: http://stackoverflow.com/q/47627477
tags question: http://stackoverflow.com/q/47621511
tags question: http://stackoverflow.com/q/47642737
tags question: http://stackoverflow.com/q/47614538
tags question: http://stackoverflow.com/q/47688235
tags question: http://stackoverflow.com/q/47565780
tags question: http://stackoverflow.com/q/47683265
tags question: http://stackoverflow.com/q/47667913
tags question: http://stackoverflow.com/q/47619946
tags question: http://stackoverflow.com/q/47657089
tags question: http://stackoverflow.com/q/47688907
tags question: http://stackoverflow.com/q/47579110
tags question: http://stackoverflow.com/q/47587246
tags question: http://stackoverflow.com/q/47646811
tags question: http://stackoverflow.com/q/47616430

http://stackoverflow.com/a/47630443
accepted answer of: http://stackoverflow.com/q/47623582
has comment: http://stackoverflow.com/comment/82600127
score: 1
type: Answer
has body: Dropping this here for now, will explain later. Using levi-cevita symbols from @jaime's answer here and the matrix form of the Rodrigues formula here and some algebra based on k = (a x b)/sin(theta) def rotmatx(p, q): eijk = np.zeros((3, 3, 3)) eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1 eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1 d = (p * q).sum(-1)[:, None, None] c = (p.dot(eijk) @ q[..., None]).squeeze() # cross product (optimized) cx = c.dot(eijk) return np.eye(3) + cx + cx @ cx / (1 + d) EDIT: dang. question changed. def rotation_matrices(angles, directions): eijk = np.zeros((3, 3, 3)) eijk[0, 1, 2] = eijk[1, 2, 0] = eijk[2, 0, 1] = 1 eijk[0, 2, 1] = eijk[2, 1, 0] = eijk[1, 0, 2] = -1 theta = angles[:, None, None] K = directions.dot(eijk) return np.eye(3) + K * np.sin(theta) + K @ K * (1 - np.cos(theta))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47623582
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82600081

http://stackoverflow.com/comment/82313315
has text: try to reinstall it and follow the steps of https://kivy.org/docs/installation/installation.html
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47671606
type: QuestionComment

http://stackoverflow.com/comment/82158046
comment on: http://stackoverflow.com/a/47595573
has text: @HamedTemsah: sorry, but I actually did not notice all the time that you have this 1 second sleep. In this case there is probably neither overloading nor rate limiting the issue.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82350859
comment on: http://stackoverflow.com/a/47694956
has text: Thanlk Jezrael. The issue is still on. Basically, I have a dataset of 377 rows and Course has 129 values. When I apply your script, I got a new dataset of 48761 rows which means 377x129. What am I doing wrong?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82087440
type: Comment
has text: Possible duplicate of [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder)
score: 0
comment on: http://stackoverflow.com/q/47564648
type: QuestionComment

http://stackoverflow.com/q/47579983
has comment: http://stackoverflow.com/comment/82117413
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47580210
has comment: http://stackoverflow.com/comment/82117545
has answer: http://stackoverflow.com/a/47580210
has title: Python re sub replace word duplication
type: Question
possible better answer: http://stackoverflow.com/a/47580208
has body: re.sub(r'[\[\d\]]', 'foo', 'web scraping [2]') I want to replace [any number] with foo. But the output is coming strange. It prints web scraping foofoofoo Why is it happening ? Thanks
has comment: http://stackoverflow.com/comment/82117191
has comment: http://stackoverflow.com/comment/82117175
has answer: http://stackoverflow.com/a/47580208
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82117503
type: AnsweredQuestion

http://stackoverflow.com/q/47636388
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47636490
tagged with: printing
score: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/47636431
has title: How to remove/delete last character from printed list in python
favorite count: 0
tagged with: character
type: Question
tagged with: python-3.x
tagged with: separator
has body: I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help. num = int(input("write number: ")) print(num, end = "=") div = 2 while num &gt; 1: if num % div == 0: num = num / div print(div, end = "*") else: div += 1 Result I got: 24=2*2*2*3* Result I want: 24=2*2*2*3 I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong. Thank you.
has answer: http://stackoverflow.com/a/47636849
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47636663
has answer: http://stackoverflow.com/a/47636431
accepted answer: http://stackoverflow.com/a/47636490
answer count: 4

http://stackoverflow.com/comment/109114681
score: 0
type: AnswerComment
has text: What is the max value one can set `DATA_UPLOAD_MAX_NUMBER_FIELDS` to?
comment on: http://stackoverflow.com/a/47585694
type: Comment

http://stackoverflow.com/q/47600071
type: AnsweredQuestion
score: 1
has title: Making an array from values of a 2D array
tagged with: python
possible better answer: http://stackoverflow.com/a/47600165
type: Question
has answer: http://stackoverflow.com/a/47600165
has body: Confusing title, not sure how to formulate myself. Example at the end, probably makes it easier to understand. So, I have an array A_Main1 where each element is another array, A_Elem0, A_Elem1...A_ElemN I want to make a new array where each element is the first element of every array A_ElemI in A_Main1 I've seen code of this before but can't remember how it's done. This is what part of my code looks like latitudeInfo = [latitude1Info[], latitude2Info[]...latitudeNInfo[]] #latitudeXInfo[0] = the actual latitude, latitudeXInfo[&gt;0] are values in someway #connected to the latitude. So the 0th element of latitudeXInfo is always the latitude I want to make a new array of all latitudes in latitudeInfo possibleLatitudes = [] possibleLatitudes.append(latitudeInfo[i][0] for i in latitudeInfo) Thinking that possibleLatitudes appends the 0th element of the i:th list in latitudeInfo but this doesn't seem to work.
answer count: 2
accepted answer: http://stackoverflow.com/a/47600098
tagged with: arrays
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47600098
favorite count: 0

http://stackoverflow.com/a/47638448
has comment: http://stackoverflow.com/comment/82240062
upvote count: 1
has comment: http://stackoverflow.com/comment/82240528
has body: You can see what methods and attributes an object has by using dir. In Python 3.6, from: a = 'hello' try: a.append(2) except AttributeError as e: print(dir(e)) You get: ['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback'] That narrows down the things we can test since we don't want a dunder, leaving only args and with_traceback. It seems then that the best you could get is to use args which returns the string in a tuple: a = 'hello' try: a.append(2) except AttributeError as e: if 'str' in e.args[0]: print('Need to handle string') elif 'float' in e.args[0]: print('Need to handle float')
has comment: http://stackoverflow.com/comment/82240284
type: Answer
answers question: http://stackoverflow.com/q/47637955
accepted answer of: http://stackoverflow.com/q/47637955
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82244358
type: Comment
type: QuestionComment
has text: Read the *definition* of silhouette, then think about this thoroughly. Don't just attempt to reverse engineer, solve the math first. Then you will see how you can sample to approximate Silhouette. And no, you *don't* want this for all data, because of runtime. It's not only quadratic memory, but also quadratic time. Silhouette is not scalable.
comment on: http://stackoverflow.com/q/47633587
score: 1

http://stackoverflow.com/comment/82327800
has text: @dengar81 I'm glad your problem was solved.
comment on: http://stackoverflow.com/q/47639630
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47665391
type: AnsweredQuestion
has title: Keras ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/66212634
tagged with: deep-learning
has answer: http://stackoverflow.com/a/56923624
has answer: http://stackoverflow.com/a/47665700
has body: I have checked all the solutions, but still, I am facing the same error. My training images shape is (26721, 32, 32, 1), which I believe it is 4 dimension, but I don't know why error shows it is 5 dimension. model = Sequential() model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape= input_shape )) So this is how I am defining model.fit_generator model.fit_generator(train_dataset, train_labels, nb_epoch=epochs, verbose=1,validation_data=(valid_dataset, valid_labels), nb_val_samples=valid_dataset.shape[0],callbacks=model_callbacks)
has answer: http://stackoverflow.com/a/54560750
possible better answer: http://stackoverflow.com/a/54560750
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/60738809
tagged with: tensorflow
type: Question
score: 65
accepted answer: http://stackoverflow.com/a/47665700
has answer: http://stackoverflow.com/a/60738597
upvote count: 66
tagged with: keras
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47542763
downvote count: 0
has body: To fix your code notice NaN!='NaN' df[df==0] = np.nan df.describe() Out[696]: 22 72 79 86 87 88 90 count 8.000000 5.000000 7.000000 6.000000 12.000000 11.000000 7.00000 mean 3.524250 1.574800 4.680857 1.227667 3.196167 4.641273 5.84200 std 3.000573 1.538745 3.752722 1.174092 2.391229 5.992560 9.24574 min 0.762000 0.254000 0.254000 0.254000 0.508000 0.254000 0.50800 25% 1.524000 0.508000 1.270000 0.317500 1.016000 0.762000 1.14300 50% 2.540000 0.762000 4.826000 0.762000 2.540000 1.270000 2.03200 75% 4.127500 2.540000 8.128000 1.968500 4.445000 5.207000 4.82600 max 8.382000 3.810000 8.890000 3.048000 7.366000 16.510000 26.41600
answers question: http://stackoverflow.com/q/47542674
type: Answer
score: 2
upvote count: 2

keras
tags question: http://stackoverflow.com/q/47692541
tags question: http://stackoverflow.com/q/47676248
tags question: http://stackoverflow.com/q/47665391
tags question: http://stackoverflow.com/q/47659318
tags question: http://stackoverflow.com/q/47585698
tags question: http://stackoverflow.com/q/47624488
tags question: http://stackoverflow.com/q/47665371
tags question: http://stackoverflow.com/q/47582014
tags question: http://stackoverflow.com/q/47543113
tags question: http://stackoverflow.com/q/47679440
tags question: http://stackoverflow.com/q/47568998
tags question: http://stackoverflow.com/q/47663759
tags question: http://stackoverflow.com/q/47676466
tags question: http://stackoverflow.com/q/47667541
tags question: http://stackoverflow.com/q/47665072
tags question: http://stackoverflow.com/q/47565825
tags question: http://stackoverflow.com/q/47617930
tags question: http://stackoverflow.com/q/47624800
tags question: http://stackoverflow.com/q/47574634
tags question: http://stackoverflow.com/q/47582982
tags question: http://stackoverflow.com/q/47593493
tags question: http://stackoverflow.com/q/47599888
tags question: http://stackoverflow.com/q/47617512
tags question: http://stackoverflow.com/q/47670737
tags question: http://stackoverflow.com/q/47616531
tags question: http://stackoverflow.com/q/47576921
tags question: http://stackoverflow.com/q/47545540
tags question: http://stackoverflow.com/q/47596137
tags question: http://stackoverflow.com/q/47643678
tags question: http://stackoverflow.com/q/47616588
tags question: http://stackoverflow.com/q/47602609
tags question: http://stackoverflow.com/q/47560765
tags question: http://stackoverflow.com/q/47600182
tags question: http://stackoverflow.com/q/47664490
tags question: http://stackoverflow.com/q/47601377
tags question: http://stackoverflow.com/q/47660917
tags question: http://stackoverflow.com/q/47571896
tags question: http://stackoverflow.com/q/47577060
tags question: http://stackoverflow.com/q/47671732
tag name: keras
tags question: http://stackoverflow.com/q/47636772
tags question: http://stackoverflow.com/q/47555568
tags question: http://stackoverflow.com/q/47596256
tags question: http://stackoverflow.com/q/47641678
tags question: http://stackoverflow.com/q/47555881
tags question: http://stackoverflow.com/q/47608273
type: Tag
tags question: http://stackoverflow.com/q/47639850
tags question: http://stackoverflow.com/q/47599436
tags question: http://stackoverflow.com/q/47557591
tags question: http://stackoverflow.com/q/47555829
tags question: http://stackoverflow.com/q/47557558
tags question: http://stackoverflow.com/q/47544687
tags question: http://stackoverflow.com/q/47584862

http://stackoverflow.com/comment/82349690
score: 0
type: AnswerComment
has text: @CarloAllocca Got to go, check the edit, hope it helps. If not these answerers might update much better one. All you need to remove in these answers is `set_index()`
comment on: http://stackoverflow.com/a/47694956
type: Comment

global
type: Tag
tags question: http://stackoverflow.com/q/47545910
tags question: http://stackoverflow.com/q/47613403
tags question: http://stackoverflow.com/q/47610008
tag name: global
tags question: http://stackoverflow.com/q/47620697
tags question: http://stackoverflow.com/q/47656346

http://stackoverflow.com/q/47635765
has title: pygame.Surface object is not callable
score: 2
tagged with: typeerror
has answer: http://stackoverflow.com/a/47638078
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82233980
has body: for event in pygame.event.get(): if event.type == pygame.QUIT: state = 2 mouseX, mouseY = pygame.mouse.get_pos() leave(mouseX, mouseY) When I press the "x" in the top left gives me an error that reads: leave(mouseX, mouseY) TypeError: 'pygame.Surface' object is not callable
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82230457
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/82278616
type: Comment
comment on: http://stackoverflow.com/q/47659782
score: 0
type: QuestionComment
has text: @chepner yeah right. Json dumps cant be used here.

http://stackoverflow.com/comment/82157570
comment on: http://stackoverflow.com/a/47598454
type: Comment
score: 0
type: AnswerComment
has text: Amit Tripathi's answer is more along the lines that you started.

http://stackoverflow.com/comment/82325003
type: AnswerComment
has text: Good catch!.. updated accordingly
type: Comment
comment on: http://stackoverflow.com/a/47682751
score: 0

http://stackoverflow.com/q/47655752
has comment: http://stackoverflow.com/comment/82269656
has comment: http://stackoverflow.com/comment/82269992
has comment: http://stackoverflow.com/comment/82269939
type: Question
has comment: http://stackoverflow.com/comment/82270063
type: UnansweredQuestion
answer count: 1
has title: Extracting and sorting data in python
has comment: http://stackoverflow.com/comment/82270050
has comment: http://stackoverflow.com/comment/82269578
score: 0
has body: Looking for help to see if this is easy enough to do using python, i need to extract data from a text file, the data will then be used in excel to view in tables. I need to extract the following data Test: Date : Critical Test Result Value: Total Value: Overall Run Time: ABT: RPT: The file contains a large amount of tests, each with the above info to gather. As fairly new at using python any help/pointers would be great thanks. Number of fails:
has answer: http://stackoverflow.com/a/47658446
tagged with: python
has comment: http://stackoverflow.com/comment/82269633

http://stackoverflow.com/q/47590564
has answer: http://stackoverflow.com/a/47594318
tagged with: python
score: 0
has body: I have a series of tests that are quite complicated. Unfortunately, the builtin Pycharm Debugger is waaay too slow to handle them. I tried making it faster, but any attempts failed, so I have to resort to using pdb. My problem is that the command line that appears if I run my tests with pycharm and come across a pdb breakpoint is quite annoying: It does not support code completion (of course I googled it, but my attempts failed). I can't even press 'up' to get the last command again Most annoyingly: When I already wrote some code in the command line and jump to the beginning of the line to edit it, the cursor automatically jumps to the end of the line. I noticed that it is not the iPython console which I get when I go into pdb debug mode when I don't use pytest. Do you have any idea on how to solve any of these issues? Ideally on how to speed up the Pycharm debugger, or how to get the iPython console also in pytest? Help is much appreciated. Thanks in advance.
tagged with: pycharm
tagged with: pytest
answer count: 1
has title: Debugging pytests in Pycharm with pdb shows annoying console
type: Question
tagged with: debugging
type: UnansweredQuestion

http://stackoverflow.com/q/47633153
downvote count: 1
has body: I want to train a 5 Layer DNN using Tensorflow on Jupyter Notebook. It perform well on normal training. But when I want to use Cross validation to find a great dropout rate. When training process, Jupyter say the kernel is dead. The Jupyter log: terminate called after throwing an instance of 'std::system_error' what(): Resource temporarily unavailable My code is here. I Google find out maybe it's because run out of memory. I try to reduce batch size and the error still occurred. The code running on Ubuntu 16.04 and 32GB RAM with GPU 1080Ti. Enviroment are Python(3.5), tensorflow (1.3.0) &amp; tensorflow-gpu (1.3.0).
has title: Run Tensorflow on Jupyter notebook but kernel dead
has comment: http://stackoverflow.com/comment/82235945
tagged with: python
has comment: http://stackoverflow.com/comment/82410668
tagged with: tensorflow
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/82369729
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82744771
has comment: http://stackoverflow.com/comment/82248950
upvote count: 1

http://stackoverflow.com/q/47670181
has body: Is there a better way to design the Message model ? I have a Message model: class Message(models.Model): """ message """ title = models.CharField(max_length=64, help_text="title") content = models.CharField(max_length=1024, help_text="content") is_read = models.BooleanField(default=False, help_text="whether message is read") create_user = models.ForeignKey(User, related_name="messages",help_text="creator") receive_user = models.CharField(max_length=1024, help_text="receive users' id") def __str__(self): return self.title def __unicode__(self): return self.title You see, I use models.CharField to store the users' id, so I can know the users who should receive this row message. I don't know whether this design type is good. or is there a better way to do that? I have considered use ManyToMany Field, but I think if user is too many, the admin create one message will create as many as users count, so I think this is not a good idea.
has comment: http://stackoverflow.com/comment/82299212
possible better answer: http://stackoverflow.com/a/47671909
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82299860
accepted answer: http://stackoverflow.com/a/47670307
has title: Is there a better way to design the Message model?
has answer: http://stackoverflow.com/a/47670307
tagged with: django
tagged with: django-models
tagged with: python
linked to: http://stackoverflow.com/q/1307014
has answer: http://stackoverflow.com/a/47671909
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82299722
has comment: http://stackoverflow.com/comment/82299210
upvote count: 1

spoonacular
type: Tag
tag name: spoonacular
tags question: http://stackoverflow.com/q/47627030

http://stackoverflow.com/comment/82132428
comment on: http://stackoverflow.com/q/47587487
type: QuestionComment
type: Comment
has text: Using `df'Name', 'ShortName'` gives me `IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices`
score: 0

http://stackoverflow.com/comment/82150253
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47596270
type: QuestionComment
has text: It looks like you might be new to the site! Are you using any packages outside the default python? Do you have something like pandas? Are you reading this data from a csv file? Are the objects from a runtime application or are they being read elsewhere? Some more clarification might help

http://stackoverflow.com/comment/82073084
comment on: http://stackoverflow.com/q/47557614
score: 0
type: Comment
has text: Your dictionary `d` output looks (sort of) ok, based on what you're asking. The keys have some extra double quotes in them, but that will be easy to fix. The values are 2-item lists, with the IP as the first list item, and the filename as the second list item (with a trailing newline, but again that will be easy to fix. So... what is the exact problem with what you've got so far? What are you unable to do/understand?
type: QuestionComment

http://stackoverflow.com/comment/82105331
comment on: http://stackoverflow.com/a/47574276
type: Comment
has text: Ohh, I just saw the code again and figured out that I created a function named 'list'. Thanks :)
score: 2
type: AnswerComment

http://stackoverflow.com/q/47614548
tagged with: flask
has title: threaded=True not working on Flask server
has body: I have an Apache server running Flask. The Flask application in called more than a thousand times per minute, which causes delays because it is run single-threaded. I have seen that adding "threaded=True" like this is supposed to help: app.run(threaded=True) But it is not helping. Is there a particular other server setting that needs to be changed to allow Flask to run multiple operations as once, rather having to wait for each page to finish before it can start on the next one?
answer count: 0
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: server
has comment: http://stackoverflow.com/comment/84155687
type: UnansweredQuestion
tagged with: multithreading
tagged with: python

http://stackoverflow.com/q/47620968
answer count: 2
tagged with: root
score: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47621012
favorite count: 0
type: Question
has body: I have a dictionary-tree like this: { b : [e], a : [b,c], c : [], e : []} How can I find the root(in this example 'a`) fast even if I have a very long dictionary?
has answer: http://stackoverflow.com/a/63870759
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47621012
tagged with: tree
type: AnsweredQuestion
has title: Find root in dictionary-tree
possible better answer: http://stackoverflow.com/a/63870759

http://stackoverflow.com/q/47621228
has title: when should I write custom methods in model vs model manager/ queryset
answer count: 1
has body: when should I write methods in the model itself and when in the model manager? is it like all methods to get something should be written in manager and others in model
type: Question
has comment: http://stackoverflow.com/comment/82200457
accepted answer: http://stackoverflow.com/a/47622247
has comment: http://stackoverflow.com/comment/82200757
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47622247
score: 0

http://stackoverflow.com/a/47601381
score: 0
has body: One way to do this with recursion is passing and returning the list, rather than n. n is then just the last element of the list. This reuses the same list object throughout the recursion, rather than creating new ones constantly, so has memory and performance advantages over e.g. Adam Smith's second version. def syracuse(seq): n = seq[-1] if n == 1: # done return seq if n % 2: # odd seq.append(n * 3 + 1) return syracuse(seq) seq.append(n // 2) # even return syracuse(seq) I have also removed a few things you don't need in your code and rearranged it a bit to simplify it. To call it, you must pass n as a single-item list: syracuse([17]) If you don't want to have to pass in a list, just add a test to the beginning: def syracuse(seq): if type(seq) is not list: seq = [seq] n = seq[-1] if n == 1: # done return seq if n % 2: # odd seq.append(n * 3 + 1) return syracuse(seq) seq.append(n // 2) # even return syracuse(seq) Or add a helper function: def syracuse2(seq): n = seq[-1] if n == 1: # done return seq if n % 2: # odd seq.append(n * 3 + 1) return syracuse2(seq) seq.append(n // 2) # even return syracuse2(seq) def syracuse(n): return syracuse2([n])
answers question: http://stackoverflow.com/q/47600975
type: Answer
has comment: http://stackoverflow.com/comment/82162193

http://stackoverflow.com/comment/82254868
score: 0
comment on: http://stackoverflow.com/a/47588025
type: Comment
has text: What is `"ItemsSource"`? If it's legacy property, you can access it so: `combobox.legacy_properties()["ItemsSource"]` Method `legacy_properties()` returns a dictionary.
type: AnswerComment

http://stackoverflow.com/q/47691330
score: -1
type: AnsweredQuestion
has title: Adding elements in a list
upvote count: 0
has answer: http://stackoverflow.com/a/47691411
accepted answer: http://stackoverflow.com/a/47691411
downvote count: 1
possible better answer: http://stackoverflow.com/a/47691440
has answer: http://stackoverflow.com/a/47691453
has answer: http://stackoverflow.com/a/47691454
favorite count: 0
has body: I have a list named p. It contains some elements like this. p = [['mon', '1006'], ['mon', '769']]. I want to add the values like (1006 + 769) and print the summation. How Can I do that??
has answer: http://stackoverflow.com/a/47691440
type: Question
has answer: http://stackoverflow.com/a/47691553
answer count: 5
tagged with: python

http://stackoverflow.com/comment/82153957
type: Comment
type: QuestionComment
score: 0
has text: How does that for the task at hand. A bunch of singleton multisets? A single multiset that you still must iterate to count?
comment on: http://stackoverflow.com/q/47597545

http://stackoverflow.com/comment/82261592
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47651733
has text: If you're doing this in a Docker image/container, why not just blast it and start from scratch? (That's one of the major benefits of containerisation!)
type: Comment

http://stackoverflow.com/comment/82247785
comment on: http://stackoverflow.com/a/47626159
has text: For example, the true y of one instance is 100, while the predict y of sigmoid is between [-1, 1], so the maxium of predict value is 1, while the error of true and predict y couldn't be minimize with limitation of predict value. It has nothing to do with train or test, because test also use sigmoid as output, which also limits range of output
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82271105
comment on: http://stackoverflow.com/q/47656127
type: Comment
type: QuestionComment
score: 0
has text: There should be something on the console, if there is an error.

http://stackoverflow.com/a/47585829
type: Answer
has comment: http://stackoverflow.com/comment/82166483
score: 1
downvote count: 0
upvote count: 1
has body: This can be done in different variations but basically it is about delegating methods: class RomanceBookSupport: @staticmethod def getTitle(book): return book.title.upper() class FictionBookSupport: @staticmethod def getTitle(book): return book.title.lower().replace(' ', '_') SUPPORTMAP = { 'romance' : RomanceBookSupport, 'fiction' : FictionBookSupport } class Book(object): def __init__(self, title): self.title = title def setCategory(self, category): self.category = category def getTitle(self): return SUPPORTMAP[self.category].getTitle(self) romance_book = Book('Love Story') romance_book.setCategory('romance') print romance_book, romance_book.getTitle() fiction_book = Book('Star Wars') fiction_book.setCategory('fiction') print fiction_book.getTitle() fiction_book.setCategory('romance') print fiction_book.getTitle()
answers question: http://stackoverflow.com/q/47585550
has comment: http://stackoverflow.com/comment/82166383
has comment: http://stackoverflow.com/comment/82129420

http://stackoverflow.com/comment/82153225
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47597022
type: QuestionComment
has text: FYI I created a tag, [tag:chained-assignment] for this subject. Perhaps it should be renamed to just SettingWithCopyWarning because chained assignment might have a broader programming context/scope.

http://stackoverflow.com/comment/82208215
has text: I tried this, but in very strange way it doesn't keep the last folder (when python script and the arg path in the same folder)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47625125

http://stackoverflow.com/a/47639942
has comment: http://stackoverflow.com/comment/82244882
has comment: http://stackoverflow.com/comment/82243856
accepted answer of: http://stackoverflow.com/q/47636049
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82246058
has comment: http://stackoverflow.com/comment/82244191
score: 1
has comment: http://stackoverflow.com/comment/82243817
type: Answer
answers question: http://stackoverflow.com/q/47636049
has body: Ultimately what I am wanting to do is filter the data as described above in addition for Weekdays, OR individual weekdays Mondays, Tuesdays, Wednesday, etc. with the CustomBusinessDay function. Have you considered using DatetimeIndex.dayofweek? The day of the week with Monday=0, Sunday=6 # Exclude Sundays data.loc[data.index.dayofweek != 6] # Weekends only data.loc[data.index.dayofweek.isin([5, 6])] # Weekdays only data.loc[~data.index.dayofweek.isin([5, 6])] Also, I think an alternative to df = df.groupby(df.index.hour).mean() would be just: df.resample('H').mean()

http://stackoverflow.com/a/54187662
score: 12
downvote count: 0
answers question: http://stackoverflow.com/q/47617701
upvote count: 12
has body: Pycharm cannot warn you that your keywords have the wrong type but if you have the documentation panel open you can see the expected type if specified in the docstring. If not, the shortcut is ctr+q with caret at the function name. One time for a popup, two times to pin the documentation panel to the right. You can alternativly raise an error if the type is incorrect. After research and a lot of testing, here is everything I found. Take whatever you need: from typing import TypedDict class PersonData(TypedDict): name: str age: int class Person: """ a person """ _ssn: int _data: PersonData def __init__(self, ssn: int, *args, **kwargs) -> None: """ Create an instance of Person :param ssn: social security number :type ssn: int :key name: person's first name, should be a str :key age: person's age in years, rounded down, should be an int :return: __init__ should return None :rtype: None """ self._ssn = ssn try: if not isinstance(kwargs['name'], str): name_type = type(kwargs["name"]).__name__ raise TypeError(f"Person() kwargs['name']: got {name_type} but" " expected type is str") except KeyError: raise KeyError("Person() missing required keyword argument 'name'") self._data['name'] = kwargs['name'] try: age_type = type(kwargs["age"]).__name__ if not isinstance(kwargs['age'], int): raise TypeError(f"Person() kwargs['age']: got {age_type} but " "expected type is int") except KeyError: raise KeyError("Person() missing required keyword argument 'age'") self._data['age'] = kwargs['age'] Instead of key you can use keyword. This example provides: Fully documented docstring used by PyCharm to generate Documentation Type checking + Raise TypeError Default values (bonus: Warn user that a default value is set) I suggest you add @property.getter and @property.setter for accessing _id and _data. And the class attribute _data is overkill, you should replace it with _name and _age as you prefer default value instead of no value. Code here. Warning : Shadows built-in name 'id' I suggest…
type: Answer

http://stackoverflow.com/a/47656184
type: Answer
answers question: http://stackoverflow.com/q/47646312
score: 0
has body: I'll post my solution because it is faster (for this small dataset) and hoping someone will make it more efficient. import netowrkx as nx import pandas as pd df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]])) df.columns= ['p', 'c'] G = nx.from_pandas_dataframe(df, 'p','c') subgraphs = list(nx.connected_components(G)) grouplist = list('BA') def defineGrouping(x): return grouplist[[n for n,i in enumerate(subgraphs) if x in i][0]] df['grp'] = df.c.map(defineGrouping) df Output: p c grp 0 1 7 A 1 1 3 A 2 1 4 A 3 3 2 A 4 5 1 A 5 6 0 B Timing because I suspected that Pandas overhead is significant @Wen's method converting connected_components back to pandas dataframe 100 loops, best of 3: 6.47 ms per loop This method of using list comprehension and enumerate: 1000 loops, best of 3: 1.14 ms per loop
has comment: http://stackoverflow.com/comment/82286041

http://stackoverflow.com/a/47545260
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82059241
answers question: http://stackoverflow.com/q/47542788
has comment: http://stackoverflow.com/comment/82069564
has comment: http://stackoverflow.com/comment/82053152
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82071361
type: Answer
accepted answer of: http://stackoverflow.com/q/47542788
has body: If the item['images'] are 1D numpy arrays, and you want to tile them in the following way: +---------------+ |item0['images']| +---------------+ |item1['images']| +---------------+ |item2['images']| +---------------+ Then this can work (doc): import dask.bag as db import numpy as np import dask.array as da b = db.from_sequence([{'img':np.arange(10)}]*4) s = da.stack([item['img'] for item in b], axis=0) print(s.compute()) Result: [[0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]]
has comment: http://stackoverflow.com/comment/82047359

http://stackoverflow.com/comment/106136414
comment on: http://stackoverflow.com/q/47622350
has text: @hpaulj Exactely.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47565885
has comment: http://stackoverflow.com/comment/82091207
type: Question
has comment: http://stackoverflow.com/comment/82090128
has comment: http://stackoverflow.com/comment/82089715
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/82090192
has comment: http://stackoverflow.com/comment/82089958
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47566870
has answer: http://stackoverflow.com/a/47566870
has comment: http://stackoverflow.com/comment/82090083
score: 0
has comment: http://stackoverflow.com/comment/82089733
has body: Helllo everyone, I have no solution to Get User who owns the Content Object in Django. So I post for your guys help! I'm building 2 models: Reaction and Notification. If user React, Notification will auto be created a object. This is my code: Model Reaction: class Reaction(models.Model): user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO') timestamp = models.DateTimeField(auto_now_add=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') def save(self, force_insert=False, force_update=False, *args, **kwargs): Notification(from_user = self.user, to_user = ???, notification_type = Notification.LIKED, target_content_type = self.content_type, target_object_id = self.object_id).save() super(Reaction, self).save(*args, **kwargs) Models Notification class Notification(models.Model): from_user = models.ForeignKey(User, related_name='from_user_noti') to_user = models.ForeignKey(User, related_name='to_user_noti') date = models.DateTimeField(auto_now_add=True, null=True) is_read = models.BooleanField(default=False) target_content_type = models.ForeignKey(ContentType, related_name='notify_target', blank=True, null=True) target_object_id = models.PositiveIntegerField(null=True) target = GenericForeignKey('target_content_type', 'target_object_id') As you saw, I have problem with get to_user fields. This field I want to get User who owner a Content Object in Django Example: Post, Comment, ... Please help me with this case!
answer count: 1
has title: Django: ContentType object access, Get user from the content_object

http://stackoverflow.com/q/47655945
type: AnsweredQuestion
tagged with: pycharm
downvote count: 0
has answer: http://stackoverflow.com/a/47656042
accepted answer: http://stackoverflow.com/a/47656042
score: 1
upvote count: 1
answer count: 1
tagged with: virtualenv
has body: I'm trying to install XGBoost package for my PyCharm project on Windows. Although I found XGBoost package in Project Interpreter - Install (+) - Available Packages menu, following error occurred during installation: Collecting xgboost Using cached xgboost-0.6a2.tar.gz No files/directories in C:\Users\\AppData\Local\Temp\pycharm-packaging\xgboost\pip-egg-info (from PKG-INFO) I've found this answer regarding the installation XGBoost on Windows and it works for me. However, when I then created a new PyCharm virtual environment, XGBoost is still not available, neither can I install it from Project Interpreter menu. So the question is how to install XGBoost for PyCharm with VirtualEnv, running on Windows? Thanks.
tagged with: xgboost
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33749735
tagged with: python
linked to: http://stackoverflow.com/q/35139108
has title: Install XGBoost for Pycharm VirtualEnv (Windows)

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

http://stackoverflow.com/q/47633005
favorite count: 0
has title: how to plot groupped dataframe by date
type: Question
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47633033
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47633033
has body: I have a grouped by ['supplier','date_order'] as Amount date_order 2011 2012 2013 2014 2015 2016 2017 supplier fourni 0.000 1667750.000 4243250.000 2530000.000 2080000.000 1036200.000 1217400.000 supp_f 5289670.200 13076233.400 14199000.000 13181860.000 16177800.000 14525880.000 1346400.000 ifou 662250.000 2135750.000 2184150.000 1829800.000 1947880.000 1424820.000 1836100.000 How can get the plot of Amount of suppliers by years for each line in a line plot ?
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/82111325
type: Comment
has text: Your solution is correct but the problem isn't the OS. That code is not compatible with Python 2. The possibility of using super without arguments was introduced in Python 3: [PEP--3135 New Super()](https://www.python.org/dev/peps/pep-3135/)
comment on: http://stackoverflow.com/a/47576148
type: AnswerComment
score: 0

http://stackoverflow.com/a/47560367
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47559305
score: 0
type: AcceptedAnswer
has body: Question 1 My code does not seem to work. I might be missing something. Problem Running the app with the code provided, displayed a small window at the bottom left hand corner. Root Cause The class rule, &lt;TrafGridLayout&gt;: is missing either cols or rows attribute. In PageLayout, transitions from one page to the next are made by swiping in from the border areas on the right or left hand side. Therefore, it is not a best practice to use Button widget's on_press event for this. Kivy GridLayout » constraint cols or rows A GridLayout must always have at least one input constraint: GridLayout.cols or GridLayout.rows. Kivy » PageLayout The PageLayout class is used to create a simple multi-page layout, in a way that allows easy flipping from one page to another using borders. Transitions from one page to the next are made by swiping in from the border areas on the right or left hand side. Solution - kv Add cols: 1 to class rule, &lt;TrafGridLayout&gt;: Snippets &lt;TrafGridLayout&gt;: cols: 1 PageLayout: Output Question 2 I would like to switch between the two pages using a button: when a button is pressed the page switches. Solution Use Kivy ScreenManager and button pressed to switch page. Example The following example illustrates the use of Kivy ScreenManager and one of button's events, on_press to switch page / screen. main.py from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen class ScreenManagement(ScreenManager): pass class FirstPage(Screen): def calculate(self, point_from, point_to): print("point_from={0}, point_to={1}".format(point_from, point_to)) class SecondPage(Screen): pass class TestApp(App): title = "Login Screen" def build(self): return ScreenManagement() if __name__ == "__main__": TestApp().run() test.kv #:kivy 1.10.0 &lt;ScreenManagement&gt;: FirstPage: id: page1 SecondPage: &lt;FirstPage&gt;: name: "first_page" BoxLayout: orientation: 'vertical' BoxLayout: Label: text: "Point From:" TextInput: id: point_from text: '' Box…
accepted answer of: http://stackoverflow.com/q/47559305
type: Answer

http://stackoverflow.com/q/47682666
accepted answer: http://stackoverflow.com/a/47682968
has body: To start off, I am a complete noob to Debian, Python, and shell scripts, so please speak to me like I am a toddler. I have a python script I am running through a virtualenv, and I want to execute it via a shell script. Here is what I'm typing in to the terminal to do so: source .profile workon cv cd Desktop/Camera python main.py I tried turning this into a shell script, but I receive the error -- source: not found I've found no answer to my problem, at least not in any terms I can understand. Any advice would be appreciated. Furthermore, before you answer, I also have no idea why it is I need to execute source .profile, I'm simply following a beginner guide for the project which can be found here: https://www.hackster.io/hackerhouse/smart-security-camera-90d7bd Thanks in advance, and sorry if this is a dumb question.
downvote count: 1
possible better answer: http://stackoverflow.com/a/47682876
has title: Unable to source .profile in shell script
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47682968
has comment: http://stackoverflow.com/comment/82324998
has comment: http://stackoverflow.com/comment/82324969
has comment: http://stackoverflow.com/comment/82324748
has comment: http://stackoverflow.com/comment/82324714
has comment: http://stackoverflow.com/comment/82324688
has comment: http://stackoverflow.com/comment/82324845
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82324880
has comment: http://stackoverflow.com/comment/82325100
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47682876
has comment: http://stackoverflow.com/comment/82324742
score: 0
answer count: 2
tagged with: bash
has comment: http://stackoverflow.com/comment/82324594
has comment: http://stackoverflow.com/comment/82325074
has comment: http://stackoverflow.com/comment/82324706
has comment: http://stackoverflow.com/comment/82324629
has comment: http://stackoverflow.com/comment/82324894
has comment: http://stackoverflow.com/comment/82324822
has comment: http://stackoverflow.com/comment/82324646
tagged with: shell
has comment: http://stackoverflow.com/comment/82324832
has comment: http://stackoverflow.com/comment/82324856

http://stackoverflow.com/a/47617792
has body: The following double loop expression does it: print([ss for ss in short_str_list if all(ss in ls for ls in seq_list) ])
score: 0
answers question: http://stackoverflow.com/q/47617611
type: Answer

http://stackoverflow.com/comment/82475883
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47682427
score: 0
has text: @NathanielManistaAtGoogle Pretty certain, I was able to successfully communicate with an ordinary server. The gRPC app was also working perfectly locally. It's not that there's an issue with gRPC, I'm just not exactly sure how to deploy it and connect to the server.

http://stackoverflow.com/q/47684616
score: 6
has answer: http://stackoverflow.com/a/47684793
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/82329900
has comment: http://stackoverflow.com/comment/82356627
favorite count: 0
has answer: http://stackoverflow.com/a/73465249
has body: Similar issues like this have been posted on StackOverflow but I did not find adequate answers to resolve this issue. I'm running Python 3.6.3 on a Windows 7 machine. From IDLE I type the following import stmt and get the subsequent error: &gt;&gt;&gt; import pyperclip Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; import pyperclip ModuleNotFoundError: No module named 'pyperclip' I tried hitting Win-R (to pup up the RUN window) and typed the following: pip3 install pyperclip pip install pyperclip But it gives me an error saying "Could not fetch the URL: https://pypi.python.org/simple/pyperclip/ Could not find a version that satisfies the requirement pyperclip... No Matching distribution found" If I visit the URL mentioned (https://pypi.python.org/simple/pyperclip/) I see a bunch of pyperclip ZIP files all dif versions. But if I select a version I'm not sure where to place them/extract them or if extracting them is even the right thing to do. Any advice?
answer count: 8
has answer: http://stackoverflow.com/a/58355382
has answer: http://stackoverflow.com/a/71654131
has answer: http://stackoverflow.com/a/50324695
has answer: http://stackoverflow.com/a/53964417
has answer: http://stackoverflow.com/a/74501577
tagged with: python
has title: ModuleNotFoundError: No module named 'pyperclip'
has answer: http://stackoverflow.com/a/68894544
type: Question
tagged with: pyperclip
type: UnansweredQuestion

http://stackoverflow.com/comment/82129270
score: 0
comment on: http://stackoverflow.com/q/47585674
type: Comment
type: QuestionComment
has text: Thanks all - I'm sure this shows my ignorance on it, but is it just `pip3 install python3-weather-api`? I tried that and `sudo pip3 install python3-weather-api` but got an error `make: pip3: Command not found`

http://stackoverflow.com/q/47638267
has title: Trying get titles from multiple pages in beautifulsoup
has body: I am trying to get all blog titles from every page on a blog but so far am only able to produce output from the last page on that blog from urllib.request import urlopen from bs4 import BeautifulSoup base_url = 'http://www.madame-love.com' n = 10 for i in range(2, n+1): html = urlopen(base_url + "/page/%d" % i) page = BeautifulSoup(html.read(), 'html.parser') for titles in page.findAll('h2'): print(titles.string)
answer count: 1
has comment: http://stackoverflow.com/comment/82235036
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47638904
accepted answer: http://stackoverflow.com/a/47638904
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82234993

http://stackoverflow.com/q/47612514
possible better answer: http://stackoverflow.com/a/47612555
has title: how to take an integer and use a fraction on it
linked to: http://stackoverflow.com/q/1806278
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47612694
has body: def main(): name=input("Enter your name: ") #just write our name nothin important print (name, "is Swag") value1=int(input("enter a value: ")) #takes in the number without doubt print(value1) value2=float(int("Enter a fraction: ")) #heres our problem but what? print(value2) main() just a simple program I am playing about with but It shows this error since you all might want to know: I write for example 1/2 an this shows Traceback (most recent call last): File "C:\Users\waliu\Documents\Waliur Uni stuff\Information systems\Python Programs\Samples\apparently fractions.py", line 8, in &lt;module&gt; main() File "C:\Users\waliu\Documents\Waliur Uni stuff\Information systems\Python Programs\Samples\apparently fractions.py", line 6, in main value2=float(input("Enter a fraction: ")) ValueError: could not convert string to float: '1/2'
accepted answer: http://stackoverflow.com/a/47612694
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47612555

http://stackoverflow.com/q/47615716
has comment: http://stackoverflow.com/comment/82190406
score: 0
has comment: http://stackoverflow.com/comment/82189790
has body: Forgive me if this is simple but I am new to python. I have daily wind speed data with one data point for every latitude(180) and longitude(360) and time(6624) which is a 3D array with numpy.shape (time, lat, lon). I am trying to extract every wind speed and put it into a new array or list so that I can plot a histogram or a probability density function. Is there a way in python to extract each of these values?
has comment: http://stackoverflow.com/comment/82191496
tagged with: histogram
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82190176
has title: Extract every value in a 3D (time, lat, lon) array and create a list or 1D array
answer count: 2
has comment: http://stackoverflow.com/comment/82189865
has answer: http://stackoverflow.com/a/47617040
has comment: http://stackoverflow.com/comment/82190189
tagged with: 3d
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/47616201

http://stackoverflow.com/q/47576635
accepted answer: http://stackoverflow.com/a/47581476
has answer: http://stackoverflow.com/a/61607411
possible better answer: http://stackoverflow.com/a/62787814
has answer: http://stackoverflow.com/a/67046746
has answer: http://stackoverflow.com/a/62787814
favorite count: 0
has answer: http://stackoverflow.com/a/54489304
type: Question
score: 37
answer count: 8
linked to: http://stackoverflow.com/q/76189026
has body: I am using DRF with the JWT package for authentication. Now, I'm trying to write a unit test that authenticates itself with a JWT token. No matter how I try it, I can't get the test API client to authenticate itself via JWT. If I do the same with an API client (in my case, Postman), everything works. This is the test case: from django.urls import reverse from rest_framework.test import APITestCase from rest_framework_jwt.settings import api_settings from backend.factories import member_factory jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER class MemberTests(APITestCase): def test_get_member(self): member = member_factory() payload = jwt_payload_handler(member.user) token = jwt_encode_handler(payload) self.client.credentials(Authorization='JWT {0}'.format(token)) response = self.client.get(reverse('member-detail', kwargs={'pk': member.pk})) assert response.status_code == 200 But I always get a 401 Authentication credentials were not provided. In response.request I see the token is there, it's just not being applied I guess. If I rewrite the test to use rest_framework.test.RequestsClient and actually send it to the live_server URL, it works. Any help on this? P.S.: I am aware of force_authenticate() and login, but I would like my unit tests to access the API the same as the API client will in production.
has answer: http://stackoverflow.com/a/62095485
upvote count: 37
has answer: http://stackoverflow.com/a/47581476
has answer: http://stackoverflow.com/a/71627695
downvote count: 0
tagged with: django
has title: Django Rest Framework JWT Unit Test
tagged with: python
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/71096796
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83170283
tagged with: jwt

http://stackoverflow.com/a/48497117
answers question: http://stackoverflow.com/q/47581331
has body: The issue seems to be parser-related, as it is manifested only with lxml parser (which is default on many systems). Using stock html.parser solves it: for link in bs.BeautifulSoup(response, 'html.parser', parseOnlyThese=SoupStrainer('a')): if link.has_attr('href'): print(link['href'])
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/82195961
score: 0
type: AnswerComment
has text: That's great thanks! But how would i make it so that the questions keep being asked? or that there's different levels with harder questions?
comment on: http://stackoverflow.com/a/47618890
type: Comment

http://stackoverflow.com/q/47609698
answer count: 1
type: Question
type: AnsweredQuestion
score: 1
upvote count: 5
has comment: http://stackoverflow.com/comment/82178690
has body: bytes object is immutable. It doesn't support item assignment: &gt;&gt;&gt; bar = b"bar" &gt;&gt;&gt; bar[0] = b"#" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'bytes' object does not support item assignment str object is also immutable: &gt;&gt;&gt; bar = "bar" &gt;&gt;&gt; bar[0] = "#" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'str' object does not support item assignment It is possible to modify bytes object with ctypes while it is not possible to do the same with str object. Could you explain why? Please have a look at the following examples. c code char* foo(char *bar) { bar[0] = '#'; return bar; } c code compilation gcc -shared -o clib.so -fPIC clib.c bytes attempt python code import ctypes clib = ctypes.CDLL('./clib.so') bar = b"bar" print("Before:", bar, id(bar)) clib.foo(bar) print("After: ", bar, id(bar)) python code output Before: b'bar' 140451244811328 After: b'#ar' 140451244811328 str attempt str object is also immutable in Python 3 but unlike bytes object it's not possible to modify it with ctypes. python code import ctypes clib = ctypes.CDLL('./clib.so') bar = "bar" print("Before:", bar, id(bar)) clib.foo(bar) print("After: ", bar, id(bar)) python code output Before: bar 140385853714080 After: bar 140385853714080
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/82179386
favorite count: 0
has title: Why it is possible to modify immutable bytes object using ctypes in python 3?
tagged with: python-3.x
tagged with: ctypes
downvote count: 4
has comment: http://stackoverflow.com/comment/82178659
accepted answer: http://stackoverflow.com/a/47610828
has comment: http://stackoverflow.com/comment/82178501
has answer: http://stackoverflow.com/a/47610828

http://stackoverflow.com/comment/82289965
type: Comment
type: QuestionComment
has text: that worked, thanks. It's weird. When I do dtypes(all_raw), it shows the type for those two column as 'int64', not sure why they become object when I convert it to numpy. Any idea?
comment on: http://stackoverflow.com/q/47665176
score: 0

http://stackoverflow.com/a/47608959
has comment: http://stackoverflow.com/comment/82176268
answers question: http://stackoverflow.com/q/47608909
has body: You need to create a queue for your files: filename_queue = tf.train.string_input_producer(["../input/training.csv"]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) From the tf.TextLineReader().read() documentation: read( queue, name=None ) [...] queue: A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. and from the Reading from files section of the API guide: A typical pipeline for reading records from files has the following stages: The list of filenames Optional filename shuffling Optional epoch limit Filename queue A Reader for the file format A decoder for a record read by the reader Optional preprocessing Example queue The tf.train.string_input_producer() call above creates the filename queue from item 4, passing in a simple list of filenames (item 1). The tf.TextLineReader() is item 5 on the above list.
type: Answer
has comment: http://stackoverflow.com/comment/82176285
has comment: http://stackoverflow.com/comment/82176304
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82176404
accepted answer of: http://stackoverflow.com/q/47608909

http://stackoverflow.com/comment/82076009
score: 0
comment on: http://stackoverflow.com/q/47557947
has text: i definitely need to include `with tag='td'` somehow. also, the templates replacing `include` have their own `include` statements (i.e. nested templates). should i just build the entire crispy-forms template deck into one template?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82529586
score: 0
type: AnswerComment
has text: What would actually trigger your Lambda code to run?
type: Comment
comment on: http://stackoverflow.com/a/47681631

http://stackoverflow.com/q/47611949
has title: How to implement fields and address them like chess
tagged with: algorithm
tagged with: python
score: -1
upvote count: 0
type: UnansweredQuestion
has body: I'm trying to implement a game called Pah Tum. (It's not relevant how it works for my issue.) I want to create a field in a console like this: A B C D 1 [] [] [] [] 2 [] [] [] [] 3 [] [] [] [] 4 [] [] [] [] I already figured out how to print that BUT: I want to define a function in which I can address specific fields and block them, like this: B3 A B C D 1 [] [] [] [] 2 [] [] [] [] 3 [] [X][] [] 4 [] [] [] [] Somehow I can't figure out how to do that without using hundred of lines of code where I print that step by step.
answer count: 1
has comment: http://stackoverflow.com/comment/82183861
downvote count: 1
has answer: http://stackoverflow.com/a/47612064
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82182133
has comment: http://stackoverflow.com/comment/82182114
tagged with: field

http://stackoverflow.com/q/47608244
tagged with: graph
has body: I have an array of angles and i want to put them on Cartesian graph as lines I look for an conversion degree to (x,y) but couldn't pick a simple and good one What's the best way to do it.
answer count: 1
type: Question
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47608340
has answer: http://stackoverflow.com/a/47608340
tagged with: python
has comment: http://stackoverflow.com/comment/82174937
tagged with: coordinates
has title: Visualization a set of angles

http://stackoverflow.com/comment/82341896
type: Comment
has text: how should I modify it?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47688771

http://stackoverflow.com/a/47564577
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82087546
score: 2
has body: You could check the binary and avoid xoring all integers from 0 to n: 0 0000 1 0001 2 0010 3 0011 4 0100 8 1000 12 1100 The binary signature of a multiple of four is '00' def x_of_4(n): return bin(n)[-2:] == '00' However, although converting to a string makes it easy to visualize and understand, it is not the best of ideas, and this method fails for n = 0. A better way to do the same is to bitwise-and-with 3 which will test the final two zeros of the binary representation (credits to @ShadowRanger in the comments: def x_of_4(n): return not n &amp; 3
answers question: http://stackoverflow.com/q/47564531
has comment: http://stackoverflow.com/comment/82087481
upvote count: 2
has comment: http://stackoverflow.com/comment/82087295

http://stackoverflow.com/comment/82594134
type: QuestionComment
comment on: http://stackoverflow.com/q/47634346
has text: well, my mistake, been executing request to production instead of sandbox, oops :0
score: 0
type: Comment

http://stackoverflow.com/q/47544449
answer count: 0
has comment: http://stackoverflow.com/comment/82045939
type: Question
has comment: http://stackoverflow.com/comment/82045846
has comment: http://stackoverflow.com/comment/82061691
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82048774
has title: Get file mouseover text
has comment: http://stackoverflow.com/comment/82054793
has body: Is there any way to get the filename or mouseover text of a file that is under the cursor in Python? For example, the cursor in the image below is over the file 'twelve'. Is there any way to get the text 'twelve' or the mouseover text of that file? Thanks. import tkinter as tk def onKeyPress(event): text.config(text='You pressed %s\n' % (event.char, )) root = tk.Tk() w = 600 h = 200 x = 50 y = 100 root.geometry("%dx%d+%d+%d" % (w, h, x, y)) frame = tk.Frame(root) frame.pack(fill='both', expand='yes') text = tk.Label(frame) text.place(x=400, y=120) root.bind('&lt;KeyPress&gt;', onKeyPress) root.mainloop()
linked to: http://stackoverflow.com/q/19524072
score: 0
tagged with: tkinter

http://stackoverflow.com/a/66483815
downvote count: 0
upvote count: 1
has body: it's a bit late to reply to this, but For those who have similar problems, there might be other reasons that this error occurs. This can be occurred from 'urls order or url names' In my case, I was sending a post request through Ajax call to a url as below codes. even though I was sending the specific url for 'topic favourite' the urls.py addressed request to topic_view and the topic_view tries to match up a object with the topic_slug which is not given to the view function. it occurs the error matching query does not exist. urls.py path('topic/&lt;slug:slug&gt;/', views.topic_view, name='topic'), path('topic/add/', views.topic_favorite_view, name='topic_favorite'), .js $.ajax({ url: $(this).data('url'), type: 'POST', data:{ csrfmiddlewaretoken: csrftoken, topic_slug: topicSlug, action: 'post', }, success: function (res) { // console.log(res) }, So what I have done is changing the url order that put the topic_favorite above topic path('topic/add/', views.topic_favorite_view, name='topic_favorite'), path('topic/&lt;slug:slug&gt;/', views.topic_view, name='topic'), or changed url name like this 'favorite/add/' 'topic/favorite/add/'
answers question: http://stackoverflow.com/q/47615512
score: 1
type: Answer

http://stackoverflow.com/comment/82186539
has text: It just seems to be looping me through the same word endlessly right now. I see it jumps between the files like it is supposed too but is not incrementing the word it is looking at and periodically I see the not found after a dump of thousands of the word sam when it should be dumping sentences that are arrayed.
comment on: http://stackoverflow.com/a/47613784
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47587042
type: Question
has answer: http://stackoverflow.com/a/47587143
linked to: http://stackoverflow.com/q/9755538
tagged with: python
has answer: http://stackoverflow.com/a/47587216
possible better answer: http://stackoverflow.com/a/47587216
answer count: 4
accepted answer: http://stackoverflow.com/a/47587143
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47587228
has answer: http://stackoverflow.com/a/47587090
has title: Selecting element in a list with constraint in Python
has comment: http://stackoverflow.com/comment/82131563
has comment: http://stackoverflow.com/comment/82131544
has body: I have a list [1,2,3,3], and I want to select a random element from this list multiple times. However, I don't want my random generator to select the same element from the same index more than once. What I'm currently have: [1,2,3,3] --&gt; [2] with index 1 [1,2,3,3] --&gt; [1] with index 0 [1,2,3,3] --&gt; [2] with index 1 (this is wrong because chose the same index) What I want is: [1,2,3,3] --&gt; [2] with index 1 [1,2,3,3] --&gt; [1] with index 0 [1,2,3,3] --&gt; [3] with index 3 [1,2,3,3] --&gt; [3] with index 4 (this is perfect, no repeats!) What should I do to solve this issue? The function random.choice(...) itself doesn't solve this. UPDATE: I noticed some of you recommended me to use shuffle. It was a really good idea. But, what if I want to keep track of the original index too at later time? I don't think shuffle and pop could do that, right?

http://stackoverflow.com/a/47615115
accepted answer of: http://stackoverflow.com/q/47615037
answers question: http://stackoverflow.com/q/47615037
type: AcceptedAnswer
type: Answer
has body: Thanks to the help from #Python IRC channel: for geo in geos: #tweet_map.CircleMarker(location=geo, radius=250) folium.CircleMarker(location=geo, radius=250).add_to(tweet_map) tweet_map.save('map.html')
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47558723
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/82083741
has comment: http://stackoverflow.com/comment/82075498
has comment: http://stackoverflow.com/comment/82076697
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47561321
tagged with: http://stackoverflow.com/tag/html
has title: Get link when clicked in an image
answer count: 1
tagged with: selenium
type: Question
accepted answer: http://stackoverflow.com/a/47561321
has body: This is the image where, when clicked, user is redirected to another page. 5,99€ Camiseta flame + Colores I'm tryin to obtain that link using Selenium in Python, but I don't know where I can obtain it from. I noticed this however, which I suppose this function does the redirection: onclick="lis_mostrarficha(0); I don't have much experience in web developing so I'm not sure how I can obtain that link without clicking, as this would take too long. Thanks,

http://stackoverflow.com/comment/82173219
type: AnswerComment
score: 1
has text: @rcgldr: That seems bad vs. saving temporary values (e.g. using `10*d4 + d5` as part of computing both `100*d3 + 10*d4 + d5` and `(10*d4 + d5) * 10 + d6`). Maybe in Python where the cost of gluing together operations is much higher than the cost of the operation itself. It's easy to say "if you care about performance don't use Python this way in the first place", but sometimes just finding an efficient way in Python is enough to not bother making a C or asm implementation. But note that actual HW division has ~30x (32-bit) or ~90x (64-bit int) the throughput cost of integer mul on x86.
comment on: http://stackoverflow.com/a/47585366
type: Comment

http://stackoverflow.com/comment/82053566
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47548499
has text: PyDev requires Java 8 and Eclipse 4.6 (Neon) in order to run and only supports Python 2.6 onwards
type: QuestionComment

http://stackoverflow.com/a/47622372
has comment: http://stackoverflow.com/comment/82203081
type: Answer
has comment: http://stackoverflow.com/comment/82203153
has comment: http://stackoverflow.com/comment/82203442
has comment: http://stackoverflow.com/comment/82203111
score: 0
answers question: http://stackoverflow.com/q/47622065
has comment: http://stackoverflow.com/comment/82202953
has body: Or use a slice object. def neighbor(i, j, grid): cut_rows = slice(max(i-1, 0), i+2) rows = grid[cut_rows] cut_cols = slice(max(j-1, 0), j+2) throw_row = 0 if max(i-1, 0) == 0 and i != 1 else 1 throw_col = 0 if max(j-1, 0) == 0 and j != 1 else 1 rest = [r[cut_cols] for r in rows] throw_away_center = rest[throw_row].pop(throw_col) flat = [i for j in rest for i in j] return set(flat) Updated to cope with 0,0 and 1,1 as well. But now it's looking quite clonky the whole thing...
has comment: http://stackoverflow.com/comment/82203062

http://stackoverflow.com/a/47663654
answers question: http://stackoverflow.com/q/47663579
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82286765
downvote count: 0
has comment: http://stackoverflow.com/comment/82286674
has body: I'm not sure how you're using your data (this is important!) but changing to a generator may give you a performance boost. All you have to do, is change your [s to (s. new_data_too_slow = (x for x in old_data if x[0] != x[2]) Again, it depends on how you're using it but this method will easily outperform most IO operations. Also because it's a generator, you get one use out of it - but you will use significantly less memory.
has comment: http://stackoverflow.com/comment/82286675
has comment: http://stackoverflow.com/comment/82286702
type: Answer

http://stackoverflow.com/comment/82331169
has text: Your link to the data does not seem to work.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47649968

http://stackoverflow.com/q/47666287
has answer: http://stackoverflow.com/a/47666630
has answer: http://stackoverflow.com/a/47667335
tagged with: python
has answer: http://stackoverflow.com/a/47666368
upvote count: 4
score: 4
type: Question
has answer: http://stackoverflow.com/a/47666577
downvote count: 0
has title: Return a list of similar authors
has answer: http://stackoverflow.com/a/47666722
type: UnansweredQuestion
has body: I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors. authors = { 'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut'] } And the function I came up with is this: def get_similar(author_list, author): for item in author_list[author]: return author_list[author] Which only returns the items for the first key. I'd like it to return all of the similar authors, like this: get_similar(authors, 'Harlan Ellison') ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut'] Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut, Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!
has answer: http://stackoverflow.com/a/47666394
has answer: http://stackoverflow.com/a/47666445
has comment: http://stackoverflow.com/comment/82291750
favorite count: 0
has answer: http://stackoverflow.com/a/47666603
tagged with: python-3.x
answer count: 8

http://stackoverflow.com/comment/82327356
type: QuestionComment
comment on: http://stackoverflow.com/q/47682662
score: 0
has text: Thanks, I know its really poorly structured but i dont have much experience in OOP and this is prototype for a large project I need done in 10 weeks. Yelp :'(
type: Comment

http://stackoverflow.com/a/47553133
has comment: http://stackoverflow.com/comment/82063076
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82062941
downvote count: 0
has comment: http://stackoverflow.com/comment/82062849
has comment: http://stackoverflow.com/comment/82063179
answers question: http://stackoverflow.com/q/47552563
has comment: http://stackoverflow.com/comment/82062997
has body: Here's what I assume is the case- the URL is of the form yourwebsite.com/blah and all the pages contain at least yourwebsite.com or www.yourwebiste.comas text so, I created a dict of 3 samples, depending on if it contains https, www or without www- d = ["https://www.example.com/index.html", "www.example.com/index.html", "example.com/index.html"] Next, since we always search for only the matches, we split it with example.com since that remains constant anyhow. for showing all the elements of dict above, we have import re for i in d: parts = re.split(r'example.com/', i) print(parts) which gives me output as follows- ['https://www.', 'index.html'] ['www.', 'index.html'] ['', 'index.html'] You can always select the second one by using parts[1] for your processing.
type: Answer
has comment: http://stackoverflow.com/comment/82065317

http://stackoverflow.com/comment/82235981
has text: well, it does not fail on Python 3.4, OP never specified the python version, but it might as well be 2.7
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47638796
type: AnswerComment

http://stackoverflow.com/a/58352686
answers question: http://stackoverflow.com/q/47610308
score: 2
upvote count: 2
downvote count: 0
has body: It is indeed a problem of unstable internet connection. you can set the default-timeout to say 60 (sec). e.g. pip --default-timeout=60 install tensorflow
type: Answer

http://stackoverflow.com/q/47630296
favorite count: 0
tagged with: jupyter-notebook
tagged with: fancyimpute
type: Question
has comment: http://stackoverflow.com/comment/82220447
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: pip
score: 2
tagged with: python
has title: Install fancyimpute on jupyter
has body: I know this have been asked before. But, a lot of version specific (platform, windows, python, annaconda, vc..) are driving me crazy. Been trying pip install from cmd, conda install from cmd. !pip install from jupyter. updating vc. isntalling ecos and w/e they are saying im missing. update - pip install success. and now when i do pip install i get "Requirement already satisfied" for all. this is the log of the error log error This is the Error im getting while trying to import You can find the C code in this temporary file: c:\users\koren\appdata\local\temp\theano_compilation_error_kggj9k --------------------------------------------------------------------------- Exception Traceback (most recent call last) &lt;ipython-input-1-af7661c2d4f1&gt; in &lt;module&gt;() 7 import warnings 8 import math ----&gt; 9 from fancyimpute import KNN 10 warnings.simplefilter('ignore', np.RankWarning) 11 pd.options.display.max_rows = 999 C:\ProgramData\Anaconda2\lib\site-packages\fancyimpute\__init__.py in &lt;module&gt;() 5 from .bayesian_ridge_regression import BayesianRidgeRegression 6 from .mice import MICE ----&gt; 7 from .matrix_factorization import MatrixFactorization 8 from .iterative_svd import IterativeSVD 9 from .simple_fill import SimpleFill C:\ProgramData\Anaconda2\lib\site-packages\fancyimpute\matrix_factorization.py in &lt;module&gt;() 14 15 import climate ---&gt; 16 import downhill 17 import numpy as np 18 import theano C:\ProgramData\Anaconda2\lib\site-packages\downhill\__init__.py in &lt;module&gt;() ----&gt; 1 from .adaptive import * 2 from .base import build, Optimizer 3 from .dataset import Dataset 4 from .first_order import * 5 C:\ProgramData\Anaconda2\lib\site-packages\downhill\adaptive.py in &lt;module&gt;() 5 6 import numpy as np ----&gt; 7 import theano 8 import theano.tensor as TT 9 C:\ProgramData\Anaconda2\lib\site-packages\theano\__init__.pyc in &lt;module&gt;() 108 object2, utils) 109 --&gt; 110 from theano.compile import ( 111 SymbolicInput, In, 112 Symbo…

http://stackoverflow.com/comment/82167522
comment on: http://stackoverflow.com/a/47587775
score: 0
has text: Appreciate it, but I am looking for a solution that doesn't require importing functions. Thanks
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82286554
comment on: http://stackoverflow.com/a/47660539
has text: It's difficult to know exactly what's going on without looking at the actual outputs, but it appears that the function `usaddress.pars` isn't returning a JSON but rather a list. You'll need to convert the list pairs to a dict that has an key-value pair structure similar to a JSON. Check out this link [here](https://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47541123
has title: elasticsearch update fields for documents with matching _id
tagged with: python-3.6
answer count: 1
has body: Here's how a typical document looks like in my ES database: { "_index": "test_index", "_type": "data_pt", "_id": "AWAEXNYdkjIRDAUZyu8d", "_version": 1, "_score": 1, "_source": { "state": "state_a", ... } } In my code, I have already searched with a query, and have stored a list of _id for them: query = { ... { 'term': 'state_a' }, ... } results = es.search(index='test_index',_source=True,body=query) hits = results['hits']['hits'] queried_id_list = [doc['_id'] for doc in hits] I'm trying to update state field of each documents with the matching _id from 'state_a' to 'state_b': for _id in queried_id_list: es.update(index='test_index',id='_id,doc_type='data_pt', body=update_query) However, this adds a ridiculous amount of overhead, since it's calling update() for every single document. If I try to put queried_id_list directly: &gt;&gt;&gt; es.update(index=test_index', id=queried_id_list, doc_type='data_pt', body=update_query) Traceback (most recent call last): ... File "/Users/username/anaconda/lib/python3.6/site-packages/elasticsearch/client/utils.py", line 76, in _wrapped return func(*args, params=params, **kwargs) File "/Users/username/anaconda/lib/python3.6/site-packages/elasticsearch/client/__init__.py", line 526, in update raise ValueError("Empty value passed for a required argument.") ValueError: Empty value passed for a required argument. How can I call a single update() to accomplish this?
type: Question
score: 0
has answer: http://stackoverflow.com/a/47541685
tagged with: elasticsearch
tagged with: python-3.x
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/47627548
has body: In your definition of CommonModel you've required that author not be null. Is that correct? Must every instance of CommonModel have an author? If not, you can alter the definition to allow null values: author = models.ForeignKey('auth.User', default=None, null=True, blank=True)
answers question: http://stackoverflow.com/q/47627344
has comment: http://stackoverflow.com/comment/82213146
type: Answer
score: 0

http://stackoverflow.com/q/47642916
has answer: http://stackoverflow.com/a/47642990
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47642931
has comment: http://stackoverflow.com/comment/82244736
has comment: http://stackoverflow.com/comment/82244751
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82244488
has title: Python convert image array(20,20) to array(400)
answer count: 2
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has body: Using Python 2.7 and Numpy. I have a B/W image stored in array(20,20) and I would like to convert it to an array(400). How can this be done in Python if I have many images, that is array(x,20,20)? Thanks a lot! EDIT: Thanks a lot. I got the problem wrong at the beginning, thus I was not able to figure out this simple piece of code.

http://stackoverflow.com/q/47559489
has body: I'm looking for a way to name a value within an expression to use it multiple times within that expression. Since the value is found inside the expression, I can't save it as a variable using a typical assign statement. I also want its use to be in the same function as the rest of the expression, so I would rather not break it out into a separate function. More specifically, I enjoy comprehension. List/dictionary comprehension is my favorite Python feature. I'm trying to use both to coerce a dictionary of untrusted structure into a trusted structure (all fields exist, and their values are of the correct type). Without what I'm looking for, it would look something like this: { ... 'outer': [{ ... 'inner': { key: { ... 'foo': { 'a': get_foo_from_value(value)['a'], 'b': get_foo_from_value(value)['b'], ... } } for key, value in get_inner_from_outer(outer) } } for outer in get_outer_from_dictionary(dictionary)] } Those function calls are actually expressions, but I would like to only evaluate get_foo_from_value(value) once. Ideally there would be something like this: 'foo': { 'a': foo['a'], 'b': foo['b'], ... } with get_foo_from_value(value) as foo So far the options I've come up with are single-item generators and lambda expressions. I'm going to include an example of each as an answer so they can be discussed separately.
answer count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/104113208
has comment: http://stackoverflow.com/comment/82078802
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47559596
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82077200
has comment: http://stackoverflow.com/comment/82077699
has answer: http://stackoverflow.com/a/47559547
type: UnansweredQuestion
tagged with: python
tagged with: python-3.6
has title: Temporary names within an expression
upvote count: 2

http://stackoverflow.com/q/47612712
score: 0
tagged with: linux
has body: I have been playing around with a web server and calling a Python routine using the CGI module. That was challenging but it works fine :) My problem is after the Python script execution, I want to introduce a routine in my script to redirect again to my home page. I have seen in this forum questions like this one and the answer in most cases is: use the command line print("Location:http://your_page"), but I have already trie it and does not work in my case. In the next paragraph I will try to explain my whole "mini project" and then I let you see my code. Remote control of wireless home system through internet. Language Python and PHP, also Linux knowledge O.S. The purpose of this project is clicking a button on a web page (internet connection) turn on and off a LED. The LED is in a wireless module somewhere at home. Setting an Apache2 web server running on BeagleBone Black (Debian O.S.). Beagle Bone Black is connected via UTP cable to LAN. Programming a ESP32 module as TCP server and also connected to Wi-Fi (LAN). Programmed Python script as CGI module to execute a TCP client connection with ESP32 module and commanding turn of and then turn off a LED. The script is executed when a button is clicked in the web page. Setting a port forward on Modem/Router to allow access from internet to the Web Server. index.html (Home page) Web Server MReyesP! Success! The Web Server is working :) Click the Button to run - "LED On/Off program" <input class=button onClick="location.href='http://my_web_page.net/cgi-bin/TCPC$ This is my resulting home page. Home page python_script.py #!/usr/bin/python3 import socket import time import cgitb cgitb.enable() print("Content-type: text/html\n\n") print(" \n ") print("<div style=\"with:100%; font-size: 40px; font-weight bold; text-align: c$ print("The LED was turned On and after 2 seconds was turned Off") client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip="192.168.2.112" port=1234 address=(ip,port) client.connect(address) data = 'le…
linked to: http://stackoverflow.com/q/25967347
has answer: http://stackoverflow.com/a/47618348
has comment: http://stackoverflow.com/comment/82184182
accepted answer: http://stackoverflow.com/a/47618348
answer count: 1
tagged with: cgi
type: Question
has comment: http://stackoverflow.com/comment/82725719
tagged with: python
tagged with: php
has title: After a CGI Python script is executed, how can I return automatically to my homepage?
tagged with: apache2
type: AnsweredQuestion

http://stackoverflow.com/comment/82087779
type: QuestionComment
comment on: http://stackoverflow.com/q/47564765
score: 0
has text: Google "memoization".
type: Comment

http://stackoverflow.com/comment/82235714
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47638678
score: 0
has text: Sorry, that was a mistake when I copied it into stack overflow. It's fixed now.

http://stackoverflow.com/a/47655766
has body: Label will not update automatically if you don't use textvariable= with StringVar(). But you can update text manually without textvariable and StringVar First you have to assign Label to variable to have access to it. lab = Label(fen1, text = 'distance :'+calculdist(x1,y1,x2,y2)) lab.pack() And later in avance you can change text using lab['text'] = 'distance :'+calculdist(x1,y1,x2,y2) EDIT: full code with better formatting to make it more readable import tkinter as tk from math import sqrt def avance(lat1=0, vert1=0, lat2=0, vert2=0): global x1, y1, x2, y2 x1 += lat1 y1 += vert1 x2 += lat2 y2 += vert2 if flag == 0: can1.coords(oval1, x1, y1, x1+60, y1+60) else: can1.coords(oval2, x2, y2, x2+30, y2+30) lab['text'] = 'distance: '+calculdist(x1,y1,x2,y2) def calculdist(x1, y1, x2, y2): dist = sqrt((x2-x1)**2+(y2-y1)**2) #dist = str(dist) dist = "{:10.5f}".format(dist) return dist def depl_gauche(): if flag == 0: avance(-10, 0) else: avance(0, 0, -10, 0) def depl_droite(): if flag == 0: avance(10, 0) else: avance(0, 0, 10, 0) def depl_haut(): if flag == 0: avance(0, -10) else: avance(0, 0, 0, -10) def depl_bas(): if flag == 0: avance(0, 10) else: avance(0, 0, 0, 10) def which(): global flag if flag == 0: flag = 1 elif flag == 1: flag = 0 #------ x1 = 100 y1 = 100 x2 = 300 y2 = 300 flag = 0 fen1 = tk.Tk() fen1.title("Exercice d'animation avec tkinter") can1 = tk.Canvas(fen1, bg='light grey', height=500, width=500) oval1 = can1.create_oval(x1, y1, x1+60, y1+60, width=2, fill='red') oval2 = can1.create_oval(x2, y2, x2+30, y2+30, width=2, fill='blue') can1.pack(side='left') tk.Button(fen1, text='Quitter', command=fen1.destroy).pack(side='bottom') tk.Button(fen1, text='Gauche', command=depl_gauche).pack() tk.Button(fen1, text='Droite', command=depl_droite).pack() tk.Button(fen1, text='Haut', command=depl_haut).pack() tk.Button(fen1, text='Bas', command=depl_bas).pack() tk.Button(fen1, text='Change', command=which).pack() lab = tk.Label(fen1, text='distance: '+calculdist(x1,…
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47655214
has comment: http://stackoverflow.com/comment/82270366

http://stackoverflow.com/comment/82313430
has text: It says element not visible
comment on: http://stackoverflow.com/a/47676003
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47547986
tagged with: python
has comment: http://stackoverflow.com/comment/82052970
favorite count: 0
has answer: http://stackoverflow.com/a/47548435
has comment: http://stackoverflow.com/comment/82053614
type: Question
tagged with: numpy
has body: I have a 2D array which describes index ranges for a 1D array like z = np.array([[0,4],[4,9]]) The 1D array a = np.array([1,1,1,1,0,0,0,0,0,1,1,1,1]) I want to have a view on the 1D array with the index range defined by z. So, for only the first range a[z[0][0]:z[0][1]] How to get it for all ranges? Is it possible to use as_strided with unequal lengths defined by z as shape? I want to avoid to copy data, actually I only want a different view on a for further computation.
answer count: 2
accepted answer: http://stackoverflow.com/a/47548312
has title: Numpy view on 1D array via 2D array as indices range
has answer: http://stackoverflow.com/a/47548312
tagged with: arrays
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47548435
type: AnsweredQuestion

http://stackoverflow.com/comment/82117249
comment on: http://stackoverflow.com/q/47569108
type: Comment
has text: @jpmc26: I couldn't find any exact duplicate. If you find one, please feel free to comment. Some proposed duplicates either didn't apply or were inefficient. I agree that the question could show more research though.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47590985
has comment: http://stackoverflow.com/comment/82139440
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82139368
has comment: http://stackoverflow.com/comment/82141971
has comment: http://stackoverflow.com/comment/82139286
has body: You run long-running while loop which stops window - it doesn't close immediatelly - but your don't get events from system to recognize QUIT event and exit loop. When you click closing button then it doesn't close window. It sends event QUIT to your program and you can decide what to do - you can exit loop and then it ends program, but you can also save some data before close, or you can ask user if it really want to exit, etc. It is simple standard mainloop which gets events, and it ends program when you press closing button (event QUIT). import pygame pygame.init() screen = pygame.display.set_mode((500,300)) # --- mainloop / event loop --- running = True while running: for event in pygame.event.get(): print (event) if event.type == pygame.QUIT: # &lt;-- closing button was pressed running = False # it will exit `while` loop pygame.quit()
accepted answer of: http://stackoverflow.com/q/47590429
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47590429
has comment: http://stackoverflow.com/comment/82139184
has comment: http://stackoverflow.com/comment/82139174
downvote count: 0

http://stackoverflow.com/comment/82199252
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47620646
type: Comment
has text: I have already done that.I have mentioned it in the comments.But this isn't a lot faster

http://stackoverflow.com/a/47684488
accepted answer of: http://stackoverflow.com/q/47684387
upvote count: 35
type: AcceptedAnswer
downvote count: 0
has body: Django uses INSTALLED_APPS as a list of all of the places to look for models, management commands, tests, and other utilities. If you made two apps (say myapp and myuninstalledapp), but only one was listed in INSTALLED_APPS, you'd notice the following behavior: The models contained in myuninstalledapp/models.py would never trigger migration changes (or generate initial migrations). You wouldn't be able to interact with them on the database level either because their tables will have never been created. Static files listed within myapp/static/ would be discovered as part of collectstatic or the test server's staticfiles serving, but myuninstalledapp/static files wouldn't be. Tests within myapp/tests.py would run but myuninstalledapp/tests.py wouldn't. Management commands listed in myuninstalledapp/management/commands/ wouldn't be discovered. So really, you're welcome to have folders within your Django project that aren't installed apps (you can even create them with python manage.py startapp) but just know that certain auto-discovery Django utilities won't work for that application.
score: 35
type: Answer
answers question: http://stackoverflow.com/q/47684387
has comment: http://stackoverflow.com/comment/82338654

http://stackoverflow.com/q/47556851
tagged with: pandas
has comment: http://stackoverflow.com/comment/82074830
tagged with: datetime
has comment: http://stackoverflow.com/comment/82071209
has comment: http://stackoverflow.com/comment/82074840
has title: Parse timestamp having hour beyond 23 in python
has comment: http://stackoverflow.com/comment/82074909
has comment: http://stackoverflow.com/comment/82074844
type: Question
has comment: http://stackoverflow.com/comment/82071138
has body: I am learning python and came across an issue where I am trying to read timestamp from CSV file in below format, 43:32.0 here 43 is at hours position and convert it to DateTime format in Pandas. I tried code, df['time'] = df['time'].astype(str).str[:-2] df['time'] = pd.to_datetime(df['time'], errors='coerce') But, this is converting all values to NaT I need the output to be in format - mm/dd/yyyy hh:mm:ss
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47557100
answer count: 1
has comment: http://stackoverflow.com/comment/82071462
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82075211
tagged with: timestamp
score: 0

http://stackoverflow.com/q/47611720
answer count: 2
has answer: http://stackoverflow.com/a/57751288
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82181716
accepted answer: http://stackoverflow.com/a/47611801
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82181691
has comment: http://stackoverflow.com/comment/82181787
score: -2
has title: python - Password checker program, while loops not working
has comment: http://stackoverflow.com/comment/82181918
tagged with: python
has body: I am making a password validator/checker program as part of my computing assignment.It must have an uppercase and lowercase letter and be at least 8 characters long. So far I have done this: new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") while new_password != new_password2: print("The passwords don't match up.") new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") if new_password == new_password2: length = len(new_password) while int(length) &lt; 8: print("Your password must be longer") new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") letters = set(new_password) lower = any(letter.islower() for letter in letters) while new_password == new_password2: if not lower: print("Your password must contain a lowercase letter") new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") upper = any(letter.isupper() for letter in letters) while new_password == new_password2 : if not upper: print("Your password must contain an uppercase letter") new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") The code runs, but for some reason, the while loops do not work as even if the condition is right,( eg. the password contains an uppercase letter), the option for the user to enter the password again is being displayed. Can someone take a look and tell me the problem here? Thanks
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/57751288
has answer: http://stackoverflow.com/a/47611801
has comment: http://stackoverflow.com/comment/82181768

http://stackoverflow.com/comment/82185874
comment on: http://stackoverflow.com/a/47613696
score: 0
type: Comment
has text: Just change the one line i showed! Numpy's dot is the equivalent to matrix-multiplication for compatible shapes! And scipy.sparse will do mat-mul too with dot. Read the docs on those to get a feeling.
type: AnswerComment

http://stackoverflow.com/comment/82076913
has text: There are no commas in your edited data. Why do you say it's comma-delimited?
comment on: http://stackoverflow.com/q/47559510
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47640554
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47692662
has answer: http://stackoverflow.com/a/47692662
tagged with: python-3.x
tagged with: python-2.7
has body: According to Django 2.0 release notes Django 2.0 onwards will only support python 3, making the 1.11.X the last release series to support python 2. See quote from the release notes page: Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series. The Django 1.11.x series is the last to support Python 2.7. However when running pip2 install Django, django version 2 is being installed (which then fails because it assumes functionality not available in python 2): (venv-crap) mbp15:server nir$ pip2 install django Collecting django Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 177kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/PATH/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/PATH/django/ I know I can manually specify requirement version below 2, making pip install a version valid for python 2, however that will complicate the installation process if I want to support both python2 and python3, and would have assumed pip will know to install only versions compatible with the python it's running from. My questions, therefore, as the following: Why is pip attempting to install Django2 with python2 instead of automatically picking the last compatible version? Isn't that part of pips capabilities? Is there a way to make a single requirements.txt that will install Django<2.0 when running from python2 and Django>=2.0 when running with python3?
upvote count: 2
type: AnsweredQuestion
tagged with: pip
tagged with: django
score: 1
has comment: http://stackoverflow.com/comment/82242318
answer count: 1
downvote count: 1
favorite count: 0
has title: Why is django 2 available under python 2?

http://stackoverflow.com/comment/82118272
score: 0
has text: You can get a slight, but noticeable performance bump by using `defaultdict`. This also cleans up the code some.
comment on: http://stackoverflow.com/a/47570669
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47618867
has answer: http://stackoverflow.com/a/47986335
type: Question
score: 0
tagged with: python
tagged with: hadoop-streaming
tagged with: mapreduce
has title: How to run Python mapreduce in Hadoop Streaming
tagged with: hadoop
has comment: http://stackoverflow.com/comment/82200311
type: UnansweredQuestion
answer count: 1
has body: I'm trying to run a mapreduce program in Apache Hadoop that counts an average sum of primes in a given input file. This is my Mapper import sys for word in sys.stdin: print(word) And this is the Reducer import sys primes = [] for word in sys.stdin: if(int(word) &gt;= 2): isPrime = True for a in range(2,int(word)): if(int(word) % a == 0): isPrime=False if isPrime: primes.append(int(word)) print(sum(primes)/float(len(primes))) Now, when I run it with a following command: python primesMapper.py primesReducer.py -r hadoop --hadoop-streaming-jar /opt/cloudera/parcels/CDH-5.10.0-1.cdh5.10.0.p0.41/lib/hadoop-mapreduce/hadoop-streaming-2.6.0-cdh5.10.0.jar hdfs://bigdata1.sis.uta.fi:/user/students/input/primes1.txt --output-dir group25/primes.txt I get no error, but nothing actually happens. It just gets stuck on the command. When I manually terminate it I can see it's stuck in the Mapper file: File "primesMapper.py", line 8, in &lt;module&gt; for line in sys.stdin: Any help?
has comment: http://stackoverflow.com/comment/82200286

http://stackoverflow.com/q/47644110
has answer: http://stackoverflow.com/a/51676877
tagged with: tensorflow
type: Question
has body: In TensorFlow I have a graph that has in it a string_input_producer that is used in it's input pipeline. I am loading the graph from a checkpoint file, so I do not have access to the original object when it was created. Nonetheless, I need to run the enqueue method of this object. I have tried getting the FIFOQueue object using get_operation_by_name and get_tensor_by_name, which obviously did not work because the queue is neither an operation nor a tensor. Is there any function like the mentioned that would do what I want? (fake e.g. get_queue_by_name) How can I solve my problem otherwise?
tagged with: python
answer count: 1
has title: How to get a Queue object from a TensorFlow graph?
has comment: http://stackoverflow.com/comment/82246920
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/51676877

http://stackoverflow.com/a/47656129
answers question: http://stackoverflow.com/q/47655689
type: Answer
score: 0
has body: cd /usr/local/lib/python2.7/dist-packages/google_news_crawler/ sudo touch logging.yaml sudo vi logging.yaml Copy paste below content into that file: disable_existing_loggers: false formatters: default: format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' #datefmt: '%Y-%m-%d %H:%M:%S' handlers: console: class: logging.StreamHandler formatter: default loggers: google_news_crawler.gnc: level: DEBUG elasticsearch: level: ERROR elasticsearch.trace: handlers: null root: handlers: [console] level: WARNING version: 1

http://stackoverflow.com/q/47598716
has title: Printing integers in a list as double digits
type: Question
has answer: http://stackoverflow.com/a/47598881
linked to: http://stackoverflow.com/q/2921847
answer count: 5
has comment: http://stackoverflow.com/comment/82155642
tagged with: python
has comment: http://stackoverflow.com/comment/82155701
has answer: http://stackoverflow.com/a/47598853
has answer: http://stackoverflow.com/a/47598797
tagged with: python-3.x
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47598786
has answer: http://stackoverflow.com/a/47598892
has body: I have a list of integers that I need to print out as a matrix. I did that as following: matrix = [mylist[i:i + n] for i in range(0, len(mylist), n)] for nlist in matrix: print(nlist) This works well; for example if my list is [1 2 3 4 5 6 7 8 9] and n is 3, it will output: [1 2 3] [4 5 6] [7 8 9] Now I don't just want those integers, I want a zero in front of them; so 01 02 03 etc. I read that this is easily done with print("{:0=2d}".format(integer)) , but it doesn't seem to work on my list or matrix. print("{:0=2d}".format(mylist)) or print("{:0=2d}".format(nlist)) gives me an error message. How can I make it work for a list? Also, a very small thing I hope I'm allowed to ask here: how do I get rid of the square brackets around my matrix? EDIT: I figured out why my code didn't work. I had this if statement that said that if the program encountered a 0, that zero had to be printed as a string "X". So sometimes I would have a list of both integers and a string. Like so: 08 07 06 05 04 03 02 01 X Should I just convert everything to a string then? Or how can I make it work?
type: UnansweredQuestion

http://stackoverflow.com/q/47685436
type: Question
has title: How to display a different image based on button clicks with pygame?
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has body: I am coding a game for a school project. I have coded it so that I use wasd to move my character. I have four different images: one facing left, one right, one forwards, and one backwards. I need to change the image being displayed as the character based on which button I press. I have a function defining each image, and I try to call that function based on which button is pressed, and then when the button goes back up, I want to display the front facing image again. All it does is every time I press, the corresponding facing image is displayed, goes away, and then the front facing image is displayed and then goes away very quickly. This is just the part that actually deals with the character: howieImg = pygame.image.load('howie front.PNG') howieImg_back = pygame.image.load('howie back.PNG') howieImg_left = pygame.image.load('howie left.PNG') howieImg_right = pygame.image.load('howie right.PNG') def howie(x, y): gameDisplay.blit(howieImg, (x, y)) def howie_back(x, y): gameDisplay.blit(howieImg_back, (x, y)) def howie_left(x, y): gameDisplay.blit(howieImg_left, (x, y)) def howie_right(x, y): gameDisplay.blit(howieImg_right, (x, y)) while not gameExit: startx = (display_width/2) starty = (display_height/2) thing_width = 25 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_w and y &gt; 0: howie_back(x, y) y_change = -3 if event.key == pygame.K_s and y &lt; display_height - character_height: howie(x, y) y_change = 3 if event.key == pygame.K_a and x &gt; 0: howie_left(x, y) x_change = -3 if event.key == pygame.K_d and x &lt; display_width - character_width: howie_right(x, y) x_change = 3 if event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_s: howie(x, y) y_change = 0 if event.key == pygame.K_a or event.key == pygame.K_d: howie(x, y) x_change = 0 x += x_change y += y_change if x &gt; display_width - character_width or x &lt; 0: x_change = 0 if y &gt; d…
score: 1
answer count: 1
tagged with: pygame
has comment: http://stackoverflow.com/comment/82333410
has answer: http://stackoverflow.com/a/47687967

http://stackoverflow.com/a/47659361
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47658584
has body: Typically you would read a certain ammount of bytes (eg 1024) in a loop. If recv returns any bytes append it to your data, else break the loop and close the connection. import socket server_address = ('httpbin.org', 80) message = b'GET / HTTP/1.1\r\n' message += b'Host: httpbin.org:80\r\n' message += b'Connection: close\r\n' message += b'\r\n' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(server_address) sock.sendall(message) data = b'' while True: buf = sock.recv(1024) if not buf: break data += buf sock.close() print(data.decode()) Note that you'll have to set the Connection header to 'close' (or use HTTP 1.0). Otherwise the loop will hang due to persistent connections by default, as implemented in HTTP 1.1. Alternatinely you could read the first bytes and parse them to get the HTTP headers. If there is a Content-Length header you can use it to calculate the ramaining bytes. ... data = b'' while b'\r\n\r\n' not in data: data += sock.recv(1) header = data[:-4].decode() headers = dict([i.split(': ') for i in header.splitlines()[1:]]) content_length = int(headers.get('Content-Length', 0)) if content_length: data += sock.recv(content_length) ... By using bytes in send and recv, this should work for Python3 as well. However this is a very basic example and will fail in many cases (HTTPS, cookies, redirects, etc), so it's best to use a library designed for HTTP requests.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47658584

http://stackoverflow.com/comment/82408831
type: Comment
type: QuestionComment
has text: Namespacing packages would solve your problem. There is a Feature Request for that -> https://github.com/pypa/warehouse/issues/2589
comment on: http://stackoverflow.com/q/47676721
score: 1

http://stackoverflow.com/a/47693941
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82462853
accepted answer of: http://stackoverflow.com/q/47693326
has comment: http://stackoverflow.com/comment/82384459
has comment: http://stackoverflow.com/comment/82347196
has body: You could split by "Function" to get a list consisting of each function. Then use a dictionary to store the name of the function and its arguments. Something like this: with open(path, 'r') as file: functions = file.read().split('Function') functions = functions[1:] # This is to get rid of the blank item at the start due to 'Function' being at the start of the file. # Right now `functions` looks like this: # [' func1\n(\n arg1 arg1\n arg2 arg2\n);\n\n', ' func2\n(\n arg3 arg3\n);\n', ' func3\n(\n arg4 arg4\n arg5 arg5\n);\n\n', ' func4\n(\n arg6 arg6\n);'] functions_to_save = ['func1'] # This is a list of functions that we want to save. You can change this to a list of whichever functions you need to save d = {} # Dictionary # Next we can split each item in `functions` by whitespace and use slicing to get the arguments for func in functions: func = func.split() # ['func1', '(', 'arg1', 'arg1', 'arg2', 'arg2', ');'] if func[0] in functions_to_save: d[func[0]] = set(func[2:-1]) # set is used to get rid of duplicates Output: &gt;&gt;&gt; d {'func1': {'arg2', 'arg1'}} There are other ways of doing this but this is probably the easiest to understand
answers question: http://stackoverflow.com/q/47693326
type: Answer
score: 0

http://stackoverflow.com/a/47642995
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47642160
answers question: http://stackoverflow.com/q/47642160
has body: Approach #1 Here's a loopy way that iterates only through the list of non-null positions - def nullnext(s, W): a = s.values idx = np.flatnonzero(s.notnull().values)+1 last_idx = idx[0] a[last_idx:last_idx+W] = np.nan for i in idx[1:]: if i &gt; last_idx + W: last_idx = i a[last_idx:last_idx+W] = np.nan return s Sample run - In [336]: s Out[336]: 0 1.0 1 NaN 2 2.0 3 3.0 4 NaN 5 NaN 6 4.0 7 5.0 8 NaN Name: NaN, dtype: float64 In [337]: nullnext(s, W=4) Out[337]: 0 1.0 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 4.0 7 NaN 8 NaN Name: NaN, dtype: float64 Approach #2 With few tweaks, we can port this onto numba for performance efficiency. The implementation involves using strides. The relevant codes would look something like this - from numba import njit # https://stackoverflow.com/a/40085052/ @Divakar def strided_app(a, L, S ): # Window len = L, Stride len/stepsize = S nrows = ((a.size-L)//S)+1 n = a.strides[0] return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n)) @njit def set_mask(mask, idx, W): last_idx = idx[0] mask[0] = True l = len(idx) for i in range(1,l): if idx[i] &gt; last_idx + W: last_idx = idx[i] mask[i] = True return mask def nullnext_numba(s, W): a = s.values idx = np.flatnonzero(s.notnull().values)+1 mask = np.zeros(len(idx),dtype=bool) set_mask(mask, idx, W) a_ext = np.concatenate((a, np.full(W,np.nan))) strided_app(a_ext, W, 1)[idx[mask]] = np.nan return pd.Series(a_ext[:-W]) Further improvement We could optimize it further to improve memory efficiency by avoiding the concatenation and do all those edits in-situ with the input series and hence improve performance as well, like so - def nullnext_numba_v2(s, W): a = s.values idx = np.flatnonzero(s.notnull().values)+1 mask = np.zeros(len(idx),dtype=bool) set_mask(mask, idx, W) valid_idx = idx[mask] limit_mask = valid_idx &lt; len(a) - W strided_app(a, W, 1)[valid_idx[limit_mask]] = np.nan leftover_idx = valid_idx[~limit_mask] if len(leftover_idx)&gt;0: a[leftover_idx[0]:] = np.nan return s
type: Answer

http://stackoverflow.com/q/47687055
has answer: http://stackoverflow.com/a/47687222
has body: I have a dictionary which houses some integer values in a list: d = {"Numbers": [5, 10, 15, 20]} How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this: d = {"Numbers": [15, 20, 25, 30]} Thanks for the help!
has comment: http://stackoverflow.com/comment/82333745
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47687231
tagged with: python-2.7
score: 0
tagged with: list
possible better answer: http://stackoverflow.com/a/47687222
accepted answer: http://stackoverflow.com/a/47687088
has title: Adding to integers in a list which is inside a dictionary
tagged with: python
has answer: http://stackoverflow.com/a/47687088
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/47687929
type: Question

http://stackoverflow.com/comment/82121347
type: AnswerComment
comment on: http://stackoverflow.com/a/47579811
has text: I don't think this answers the question. As the authors of that paper say, "Note that we don't make any claims about the magnitude of the difference between p2 and p1 in the entire population — only that it exists." The question is about constructing a confidence interval around a value of 0.11, not zero.
score: 0
type: Comment

http://stackoverflow.com/q/47558518
tagged with: deep-learning
type: Question
score: 0
has body: How do I solve this issue? def random_mini_batches(train_inputs, train_targets, mini_batch_size = 64, seed = 0): m = 17000 mini_batches = [] np.random.seed(seed) permutation = list(np.random.permutation(m)) shuffled_X = train_inputs[:, permutation] shuffled_Y = train_targets[:, permutation].reshape((10,m)) Error: /home/kkkk/Desktop/ in random_mini_batches(X, Y, mini_batch_size, seed) m = 17000 mini_batches = [] np.random.seed(seed) 49 permutation = list(np.random.permutation(m)) ---&gt; 50 shuffled_X = train_inputs[:, permutation] 51 shuffled_Y = train_targets[:, permutation].reshape((10,m)) 52 IndexError: too many indices for array Is this something relating to the dimension of the shuffled_X and shuffled_Y?
has comment: http://stackoverflow.com/comment/82076525
upvote count: 1
tagged with: machine-learning
type: UnansweredQuestion
has title: Too many indices for an array
answer count: 1
downvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/82076166
has comment: http://stackoverflow.com/comment/82076378
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47558946
has comment: http://stackoverflow.com/comment/82075290
has comment: http://stackoverflow.com/comment/82076715
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82076451

http://stackoverflow.com/q/47590867
tagged with: class
type: Question
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82139664
score: 1
has title: Python: Change class variable with method from another file
answer count: 1
has answer: http://stackoverflow.com/a/47591419
accepted answer: http://stackoverflow.com/a/47591419
has body: I want to change class dictionary in main file with a method from another file. When I call the method it acts like it did it's job, yet when dictionary is called from the main file again, it looses the appended entry. Main file, testmain.py: import testside class MainClass(object): objects = {'three': 'four'} if __name__ == '__main__': testside.SideClass.add_to('one', 'two') # prints {'three': 'four', 'one': 'two'} print(MainClass.objects) # prints {'three': 'four'} Side file, testside.py: import testmain class SideClass(object): @staticmethod def add_to(name, thing): testmain.MainClass.objects[name] = thing print(testmain.MainClass.objects) What can I do to change class value from outside the file? Note, that I don't want to create an instance of MainClass().
has comment: http://stackoverflow.com/comment/82140561
tagged with: import
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/a/47927961
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47548945
score: 1
type: Answer
has body: You can write to a dataset as many times as you want - you just can't have twice a dataset with the same name. This is the error you're getting. Note that you are creating a dataset and at the same time you are putting some data inside of it. In order to write other data to it, it has to be large enough to accomodate it. Anyway, I believe you are confusing groups and datasets. Groups are created with e.g. grp = f.create_group('bar') # this create the group '/bar' and you want to store datasets in a dataset, created like you said with: dst = f.create_dataset('foo',shape=(100,)) # this create the dataset 'foo', with enough space for 100 elements. you only need to create groups and datasets once - but you can refer to them through their handles, (grp and dst), in order to write in them. I suggest you first go through your file once, create your desired groups and datasets using the 'shape' parameter to properly size it, and then populate the datasets with actual data.

data-science
tags question: http://stackoverflow.com/q/47665124
tags question: http://stackoverflow.com/q/47636049
tags question: http://stackoverflow.com/q/47584414
tags question: http://stackoverflow.com/q/47604717
tags question: http://stackoverflow.com/q/47605085
tags question: http://stackoverflow.com/q/47630631
type: Tag
tags question: http://stackoverflow.com/q/47607443
tags question: http://stackoverflow.com/q/47619249
tags question: http://stackoverflow.com/q/47596202
tag name: data-science
tags question: http://stackoverflow.com/q/47579274
tags question: http://stackoverflow.com/q/47619691
tags question: http://stackoverflow.com/q/47660917
tags question: http://stackoverflow.com/q/47689825
tags question: http://stackoverflow.com/q/47549176
tags question: http://stackoverflow.com/q/47574478
tags question: http://stackoverflow.com/q/47565616
tags question: http://stackoverflow.com/q/47682681
tags question: http://stackoverflow.com/q/47551596
tags question: http://stackoverflow.com/q/47617930
tags question: http://stackoverflow.com/q/47676138

http://stackoverflow.com/q/47660764
has title: feed placeholder traceback in tensorflow: 'tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor
tagged with: tensorflow
tagged with: python-3.x
type: Question
score: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47661383
answer count: 1
has body: Why does the following piece of code throw an exception? I feed the placeholder via feed_dict= in the for loop, but when I print the values of x or y_tensor, I get the following error message: 'tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype float and shape [?,5]'. Surprisingly, I don't get the error for a certain tensor when I print another one. For instance, when I only print y_tensor, I don't get the error message for the line where I declared x, and the opposite. I use the range of 10 only for testing the issue. The main problem is that the optimization can't work under this condition. How do I fix this? Here The Code: x = tf.placeholder(tf.float32, [None, 5], name='input') W = tf.Variable(tf.zeros([5,1])) b = tf.Variable(tf.zeros([1])) y = tf.nn.softmax(tf.matmul(x, W) + b) y_tensor = tf.placeholder(tf.float32, [None, 1], name='output') cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_tensor * tf.log(y), reduction_indices=[1])) optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) session = tf.Session() init = tf.global_variables_initializer() session.run(init) for i in range(10): batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i], dataE[i]]] batch_ys = [[dataG[i]]] session.run(optimizer ,feed_dict={x: batch_xs, y_tensor: batch_ys}) print(session.run(y))

http://stackoverflow.com/a/48715648
downvote count: 0
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/84547687
has comment: http://stackoverflow.com/comment/84430587
answers question: http://stackoverflow.com/q/47563103
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47563103
upvote count: 6
has body: As you note in your answer, the TZ environment variable is the key here. On unix-type systems, this supports more "friendly" values like "US/Pacific" or, indeed, "America/Denver", but on Windows, it doesn't. Although it's not available on Windows, the documentation for the time.tzset function describes the format you'll need to set TZ in to get what you want. It's... not pretty. But it works: C:\Users\zorb&gt;set TZ=MST+07MDT,M3.2.0,M11.1.0 C:\Users\zorb&gt;python.exe &gt;&gt;&gt; import time &gt;&gt;&gt; time.tzname ('MST', 'MDT') &gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2018, 2, 9, 16, 27, 7, 164062) (This was at 15:27 in Pacific time.) The structure of this format is: Standard time abbrevation (MST) UTC offset of standard time, in hours (+07) Daylight time abbreviation When daylight time starts (see below) When daylight time ends (see below) The format for the start and end of daylight time is: M (for "month-based") Month number - 3/March or 11/November, in this case. Week of the month - 1 through 5, meaning the 1st through 5th occurrence of the day named below. Day of the week - 0 for Sunday through 6 for Saturday There are also options to specify the time at which daylight time starts and ends (but it defaults to 02:00:00, so unnecessary in this case) and the offset for daylight time (but it defaults to 1 hour, so also not necessary). (edit) Turns out this is actually a glibc feature, not directly a python one. More detailed info in the glibc docs.

http://stackoverflow.com/comment/82282516
type: Comment
has text: _The problem is that one-to-one relationship is not unique so I can create two differents actors_ Then, don't user a One-To-One relation, this is exactly what it is meant for.
comment on: http://stackoverflow.com/q/47661382
score: 1
type: QuestionComment

http://stackoverflow.com/q/47546602
has comment: http://stackoverflow.com/comment/82072666
tagged with: anaconda
tagged with: convolution
has body: I am trying to pass a tensor to a CNN in python. I am using tf.layers.conv2d for this. I want to get the output dimensions as half of the input. I understand that I can use a padding of 'same' followed by a max pooling layer to achieve this, but another way that I found out in a recent paper is to use a 3x3 kernel with a 2x2 stride in addition to a 1x1 padding Now, as I understand, conv2d allows for a parameter called padding which can be either 'valid' or 'same', which does not allow for a padding of a specific length. Is there any way that this can be achieved directly in the operation? I am asking since the idea is to use multiple convolution layers, each successively halving the dimensions both length and width-wise. If someone can point out a similar topic or help with this, it would be great. Edit: I have been asked to include the code. But there is not much of a code since I am stuck at the very first point where the CNN needs to be designed. Nonetheless, here is the part that accepts the initial input and starts defining the CNN (here I have kept padding='same' since I was checking if that would work): def conv2d(z): output = tf.layers.conv2d(z,strides=[2,2],filters=3,padding='same',kernel_size=3); I am stuck at this point since going any further needs this initial layer to be correctly defined as successive layers will also work on the same principle. Also, my initial input size is a 224x224 image with 1 channel (grayscale image)
tagged with: python
has comment: http://stackoverflow.com/comment/82067237
tagged with: padding
has answer: http://stackoverflow.com/a/47626964
type: UnansweredQuestion
score: 1
answer count: 1
has title: How to add specific padding in conv2d
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/47686690
downvote count: 0
score: 6
answer count: 6
has answer: http://stackoverflow.com/a/47686748
upvote count: 6
has comment: http://stackoverflow.com/comment/82333069
has comment: http://stackoverflow.com/comment/82333057
has answer: http://stackoverflow.com/a/47686784
duplicate of: http://stackoverflow.com/q/17153779
type: AnsweredQuestion
has body: There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation(). def chooseName(): name = "" name = raw_input("Let's begin with your name. What is it? ") return name def nameConfirmation(): name = chooseName() print ("Right... So your name is", name,".") This is the output it gives. Right... So your name is Raven . How do I get rid of the space in between the name and the punctuation?
duplicate of: http://stackoverflow.com/q/493386
possible better answer: http://stackoverflow.com/a/47686856
has answer: http://stackoverflow.com/a/47686735
has answer: http://stackoverflow.com/a/47686731
has answer: http://stackoverflow.com/a/47686856
tagged with: python
linked to: http://stackoverflow.com/q/255147
has answer: http://stackoverflow.com/a/73017163
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47686735
has title: Why is there an extra space in between a variable and punctuation in a string? Python

http://stackoverflow.com/comment/82334298
type: AnswerComment
comment on: http://stackoverflow.com/a/47687326
score: 0
type: Comment
has text: @somerandomguy95, `file_a` is not necessary a `.py`? It **only** have **that** line? I am thinking right now in some interesting ideas... if the first one is "yes" look at [configparser](https://docs.python.org/3/library/configparser.html), if the first *or* second question is "yes" look at [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)...

http://stackoverflow.com/comment/82040283
comment on: http://stackoverflow.com/a/47541445
type: AnswerComment
has text: @O.rka I don't believe you can omit timestamps if you're using pandas.
score: 0
type: Comment

http://stackoverflow.com/a/47676364
accepted answer of: http://stackoverflow.com/q/47676270
has body: If you need to remove an uppercase ASCII letter with an underscore after it, only when not preceded with a word char and when followed with an alphanumeric char, you may use import re s = '(X_xy09 and X_foobar or (X_abc123 and X_something))' print(re.sub(r'\b[A-Z]_([a-zA-Z0-9])', r'\1', s)) See the Python demo and a regex demo. Pattern details \b - a leading word boundary [A-Z]_ - an ASCII uppercase letter and _ ([a-zA-Z0-9]) - Group 1 (later referenced to with \1 from the replacement pattern): 1 alphanumeric char.
score: 3
answers question: http://stackoverflow.com/q/47676270
has comment: http://stackoverflow.com/comment/82311642
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47606741
tagged with: mocking
tagged with: python
upvote count: 16
accepted answer: http://stackoverflow.com/a/47606924
score: 16
has comment: http://stackoverflow.com/comment/82172130
possible better answer: http://stackoverflow.com/a/47606992
type: AnsweredQuestion
has title: Testing that a method in instance has been called in mock
has answer: http://stackoverflow.com/a/47606924
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47606992
downvote count: 0
has comment: http://stackoverflow.com/comment/82172177
favorite count: 0
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/82172656
type: Question
has body: I have this sort of setup where I'm testing a class which is using another class, and I want to mock the latter so I'm only testing the first class itself. nuclear_reactor.py: class NuclearReactor(): def __init__(self): print "initializing the nuclear reactor" def start(self): print "starting the nuclear reactor" nuclear_manager.py: from nuclear_reactor import NuclearReactor class NuclearManager(): def __init__(self): print "manager creating the nuclear reactor" self.reactor = NuclearReactor() def start(self): print "manager starting the nuclear reactor" self.reactor.start() test_nuclear_manager.py: from mock import Mock import nuclear_manager from nuclear_manager import NuclearManager def test(): mock_reactor = nuclear_manager.NuclearReactor = Mock() nuke = NuclearManager() nuke.start() nuke.start() print mock_reactor.mock_calls print mock_reactor.start.call_count test() What I'd like to test is that NuclearReactor.start is called, but when I run this I get: manager creating the nuclear reactor manager starting the nuclear reactor manager starting the nuclear reactor [call(), call().start(), call().start()] 0 Which I totally understand since start is an attribute of the instance and not of the class, and I could parse the mock_calls, but isn't there a better way to check that the call of an instantiated mocked class is made? I could use dependency injection in NuclearManager to pass a mock NuclearReactor, but I'm thinking there would be an alternative way using just mock.

http://stackoverflow.com/comment/82135609
has text: Assuming those libs are OSS: select the one which depends on the older version of numpy, check if it works with the version required by the other lib, if yes update the requirement file and submit a patch, else fix it and submit a patch.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47588957
score: 1

http://stackoverflow.com/a/47637101
type: Answer
answers question: http://stackoverflow.com/q/47636668
score: -1
upvote count: 0
downvote count: 1
has body: I saved the reference of the label instead of the ref of the picture. self.image = [] for category in categories: self.image.append(PhotoImage(file=category[2]+".png")) imageLabel = Label(master, image=self.image[i]) imageLabel.grid(row=0, column=i) i = i + 1 this works now!

http://stackoverflow.com/q/47670803
favorite count: 0
duplicate of: http://stackoverflow.com/q/43404210
type: Question
answer count: 0
has title: How can I get the memory used by a list in Python?
upvote count: 1
type: UnansweredQuestion
downvote count: 0
has body: I know that getsizeof() is not a reliable indicator of memory, because as the documentation says: "Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to." So for a list it doesn't tell you how much RAM is consumed by the objects that those pointers refer to. How can I see how much memory is used by those? NB: In fine I am trying to compare the memory used by Numpy arrays and lists.
has comment: http://stackoverflow.com/comment/82301101
tagged with: python
has comment: http://stackoverflow.com/comment/82300597
has comment: http://stackoverflow.com/comment/82300593
has comment: http://stackoverflow.com/comment/82301437
has comment: http://stackoverflow.com/comment/82301329
score: 1
has comment: http://stackoverflow.com/comment/82302881
linked to: http://stackoverflow.com/q/43404210
tagged with: memory
linked to: http://stackoverflow.com/q/131303

http://stackoverflow.com/comment/82209760
type: AnswerComment
score: 1
has text: @AquilesPáez [pd.crosstab](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html#pandas-crosstab) supports one function at a time.
type: Comment
comment on: http://stackoverflow.com/a/47581428

http://stackoverflow.com/comment/82086473
has text: Sounds like you don't have the Python development files installed, something like `python-dev` in package manager.
comment on: http://stackoverflow.com/q/47564043
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47672350
score: 0
answers question: http://stackoverflow.com/q/47671733
has body: I am also a bit confused by the given code snippet, but if you just want to select certain years (as str values) in the dataframe, you could for example create a list of the years and then filter the dataframe accordingly. years_to_select = ['2012', '2013', '2014'] filtered_df = original_df[original_df['year'].isin(years_to_select)]
has comment: http://stackoverflow.com/comment/82303888
type: Answer

http://stackoverflow.com/q/47678961
answer count: 3
downvote count: 0
tagged with: dataframe
upvote count: 1
score: 1
has body: I have a dataframe with more rows and columns but example with one is here: id values 1 [v1, v2, v1] How to get unique values from list in pandas column? Desired output in second column v1, v2 I have tried with df['values'].unique() but obviously it's not working.
favorite count: 0
has title: Get unique from list as values in Pandas python
has answer: http://stackoverflow.com/a/47679364
type: Question
has answer: http://stackoverflow.com/a/47680095
has answer: http://stackoverflow.com/a/47679040
type: UnansweredQuestion
tagged with: python
tagged with: pandas

http://stackoverflow.com/q/47696262
accepted answer: http://stackoverflow.com/a/47696522
tagged with: python
has answer: http://stackoverflow.com/a/47696522
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/82352085
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has body: I'm reading two csv files with pandas. df1= pd.read_csv('file_1.csv') df2 = pd.read_csv('file_2.csv') data = pd.merge(df1, df2, on='id') The problem I'm facing is that the final data frame, data, has fewer rows since some id values are missing from both input files.What I'll like to do is to have a default value for all the cells in both cases, like: data = pd.merge(df1, df2, on='id',default_vaue=0)
favorite count: 0
type: Question
has title: Add default values while merging tables in pandas
has comment: http://stackoverflow.com/comment/82352360
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/47575121
answers question: http://stackoverflow.com/q/47571727
score: 0
type: Answer
has body: Just keep track somehow of which line is the first one of each block, and write _sum in that position. For instance, I haven't checked, but something like this should work lines = open("file.txt", "r").read().splitlines() _sum = -1 last_first_line = -1 for i, line in enumerate(lines): if not line.startswith('fit') : _sum += float(line) lines[i] = '{:0.6f}'.format(1.) if line.startswith('fit'): if last_first_line &gt; 0: lines[last_first_line] = _sum _sum = 0 last_first_line = i + 1 lines[last_first_line] = _sum with open('output.txt', 'w') as out: out.write('\n'.join(lines))

http://stackoverflow.com/comment/82276384
comment on: http://stackoverflow.com/q/47658456
type: Comment
type: QuestionComment
score: 0
has text: First, please provide a [mcve]. It also depends on what you do; update the figure and save it, or update the figure and show it, or both? In case you want to show it, would you like to replace the figure or show one after the other?

http://stackoverflow.com/comment/82239252
score: 0
comment on: http://stackoverflow.com/q/47638093
type: Comment
type: QuestionComment
has text: Sure I iterate through the list and compute error between two values. If the error is < some threshold then it is grouped otherwise a new 'entity group' is created and then that is compared again

http://stackoverflow.com/comment/82305351
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47671283
has text: may be you wanted to have a look on url https://techarena51.com/blog/how-to-install-python-3-and-flask-on-linux/ also is there any specific reason to create a class? most of the example i have seen using functions only

http://stackoverflow.com/q/47684057
answer count: 3
downvote count: 0
has title: How to resample and round every index into nearest seconds?
has answer: http://stackoverflow.com/a/47704513
favorite count: 0
type: Question
has body: My data looks like (the datatype is Pandas DataFrame) : price = time bid 03:03:34.797000 116.02 03:03:34.797000 116.02 03:03:54.152000 116.02 03:03:54.169000 116.02 03:03:54.169000 116.02 03:07:36.899000 116.24 03:07:48.760000 116.24 03:07:48.760000 116.24 03:07:48.761000 116.24 I tried to resample the data into second level data and align every data into the nearest seconds no earlier than the original time. I expect the result to be: 03:04:00 116.02 03:05:00 NaN 03:06:00 NaN 03:07:00 NaN 03:08:00 116.24 and used price.resample('Min').last() However I got. 03:03:34.797000 116.02 03:04:34.797000 NaN 03:05:34.797000 NaN 03:06:34.797000 NaN 03:07:34.797000 116.24 Everything goes well except the alignment. Anyone could help me solve the problem? Thanks.
tagged with: database
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47684306
has answer: http://stackoverflow.com/a/47684269
tagged with: pandas
score: 3
upvote count: 3

http://stackoverflow.com/a/47601017
has body: You can use builtins and still keep the association. E.g.: data_list = sorted(lst, key=lambda x: x[1])
accepted answer of: http://stackoverflow.com/q/47600973
type: Answer
answers question: http://stackoverflow.com/q/47600973
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47588025
has body: If each custom combo box contains 1 standard combo box, there are few things to resolve it: Find the first combo box (for example) by using found_index criterion. Then find descendant combo box unambiguously. The code should look so: custom_combo = app.Dialog.child_window(auto_id="AgrementTypeFilter", control_type="Custom", found_index=0) real_combobox = custom_combo.child_window(auto_id="CheckBoxEdit", control_type="ComboBox").wrapper_object() real_combobox.item_count() Another way is using best match names if they are different: combobox = app.Dialog.ComboBoxCCP.wrapper_object() combobox.item_count() Finally you can also enumerate all the descendants of this control type: comboboxes = app.Dialog.descendants(control_type="ComboBox") target_combobox = [combo for combo in comboboxes if combo.item_count() == 12][0] Method descendants() will return filtered list of wrappers. Then it's easy to iterate it and find the target one.
has comment: http://stackoverflow.com/comment/82157589
has comment: http://stackoverflow.com/comment/82313476
has comment: http://stackoverflow.com/comment/82170071
score: 0
has comment: http://stackoverflow.com/comment/82279020
has comment: http://stackoverflow.com/comment/82170061
has comment: http://stackoverflow.com/comment/82324061
has comment: http://stackoverflow.com/comment/82147156
has comment: http://stackoverflow.com/comment/82240090
has comment: http://stackoverflow.com/comment/82254868
has comment: http://stackoverflow.com/comment/82294561
answers question: http://stackoverflow.com/q/47583544
type: Answer

http://stackoverflow.com/comment/110206863
type: AnswerComment
comment on: http://stackoverflow.com/a/60553318
has text: I do not really understand how your solution extracts the multiple rotation matrices. Can you elaborate a bit more. From what I understand your Nx3x3 is the extracted rotation matrices, right?
score: 0
type: Comment

http://stackoverflow.com/a/47541336
score: 3
has comment: http://stackoverflow.com/comment/82040534
has comment: http://stackoverflow.com/comment/82040116
has body: scipy.spatial.distance.cdist + np.where ary=scipy.spatial.distance.cdist(df1'A', 'B', 'C', df2'A', 'B', 'C', metric='euclidean') order=np.where(ary==ary.min(1)[:,None]) df2['New']=df1.reindex(order[1]).Label.values df2 Out[612]: A B C Label New 0 3 3 3 2 2 1 2 2 2 1 1 2 4 4 4 3 3 EDIT : By using cold's argmin() ary = scipy.spatial.distance.cdist(df2'A', 'B', 'C', df1'A', 'B', 'C', metric='euclidean') df2['New']=df1.reindex(ary.argmin(1)).Label.values df2 Out[659]: A B C Label New 0 3 3 3 2 2 1 2 2 2 1 1 2 4 4 4 3 3 3 3 3 3 3 2
type: Answer
has comment: http://stackoverflow.com/comment/82040633
answers question: http://stackoverflow.com/q/47541166
has comment: http://stackoverflow.com/comment/82040667
has comment: http://stackoverflow.com/comment/82040113
downvote count: 0
has comment: http://stackoverflow.com/comment/82040447
has comment: http://stackoverflow.com/comment/82040026
upvote count: 3

http://stackoverflow.com/a/47598184
downvote count: 0
has body: you can format it this way. pass in a dictionary of possible values for a and map it to your string. dictionary = { 'a':[5,10,15] } def func(d): for i in range(3): print('a is {{a[{0}]}}'.format(i).format_map(d)) func(dictionary) print: a is 5 a is 10 a is 15
type: Answer
answers question: http://stackoverflow.com/q/47597831
score: 2
upvote count: 2

http://stackoverflow.com/a/47606957
has body: If you don't want any console window to appar under windows. Do start On windows, execute it with pythonw. The hotkey is Windows + r pythonw C:\Users\yourUser\Desktop\hidden.py
answers question: http://stackoverflow.com/q/47606701
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82181905

http://stackoverflow.com/comment/82078368
comment on: http://stackoverflow.com/a/47560261
type: AnswerComment
type: Comment
has text: looks great but in this case of the `create` u avoided the `user` is that on purpose?
score: 0

http://stackoverflow.com/comment/82281886
score: 0
type: AnswerComment
has text: Unfortunately the URL is behind a login page that only specific people have access to. Is there other information I could give you that might serve as a placeholder for the URL?
comment on: http://stackoverflow.com/a/47660624
type: Comment

http://stackoverflow.com/q/47656041
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47657361
score: 6
tagged with: django
has answer: http://stackoverflow.com/a/47657107
accepted answer: http://stackoverflow.com/a/47657107
has body: Hello I want to know that how can I split string of dictionary values This is my crawler which is returns dictionary data looks like data = { {0:'http://..., product name, product price'}, {1:'http://...2, product name2, product price2'}, {N:'http://...2, product name2, product price n'} } I want to split these data by comma like, for value in data.values(): href, product_name, product_price = str(value).split(",") in Django This is my crawler.py import requests from urllib import parse from bs4 import BeautifulSoup def spider(item_name): url_item_name = parse.quote(item_name.encode('euc-kr')) url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name resp = requests.get(url) resp.raise_for_status() resp.encoding='euc-kr' plain_text = resp.text soup = BeautifulSoup(plain_text, 'lxml') mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]}) #for link in soup.select('div.list_info p.info_tit a') : data = {} count = -1; for link in mytag: if(link.find('a')): count+=1 href = link.find('a').get('href') product_name = link.find('a').string data[count] = str(href) + ", " + str(product_name) else: product_price = link.string if(product_price): data[count] = data[count] +", " + str(product_price) for value in data.values(): print(value) resp.close() return data and this is my views def post_shop_list(request): posts = spider("product name") return render(request, 'blog/post_list.html',{'posts' : posts}) and this is my post_list.html {% for key, value in posts.items %} {{key}} product name :{{value}} {% endfor %} Thank you .. !!
type: Question
has title: Django How can i split string using template tag
upvote count: 6
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47657361

http://stackoverflow.com/comment/82210109
score: 0
type: QuestionComment
has text: You need to set a breakpoint at the line that prints the `"Unable to create process using"`, guess what's wrong with variable values, then track the erroneous value back to its origin.
type: Comment
comment on: http://stackoverflow.com/q/47625868

http://stackoverflow.com/comment/82330093
has text: Worked perfectly. Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/47626873
score: 0
type: Comment

http://stackoverflow.com/q/47552529
has comment: http://stackoverflow.com/comment/82061972
has body: So I was experimenting with somo Odoo code (Qweb templates to be more specific) and I found this function def foreach_iterator(base_ctx, enum, name): ctx = base_ctx.copy() if not enum: return if isinstance(enum, int): enum = xrange(enum) size = None if isinstance(enum, Sized): ctx["%s_size" % name] = size = len(enum) if isinstance(enum, Mapping): enum = enum.iteritems() else: enum = izip(*tee(enum)) value_key = '%s_value' % name index_key = '%s_index' % name first_key = '%s_first' % name last_key = '%s_last' % name parity_key = '%s_parity' % name even_key = '%s_even' % name odd_key = '%s_odd' % name for index, (item, value) in enumerate(enum): ctx[name] = item ctx[value_key] = value ctx[index_key] = index ctx[first_key] = index == 0 if size is not None: ctx[last_key] = index + 1 == size if index % 2: ctx[parity_key] = 'odd' ctx[even_key] = False ctx[odd_key] = True else: ctx[parity_key] = 'even' ctx[even_key] = True ctx[odd_key] = False yield ctx # copy changed items back into source context (?) # FIXME: maybe values could provide a ChainMap-style clone? for k in base_ctx.keys(): base_ctx[k] = ctx[k] This function is how t-foreach is implemented so it is supposed to create an iterator over whatever you pass into it. But... &gt;&gt;&gt; list(foreach_iterator({},[1,2,3],"name")) [{'name': 2, 'name_even': False, 'name_first': False, 'name_index': 1, 'name_last': True, 'name_odd': True, 'name_parity': 'odd', 'name_size': 2, 'name_value': 2}, {'name': 2, 'name_even': False, 'name_first': False, 'name_index': 1, 'name_last': True, 'name_odd': True, 'name_parity': 'odd', 'name_size': 2, 'name_value': 2}] and then &gt;&gt;&gt; k = foreach_iterator({},[1,2],"name") &gt;&gt;&gt; k.next() {'name': 1, 'name_even': True, 'name_first': True, 'name_index': 0, 'name_last': False, 'name_odd': False, 'name_parity': 'even', 'name_size': 2, 'name_value': 1} &gt;&gt;&gt; k.next() {'name': 2, 'name_even': False, 'name_first': False, 'name_index': 1, 'name_last': True, 'name_odd': True, '…
tagged with: python
has comment: http://stackoverflow.com/comment/82082152
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47562196
answer count: 1
has title: obscure iterator behavior in Python
type: Question
accepted answer: http://stackoverflow.com/a/47562196
has comment: http://stackoverflow.com/comment/82061688

http://stackoverflow.com/a/47610022
type: Answer
has comment: http://stackoverflow.com/comment/82179600
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47609841
has body: A one-line solution! output = [l[:4] + [str(sum(int(j[4]) for j in lists if j[:3] == l[:3] and j[4]))] for l in (l for l in lists if l[3])] which gives output as: [['x1', 'y1', 'z1', '10', '10'], ['x2', 'y2', 'z2', '20', '20']] Instead of trying to explain that line, I have expanded the process into a larger for-loop Scroll down for a proper explanation of how it is working. output = [] for l in (l for l in lists if l[3]): sm = 0 for j in lists: if j[:3] == l[:3] and j[4]: sm += int(j[4]) sm = str(sm) if sm == l[3]: output.append(l[:4] + [sm]) how? Well, we are looping through the lists in the generator: l for l in lists if l[3]. Essentially, we just want to start looping through the lists that actually have a value in the third index so that we can sum up the other lists which have the same first three elements and compare this to l[3]. We then declare a sum variable (sm) as 0 which we will add the other lists elements to. Next we want to begin looping through the other lists in lists which may have the same first three elements. We then check if the first three elements are the same (j[:3] == l[:3]) and also check if there is actually something to add to the sum in the fourth element (otherwise we will get an error when trying to convert an empty string to an int). Then, if it passes this test, we add j[4] to sm and continue onto the next list. Next we convert the sum (sm) to a string since that is the data type it needs to be in the end and saves converting l[3] to an integer. Finally we compare this string to the fourth element in our original list - if it is the same, then we append the original list along with the sum (using list concatenation) to the output list.
accepted answer of: http://stackoverflow.com/q/47609841

http://stackoverflow.com/q/47558240
has answer: http://stackoverflow.com/a/47558619
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/82075086
has title: numpy select each row with different lengths
answer count: 2
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82074198
has answer: http://stackoverflow.com/a/47558651
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82074835
tagged with: python-3.5
type: UnansweredQuestion
has body: I have two array s x=array([[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [2, 2, 2, 2, 2]]) I want to subselect elements in each row by the length in array y y = array([3, 2, 4]) My target is z: z = array([[0, 0, 0], [1, 0,], [2, 2, 2, 2]]) How could I do that with numpy functions instead of list/loop? Thank you so much for your help.
tagged with: arrays

http://stackoverflow.com/comment/82209345
comment on: http://stackoverflow.com/q/47625499
type: QuestionComment
type: Comment
has text: thanks. This is a complete code, and its very small, so I chose to put it all on the web.
score: 0

http://stackoverflow.com/comment/82292858
has text: I think it is not about which extensions I use. It's about where do I keep those implementations.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47620775
score: 0

http://stackoverflow.com/q/47614135
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/82186759
has comment: http://stackoverflow.com/comment/82186806
score: 3
has body: I feel like I've tried everything to get this working and it just wont run... I'm also still learning python, my class for it started the start of fall a few months ago. Long story short, I'm making a text-based "escape the room" game in Python. The player chooses objects to interact with, and the results gives them items to use until they find the key to unlock the door. It's quite short and linear, to save my sanity. I think this is the part of my code that isn't running, which is in a big function that contains similar code for all 4 objects (sorry if its a little long. This is all basically, "While they choose the painting, describe it, as them if they want to search it, (1=yes, 2=no). If they do, describe the search result. Because this is the last object for the story (safe behind painting has the door key), Once the safe is opened and they have the key, I don't want it to ask them the main question again, but it does!? main question that is repeated is; def main_choice_input(): main_choice = input(""" What would you like to check out? (1=Bed, 2=Desk, 3=Dresser, 4=Painting): """) return main_choice; #code for describing the objects, the inputs for the player to search them #and the search results, if tried to name them as self-explanatory as #possible previous whiles are for the other objects, this is all in one big function. while main_choice == "4": painting_description() #painting_input is the "search this?" question painting_input = painting_interaction() if painting_input =="1": painting_search(painting_input,dresser_input) if use_key=="1" and painting_input =="1": #If they 'used the key' on the desk to get the code: painting_search(painting_input,dresser_input) unlock = input(""" Would you like to unlock the safe? [1=Yes/2=No]: """) if unlock == "1": #print (story for opening the safe) safe=1 #for ending the game- checking if the safe is open if unlock == "2": print(""" That's too bad, let's try again...""") main_choice = main_choice_input() main_route(m…
tagged with: while-loop
tagged with: if-statement
upvote count: 3
has title: Nested while/if code is skipped by program?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90602244
answer count: 0
tagged with: function
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47606400
has body: how to combine numpy 3d array shape (326, 25, 16) and 1d array shape (326,) the array shape (326, 25, 16) is input for CNN and array shape (326,) is the labels.
tagged with: python
has title: How to combine numpy 3d array shape (326, 25, 16) and 1d array shape (326,)
favorite count: 0
has answer: http://stackoverflow.com/a/47606689
type: Question
tagged with: numpy
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/82184794
comment on: http://stackoverflow.com/a/47613196
has text: Ah got! Thank you so much!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47661180
tagged with: perl
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47683891
has answer: http://stackoverflow.com/a/47683891
has title: How can I assign a weight for frequency score to a graph's edge using Graph::Easy
possible better answer: http://stackoverflow.com/a/47661977
has body: How do I assign a weight or frequency score to an graph's edge using Graph::Easy? I have a list of bigrams and their frequencies. I can easily create a (mathematical) graph of only the bigrams using Graph::Easy. The output is exactly what I desire. But when I try to "set_attribute" I get an error that says, "'frequency' is not a valid attribute name". What am I doing wrong? Using Graph::Easy, how do I make frequency a valid attribute? #!/usr/bin/perl # graph.pl - given a list of bigrams and their frequencies, output graphml # require use Graph::Easy; use strict; # initialize my $graph = Graph::Easy-&gt;new; # process the data while ( &lt;DATA&gt; ) { # parse chop; my ( $nodes, $frequency ) = split( "\t", $_ ); my ( $source, $target ) = split( ' ', $nodes ); # update the graph my $edge = $graph-&gt;add_edge( $source, $target ); # error happen here $edge-&gt;set_attribute( 'frequency', $frequency ); } # output &amp; done print $graph-&gt;as_graphml(); exit; # a set of bigrams and their frequencies __DATA__ cds classroom 4 maximum registration 4 may want 3 anomalies within 2 resulting analysis 2 participants may 2 corpus without 2 journal articles 2 quickly learn 2 active reading 2 text mining 2 literally count 2 find patterns 2 14 million 2 digital humanities 2 humanities research 2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47661977
tagged with: graph
answer count: 2
upvote count: 3

http://stackoverflow.com/q/47641736
tagged with: dataframe
tagged with: python
score: 0
answer count: 0
tagged with: pandas
has title: Adding Python list as new column into Pandas DataFrame + "ValueError: Length of values does not match length of index"
has comment: http://stackoverflow.com/comment/82242676
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82243308
has body: I have a Python list of Pandas Dataframes and a list of lists containing numbers. df_list = [df,df,df,df] #Four Dataframes id_list = [[123, 452],[342, 533, 222, 402, 124],[125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],[154, 122, 563]] ##Four lists As shown below, I tried to insert each list in id_list as a new column ('order_id') into each Dataframe from df_list. for df in df_list: print(len(df.index)) #checked the number of rows for each Dataframe to ensure it matches the size of each list in id_list for id in id_list: df['order_id'] = id After I run this code, I get the "ValueError:Length of values does not match length of index". I made sure the length of each id_list matches that of each DataFrame. What can I do to resolve this error and successfully add each id_list into each Dataframe? Thank you!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82241946
has comment: http://stackoverflow.com/comment/82242633

http://stackoverflow.com/comment/82195136
type: AnswerComment
score: 0
has text: no i am storing the list as character platform is the model in which there is a char field as list so platform.list just gives me that entire row
comment on: http://stackoverflow.com/a/47618345
type: Comment

http://stackoverflow.com/comment/82341310
comment on: http://stackoverflow.com/a/47651333
has text: @python I don't use `tix` and I don't know any link to its documentation. However I have implemented a `CheckboxTreeview` from a `ttk.Treeview` (it 's the second answer to https://stackoverflow.com/questions/5104330/how-to-create-a-tree-view-with-checkboxes-in-python) that already propagates the checking to the children.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82084099
type: Comment
has text: @TyrelBarstow I am glad Evan questioned the sum(level) stuff. It is not needed. Glad, this could help.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47558190

http://stackoverflow.com/comment/82140997
type: Comment
type: QuestionComment
has text: Ciao, I just have done it. Thanks for the suggestion
score: 0
comment on: http://stackoverflow.com/q/47552206

http://stackoverflow.com/a/47542753
answers question: http://stackoverflow.com/q/47542674
type: Answer
accepted answer of: http://stackoverflow.com/q/47542674
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8
has body: This should be pretty simple using mask. df.mask(df == 0).describe() 22 72 79 86 87 88 90 count 8.000000 5.000000 7.000000 6.000000 12.000000 11.000000 7.00000 mean 3.524250 1.574800 4.680857 1.227667 3.196167 4.641273 5.84200 std 3.000573 1.538745 3.752722 1.174092 2.391229 5.992560 9.24574 min 0.762000 0.254000 0.254000 0.254000 0.508000 0.254000 0.50800 25% 1.524000 0.508000 1.270000 0.317500 1.016000 0.762000 1.14300 50% 2.540000 0.762000 4.826000 0.762000 2.540000 1.270000 2.03200 75% 4.127500 2.540000 8.128000 1.968500 4.445000 5.207000 4.82600 max 8.382000 3.810000 8.890000 3.048000 7.366000 16.510000 26.41600 All values satisfying df == 0 are masked, and describe will not take these into account when calculating stats.

http://stackoverflow.com/q/47557905
score: 2
has title: AttributeError: type object 'StringMethods' has no attribute '_make_accessor'
downvote count: 0
favorite count: 0
type: Question
tagged with: attributeerror
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I know there are so man questions asking of "AttributeError" But i couldn't solve my problem. It seems to be a problem with os, because it works well on my friend's computer that uses mac, which causes problems on my computer using windows. import pandas as pd import numpy as np import konlpy from konlpy.tag import Twitter import nltk from gensim import models import re import requests import pickle with open('labeled_data.pkl', 'rb') as data: data_refd = pickle.load(data) data_refd.shape So far this is my code, and of course 'labeled_data.pkl' is in my home directory. And I got the following error. --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-7-df61982f39de&gt; in &lt;module&gt;() 1 with open('labeled_data.pkl', 'rb') as data: ----&gt; 2 data_refd = pickle.load(data) 3 data_refd.shape() C:\Users\ji\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in &lt;module&gt;() 104 105 --&gt; 106 class Index(IndexOpsMixin, PandasObject): 107 """ 108 Immutable ndarray implementing an ordered, sliceable set. The basic object C:\Users\ji\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in Index() 177 178 # String Methods --&gt; 179 str = accessor.AccessorProperty(strings.StringMethods) 180 181 def __new__(cls, data=None, dtype=None, copy=False, name=None, C:\Users\ji\Anaconda3\lib\site-packages\pandas\core\accessor.py in __init__(self, accessor_cls, construct_accessor) 45 self.accessor_cls = accessor_cls 46 self.construct_accessor = (construct_accessor or ---&gt; 47 accessor_cls._make_accessor) 48 self.__doc__ = accessor_cls.__doc__ 49 AttributeError: type object 'StringMethods' has no attribute '_make_accessor' I do not know what the problem is. I would appreciate your help.
answer count: 0
tagged with: pandas

http://stackoverflow.com/q/47670547
tagged with: nose
type: AnsweredQuestion
answer count: 2
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47808654
score: 5
has body: I am running a couple of nosetests with test cases in different modules (files) each containing different tests. I want to define a function/method that is only called once during the execution with nosetest. I looked at the documentation (and e.g. here) and see there are methods like setup_module etc. - but where and how to use them? Put them into my __init__.py? Something else? I tried to use the following: class TestSuite(basicsuite.BasicSuite): def setup_module(self): print("MODULE") ... but this printout is never done when I run the test with nosetest. I also do not derive from unittest.TestCase (which will result in errors).
has answer: http://stackoverflow.com/a/47808654
possible better answer: http://stackoverflow.com/a/47885934
upvote count: 5
has title: How to define a setup method only called once during testing with nosetest?
tagged with: python
has answer: http://stackoverflow.com/a/47885934
linked to: http://stackoverflow.com/q/30750621

http://stackoverflow.com/comment/82067479
has text: It's passing the object to your function. You need to mutate it, not replace it.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47555265

http://stackoverflow.com/a/47600435
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47599127
upvote count: 1
has comment: http://stackoverflow.com/comment/82159547
type: Answer
has body: What I'd ultimately like to do is filter by an Association Object's attribute values using a regex expression, such that I could do .any(url={{REGEX EXPRESSION}}). Is this a possibility? Sure is. You can pass about any SQL expression to any() as criterion. For example a LIKE expression, using startswith(), contains(), like() itself, or what have you: session.query(Result).\ filter(Result.related_images.any( Image.url.startswith('result1'))) Using regexp is a bit DB specific usually, and you've omitted that bit of information in your question, so I've tried to avoid it in this answer. But you'd use it the same way as the LIKE expression here.
accepted answer of: http://stackoverflow.com/q/47599127
score: 1

http://stackoverflow.com/comment/82052955
has text: @PM2Ring Then why is `True` returned?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47548113
score: 0

http://stackoverflow.com/comment/82204951
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47623228
type: Comment
has text: Give your example in your post above. You can edit your post by adding your example.

http://stackoverflow.com/a/47676107
accepted answer of: http://stackoverflow.com/q/47666679
type: Answer
upvote count: 2
has body: Closing figure at the end of animation You could in principle create a new figure inside the loop. Then closing one figure will allow the program to continue and create the next figure and show it. The figure can be closed automatically at the end of the animation. import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def createanimatedfig(omega): fig, ax = plt.subplots() ax.axis([0,2*np.pi,-1,1]) ax.set_title(u"animated sin(${:g}\cdot t$)".format(omega)) t = np.linspace(0,2*np.pi) x = np.sin(omega*t) line, = ax.plot([],[], lw=3) ani = FuncAnimation(fig,animate, len(t), repeat=False, fargs=(t,x,line, len(t)), interval=20) plt.show() def animate(i, t,x, line, maxsteps): line.set_data(t[:i],x[:i]) if i >= maxsteps-1: plt.close(line.axes.figure) omegas= [1,2,4,5] for omega in omegas: createanimatedfig(omega) Note that the above will produce an error when run with the TkAgg backend. In this case you need to postpone the figure closing to after the animation has truely stopped. To this end a timer may be used. def animate(i, t,x, line, maxsteps): line.set_data(t[:i],x[:i]) if i >= maxsteps-1: timer = line.axes.figure.canvas.new_timer(interval=10) timer.single_shot = True timer.add_callback(lambda : plt.close(line.axes.figure)) timer.start() Run animations within single figure Alternatively you may use a single figure to show all animations one after the other. This would require to have some control over when which animation stops and so the use of a class to handle the steps is useful. import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation class Ani(): def __init__(self,omegas, nsteps, line): self.nsteps = nsteps self.omegas = omegas self.line=line self.step = 0 self.i = 0 def getdata(self,j): t = np.arange(0,j)/float(self.nsteps)*2*np.pi x = np.sin(self.omegas[self.step]*t) return t,x def gen(self): for i in range(len(self.omegas)): tit = u"animated sin(${:g}\cdot t$)".format(self.om…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47666679
score: 2

http://stackoverflow.com/a/47635500
accepted answer of: http://stackoverflow.com/q/47635397
has comment: http://stackoverflow.com/comment/82230613
has comment: http://stackoverflow.com/comment/82230571
has body: Factorizing by sorting and assigning by reshaping i.e df1'node1','node2' = (pd.factorize(np.sort(df1'node1','node2'.values.reshape(-1)))[0]+1).reshape(-1,len(df1)).T node1 node2 weight 0 1 3 1 1 1 4 2 2 2 4 1 3 3 5 1 Another approach with melt and factorize and renaming with dict vals = pd.factorize(df1'node1','node2'.melt().sort_values('value')['value']) to_rename = dict(zip(vals[1],np.unique(vals[0]+1))) # {2: 1, 3: 2, 6: 3, 7: 4, 28: 5} df1'node1','node2' = df1'node1','node2'.apply(lambda x : x.map(to_rename)) # Also df1'node1','node2' = df1'node1','node2'.replace(to_rename) Thanks @jezrael node1 node2 weight 0 1 3 1 1 1 4 2 2 2 4 1 3 3 5 1
answers question: http://stackoverflow.com/q/47635397
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/82230323
has comment: http://stackoverflow.com/comment/82230410
has comment: http://stackoverflow.com/comment/82230812
downvote count: 0
has comment: http://stackoverflow.com/comment/82230494
upvote count: 7
type: AcceptedAnswer

http://stackoverflow.com/q/47680678
upvote count: 1
score: 1
tagged with: tensorboard
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I'm trying to visualize the filters of a convolutional layer using this code, but cannot get the image to write to my summary file. I have scalars that I am outputting with no issue, and I attempted to modify the code to add the image as follows summary = tf.Summary() summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward)) summary.value.add(tag='Perf/Length', simple_value=float(mean_length)) with tf.variable_scope(self.name + "/conv1", reuse=True): weights = tf.get_variable("weights") grid = put_kernels_on_grid(weights) image = tf.summary.image('conv1/weights', grid, max_outputs=1) summary.value.add(tag='conv1/weights', image=image) self.summary_writer.add_summary(summary, episode_count) With only the scalars, this works fine, but adding the image gives the error TypeError: Parameter to MergeFrom() must be instance of same class: expected Image got Tensor. for field Value.image I also tried adding the image summary directly by changing the code to summary = tf.Summary() summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward)) summary.value.add(tag='Perf/Length', simple_value=float(mean_length)) with tf.variable_scope(self.name + "/conv1", reuse=True): weights = tf.get_variable("weights") grid = put_kernels_on_grid(weights) image = tf.summary.image('conv1/weights', grid, max_outputs=1) self.summary_writer.add_summary(image, episode_count) self.summary_writer.add_summary(summary, episode_count) But got the error AttributeError: 'Tensor' object has no attribute 'value' What is the correct way to output my image to my summary file?
has title: Outputting an image summary to Tensorboard
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47725080
has answer: http://stackoverflow.com/a/47706769
downvote count: 0

http://stackoverflow.com/q/47685174
has comment: http://stackoverflow.com/comment/82330381
upvote count: 0
downvote count: 2
has body: I'm trying to get make a comments section for a website with the backend written in python. As of now, everything works fine except I cannot figure out how to format the date and time the way I want. What I am trying to have at the time of posting is either of these: Posted on Tue, 06/12/18 at - 11:20 or Posted on 06/12/18 at - 11:21 Currently, what I have when the method is called is this: import time from datetime import * time = ("Posted on " + str(datetime.now().day) + "/" + str(datetime.now().month) + " at: " + str(datetime.now().hour) + ":" + str(datetime.now().minute))
has answer: http://stackoverflow.com/a/47685214
has comment: http://stackoverflow.com/comment/82330047
possible better answer: http://stackoverflow.com/a/47685215
has comment: http://stackoverflow.com/comment/82330006
has comment: http://stackoverflow.com/comment/82331972
has comment: http://stackoverflow.com/comment/82330076
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47685215
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82330055
has comment: http://stackoverflow.com/comment/82331923
accepted answer: http://stackoverflow.com/a/47685214
has comment: http://stackoverflow.com/comment/82330293
score: -2
tagged with: strftime
tagged with: datetime
has comment: http://stackoverflow.com/comment/82346089
tagged with: python
has comment: http://stackoverflow.com/comment/82330045
type: AnsweredQuestion
answer count: 2
has title: How to format dates and times?
has comment: http://stackoverflow.com/comment/82332002
has comment: http://stackoverflow.com/comment/82330013

http://stackoverflow.com/a/47612588
answers question: http://stackoverflow.com/q/47612502
type: Answer
accepted answer of: http://stackoverflow.com/q/47612502
has comment: http://stackoverflow.com/comment/82183395
upvote count: 12
score: 12
type: AcceptedAnswer
downvote count: 0
has body: You have to check if all of the strings in the first list is contained by any string in the second list: def all_exist(avalue, bvalue): return all(any(x in y for y in bvalue) for x in avalue) items = ['greg','krista','marie'] print(all_exist(['greg', 'krista'], items)) # -&gt; True print(all_exist(['gre', 'kris'], items)) # -&gt; True print(all_exist(['gre', 'purple'], items)) # -&gt; False print(all_exist([], items)) # -&gt; True
has comment: http://stackoverflow.com/comment/95324679

http://stackoverflow.com/q/47599227
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47599853
has comment: http://stackoverflow.com/comment/82156869
has comment: http://stackoverflow.com/comment/82156860
has title: How do I check whether a variable was changed?
has body: Say I have two lists [['1', '2', '1', '3', '1', '3'], ['A', 'G', 'T', 'T', 'T', 'G']] In this case each index matches the number on the left with the letter on the right, so 1 : A, and 2 : G and so on. I want to see if AT LEAST one number on the left changes mapping. So, I want to know if ANY number changes mapping. So if 1 : A changes to 1 : T, I would have True returned.
type: Question
has answer: http://stackoverflow.com/a/47599368
has comment: http://stackoverflow.com/comment/82156792
has answer: http://stackoverflow.com/a/47599418

http://stackoverflow.com/a/47796673
has body: I haven't coded in python in a long time, so my experience in this is extremely limited, but what you should do in these situations is go through each point in the code step by step and seeing what it does. Usually you'll find that somewhere along the line the output of something isn't what you expect it to be and breaks the code. I spent about 5 minutes setting up the code and adding some print statements along the way to see the code output and immediately found the issue. https://repl.it/repls/MoistInstructiveIcelandichorse Obviously operators[k][2] is being treated as a string rather than a list, so when you iterate through it, you'll be going through each character rather than each item. After a quick look at your list it seems like your list of operator expertise is a string and not a list. I'm not sure if that's intentional or not, but to make your code work you'll need to sort that out somehow.
type: Answer
has comment: http://stackoverflow.com/comment/82560912
score: 0
accepted answer of: http://stackoverflow.com/q/47676558
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47676558

http://stackoverflow.com/comment/82324568
has text: 0 and 1 are two clusters based on euclidean distances
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47682576

http://stackoverflow.com/comment/82310629
type: Comment
type: QuestionComment
has text: @CharlesPehlivanian you call it "service". I think you need two parts: One part which creates a traceback with more detailed information and a second part which renders this as HTML.
score: 0
comment on: http://stackoverflow.com/q/47674185

http://stackoverflow.com/comment/82205396
type: Comment
type: QuestionComment
has text: As a rule of thumb, whenever you want to do something concurrently inside Django, you should use celery project
score: 1
comment on: http://stackoverflow.com/q/47623219

http://stackoverflow.com/q/47683871
linked to: http://stackoverflow.com/q/2323988
has answer: http://stackoverflow.com/a/47683957
score: 3
has body: I'm trying to find all lines that are all caps using regex, and so far I've tried this: re.findall(r'\b\n|[A-Z]+\b', kaizoku) So far my database is as follows: TRAFALGAR LAW You shall not be the pirate king. MONKEY D LUFFY Now! DOFLAMINGO'S UNDERLINGS: Noooooo! I want it to return TRAFALGAR LAW MONKEY D LUFFY DOFLAMINGO'S UNDERLINGS: But it's returning something else. (Namely this: TRAFALGAR LAW Y MONKEY D LUFFY N DOFLAMINGO' S UNDERLINGS: N EDIT So far I really think the best fit for the answer is @Jan's answer rx = re.compile(r"^([A-Z ':]+$)\b", re.M) rx.findall(string) EDIT2 Found out what's wrong, thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/82327334
tagged with: regex
has comment: http://stackoverflow.com/comment/82327321
has title: Find the line with all caps in Regex Python
has answer: http://stackoverflow.com/a/47683912
accepted answer: http://stackoverflow.com/a/47683915
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82327527
answer count: 3
has answer: http://stackoverflow.com/a/47683915
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47683957
favorite count: 0
has comment: http://stackoverflow.com/comment/82327316
linked to: http://stackoverflow.com/q/8222855
type: Question
has comment: http://stackoverflow.com/comment/82328202

http://stackoverflow.com/comment/82113351
type: Comment
has text: If you meant "defaults" instead of "requires", you should write it that way. These types of technicalities matter when talking about technical subjects to beginners. Also, the default is 20, not 12.
comment on: http://stackoverflow.com/a/47576442
score: 0
type: AnswerComment

http://stackoverflow.com/q/47611584
has answer: http://stackoverflow.com/a/47613446
score: 0
has title: Open terminal in same window (Ubuntu)
has body: I've an issue. I want to create a .desktop executable file which will execute a command in the terminal. I used the below code for the same. [Desktop Entry] Version=1.0 Type=Application Terminal=true Exec=python2 ./main.py Name=Air Hockey Comment=This runs Air Hockey in one click Icon=./logo.png The terminal which opens up with this code has default directory as it's address. I want to launch it in the directory from which this (.desktop) file is executed. I've tried use %k but it proved to be of no good.
tagged with: shell
type: Question
answer count: 2
tagged with: terminal
has answer: http://stackoverflow.com/a/47621770
has comment: http://stackoverflow.com/comment/82199498
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu

http://stackoverflow.com/q/47542954
type: UnansweredQuestion
has body: I'm not sure why I get this error when I test this function. Can anyone please help me fix this? time_file.readlines() builtins.ValueError: I/O operation on closed file. I want to create a table for the time and insert all the values listed below, like idx, date, start, end, duration into the table. def create_time_table(db, time_file): '''Time Table should be ID,Date,Start,End,Duration ''' con = sqlite3.connect(db) cur = con. cursor() cur.execute('''DROP TABLE IF EXISTS Time''') # create the table cur.execute('''CREATE TABLE TIME(idTEXT, DateTEXT, StartTEXT, EndTEXT, DurationTEXT)''') # insert the rows time_file.readlines() for line in time_file: data = line.split(',') idx = data[0] date = data[1] start = data[2] end = data[3] duration = data[4] cur.execute('''INSERT INTO TIME VALUES(?, ?, ?, ?, ?)''',(idx, date, start, end, duration)) if __name__ == '__main__': file2 = open('time.csv', 'r') create_time_table("exams.db", file2) file2.close()
has comment: http://stackoverflow.com/comment/82044042
has comment: http://stackoverflow.com/comment/82043288
tagged with: python
has answer: http://stackoverflow.com/a/47558947
has comment: http://stackoverflow.com/comment/82043273
has comment: http://stackoverflow.com/comment/82043911
score: 0
has comment: http://stackoverflow.com/comment/82043506
tagged with: file-io
has comment: http://stackoverflow.com/comment/82043929
has comment: http://stackoverflow.com/comment/82043377
answer count: 1
has title: inserting time values into databases
has comment: http://stackoverflow.com/comment/82043126
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82173769
has text: All reasons are not connected to the hardware. Performance testing is done by giving equal load to all hardware. Old computers maybe got: `low CAS latency(RAM)`, wide processor frequency(8 core slower than 2 core on single core processes(fill_core(overload) >> switch to empty) ), and more and more. This means that all hardware components of your software must be adjusted according to the operating feature. Expensive is not always good, the good one is best suited to your work. **I strongly advise you to read the processor, memory and bridge technical documents.**
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47606295
score: 0

http://stackoverflow.com/a/47575541
upvote count: 2
downvote count: 0
type: Answer
has body: Python 3 differentiates between byte strings and unicode strings. So in Python 3 your "world" string is a sequence of Unicode code points, not a simple byte string. So in Python 3 try: ctypes_hello(b"world") To pass a byte string to the function.
score: 2
answers question: http://stackoverflow.com/q/47575449

http://stackoverflow.com/a/47681357
has body: I think this ... message_to_user("You managed to complete",levelcounter,"levels",green,0,40) should become... message_to_user("You managed to complete" +str(levelcounter)+" levels",green,0,40)
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47681303
score: 1

http://stackoverflow.com/q/47579491
has comment: http://stackoverflow.com/comment/82128551
has comment: http://stackoverflow.com/comment/82128256
has title: Integrating pinax-badges in django with a points system
score: 0
has body: I am having trouble getting pinax-badges to work in my project. I followed the minimal usage example provided by creating a badges.py file in my app: #badges.py from pinax.badges.base import Badge, BadgeAwarded from pinax.badges.registry import badges class PointsBadge(Badge): slug = "points" levels = [ "Bronze", "Silver", "Gold", ] events = ["points_awarded",] multiple = False def award(self, **state): user = state["user"] points = user.get_profile().points if points &gt; 10000: return BadgeAwarded(level=3) elif points &gt; 7500: return BadgeAwarded(level=2) elif points &gt; 5000: return BadgeAwarded(level=1) badges.register(PointsBadge) and a pretty bad points function that in my users model that calls a takes a parameter of amount and adds it to the points field in my user model. #User Model class User(AbstractUser): .... points = models.IntegerField(default=0) def award_points(self,amount): self.amount = amount self.points+=amount self.save() Now the function i am calling in a signal that checks when a user logs in and awards them some points.Like so #signal.py from django.contrib.auth.signals import user_logged_in,user_logged_out from django.dispatch import receiver from django.conf import settings from pinax.badges.registry import badges @receiver(user_logged_in) def award(sender,request ,user, **kwargs): user = request.user.award_points(5000) badges.possibly_award_badge("points_awarded", user=user) I registered the signal as well just to make sure. I am still not getting the desire result, which is, as soon as a user logs in and is awarded 5000 points which is enough for a level 1 badge as defined in the badges.py file. Apart from the signal i am not sure there is a more efficient way to achieve this result unless of course someone recommends a different method all together. Responses Appreciated.
tagged with: pinax
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49219529
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85439976
tagged with: python

plot
tags question: http://stackoverflow.com/q/47561507
tags question: http://stackoverflow.com/q/47644966
tags question: http://stackoverflow.com/q/47622542
tags question: http://stackoverflow.com/q/47688696
tags question: http://stackoverflow.com/q/47585820
tags question: http://stackoverflow.com/q/47681016
tags question: http://stackoverflow.com/q/47573083
tags question: http://stackoverflow.com/q/47658083
tags question: http://stackoverflow.com/q/47597119
tags question: http://stackoverflow.com/q/47686227
tags question: http://stackoverflow.com/q/47625963
type: Tag
tags question: http://stackoverflow.com/q/47563831
tags question: http://stackoverflow.com/q/47618601
tags question: http://stackoverflow.com/q/47645291
tags question: http://stackoverflow.com/q/47597577
tags question: http://stackoverflow.com/q/47551753
tags question: http://stackoverflow.com/q/47649787
tags question: http://stackoverflow.com/q/47562213
tag name: plot
tags question: http://stackoverflow.com/q/47688556
tags question: http://stackoverflow.com/q/47554585
tags question: http://stackoverflow.com/q/47546626
tags question: http://stackoverflow.com/q/47559382
tags question: http://stackoverflow.com/q/47578680
tags question: http://stackoverflow.com/q/47572380
tags question: http://stackoverflow.com/q/47598236
tags question: http://stackoverflow.com/q/47552392
tags question: http://stackoverflow.com/q/47621464
tags question: http://stackoverflow.com/q/47568085
tags question: http://stackoverflow.com/q/47591341
tags question: http://stackoverflow.com/q/47541127
tags question: http://stackoverflow.com/q/47693399
tags question: http://stackoverflow.com/q/47647135
tags question: http://stackoverflow.com/q/47651752
tags question: http://stackoverflow.com/q/47566009
tags question: http://stackoverflow.com/q/47595158
tags question: http://stackoverflow.com/q/47686623
tags question: http://stackoverflow.com/q/47687414
tags question: http://stackoverflow.com/q/47655934
tags question: http://stackoverflow.com/q/47681909
tags question: http://stackoverflow.com/q/47626773
tags question: http://stackoverflow.com/q/47664754
tags question: http://stackoverflow.com/q/47668971
tags question: http://stackoverflow.com/q/47563682
tags question: http://stackoverflow.com/q/47587547

http://stackoverflow.com/comment/82208102
type: Comment
type: QuestionComment
has text: this belongs on https://codereview.stackexchange.com/
score: 2
comment on: http://stackoverflow.com/q/47625072

http://stackoverflow.com/comment/82147229
type: Comment
has text: Thank you @dirkgroten... This seems a complete solution
type: AnswerComment
comment on: http://stackoverflow.com/a/47591805
score: 0

http://stackoverflow.com/q/47552717
has answer: http://stackoverflow.com/a/47631850
answer count: 1
tagged with: python-unittest
type: Question
accepted answer: http://stackoverflow.com/a/47631850
tagged with: report
has comment: http://stackoverflow.com/comment/82062463
tagged with: python
has body: I am running Unit TestCases from Python Using XMLTestRunner. This is my main file: #LoggingService.py class LoggerWriter: # used to redirect console msgs to the log def write(self, message): log_event('warning', 'Console', message) def direct_console_to_log(): global console_redirected # This function can be called several times. Avoid redirecting more than once if not console_redirected: console_output = LoggerWriter() sys.stderr = console_output sys.stdout = console_output console_redirected = True def log_event(level, _id, event_details): # log the event pass This is my one of the testing file: #LoggingServiceTest.py import unittest import LoggingService from LoggingService import direct_console_to_log class Test(unittest.TestCase): @patch('LoggingService.log_event') def test_log_writer(self,log_mock): direct_console_to_log() print ('console msg') self.assertTrue(log_mock.called) if __name__ == "__main__": unittest.main() I used to run all the test file from XMLRunner.py: #XMLRunner.py from xmlrunner import XMLTestRunner import unittest test_modules = [file1.Test, file2.Test, LoggingServiceTest.py, .... file25.Test] suite = unittest.TestSuite() for test_module in test_modules: tests = unittest.TestLoader().loadTestsFromTestCase(test_module) suite.addTests(tests) if __name__ == '__main__': # import xmlrunner # unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports')) XMLTestRunner(output='test-reports').run(suite) When I am trying to run LoggingServiceTest.py file from "XMLRunner.py", then the test report does not generate.But when I try without "LoggingServiceTest.py", then the report generates successfully. And I am not sure, what is happening with the test case function (test_log_writer(self,log_mock)) in LoggingServiceTest.py running. Can anyone clear me I use the following command to run the test case: Python2.7.14\python.exe -m coverage run -p --branch --source=. --omit=Unit_Tests/*.py Unit_Tests/Testing.py
has comment: http://stackoverflow.com/comment/82062212
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Test report is not creating while running from XMLRunner

http://stackoverflow.com/comment/82154208
type: AnswerComment
has text: my apologies, it does now, took a little fit,
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47597606

http://stackoverflow.com/comment/82088767
has text: Possible duplicate of [How to install Python MySQLdb module using pip?](https://stackoverflow.com/questions/25865270/how-to-install-python-mysqldb-module-using-pip)
type: Comment
comment on: http://stackoverflow.com/q/47564965
type: QuestionComment
score: 2

http://stackoverflow.com/a/47678936
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47678389
has comment: http://stackoverflow.com/comment/82317236
score: 0
has body: I think what you actually want can be achieved using resample - basically a groupby for datetimes. Assuming you need transaction sum within 6 hours, you can use this: def boo(dict_dfs, hours): return {k: v.resample(f'{hours}H').sum() for k,v in dict_dfs.items()} now, if you 100% sure you need dicts instead, use groupby: def boo(dict_dfs, hours): return {k:{hr:v for hr, v in df.groupby(Grouper(key='Time', freq=f'{hours}H'))} for k, df in dict_dfs.items()} Btw, if you want to loop through {key, value} on dicts, use dict.items(), not dict itself. And one more note: I saw many times people overcomplicating their data structures. Most of the time you don't need dict of dataframes - you can use one dataframe, just having a category column or even a multi-index (like, [category, Time] multi-index in your case. With that, you'll get more reusable, fast and clean code!
type: Answer
accepted answer of: http://stackoverflow.com/q/47678389
has comment: http://stackoverflow.com/comment/82318265

http://stackoverflow.com/comment/82158032
score: 0
has text: Yeah, it is, thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47599745

http://stackoverflow.com/q/47648038
type: Question
linked to: http://stackoverflow.com/q/21619230
has comment: http://stackoverflow.com/comment/82255375
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47648986
downvote count: 0
tagged with: pyspark
upvote count: 1
has comment: http://stackoverflow.com/comment/82255877
tagged with: python
has title: How to replace special character using regex in pyspark
has body: I am trying to replace }{ in a text file with },{ but I'm getting an error saying return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer I am coding a spark job with python (pyspark). Code: from pyspark.sql import SparkSession import re if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: PythonBLEDataParser.py &lt;file&gt;", file=sys.stderr) exit(-1) spark = SparkSession\ .builder\ .appName("PythonBLEDataParser")\ .getOrCreate() toJson = spark.sparkContext.textFile("/root/vasi/spark-2.2.0-bin-hadoop2.7/vas_files/BLE_data_Sample.txt") toJson1 = re.sub("}{","},{",toJson) #i want to replace }{ with },{ print(toJson1) Sample data: {"EdgeMac":"E4956E4E4015","BeaconMac":"247189F24DDB","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"} {"EdgeMac":"E4956E4E4016","BeaconMac":"247189F24DDC","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"} {"EdgeMac":"E4956E4E4017","BeaconMac":"247189F24DDD,"RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
score: 1
answer count: 1
tagged with: regex
favorite count: 0

http://stackoverflow.com/comment/82190353
type: Comment
comment on: http://stackoverflow.com/a/47615861
type: AnswerComment
has text: @RelaxZeroC do you want _abc to be shared across the instances of A,B and C class objects in such a way that changing _abc will affect it for all three class objects?
score: 0

http://stackoverflow.com/comment/82083478
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47562792
has text: `__init__` is **not** a `@classmethod` and by `toString` (which is not a classmethodas well) you probably mean `__str__`

http://stackoverflow.com/q/47583259
has answer: http://stackoverflow.com/a/75931778
tagged with: python
has body: I'm trying to zip 2 simple lists in Python 3.5, and can't figure out how to access the contents. I've read now that zip() is a generator, and I have to call list(zip()) if I want to store the contents. However, I'm experiencing an error when doing so. For example: row = [1, 2, 3] col = ['A', 'B', 'C'] z = zip(row, col) When I call 'z', I see the following: &gt;&gt;&gt; z &lt;zip object at 0x0283C8F0&gt; But when I call list(z), I get the following error: &gt;&gt;&gt; list(z) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'zip' object is not callable I also get the same error when attempting to assign the list to a variable, such as: l = list(zip(row, col)) Apologies if this has already been answered, but I cannot for the life of me find a solution via search. Any ideas would be greatly appreciated!!
upvote count: 13
score: 12
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82124669
answer count: 2
possible better answer: http://stackoverflow.com/a/75931778
has comment: http://stackoverflow.com/comment/82124636
has answer: http://stackoverflow.com/a/47583370
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: typeerror
has title: TypeError: 'zip' object is not callable in Python 3.x
linked to: http://stackoverflow.com/q/45740182
accepted answer: http://stackoverflow.com/a/47583370
has comment: http://stackoverflow.com/comment/82124376
has comment: http://stackoverflow.com/comment/82124398

http://stackoverflow.com/a/47599510
downvote count: 0
has body: You need to have a reference for the image in order to later be able to delete it as in: canvImg = imageIQ1.create_image(0, 0, image=img, anchor="nw") and then when you call: imageIQ1.delete(canvImg) it will get deleted. Based on this you can put that in an event method like: def motion(event): x, y = event.x, event.y someSpecificX = 142 someSpecificY = 53 marginX = 100 marginY = 100 print(x, y) if x in range(someSpecificX - marginX, someSpecificX + marginX): if y in range(someSpecificY - marginY, someSpecificY + marginY): imageIQ1.delete(canvImg) imageIQ1.bind('&lt;Button-1&gt;', motion) Your final code should look like: from tkinter import * from PIL import ImageTk, Image root = Tk() imageIQ1 = Canvas(root, width=1000, height=1000) imageIQ1.pack() original = Image.open("prison.jpg") original = original.resize((1000,1000)) #resize image img = ImageTk.PhotoImage(original) canvImg = imageIQ1.create_image(0, 0, image=img, anchor="nw") def motion(event): x, y = event.x, event.y someSpecificX = 142 someSpecificY = 53 marginX = 100 marginY = 100 print(x, y) if x in range(someSpecificX - marginX, someSpecificX + marginX): if y in range(someSpecificY - marginY, someSpecificY + marginY): imageIQ1.delete(canvImg) imageIQ1.bind('&lt;Button-1&gt;', motion) root.mainloop()
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82157880
type: Answer
accepted answer of: http://stackoverflow.com/q/47599379
answers question: http://stackoverflow.com/q/47599379

http://stackoverflow.com/comment/82296463
score: 0
has text: its not an audio signal, its an accelerometer sensor signal
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47662630

http://stackoverflow.com/a/47635601
score: 0
accepted answer of: http://stackoverflow.com/q/47622238
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47622238
has body: As @lb-ben-johnston said I changed content_panels [] Thanks @lb-ben-johnston!
type: Answer

http://stackoverflow.com/q/47644135
score: 1
has comment: http://stackoverflow.com/comment/82246991
has answer: http://stackoverflow.com/a/47644211
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82246963
answer count: 5
has answer: http://stackoverflow.com/a/47644226
has answer: http://stackoverflow.com/a/47644170
has comment: http://stackoverflow.com/comment/82246953
has answer: http://stackoverflow.com/a/47644217
tagged with: python
has answer: http://stackoverflow.com/a/47644186
has comment: http://stackoverflow.com/comment/82246979
tagged with: python-3.x
has body: I have a function that receives a time, in a string, and another number to add to the time: def get_hours(hm): return int(hm.split(':')[0]) def get_minutes(hm): return int(hm.split(':')[1]) def add_minutes(hm, incr): """Increment the given time by the given amount of minutes. Requires: - hm str with a time represented as HH:MM; - incr int with the number of minutes. Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes. """ if get_minutes(hm)+incr&gt;=60: if get_hours(hm)==23: return '00:'+str((get_minutes(hm)+incr)-60) else: return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60) else: return str(get_hours(hm))+':'+str((get_minutes(hm)+incr)) The problem is when the time is 16:05 or 04:06, it doesn't display the zeros, so it's just 16:5 and 4:6. How can i make this work?
has comment: http://stackoverflow.com/comment/82246966
has comment: http://stackoverflow.com/comment/82246984
type: UnansweredQuestion
has title: How to add zero to a time
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82361298
has text: Is the data file comma delimited or is it tab delimited? The example you provided showed tab-delimited data but I assumed you presented it that way for ease of reading. Since the file is named file.csv, I assumed that it is actually a comma-separated value file. If it is actually CSV, it's hard to know the source of the error without looking at the file. It is probably a stray comma somewhere.
type: AnswerComment
comment on: http://stackoverflow.com/a/47687865
score: 0
type: Comment

http://stackoverflow.com/q/47541127
upvote count: 4
has title: Pandas.plot Multiple plot same figure
accepted answer: http://stackoverflow.com/a/47541316
answer count: 1
has comment: http://stackoverflow.com/comment/82039586
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/47541316
tagged with: plot
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82039701
type: AnsweredQuestion
has body: I have multiple CSV files that I am trying to plot in same the figure to have a comparison between them. I already read some information about pandas problem not keeping memory plot and creating the new one every time. People were talking about using an ax var, but I do not understand it... For now I have: def scatter_plot(csvfile,param,exp): for i in range (1,10): df = pd.read_csv('{}{}.csv'.format(csvfile,i)) ax = df.plot(kind='scatter',x=param,y ='Adjusted') df.plot.line(x=param,y='Adjusted',ax=ax,style='b') plt.show() plt.savefig('plot/{}/{}'.format(exp,param),dpi=100) But it's showing me ten plot and only save the last one. Any idea?
tagged with: pandas
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/comment/82048494
has text: install bs4 as it is package , while BeautifulSoup is a class
type: Comment
comment on: http://stackoverflow.com/q/47545740
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82071533
comment on: http://stackoverflow.com/q/47556992
type: QuestionComment
type: Comment
has text: I haven't gone though your code in detail but it looks like you create a new rectangle each time you go though the loop. You'll find that the performance is improved if you create the shape initially and then change the position of the object rather than deleting them all and starting again.
score: 1

http://stackoverflow.com/q/47578353
answer count: 12
downvote count: 0
has answer: http://stackoverflow.com/a/68495942
has answer: http://stackoverflow.com/a/76687164
has answer: http://stackoverflow.com/a/70439111
has answer: http://stackoverflow.com/a/63691249
favorite count: 0
linked to: http://stackoverflow.com/q/18939596
type: Question
has answer: http://stackoverflow.com/a/69700943
has answer: http://stackoverflow.com/a/76687077
has body: Being new to python I am just trying to figure out the difference between filter() and map(). I wrote a sample script as follows: def f(x): return x % 2 == 0 def m(y): return y * 2 list = [1,2,3,4] flist = filter(f, list) print(list) print(flist) mlist = map(m, list) print(list) print(mlist) We see that to both the filter and map we pass a list and assign their output to a new list. Output of this script is [1, 2, 3, 4] [2, 4] [1, 2, 3, 4] [2, 4, 6, 8] Question arises is that function call of both filter and map looks same so how will they behave if we interchange the contents of functions passed to them. def f(x): return x * 2 def m(y): return y % 2 == 0 list = [1,2,3,4] flist = filter(f, list) print(list) print(flist) mlist = map(m, list) print(list) print(mlist) This results in [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] [False, True, False, True] This shows filter evaluates the function and if true it returns back the passed element. Here the function def f(x): return x * 2 evaluates to def f(x): return x * 2 != 0 In contrast map evaluates the function expression and returns back the result as items. So filter always expects its function to do comparison type of task to filter out the elements while map expects its functions to evaluate a statement to get some result. Is this understanding correct?
score: 18
upvote count: 18
has answer: http://stackoverflow.com/a/57074649
possible better answer: http://stackoverflow.com/a/57074649
has answer: http://stackoverflow.com/a/53601042
tagged with: python
has answer: http://stackoverflow.com/a/73520545
has comment: http://stackoverflow.com/comment/82113847
has answer: http://stackoverflow.com/a/67768453
has comment: http://stackoverflow.com/comment/82114036
has title: Python difference between filter() and map()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65606099
has answer: http://stackoverflow.com/a/47578636
accepted answer: http://stackoverflow.com/a/47578636

http://stackoverflow.com/q/47559877
has comment: http://stackoverflow.com/comment/82078840
has body: In the Linux subsystem for Windows10 I have encountered a new error when trying to conda install, update, remove any new package. For example: c/.../...$ conda install numpy Error: could not import Crypto (required for signature verification). Run the following command: $ conda install -n root pycrypto If I enter the suggested command it returns the same error. If anyone can solve this issue without having to clean install Python this would be helpful. Here is my version of Python and Anaconda: Python 2.7.12 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:42:40) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details.
has title: "could not import Crypto" running "conda install numpy"
type: Question
has answer: http://stackoverflow.com/a/47561729
has answer: http://stackoverflow.com/a/47559957
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 2
tagged with: anaconda
tagged with: pycrypto

http://stackoverflow.com/q/47628254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47640157
possible better answer: http://stackoverflow.com/a/47628305
accepted answer: http://stackoverflow.com/a/47632750
has body: I am using pyspark 2.2.0. To add a new column of incrementing value. I have used following code: new_df = df.withColumn('Id', monotonically_increasing_id()) But it breaks after row number 352 like this: Any option to fix this ?
answer count: 3
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/47628305
has title: why adding a new id column with monotonically increasing id break after 352
favorite count: 0
tagged with: apache-spark-sql
type: Question
upvote count: 5
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47632750

http://stackoverflow.com/comment/82220104
score: 0
type: Comment
has text: `list` is a type name in python, you shouldn't use it as a variable name (and, besides that, probably `list` is not a good name for a dictionary anyway..)
type: AnswerComment
comment on: http://stackoverflow.com/a/47630988

http://stackoverflow.com/a/47661045
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47660726
has body: You could use np.atleast_2d to promote 1D arrays to 2D: a = np.atleast_2d(a) If you put this inside of your loop then you can henceforth treat all as as 2D (or higher-dimensional) arrays. For example, In [103]: a1 = np.array([1,2,3,4,5]) In [105]: np.atleast_2d(a1) Out[107]: array([[1, 2, 3, 4, 5]]) while higher-dimensional arrays are unchanged: In [104]: a2 = np.array([[1,2],[3,4]]) In [108]: np.atleast_2d(a2) Out[108]: array([[1, 2], [3, 4]])
answers question: http://stackoverflow.com/q/47660726
upvote count: 2
has comment: http://stackoverflow.com/comment/82283407

http://stackoverflow.com/comment/82319520
type: QuestionComment
has text: I have to create a new word but I don't know how to merge it.
score: 0
comment on: http://stackoverflow.com/q/47678290
type: Comment

http://stackoverflow.com/a/47780264
has comment: http://stackoverflow.com/comment/131393948
answers question: http://stackoverflow.com/q/47659249
upvote count: 5
score: 5
has body: Use my python pacakge geographiclib. After pip install geographiclib do $ python Python 2.7.14 (default, Nov 2 2017, 18:42:05) &gt;&gt;&gt; from geographiclib.geodesic import Geodesic &gt;&gt;&gt; geod = Geodesic.WGS84 &gt;&gt;&gt; g = geod.Inverse(41.4107628,2.1745004, 41.4126728,2.1704725) &gt;&gt;&gt; print "The initial direction is {:.3f} degrees.".format(g['azi1']) The initial direction is -57.792 degrees. The direction is measured clockwise from north. So -57.8 degrees = 302.2 degrees = northwest-by-west; see Points of the compass.
type: Answer
has comment: http://stackoverflow.com/comment/82596653
has comment: http://stackoverflow.com/comment/131421680
downvote count: 0

http://stackoverflow.com/q/47687141
has title: In Odoo8, how do I import a module's .py file into a custom module?
answer count: 1
has body: Ok, so here comes. Brace yourselves. I'm trying to overwrite a method (get_followup_table_html) from a class (res_partner) located in a module (account_followup) in Odoo 8, by creating a custom module (account_followup_upgrade) that inherits the class and defines and redefines the method. The changes are very small, as the method's only purpose is to create an html table to be included in emails sent to customers; I have just copied the original method and modified the html code parts. That being said, it works, mostly. My files, in my custom module's folder, include: __openerp__.py (not full file, just the important bit): 'depends': ['account_followup'], __init__.py: # -*- coding: utf-8 -*- import mymodule mymodule.py: # -*- coding: utf-8 -*- from openerp.osv import osv # I need to modify a method in this class class res_partner(osv.osv): # So I inherit it _inherit = 'res.partner' # And define a method called the same as the original, with the same arguments def get_followup_table_html(self, cr, uid, ids, context=None): """ Build the html tables to be included in emails send to partners, when reminding them their overdue invoices. :param ids: [id] of the partner for whom we are building the tables :rtype: string """ try: from report import account_followup_print except ImportError: return 'import failed' # The code that follows generates an html table assert len(ids) == 1 if context is None: context = {} partner = self.browse(cr, uid, ids[0], context=context).commercial_partner_id #copy the context to not change global context. Overwrite it because _() looks for the lang in local variable 'context'. #Set the language to use = the partner language context = dict(context, lang=partner.lang) followup_table = '' if partner.unreconciled_aml_ids: company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id current_date = fields.date.context_today(self, cr, uid, context=context) rml_parse = account_followup_print.report_rappel(cr, uid, "followup_r…
tagged with: python
tagged with: module
score: 2
type: AnsweredQuestion
tagged with: odoo-8
linked to: http://stackoverflow.com/q/47472027
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47691531
upvote count: 2
has answer: http://stackoverflow.com/a/47691531

http://stackoverflow.com/comment/82279456
comment on: http://stackoverflow.com/q/47660227
type: QuestionComment
has text: Isn't this what functions are made for? `def ask_question(): ...`
score: 0
type: Comment

http://stackoverflow.com/comment/82247418
type: Comment
type: AnswerComment
has text: @PaulPanzer To conclusively reach conclusions, I think we need to run both methods and profile them separately. Might do it later.
comment on: http://stackoverflow.com/a/47643542
score: 0

http://stackoverflow.com/comment/82229117
comment on: http://stackoverflow.com/q/47635626
has text: This is created for you by `django-admin.py startproject`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47687596
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Another solution using regex: import re str = '--"I like salami. "-I want to walk to the shops"' print re.sub("[-\"]", repl="", string=str) output: I like salami. I want to walk to the shops
answers question: http://stackoverflow.com/q/47687203

http://stackoverflow.com/comment/82178792
score: 0
comment on: http://stackoverflow.com/q/47608215
has text: now i want to select a button for this new=br.find_element_by_id('buttonname') new.click() but it throws error like attribute cannot find find_element_by_id how to solve this
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47691425
tags question: http://stackoverflow.com/q/47624752
tags question: http://stackoverflow.com/q/47697797
tags question: http://stackoverflow.com/q/47644019
type: Tag
tags question: http://stackoverflow.com/q/47643379
tags question: http://stackoverflow.com/q/47619679
tags question: http://stackoverflow.com/q/47557057
tags question: http://stackoverflow.com/q/47579267
tags question: http://stackoverflow.com/q/47571388
tags question: http://stackoverflow.com/q/47540863
tags question: http://stackoverflow.com/q/47670928
tags question: http://stackoverflow.com/q/47664709
tags question: http://stackoverflow.com/q/47581175
tags question: http://stackoverflow.com/q/47669609
tags question: http://stackoverflow.com/q/47606927
tags question: http://stackoverflow.com/q/47663908
tags question: http://stackoverflow.com/q/47644176
tags question: http://stackoverflow.com/q/47682691
tags question: http://stackoverflow.com/q/47686313
tags question: http://stackoverflow.com/q/47687049
tags question: http://stackoverflow.com/q/47621671
tags question: http://stackoverflow.com/q/47659073
tags question: http://stackoverflow.com/q/47542657
tags question: http://stackoverflow.com/q/47684058
tags question: http://stackoverflow.com/q/47559510
tags question: http://stackoverflow.com/q/47669376
tags question: http://stackoverflow.com/q/47666724
tags question: http://stackoverflow.com/q/47661161
tags question: http://stackoverflow.com/q/47619436
tags question: http://stackoverflow.com/q/47659445
tags question: http://stackoverflow.com/q/47640258
tag name: csv
tags question: http://stackoverflow.com/q/47585688
tags question: http://stackoverflow.com/q/47649972
tags question: http://stackoverflow.com/q/47564583
tags question: http://stackoverflow.com/q/47584862
tags question: http://stackoverflow.com/q/47605286
tags question: http://stackoverflow.com/q/47631539
tags question: http://stackoverflow.com/q/47625436
tags question: http://stackoverflow.com/q/47544293
tags question: http://stackoverflow.com/q/47602097
tags question: http://stackoverflow.com/q/47657999
tags question: http://stackoverflow.com/q/47574798
tags question: http://stackoverflow.com/q/47667478
tags question: http://stackoverflow.com/q/47668634
tags question: http://stackoverflow.com/q/47601487
tags question: http://stackoverflow.com/q/47544050
tags question: http://stackoverflow.com/q/47585560
tags question: http://stackoverflow.com/q/47674723
tags question: http://stackoverflow.com/q/47558810
tags question: http://stackoverflow.com/q/47592490
tags question: http://stackoverflow.com/q/47559515
tags question: http://stackoverflow.com/q/47575008
tags question: http://stackoverflow.com/q/47627200
tags question: http://stackoverflow.com/q/47561507
tags question: http://stackoverflow.com/q/47652022
tags question: http://stackoverflow.com/q/47543824
tags question: http://stackoverflow.com/q/47639656
tags question: http://stackoverflow.com/q/47546210
tags question: http://stackoverflow.com/q/47693862
tags question: http://stackoverflow.com/q/47664138
tags question: http://stackoverflow.com/q/47664981
tags question: http://stackoverflow.com/q/47611492
tags question: http://stackoverflow.com/q/47658722
tags question: http://stackoverflow.com/q/47644448
tags question: http://stackoverflow.com/q/47586900
tags question: http://stackoverflow.com/q/47541237
tags question: http://stackoverflow.com/q/47622691
tags question: http://stackoverflow.com/q/47686819
tags question: http://stackoverflow.com/q/47654716
tags question: http://stackoverflow.com/q/47626451
tags question: http://stackoverflow.com/q/47677101
tags question: http://stackoverflow.com/q/47589327
tags question: http://stackoverflow.com/q/47608347
tags question: http://stackoverflow.com/q/47643944
tags question: http://stackoverflow.com/q/47646030
tags question: http://stackoverflow.com/q/47620972
tags question: http://stackoverflow.com/q/47670839
tags question: http://stackoverflow.com/q/47669297

http://stackoverflow.com/comment/82282684
type: AnswerComment
comment on: http://stackoverflow.com/a/47661564
type: Comment
has text: Python 3.6.2, Requests 2.18.4
score: 0

http://stackoverflow.com/a/47618441
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82195277
has comment: http://stackoverflow.com/comment/82195267
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47618336
has comment: http://stackoverflow.com/comment/82195431
has comment: http://stackoverflow.com/comment/82195137
has comment: http://stackoverflow.com/comment/82196811
has comment: http://stackoverflow.com/comment/82195729
type: Answer
has comment: http://stackoverflow.com/comment/82195259
has comment: http://stackoverflow.com/comment/82195301
has comment: http://stackoverflow.com/comment/82196217
accepted answer of: http://stackoverflow.com/q/47618336
has body: import requests if __name__ == '__main__': list = ["aapl", "goog", "jnj", "msft"] for items in list: req = requests.get('https://finance.google.com/finance/historical?q=' + items + '&amp;output=csv') with open(items+".csv","w") as file: file.write(req.text)

http://stackoverflow.com/q/47560444
has title: In python using Tkinter why isn't a new window opening under this IF statement?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82078710
has comment: http://stackoverflow.com/comment/82079246
score: 0
has answer: http://stackoverflow.com/a/47560511
tagged with: if-statement
tagged with: user-interface
has comment: http://stackoverflow.com/comment/82082573
has comment: http://stackoverflow.com/comment/82078953
has comment: http://stackoverflow.com/comment/82078884
has body: I am trying to make a simple GUI for an alarm using Tkinter and the sound plays when the imputed time is reached. However, it should also open a new window with a snooze button on it that when pressed waits five minutes before the sound goes off again. For some reason this new window doesn't open and the rest of the code runs without error and I just can't figure out why. Any help is greatly appreciated. if str(Time) == str(Alarm): winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME) #Plays alarm sound GoingOff = Toplevel() #Should open new window, why doesn't it open??? GoingOff.geometry('309x225') GoingOff.title('Wake Up') label2 = Label(GoingOff, text = '\nSnooze?') label2.pack() def Snooze5(): #Code for the snooze function to be called when the button is pressed. time.sleep(300) winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME) Snooze5 = Button(GoingOff,font=("Helvetica", 16), text="Snooze for 5 minutes", width = 16, height = 4, command=Snooze5) Snooze5.pack() else: time.sleep(5)
type: Question
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82078839
has comment: http://stackoverflow.com/comment/82079220
has comment: http://stackoverflow.com/comment/82078640
type: UnansweredQuestion

http://stackoverflow.com/comment/82285327
has text: `[0]['child'][0]['text']` on its own doesn't mean anything without a name on which it acts on. Assign something to `x[0]['child']`, e.g `sub = x[0]['child']` and then grab `sub[0]['text']` and `sub[1]['group']` (if this is what you're asking)
type: QuestionComment
comment on: http://stackoverflow.com/q/47663040
score: 2
type: Comment

http://stackoverflow.com/comment/82201137
comment on: http://stackoverflow.com/a/47614912
score: 0
type: AnswerComment
has text: @Jason, When you take a new picture, you need to set `img_src` to the new file: `img_src = 'C:/some/new/image.jpg'`. When you restart your GUI, it will start with whatever image you have hard-coded into it (in this case the TEST.jpg). If you want the app to remember the changes you make, then you should look at kivy.config.
type: Comment

http://stackoverflow.com/comment/82200389
has text: Your code is throwing away the sorted list that `sorted(list_members, key = lambda member: member.name)` returns (even if it worked).
score: 0
comment on: http://stackoverflow.com/q/47621044
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82321433
comment on: http://stackoverflow.com/q/47680901
type: QuestionComment
type: Comment
has text: Fair enough. The faulty conditional is the main problem. And my dupe targets don't apply because he's popping from the end of the list, which is safe to do. Sorry about that.
score: 1

http://stackoverflow.com/a/47556786
has body: I solved my problem. In method run() I get the object in each iteration of the while loop: def run(self): while True: repartidor = Repartidor.objects.get(pk=1) condition = repartidor.get_thread_state() if condition: do_something() time.sleep(1) else: pass time.sleep(1)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47556284

http://stackoverflow.com/comment/82288754
score: 0
comment on: http://stackoverflow.com/q/47661443
has text: Consider accepting the answer that correctly solves your issue. If neither do, please add expected output. I personally struggle with the fact that you provided sample data that would count to zero..Consider updating the data in the question before adding expected output.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82173333
type: Comment
type: QuestionComment
has text: for first question: did you try import ? did you have problem ? next time first try, next ask.
comment on: http://stackoverflow.com/q/47605598
score: 1

http://stackoverflow.com/comment/82141049
score: 1
type: Comment
type: QuestionComment
has text: I guess it's a network problem. Have you try compressing the dataframe and then copy it?
comment on: http://stackoverflow.com/q/47591848

http://stackoverflow.com/q/47567380
tagged with: python
has answer: http://stackoverflow.com/a/47567656
type: Question
linked to: http://stackoverflow.com/q/10617286
score: 5
answer count: 1
downvote count: 0
tagged with: django
has body: Is there a way to treat a file in request.FILES same as a disk file? I want to do something like this: with open(file_in_request, 'rb') as file: #read data from that file Only, I don't want to have to save it to disk first. I will be encrypting that file and save the encrypted file to disk instead.
favorite count: 0
type: AnsweredQuestion
has title: How to open and read file from request.FILES without saving it to disk
upvote count: 5
accepted answer: http://stackoverflow.com/a/47567656

http://stackoverflow.com/comment/82140083
comment on: http://stackoverflow.com/a/47590967
type: Comment
type: AnswerComment
has text: this is what iam getting
score: 0

http://stackoverflow.com/comment/82195156
score: 0
has text: Here is my Code
type: QuestionComment
comment on: http://stackoverflow.com/q/47618336
type: Comment

http://stackoverflow.com/q/47583186
tagged with: python
type: UnansweredQuestion
has title: kernel dies when loading .mat file with scipy
has body: I'm trying to load a .mat dataset using scipy but every time I run it the kernel dies and restarts without loading the file. I tried this using jupyter notebook and spyder and both give the same result the code I used is: import scipy.io as sio mat = sio.loadmat('lateral.mat') can anyone tell me where is th problem? my OS is windows 8
tagged with: kernel
score: 0
has comment: http://stackoverflow.com/comment/82143075
has comment: http://stackoverflow.com/comment/82124106
tagged with: scipy
has comment: http://stackoverflow.com/comment/82186553
type: Question
answer count: 0
tagged with: mat-file

http://stackoverflow.com/q/47596479
downvote count: 0
has comment: http://stackoverflow.com/comment/90144536
score: 7
tagged with: string
upvote count: 7
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90156734
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47596522
linked to: http://stackoverflow.com/q/22604564
type: Question
has body: I know that DataFrame can be be converted to string using to_string function: import pandas as pd df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3, 'B' : ['Aa', 'Bb', 'Cc'] * 4}) dfstr = df.to_string() print(dfstr) Output: A B 0 one Aa 1 one Bb 2 two Cc 3 three Aa 4 one Bb 5 one Cc 6 two Aa 7 three Bb 8 one Cc 9 one Aa 10 two Bb 11 three Cc How can I convert this dfstr back to a DataFrame object? Edit: I am asking specifically how the string created by df.to_string() function can be converted back to a dataframe object, not about general ways of converting text data (string) to dataframes as discussed on How to create a Pandas DataFrame from a string .
tagged with: dataframe
tagged with: python
has title: How to convert string from df.to_string() back to DataFrame
duplicate of: http://stackoverflow.com/q/22604564
tagged with: pandas
has answer: http://stackoverflow.com/a/47596522
type: AnsweredQuestion

kivy
tags question: http://stackoverflow.com/q/47630155
tags question: http://stackoverflow.com/q/47628023
tags question: http://stackoverflow.com/q/47620607
tags question: http://stackoverflow.com/q/47641482
type: Tag
tag name: kivy
tags question: http://stackoverflow.com/q/47682906
tags question: http://stackoverflow.com/q/47615106
tags question: http://stackoverflow.com/q/47686791
tags question: http://stackoverflow.com/q/47686795
tags question: http://stackoverflow.com/q/47680463
tags question: http://stackoverflow.com/q/47588758
tags question: http://stackoverflow.com/q/47609965
tags question: http://stackoverflow.com/q/47559305
tags question: http://stackoverflow.com/q/47670361
tags question: http://stackoverflow.com/q/47674518
tags question: http://stackoverflow.com/q/47562521
tags question: http://stackoverflow.com/q/47611733
tags question: http://stackoverflow.com/q/47613459
tags question: http://stackoverflow.com/q/47547164
tags question: http://stackoverflow.com/q/47681927
tags question: http://stackoverflow.com/q/47542393
tags question: http://stackoverflow.com/q/47605180
tags question: http://stackoverflow.com/q/47645843
tags question: http://stackoverflow.com/q/47693921
tags question: http://stackoverflow.com/q/47607951
tags question: http://stackoverflow.com/q/47661567
tags question: http://stackoverflow.com/q/47610336
tags question: http://stackoverflow.com/q/47662872
tags question: http://stackoverflow.com/q/47628895
tags question: http://stackoverflow.com/q/47586678
tags question: http://stackoverflow.com/q/47572872
tags question: http://stackoverflow.com/q/47574116
tags question: http://stackoverflow.com/q/47639700
tags question: http://stackoverflow.com/q/47587333
tags question: http://stackoverflow.com/q/47565468
tags question: http://stackoverflow.com/q/47552735
tags question: http://stackoverflow.com/q/47621111
tags question: http://stackoverflow.com/q/47601583
tags question: http://stackoverflow.com/q/47590717
tags question: http://stackoverflow.com/q/47671606
tags question: http://stackoverflow.com/q/47652782
tags question: http://stackoverflow.com/q/47592032
tags question: http://stackoverflow.com/q/47581333
tags question: http://stackoverflow.com/q/47609028
tags question: http://stackoverflow.com/q/47680063

http://stackoverflow.com/comment/82355096
comment on: http://stackoverflow.com/q/47697625
type: Comment
type: QuestionComment
has text: `data['sites']` is a `list`, not a `dict`. You need to use `data['sites'][0]` instead. You may want to reformat your JSON to get a better picture of the structure.
score: 3

http://stackoverflow.com/a/52444110
score: 0
type: Answer
has body: I don't know an easy way to do it but it can be done. If you print fig you see that each violin has a range in the layout. The range value is defined according to the violin itself. If you set the same range value for all violin, then you get what you want : for name,axi in fig['layout'].items(): if name[:4] == 'xaxi': axi['range'] = [-1,1] Of course [-1,1] should be changed to fit your data.
answers question: http://stackoverflow.com/q/47600727

http://stackoverflow.com/comment/82291655
has text: How can I run as root user? I am in Windows using Git Bash there is no "sudo" command
comment on: http://stackoverflow.com/a/47666217
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82210329
has text: Unfortunately that appears to be inverting the values? False now = True, True now = False? the values I am looking for are still buried in the data abbreviation
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47626223

http://stackoverflow.com/comment/82178354
score: 1
type: Comment
has text: Yep. Will post solution as soon as I can.
type: AnswerComment
comment on: http://stackoverflow.com/a/47599901

http://stackoverflow.com/a/47669214
upvote count: 1
has body: For adding a dynamic dropdown send column names from the backend. {% for column in columns %} Column {{column.id}}: {{column.name}} {% endfor %}
has comment: http://stackoverflow.com/comment/82297786
answers question: http://stackoverflow.com/q/47668906
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82302426
downvote count: 0

http://stackoverflow.com/q/47579112
type: UnansweredQuestion
answer count: 1
favorite count: 0
tagged with: docker
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47579177
type: Question
tagged with: pipe
has comment: http://stackoverflow.com/comment/82115285
has title: Pipe output of one iteration of a python for loop to another script
has comment: http://stackoverflow.com/comment/82118432
has comment: http://stackoverflow.com/comment/82122309
tagged with: shell
score: 1
has comment: http://stackoverflow.com/comment/82122118
has comment: http://stackoverflow.com/comment/82122196
downvote count: 0
has body: Each instance of the for loop, spits out the contents of one binary file which should be captured by another script to do further processing. For example: script1.py filename = glob.glob('*.txt') for i in range(len(filename)): with open(filename[i], 'rb') as g: sys.stdout.write(g.read()) script2.py from subprocess import call script = "cat &gt; test.fil" call(script,shell=True) Command: python script1.py | python script2.py If I execute this command, it waits for all iterations to be completed before piping the output to script2.py. I would like this to be done batchwise. For example, once data from one binary file is pushed to stdout, launch script2.py. script2.py cannot be called from script1.py. Both the scripts need to be run in different docker containers. It would be better to avoid a docker installation inside a docker container.
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47685090
score: 7
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82333519
accepted answer: http://stackoverflow.com/a/47688018
upvote count: 7
has body: I'm generating gzip files from python using the following code: (using python 3) file = gzip.open('output.json.gzip', 'wb') dataToWrite = json.dumps(data).encode('utf-8') file.write(dataToWrite) file.close() However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2): this.http.get("output.json.gzip") .map((res:Response) =&gt; { var resText:any = new Uint8Array(res.arrayBuffer()); var result = ""; try { result = pako.inflate(resText, {"to": "string"}); } catch (err) { console.log("Error " + err); } return result; }); But I'm getting this error in the console: unknown compression method. Should I be doing something else to properly inflate gzip files?
has answer: http://stackoverflow.com/a/47688018
favorite count: 0
type: Question
has title: Pako not able to deflate gzip files generated in python
tagged with: gzip
has comment: http://stackoverflow.com/comment/82329822
tagged with: javascript
tagged with: python
tagged with: pako
type: AnsweredQuestion
tagged with: angular

http://stackoverflow.com/comment/82115686
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47579263
type: AnswerComment
has text: But with this I find subsequent calls keep adding to outlist created by previous call to the function. How to correct that?

http://stackoverflow.com/q/47564015
has answer: http://stackoverflow.com/a/47564122
accepted answer: http://stackoverflow.com/a/47564122
has answer: http://stackoverflow.com/a/47564119
possible better answer: http://stackoverflow.com/a/47564119
tagged with: python
linked to: http://stackoverflow.com/q/14547916
has body: So I have a JSON that looks like this: [ { "Domain": "apple.com", "A": [ "17.142.160.59", "17.172.224.47", "17.178.96.59" ], "NS": [ "c.ns.apple.com.", "b.ns.apple.com.", "a.ns.apple.com.", "f.ns.apple.com.", "nserver5.apple.com.", "nserver6.apple.com.", "d.ns.apple.com.", "e.ns.apple.com." ] } ] While I can retrieve the nested information manually like viz. print(data[0]["Domain"]) --- Returns: apple.com print(data[0]["A"][0]) --- Returns: 17.142.160.59 How can I loop through the information that let me retrieve the Domain, the the nested Ainformation, the nestedNS` information etc.? I tried doing this: for i in data["Domain"]: print(data[i]["Domain"]) for j in ... // could not figure out, either way first loop fails. in vain. Thanks for any help!
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82086060
has comment: http://stackoverflow.com/comment/82086202
answer count: 2
tagged with: http://stackoverflow.com/tag/json
has title: Looping over Nested JSON Elements
type: Question
linked to: http://stackoverflow.com/q/14048948

http://stackoverflow.com/comment/82154377
has text: something I learned with QA: first test (don't believe) the test itself!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47592732
score: 0

http://stackoverflow.com/comment/82072486
comment on: http://stackoverflow.com/a/47556833
score: 0
has text: How would `sum(len(e.intersection(s)) == 2 for s in l)` perform (comp or generator)?
type: Comment
type: AnswerComment

file
tags question: http://stackoverflow.com/q/47663908
type: Tag
tags question: http://stackoverflow.com/q/47543380
tags question: http://stackoverflow.com/q/47639221
tags question: http://stackoverflow.com/q/47638964
tags question: http://stackoverflow.com/q/47640258
tags question: http://stackoverflow.com/q/47689316
tags question: http://stackoverflow.com/q/47659506
tags question: http://stackoverflow.com/q/47546021
tags question: http://stackoverflow.com/q/47572452
tags question: http://stackoverflow.com/q/47574672
tags question: http://stackoverflow.com/q/47562769
tags question: http://stackoverflow.com/q/47604955
tags question: http://stackoverflow.com/q/47613061
tags question: http://stackoverflow.com/q/47688655
tag name: file
tags question: http://stackoverflow.com/q/47600315
tags question: http://stackoverflow.com/q/47561840
tags question: http://stackoverflow.com/q/47587633
tags question: http://stackoverflow.com/q/47655938
tags question: http://stackoverflow.com/q/47585163
tags question: http://stackoverflow.com/q/47613575
tags question: http://stackoverflow.com/q/47627500
tags question: http://stackoverflow.com/q/47697211
tags question: http://stackoverflow.com/q/47585705
tags question: http://stackoverflow.com/q/47658805
tags question: http://stackoverflow.com/q/47678422
tags question: http://stackoverflow.com/q/47541623
tags question: http://stackoverflow.com/q/47657424
tags question: http://stackoverflow.com/q/47588101
tags question: http://stackoverflow.com/q/47627477
tags question: http://stackoverflow.com/q/47635766
tags question: http://stackoverflow.com/q/47580006
tags question: http://stackoverflow.com/q/47641949
tags question: http://stackoverflow.com/q/47632855

http://stackoverflow.com/q/47670326
has answer: http://stackoverflow.com/a/47670916
accepted answer: http://stackoverflow.com/a/47670353
tagged with: python
has comment: http://stackoverflow.com/comment/130098742
score: 4
has answer: http://stackoverflow.com/a/47670353
upvote count: 4
type: AnsweredQuestion
has title: Pandas Multi-index slice only on secondary index
linked to: http://stackoverflow.com/q/13389203
answer count: 2
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/33194016
tagged with: multi-index
possible better answer: http://stackoverflow.com/a/47670916
has body: I have the following pandas (related to the example here: pandas: slice a MultiIndex by range of secondary index) import numpy as np import pandas as pd variable = np.repeat(['a','b','c'], [5,5,5]) time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20] arra = [variable, time] index=pd.MultiIndex.from_arrays(arra, names=("variable", "time")) s = pd.Series( np.random.randn(len(sequence)), index=index ) Output would be # In [1]: s variable time a 0 -1.284692 1 -0.313895 5 -0.980222 10 -1.452306 20 -0.423921 b 0 0.248625 1 0.183721 5 -0.733377 10 1.562653 20 -1.092559 c 0 0.061172 1 0.133960 5 0.765271 10 -0.648834 20 0.147158 dtype: float64 If I slice here on both multiindex, it would work like this: # In [2]: s.loc[("a",0),:] variable time a 0 1.583589 1 -1.081401 5 -0.497904 10 0.352880 20 -0.179062 dtype: float64 But how can I just slice on secondary index "time" at e.g. time=0 and get every row with first index? The following won't work: # In [3]: s.loc[(0),:] KeyError: 0 How would I do that here?
favorite count: 0
type: Question

http://stackoverflow.com/comment/82317176
comment on: http://stackoverflow.com/q/47678700
type: Comment
score: 0
type: QuestionComment
has text: Maybe you want to outline what you are trying to do. Then one could reason about approaches (like hacky function-attributes). The callback itself is only called with ```callback(xk)```, where ```xk``` is the current x-vector.

http://stackoverflow.com/a/47554543
upvote count: 7
answers question: http://stackoverflow.com/q/47554439
score: 7
type: Answer
has body: 85 microseconds is too small a delay to be measured reliably and repeatedly. For example, CPU cache effects (or context switches, or paging) may dominate the computation time (and alter it to make that timing meaningless). (I guess you are on Linux/x86-64) As a rule of thumb, try to have a run lasting about half a second at least, and repeat the benchmarking a few times. You could also use time(1) for measurements. See also time(7). There are several notions of time (elapsed "real" time, monotonic time, process cpu time, thread cpu time, etc...). You could consider using clock(3) or clock_gettime(2) to measure time. BTW, you might compile with a more recent version of GCC (in November 2017, GCC7 and in a few weeks GCC8) and you want to compile with gcc -march=native -O3 for benchmarking purposes. Try also other optimization options and tuning. You could also try another compiler, e.g. Clang/LLVM. Look also at this answer (regarding parallelization) to a relevant question. Probably the numpy package is using (internally) similar techniques (outside of the Python GIL), so could be faster than your naive sequential matrix multiplication code in C.
downvote count: 0

http://stackoverflow.com/comment/82463411
has text: They are doing the same thing: `if margin > 0:` ...`dW[j, :] += X[:, i].T`. Be sure to note that the actual value of `margin` is not used in the update.You could write that, avoiding the `if` statement, as `dW[j, :] += (margin > 0) * X[:, i].T`. Which is what the vectorized code is based on.
type: Comment
comment on: http://stackoverflow.com/a/47739631
score: 0
type: AnswerComment

http://stackoverflow.com/q/47657795
tagged with: polygon
accepted answer: http://stackoverflow.com/a/47660533
answer count: 1
has answer: http://stackoverflow.com/a/47660533
downvote count: 0
has comment: http://stackoverflow.com/comment/82275227
has comment: http://stackoverflow.com/comment/82275018
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82277851
has comment: http://stackoverflow.com/comment/82274836
has comment: http://stackoverflow.com/comment/82274516
has title: How to calculate area of polygon from list of points with python?
has comment: http://stackoverflow.com/comment/82280467
upvote count: 5
linked to: http://stackoverflow.com/q/24467972
has comment: http://stackoverflow.com/comment/82274963
tagged with: python
has comment: http://stackoverflow.com/comment/82274637
has body: I have a list/array of 2D points which form a non-convex non-self-intersecting shape. I want to calculate the area enclosed by that polygon. First I need to form a polygon with the points that I get provided as a 'curve-walk' (non self intersecting). If I can triangulate that polygon I can calculate the area ( I can tolerate a small relative error). Using scipy's scipy.spatial.ConvexHull() results in the wrong shape and area , obviously, but I have not found a available algorithm in the big math packages which does this. Can anyone tell me how to do that ?
type: Question
tagged with: geometry
score: 5

http://stackoverflow.com/comment/82155642
type: QuestionComment
has text: what error are you getting?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47598716

http://stackoverflow.com/comment/82094313
type: Comment
has text: I fixed that one but then I get stuck in plotting the boundary. Can you please have a look? Ideally, I want to use the my_svm.SVC.predict for plotting boundary but it gives me error as in https://stackoverflow.com/questions/47568428/typeerror-decision-function-missing-1-required-positional-argument-x
comment on: http://stackoverflow.com/a/47568373
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82277951
type: AnswerComment
comment on: http://stackoverflow.com/a/47639772
score: 0
type: Comment
has text: Oh! My bad! I'll fix that! Really sorry

http://stackoverflow.com/q/47682427
type: Question
has answer: http://stackoverflow.com/a/48970916
tagged with: heroku
has title: How to deploy gRPC server/client to heroku?
tagged with: grpc
upvote count: 5
tagged with: python
tagged with: deployment
has body: I deployed my python gRPC server to Heroku and was wondering how I could test it with a local Python client. server.py def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) icp_pb2_grpc.add_MyServicer_to_server(MyServicer(), server) server_port = os.environ.get('PORT', 50051) server.add_insecure_port('[::]:'+ str(server_port)) server.start() print("==== SERVER RUNNING =====") try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve() client.py def run(): # Is the channel url correct? channel = grpc.insecure_channel('https://www.HEROKUURL.com:50051') stub = my_grpc.MyStub(channel) file = _get_file_content() response = stub.Predict(icp_pb2.MyRequest(file_content=file)) print("received: " + response.results) I am using the client from my computer and am not receiving any response from the server. I am able to successfully communicate with the server if it is launched locally. What am I doing wrong?
has comment: http://stackoverflow.com/comment/82475883
score: 5
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82359584
favorite count: 0

http://stackoverflow.com/q/47565631
favorite count: 0
tagged with: timestamp
type: Question
tagged with: pandas
tagged with: datetime
tagged with: python
score: -1
tagged with: numpy
type: AnsweredQuestion
upvote count: 0
has title: compare a timestamp index with a fixed date in python
has body: I have a dataframe with timestamp index. I want to delete all rows with timestamp index after 2001-01-01. After some googling, I get to this: df.index[1].date() &lt; pd.datetime.strptime('20010101', "%Y%m%d").date()) It works fine as it shows the first index is less than 2001-01-01. So I happily applied to: df.index.date() &lt; pd.datetime.strptime('20010101', "%Y%m%d").date() and got this instead: TypeError: 'numpy.ndarray' object is not callable. to give you a sense of what the index looks like, when I just enter: df.index[1] it returns: Timestamp('1964-01-03 00:00:00')
has answer: http://stackoverflow.com/a/47566513
accepted answer: http://stackoverflow.com/a/47566513
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82089301

http://stackoverflow.com/comment/82305474
type: Comment
type: QuestionComment
score: 0
has text: Add `# pylint: disable=E1123` to the line that calls your decorated function.
comment on: http://stackoverflow.com/q/47673229

http://stackoverflow.com/comment/82190406
comment on: http://stackoverflow.com/q/47615716
type: Comment
type: QuestionComment
score: 0
has text: Here is a sample of the data (wind_speedjja[0:1,:,:]) array([[[ 3.84302425, 3.85788465, 3.87297344, ..., 3.79931521, 3.81356525, 3.82767272], [ 2.61478281, 2.61992002, 2.62531614, ..., 2.6005969 , 2.60529995, 2.60992217], ..., [ 7.33358574, 7.19630527, 7.33323956, ..., 7.54264212, 7.53644514, 7.49996758], [ 7.13919353, 7.22122383, 7.55467606, ..., 6.97763348, 7.11504269, 7.16432858]]], dtype=float32)

http://stackoverflow.com/q/47636145
has comment: http://stackoverflow.com/comment/82230419
has comment: http://stackoverflow.com/comment/82230471
tagged with: cgi
has comment: http://stackoverflow.com/comment/82230863
has body: I have been at this for about an hour and a half now, and I have not been able to devise a solution. I have been working with the following code: form = cgi.FieldStorage() usrName = form.getvalue('uname') usrPW = form.getvalue('psw') while(usrPW == None): form = cgi.FieldStorage() usrName = form.getvalue('uname') usrPW = form.getvalue('psw') #usrName = str(usrName) # usrPW = str(usrPW) connection = pymysql.connect(host = 'localhost', user='golden', password='password', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: #create a new record in the database sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, (usrName, usrPW)) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() This is my attempt to pass data from my form, named uname and psw, respectively. This code worked when I had hard coded the values for uname and psw in the cursor.execute() call, however, when I try to send the form data to the query I get one of two results: 404 with unable to find file If I remove the while(usrPW == None): at the top (and the commands within the while loop), it executes immediately after the page is loaded- before I can type anything in and passes in nothing to both parameters, causing an error. Any thoughts on how to fix this?? How do I properly pass data from a python CGI form to a mySQL database? EDIT: Traceback update. Provided I comment out the while loop and hardcode usrName and usrPW, I get the following: 127.0.0.1 - - [04/Dec/2017 08:09:34] "GET /cgi-bin/login.py HTTP/1.1" 200 - 127.0.0.1 - - [04/Dec/2017 08:09:39] code 404, message File not found 127.0.0.1 - - [04/Dec/2017 08:09:39] "GET /action_page.php?uname=a&amp;psw=b HTTP/1.1" 404 However, the values get entered into the database, interestingly enough. In the case that I leave the while loop running, it just loads indefinitely.
tagged with: mysql
tagged with: forms
type: Question
has comment: http://stackoverflow.com/comment/82230400
answer count: 0
linked to: http://stackoverflow.com/q/7956696
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82231127
has comment: http://stackoverflow.com/comment/82231070
tagged with: python
has comment: http://stackoverflow.com/comment/82230692
has title: Passing form data of Python CGI script to mySQL query
score: 0

http://stackoverflow.com/a/47607342
has comment: http://stackoverflow.com/comment/82173874
upvote count: 10
answers question: http://stackoverflow.com/q/47607311
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82173953
has body: List comprehensions are for mapping or filtering of lists. They cannot have an internal state, which is what you would need to do this efficiently. However in Python 3 there is itertools.accumulate for that: import itertools print(list(itertools.accumulate([1, 4, 9, 16]))) # [1,5,14,30]
accepted answer of: http://stackoverflow.com/q/47607311
score: 10
type: Answer

http://stackoverflow.com/q/47547298
duplicate of: http://stackoverflow.com/q/10239668
has title: Indentation Error Python Not Working
type: Question
has answer: http://stackoverflow.com/a/47547634
answer count: 2
has comment: http://stackoverflow.com/comment/82051451
has body: Im trying to run my code and there is an File "C:/trcrt/trcrt.py", line 42 def checkInternet(): ^ IndentationError: unexpected unindent The code supposed to check for the traceroute to a website... i know... its not very smart but its what i was told to do Ive checked the code using pep8 and eveything is seems to be fine... ''' Developer: Roei Edri File name: trcrt.py Date: 24.11.17 Version: 1.1.0 Description: Get an url as an input and prints the traceroute to it. ''' import sys import urllib2 i, o, e = sys.stdin, sys.stdout, sys.stderr from scapy.all import * from scapy.layers.inet import * sys.stdin, sys.stdout, sys.stderr = i, o, e def trcrt(dst): """ Check for the route for the given destination :param dst: Final destination, in a form of a website. :type dst: str """ try: pckt = IP(dst=dst)/ICMP() # Creates the # packet ip = [p for p in pckt.dst] # Gets the ip print "Tracerouting for {0} : {1}".format(dst, ip[0]) for ttl in range(1, 40): pckt = IP(ttl=ttl, dst=dst)/ICMP() timeBefore = time.time() reply = sr1(pckt, verbose=0, timeout=5) timeAfter = time.time() timeForReply = (timeAfter - timeBefore)*1000 if reply is not None: print "{0} : {1} ; Time for reply: {2}".format(ttl, reply.src, timeForReply) if reply.type == 0: print "Tracerout Completed" break else: print "{0} ... Request Time Out".format(ttl) def checkInternet(): """ Checks if there is an internet connection :return: True if there is an internet connection """ try: urllib2.urlopen('http://45.33.21.159', timeout=1) return True except urllib2.URLError as IntError: return False Thanks for any help... Btw pep8 says "module level import not at top of file" for lines 12,13
tagged with: python
possible better answer: http://stackoverflow.com/a/47547634
linked to: http://stackoverflow.com/q/10239668
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82051407
score: 0
accepted answer: http://stackoverflow.com/a/47547324
has comment: http://stackoverflow.com/comment/82051391
tagged with: indentation
has answer: http://stackoverflow.com/a/47547324

http://stackoverflow.com/q/47573258
tagged with: pypdf
downvote count: 0
answer count: 1
score: 4
has answer: http://stackoverflow.com/a/47591251
has title: Writing text over a PDF in python3
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/pdf
accepted answer: http://stackoverflow.com/a/47591251
tagged with: python
has body: I am trying to write some string to a PDF file at some position. I found a way to do this and implemented it like this: from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = io.StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.drawString(10, 100, "Hello world") can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(file("original.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = file("destination.pdf", "wb") output.write(outputStream) outputStream.close() It throws me an error at can.save() line The error : File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfgen/canvas.py", line 1237, in save self._doc.SaveToFile(self._filename, self) File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfbase/pdfdoc.py", line 224, in SaveToFile f.write(data) TypeError: string argument expected, got 'bytes' Have read up at a lot of places on the internet. Found the same method everywhere. Is it the wrong way to do. Am I missing something?
upvote count: 4
tagged with: python-3.x
tagged with: canvas

http://stackoverflow.com/comment/82126666
comment on: http://stackoverflow.com/q/47584441
score: 0
type: Comment
type: QuestionComment
has text: @Makoto: you're right, I changed "reading" to "opening". Opening is the slowest in what I'm doing, the rest is fast in comparison.

http://stackoverflow.com/q/47571388
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82103524
score: 0
has comment: http://stackoverflow.com/comment/82106997
answer count: 1
accepted answer: http://stackoverflow.com/a/47583235
tagged with: scrapy
has answer: http://stackoverflow.com/a/47583235
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82100065
has title: How do I scrape to csv in scrapy
has comment: http://stackoverflow.com/comment/82103271
has comment: http://stackoverflow.com/comment/82103435
has comment: http://stackoverflow.com/comment/82117729
tagged with: python
has comment: http://stackoverflow.com/comment/82107331
has comment: http://stackoverflow.com/comment/82103618
has body: How do I scrape a page to csv? My csv does not appear or appears blank I have ran: scrapy crawl jobs -o output.csv . While the csv appears, nothing appears into it. # -*- coding: utf-8 -*- import scrapy from scrapy import cmdline cmdline.execute("scrapy crawl jobs".split()) from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from craigslist_sample.items import CraigslistSampleItem class MySpider(CrawlSpider): name = "jobs" allowed_domains = ["sfbay.craigslist.org"] start_urls = ["http://sfbay.craigslist.org/search/npo"] rules = ( Rule(SgmlLinkExtractor(allow=(), restrict_xpaths=('//a[@class="button next"]',)), callback="parse_items", follow= True), ) def parse_items(self, response): hxs = HtmlXPathSelector(response) titles = hxs.xpath('//span[@class="pl"]') items = [] for titles in titles: item = CraigslistSampleItem() item["title"] = titles.xpath("a/text()").extract() item["link"] = titles.xpath("a/@href").extract() items.append(item) return(items) class MySpider(CrawlSpider): name = 'csvexample' start_urls = ['C:/example.csv'] delimiter = ',' headers = ['Address', 'Website']
has comment: http://stackoverflow.com/comment/82106914
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82103373

http://stackoverflow.com/comment/82154014
comment on: http://stackoverflow.com/q/47597289
type: Comment
type: QuestionComment
score: 0
has text: @sabal202 you sum your numbers in pairs 1st + 2nd, 3rd + 4th, etc. Those pairs you again sum in pairs and so on, so you end up with all the sums for aligned 1, 2, 4, 8 etc blocks. You can piece these together to obtain the sums of ranges in logarithmic time. And updating also involves only O(log n) pieces.

http://stackoverflow.com/q/47653306
linked to: http://stackoverflow.com/q/40809758
tagged with: networkx
has comment: http://stackoverflow.com/comment/98289960
has title: Set the rank of nodes (subgraph) using just networkx
score: 7
linked to: http://stackoverflow.com/q/22207802
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/98248235
answer count: 0
has body: I have been building a graph via Python using the Networkx library only. My program outputs a .dot file with nx.drawing.nx_pydot.to_pydot() and uses the dot engine to draw that file with Graphviz, by calling write_png("output.png") on the dot object. My dot file could look like this: strict digraph { a; b; c; a -&gt; b; a -&gt; c; } I want to add the dot file to be as follows: strict digraph { a; b; c; a -&gt; b; a -&gt; c; {rank=same; a b}; } Because in the previous case b and c are drawn below a and in the later case c is drawn below a and b, which are at the same level. I cannot find, in the documentation, how to make this simple change. I understand this is the same as declaring a subgraph and setting its attribute, but the part I am struggling with is setting the rank attribute of that subgraph. After my graph has been constructed, the following code handles the output. DG = myGraphBuildFunction(dictOfEdges) p = nx.drawing.nx_pydot.to_pydot(DG) p.write_png('example.png') nx.drawing.nx_pydot.write_dot(DG, "Output.dot") print("Graph Generated") How can I easily set the rank of some nodes from here? I want to avoid the pygraphviz library, but I am fine with the graphviz library. Pygraphviz won't easily install on Windows via pip install and I need to keep this program "easy to use and maintain", as I am not the only one who will be potentially using it.
type: UnansweredQuestion
downvote count: 0
tagged with: python
upvote count: 7

http://stackoverflow.com/comment/97595548
has text: For positions, the conversion can be accomplished simply by swapping the Y and Z values.
comment on: http://stackoverflow.com/q/47662760
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47541472
has body: I know this is an exact copy of this question, but I've been trying different solutions for a while and didn't come up with anything. I have this simple script that uses PRAW to find posts on Reddit. It takes a while, so I need it to stay alive when I log out of the shell as well. I tried to set it up as a start-up script, to use nohup in order to run it in the background, but none of this worked. I followed the quickstart and I can get the hello word app to run, but all these examples are for web applications and all I want is start a process on my VM and keep it running when I'm not connected, without using .yaml configuration files and such. Can somebody please point me in the right direction?
type: Question
accepted answer: http://stackoverflow.com/a/47548690
has answer: http://stackoverflow.com/a/47548690
tagged with: google-compute-engine
tagged with: python
has title: Run python script on Google Cloud Compute Engine
type: AnsweredQuestion
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/47455680
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47637853
has answer: http://stackoverflow.com/a/47638139
tagged with: redis-py
has comment: http://stackoverflow.com/comment/82234051
upvote count: 0
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has title: How to create nested structure in redis using python?
tagged with: redis
has body: redis = {} redis['A'] = {} redis['A']['1'] = value1 redis['A']['2'] = value2 redis['A']['3'] = value3 I need to make above structure in redis using python. I have established connection using redis-py client in python like this: _connection = redis.StrictRedis(host='localhost', port=6379, db=0) please let me know how to create , store and get values in redis using python?
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/82233939

http://stackoverflow.com/a/47660528
answers question: http://stackoverflow.com/q/47660378
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47660378
downvote count: 0
has body: Try threading.Timer: For example: from flask import Flask from flask import jsonify import subprocess import threading app = Flask(__name__) def _reboot(): subprocess.call("/sbin/reboot") @app.route('/api/reboot') def reboot(): t = threading.Timer(1, _reboot) t.start() return jsonify(triggered='reboot') if __name__ == '__main__': app.run(debug=True,host="0.0.0.0")
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82279967

http://stackoverflow.com/q/47576241
has comment: http://stackoverflow.com/comment/82109329
has comment: http://stackoverflow.com/comment/82109401
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82109479
has comment: http://stackoverflow.com/comment/82109791
has answer: http://stackoverflow.com/a/47576376
tagged with: python
score: -1
has title: I need help making a program to tell if the shape you input is a parallelogram
answer count: 2
has answer: http://stackoverflow.com/a/47576329
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82109474
has comment: http://stackoverflow.com/comment/82109370
has body: I'm trying to make the a and b equal the same and when a and b are the same, c and d have to be the same, but they can be different from a and b play = True while play: a = float(input("Enter length of side A: ")) b = float(input("Enter length of side B: ")) c = float(input("Enter length of side C: ")) d = float(input("Enter length of side D: ")) if 'a' == 'b' and 'c' == 'd': print("It's a parallelogram") elif 'a' == 'c' and 'b' == 'd': print("It's a parallelogram") elif 'b' == 'c' and 'a' == 'd': print("It's a parallelogram") else: print("It is not a parallelogram") continue

http://stackoverflow.com/a/47611963
has body: your fitFunc needs to be vectorized so try using a numpy array for zz4u zz4u = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0] or better yet zz4u = np.arange(0, 7.5, 0.5).
accepted answer of: http://stackoverflow.com/q/47595801
score: 1
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47595801
type: AcceptedAnswer

http://stackoverflow.com/a/47715663
has body: Your issue is that cookies are only sent based on the domain. Your code has var settings = { "crossDomain": true, "url": "http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&amp;tracking_id=123123123", "method": "GET", } The url is 127.0.0.1:8000 and it should be local.com:8000 if you want the cookies to be passed.
has comment: http://stackoverflow.com/comment/82391941
has comment: http://stackoverflow.com/comment/123060580
downvote count: 0
answers question: http://stackoverflow.com/q/47652495
has comment: http://stackoverflow.com/comment/82411777
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/118476962
has comment: http://stackoverflow.com/comment/82391623

http://stackoverflow.com/a/64828162
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has body: As pointed out, you have to use scoped session, so instead of your conn: from sqlalchemy.orm import sessionmaker, scoped_session db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) And then whenever you connect to your db in a thread, remembeer to open and close a session, you dont want sessions to be shared by threads, because this will lead to bad things, so: def worker(sth): session = db_session() "do sth very important" res = session.query(YourModel).filter(YourModel.sth = sth).first() print(res) session.close() And then you can use such workers in your multithreaded operations. I hope it helped.
accepted answer of: http://stackoverflow.com/q/47686853
answers question: http://stackoverflow.com/q/47686853

http://stackoverflow.com/comment/82420125
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47713800
has text: _mysql.c: In function ‘_mysql_ConnectionObject_ping’: _mysql.c:2005:41: error: ‘MYSQL {aka struct st_mysql}’ has no member named ‘reconnect’ if ( reconnect != -1 ) self->connection.reconnect = reconnect; ^ error: command 'gcc' failed with exit status 1

http://stackoverflow.com/comment/82356495
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47681020
type: QuestionComment
has text: Yes, that would work too. Thanks

http://stackoverflow.com/comment/82284548
type: AnswerComment
has text: In your python console run `import django` and then `django.VERSION`
score: 0
comment on: http://stackoverflow.com/a/47662485
type: Comment

http://stackoverflow.com/comment/82325786
has text: It would be helpful to mention Python3.6. 'execfile' does not work
score: 0
comment on: http://stackoverflow.com/q/47683022
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82289970
type: QuestionComment
comment on: http://stackoverflow.com/q/47652524
type: Comment
score: 0
has text: @dark980 `x1+x2+x3 <= 600; x3+x4+x5 >= 300; x1+x2+x3 +x4+...+xn == 1000;` those are all conditions or you have more? How much is `n`?

http://stackoverflow.com/a/47586156
accepted answer of: http://stackoverflow.com/q/47586125
has comment: http://stackoverflow.com/comment/82130022
answers question: http://stackoverflow.com/q/47586125
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/82130049
downvote count: 0
type: Answer
has body: Using isin, cause, the user_id is not the index , we can not using .drop here. threshold = 10 value_counts = ratings['user_id'].value_counts() to_remove = value_counts[value_counts &lt;= threshold].index ratings.loc[~ratings['user_id'].isin(to_remove),:]
type: AcceptedAnswer

http://stackoverflow.com/comment/82104904
has text: And fix the indentation. Should the `return` statment really be _inside_ the loop?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47574090

http://stackoverflow.com/comment/83658912
score: 0
type: AnswerComment
has text: @neuro sorry for asking again, but as you seem very experienced with waf, I would very much appriciate if you would tell me, where to find this in the documentation?
type: Comment
comment on: http://stackoverflow.com/a/47712281

http://stackoverflow.com/q/47641286
has comment: http://stackoverflow.com/comment/82241126
tagged with: pandas
has comment: http://stackoverflow.com/comment/82241216
has answer: http://stackoverflow.com/a/47641452
linked to: http://stackoverflow.com/q/47641184
has comment: http://stackoverflow.com/comment/82241072
has comment: http://stackoverflow.com/comment/82241137
tagged with: python
has title: converting pandas dataframe to contain a dictionary or list of lists
has answer: http://stackoverflow.com/a/47664763
has comment: http://stackoverflow.com/comment/82241271
answer count: 4
has comment: http://stackoverflow.com/comment/82241034
has body: state Year Month count 0 alabama 2017.0 10.0 31 1 alabama 2017.0 11.0 30 2 alabama 2017.0 12.0 31 3 alabama 2018.0 1.0 31 4 alabama 2018.0 2.0 28 5 alabama 2018.0 3.0 31 6 alabama 2018.0 4.0 30 7 alabama 2018.0 5.0 31 8 alabama 2018.0 6.0 30 9 alabama 2018.0 7.0 14 10 arkansas 2017.0 10.0 31 11 arkansas 2017.0 11.0 30 12 arkansas 2017.0 12.0 31 Can I convert dataframe above to: Month state alabama {2017:10.0, 2017:11.0, 2017:12.0, 2018:1.0, 2018:2.0, 2018:3.0, 2018:4.0, 2018:5.0, 2018:6.0, 2018:7.0} arkansas {2017:10.0, 2017:11.0, 2017:12.0} related to converting pandas dataframe to contain a list based on @Vaishali's comment below, since dictionary cannot contain duplicate keys, this should be ok too: Month state alabama [[2017,10.0], [2017,11.0], [2017,12.0], [2018,1.0], [2018,2.0], [2018,3.0], [2018,4.0], [2018,5.0], [2018,6.0], 2[018,7.0]] arkansas [[2017,10.0], [2017,11.0], [2017,12.0]]
has answer: http://stackoverflow.com/a/47641430
upvote count: 2
has comment: http://stackoverflow.com/comment/82241055
has comment: http://stackoverflow.com/comment/82241230
has comment: http://stackoverflow.com/comment/82241082
possible better answer: http://stackoverflow.com/a/47641444
score: 1
has comment: http://stackoverflow.com/comment/82241092
downvote count: 1
has comment: http://stackoverflow.com/comment/82241106
has answer: http://stackoverflow.com/a/47641444
favorite count: 0
has comment: http://stackoverflow.com/comment/82241174
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47641452

http://stackoverflow.com/q/47554060
has comment: http://stackoverflow.com/comment/82065003
has comment: http://stackoverflow.com/comment/82065056
has answer: http://stackoverflow.com/a/47554474
accepted answer: http://stackoverflow.com/a/47554226
has title: Python - compare list elements with dictionary elements
has body: I have a dictionary and a list. I need to compare the "id" tag of the dictionaries (integer) with the list elements. Something like this: l = [[1], [7], [9]] dict = { "first":{ "id": "0" }, "second":{ "id": "7" }, "third":{ "id": "4" } } for i in l: for j in dict: if i == dict[j]["id"]: print("Yay!") else: print("Nay!") I want to be able to check if any elements of list 'l' can be found in the "id" tags of dictionaries. How do I do that?
possible better answer: http://stackoverflow.com/a/47554350
has answer: http://stackoverflow.com/a/47554226
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82064991
has comment: http://stackoverflow.com/comment/82064840
has answer: http://stackoverflow.com/a/47554350
has comment: http://stackoverflow.com/comment/82065187
has answer: http://stackoverflow.com/a/47554365
tagged with: compare
tagged with: python
answer count: 6
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82064845
has answer: http://stackoverflow.com/a/47554415
type: Question
score: 0
has answer: http://stackoverflow.com/a/47554280

http://stackoverflow.com/a/47635978
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/47631270
has body: Note: I did convert those dates to datetimes using df['Date'] = pd.to_datetime(df.Date) One way to do this is to use pd.concat then use pandas plot: pd.concat([df1,df2], keys=['df1','df2'])\ .set_index('Date', append=True)\ .unstack(0)['Value']\ .reset_index(0, drop=True)\ .fillna(0).plot(marker='o') More like a scatter plot: pd.concat([df1,df2], keys=['df1','df2'])\ .set_index('Date', append=True)\ .unstack(0)['Value']\ .reset_index(0, drop=True)\ .plot(marker='o',linestyle='none')
type: Answer
accepted answer of: http://stackoverflow.com/q/47631270
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82289787
score: 0
type: Comment
has text: And great, I can't edit my comment anymore, but the last sample should be `from a.b import c; a.b.c()`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47665182

http://stackoverflow.com/q/47624347
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/25226871
upvote count: 1
favorite count: 0
type: Question
tagged with: perceptron
tagged with: nltk
tagged with: python
tagged with: pos-tagger
accepted answer: http://stackoverflow.com/a/47627822
tagged with: nlp
has title: Read my own dataset for NLTK Part of Speech tagging using PerceptronTagger
has answer: http://stackoverflow.com/a/47627822
type: AnsweredQuestion
has body: I'm new to NLTK and still pretty new to python. I want to use my own dataset to train and test NLTK's Perceptron tagger. The training and testing data has the following format (it's just saved in a txt file): Pierre NNP Vinken NNP , , 61 CD years NNS old JJ , , will MD join VB the DT board NN as IN a DT nonexecutive JJ director NN Nov. NNP 29 CD . . I want to call these functions on the data: perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False) perceptron_tagger.train(train_data) accuracy = perceptron_tagger.evaluate(test_data) I've tried a few things but I just can't figure out what format the data is expected to be in. Any help would be appreciated! Thanks
score: 1

http://stackoverflow.com/comment/82397822
type: QuestionComment
type: Comment
has text: I did indeed inspire me, thank you. I've replaced the line `return None` with `pytest.skip('not odd')`. I'm not convinced this is the intended use case of but it's significantly better from where I was. If you want to post that as an answer I can give you credit @IgnacioVergaraKausel
score: 0
comment on: http://stackoverflow.com/q/47696002

http://stackoverflow.com/a/47648179
type: Answer
accepted answer of: http://stackoverflow.com/q/47648133
has comment: http://stackoverflow.com/comment/85396446
downvote count: 0
answers question: http://stackoverflow.com/q/47648133
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99566993
has body: In Python for compare by not equal need !=, not &lt;&gt;. So need: def mape_vectorized_v2(a, b): mask = a != 0 return (np.fabs(a - b)/a)[mask].mean() Another solution from stats.stackexchange: def mean_absolute_percentage_error(y_true, y_pred): y_true, y_pred = np.array(y_true), np.array(y_pred) return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
upvote count: 38
score: 38

http://stackoverflow.com/comment/82255880
has text: ```s= ["In Progress", "On Hold", "On Hold", "Completed"]``` and set(s) you will get ```{'Completed', 'In Progress', 'On Hold'}``` or you can do list(set(s)) to get list as output ```['Completed', 'In Progress', 'On Hold']```
type: QuestionComment
comment on: http://stackoverflow.com/q/47648747
score: 0
type: Comment

http://stackoverflow.com/comment/82129685
has text: Here is the link to it: https://data.ny.gov/api/views/nqur-w4p7/rows.json?accessType=DOWNLOAD
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47585856
score: 0

http://stackoverflow.com/q/47606629
tagged with: 32bit-64bit
linked to: http://stackoverflow.com/q/3117626
has body: I have a 64-bits Windows 7 computer, with several 64-bits programs installed and working perfectly. However, when I try to execute Python 3.5 or Python 3.6 for 64-bits I receive the following error "The application could not be properly initialize. We must quit." I have installed Python 3.5 for 32-bits and it works. The problem is that I'm trying to install Cantera, which requires to have the same architecture for Matlab (64-bits) and Python, so I need 64-bit Python. Could you please provide information about how to fix this problem? Thanks
tagged with: python
has comment: http://stackoverflow.com/comment/82173100
has comment: http://stackoverflow.com/comment/82174129
score: -1
answer count: 3
has comment: http://stackoverflow.com/comment/82171741
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/47606687
has answer: http://stackoverflow.com/a/47606658
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47607026
has title: 64-bit Python not working in 64-bit computer, whereas 32-bit Python works
has comment: http://stackoverflow.com/comment/82172082

http://stackoverflow.com/a/47624333
accepted answer of: http://stackoverflow.com/q/47624292
score: 0
answers question: http://stackoverflow.com/q/47624292
type: AcceptedAnswer
has body: To print the last three rows, which I assume means two rows with "sides" and one row at the bottom, change the line with the for statement to: for i in A[-2:]: If you want the last three rows of A itself (in addition to the bottom row of dashes), then for i in A[-3:]:
has comment: http://stackoverflow.com/comment/82206527
type: Answer

http://stackoverflow.com/q/47603155
has answer: http://stackoverflow.com/a/47603562
has answer: http://stackoverflow.com/a/47700566
tagged with: python
tagged with: google-cloud-storage
has body: I wanted to test some code interacting with GCS that I have running locally today. My plan is to: save a service account JSON file in GDrive download it to Colaboratory's 'local' /tmp !export GOOGLE_APPLICATION_CREDENTIALS=&lt;path_to_service_account_file&gt; storage_client = storage.Client('my-project') and play with different methods / properties. I installed !pip install --upgrade google-cloud but when testing bullet 4 (expecting an authentication error), I get a message re dependencies issues: ContextualVersionConflictTraceback (most recent call last) &lt;ipython-input-13-7346ac058842&gt; in &lt;module&gt;() ----&gt; 1 from google.cloud import storage 2 3 4 # Authenticate to GCS. 5 from google.colab import auth /usr/local/lib/python2.7/dist-packages/google/cloud/storage/__init__.py in &lt;module&gt;() 33 34 from pkg_resources import get_distribution ---&gt; 35 __version__ = get_distribution('google-cloud-storage').version 36 37 from google.cloud.storage.batch import Batch /usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_distribution(dist) 554 dist = Requirement.parse(dist) 555 if isinstance(dist, Requirement): --&gt; 556 dist = get_provider(dist) 557 if not isinstance(dist, Distribution): 558 raise TypeError("Expected string, Requirement, or Distribution", dist) /usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_provider(moduleOrReq) 428 """Return an IResourceProvider for the named module or requirement""" 429 if isinstance(moduleOrReq, Requirement): --&gt; 430 return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] 431 try: 432 module = sys.modules[moduleOrReq] /usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in require(self, *requirements) 970 included, even if they were already activated in this working set. 971 """ --&gt; 972 needed = self.resolve(parse_requirements(requirements)) 973 974 for dist in needed: /usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in resolve(self, requirements, env…
has title: google cloud libs not working on Colaboratory
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: google-colaboratory
favorite count: 0
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47603562
accepted answer: http://stackoverflow.com/a/47700566

http://stackoverflow.com/comment/82216655
type: QuestionComment
has text: @martineau I tried your code and still the same problem, and the error line is `f.close()`, which is strange. This line can never be wrong, it seems the line above it would always be wrong. For example, now the wrong line is `f.close()`, if I add a comment line `#...` above `f.close()`, then the comment line would be the error line.
comment on: http://stackoverflow.com/q/47628400
score: 0
type: Comment

http://stackoverflow.com/comment/82291791
score: 0
has text: I also realized that I had left a previous line where I left a function that I deleted. Now can anyone help me with making it so that if my sprite goes over it, it will trigger something?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47666220

http://stackoverflow.com/comment/82302632
type: QuestionComment
has text: [`any(iterable)`](https://docs.python.org/3/library/functions.html#any)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47671865

http://stackoverflow.com/comment/82220079
score: 0
type: Comment
has text: thanks a lot..below one is working fine..actually i missed headers=headers.....once again thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/47629720

http://stackoverflow.com/q/47664138
score: 1
has body: I have a code which takes a user's input which is supposed to be a first and last name. My code then takes that input and searches a csv for projects and hours that the input name is associated to. The problem I'm running into is if I misspell or don't capitalize the first letter of each name the code will not work. Is there a function or a way out there where if the user inputs the first 3 letters right or something similar the code will automatically assume the correct spelling and change the input accordingly? I'm a very novice coder so any help would be great. Here's my code for reference: import csv # I've used full name to avoid duplicate first names in report full_name = input('Enter your full name: ') with open('Report1.csv') as csvfile: hour_summation = {} read_csv = csv.reader(csvfile, delimiter=',') for row in read_csv: if ' '.join((row[0], row[1])) == full_name.strip(): hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3])) print('This is {} full hours report:'.format(full_name)) for k, v in hour_summation.items(): print(k + ': ' + str(v) + ' hours')
has comment: http://stackoverflow.com/comment/82287620
tagged with: python
has comment: http://stackoverflow.com/comment/82287906
type: AnsweredQuestion
tagged with: spell-checking
has answer: http://stackoverflow.com/a/47664273
downvote count: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82287645
linked to: http://stackoverflow.com/q/17388213
tagged with: loops
has title: Spell check for python input
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82287812
accepted answer: http://stackoverflow.com/a/47664273
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/47679966
has comment: http://stackoverflow.com/comment/82389937
has comment: http://stackoverflow.com/comment/82322998
tagged with: mutation
has comment: http://stackoverflow.com/comment/82400241
tagged with: traveling-salesman
has comment: http://stackoverflow.com/comment/82400306
has title: How can I improve this genetic algorithm for the TSP?
has answer: http://stackoverflow.com/a/48290905
has comment: http://stackoverflow.com/comment/82367836
has comment: http://stackoverflow.com/comment/82331642
has body: This is my genetic algorithm, step by step: Generate two initial population's randomly, and select the fittest tour from both. Perform an ordered crossover, which selects a random portion of the first fit tour and fills in the rest from the second, in order. Mutates this tour by randomly swapping two cities if the tour is only 1.3 times as good as the top 10% tour in the initial population (which I have literally just done by induction, singling out poor tours that are produced) - I would love to change this but can't think of a better way. The mutation is selected from a population of several mutations. Returns the tour produced. The mutation, however is almost ALWAYS worse, if not the same as the crossover. I'd greatly appreciate some help. Thanks!
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82350465
answer count: 1
has comment: http://stackoverflow.com/comment/82322817
tagged with: crossover
has comment: http://stackoverflow.com/comment/82323851
type: Question
has comment: http://stackoverflow.com/comment/82322634
tagged with: genetic-algorithm
score: 0

http://stackoverflow.com/q/47615999
has body: I have a piece of code that looks like this: myfunction(a, b, c) myfunction(d, e, f) myfunction(g, h, i) myfunction(j, k, l) The number of arguments do not change, but the function has to be called consecutively with different values each time. These values are not automatically generated and are manually inputted. Is there an inline solution to do this without creating a function to call this function? Something like: myfunction(a, b, c)(d, e f)(g, h, i)(j, k, l) Any help appreciated. Thanks in advance!
has comment: http://stackoverflow.com/comment/82190419
upvote count: 4
has title: Calling a function multiple times consecutively with different arguments in Python (3.x)?
score: 4
accepted answer: http://stackoverflow.com/a/47616216
possible better answer: http://stackoverflow.com/a/63273454
type: AnsweredQuestion
tagged with: function
has comment: http://stackoverflow.com/comment/82190924
has answer: http://stackoverflow.com/a/47616216
downvote count: 0
has comment: http://stackoverflow.com/comment/82190903
has comment: http://stackoverflow.com/comment/82190436
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47616068
has answer: http://stackoverflow.com/a/47616202
has comment: http://stackoverflow.com/comment/82190398
type: Question
tagged with: shortcut
linked to: http://stackoverflow.com/q/5893163
has comment: http://stackoverflow.com/comment/82190285
has answer: http://stackoverflow.com/a/63273454
has answer: http://stackoverflow.com/a/63669721
tagged with: python
answer count: 5
has comment: http://stackoverflow.com/comment/82190928

http://stackoverflow.com/a/68106107
downvote count: 0
type: Answer
has body: Worked on my machine using pip install "websockets==8.1"
has comment: http://stackoverflow.com/comment/128050055
answers question: http://stackoverflow.com/q/47665760
upvote count: 5
score: 5

http://stackoverflow.com/comment/82218150
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47629806
has text: yeah haha i was trying to figure out if either fetch was the problem.. @bruno

http://stackoverflow.com/q/47643944
has answer: http://stackoverflow.com/a/47644420
favorite count: 0
type: Question
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
has body: I am very new to Python but I'm trying to learn more and my first mini project that I've given myself is to create a code that can receive the input for a given user name and then output the amount of hours they worked on a certain project. I receive a csv at the end of the week for employees in my department and within that csv I have various projects that they are working on and the hours dedicated to that project. The catch with the csv file is there are duplicate projects for that user so when my csv outputs I need it to only show one project name and ALL the hours associated with that project. How can I get my code to read the duplicates and only count the hours from the duplicates and just use one project name? Here is the code I've come up with so far: import csv with open('Report.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') firsts = [] lasts = [] projects = [] hours = [] for row in readCSV: first = row[0] last = row[1] project = row[2] hour = row[3] firsts.append(first) lasts.append(last) projects.append(project) hours.append(hour) First_name = input("Please enter the first name: ") First_1 = firsts.index(First_name) Last_1 = lasts[First_1] project_1 = projects[First_1] hours_1 = hours[First_1] print(First_1, Last_1, project_1, hours_1) Here is a sample of the csv First Last Project Hours David Ayers AD-0002 Training 24 Oriana Morfitt AD-0002 Training 24 David Ayers AD-0003 Personal Time 8 David Ayers AD-0004 Sick Time 0 Oriana Morfitt AD-0005 Vacation 40 Sujatha Kavuri Beeline Blank 29 Sujatha Kavuri Beeline Blank 16 Sujatha Kavuri OPS-0001 General Operational Support 6 Jeff Moore OPS-0001 General Operational Support 5 Sri Mantri SRV-0001 Service Requests for Base and Direct Services 4 Prasanth Musunuru SRV-0001 Service Requests for Base and Direct Services 11 Prasanth Musunuru SRV-0001 Service Requests for Base and Direct Services 10 Jeff Moore SRV-0006 Standards and Processes 5 Jeff Moore SRV-0006 Standards and Processes 3 Jeff Moore SRV…
answer count: 1
tagged with: input
tagged with: python
has title: using user input to extract data from csv file
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/47673008
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/373335
tagged with: python
tagged with: docker
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47673121
answer count: 2
has title: How to schedule a periodic task in Python?
downvote count: 0
has body: How can I schedule a periodic task in python without blocking? Here is a simple situation. Assume this ticket variable becomes invalid after 2 hours. So I need to fetch it from a serve. ticket = 1 # It expires every 2 hours def process_using_ticket(): # This function is called using a get request from flask server print('hello', ticket) How can I reset to 1 every two hours without blocking? One way could be to start a thread and sleep for 2 hours and then reset the variable but I am wondering if there are better alternatives. Note: Everything runs in a docker.
accepted answer: http://stackoverflow.com/a/47673156
has comment: http://stackoverflow.com/comment/82305505
tagged with: scheduled-tasks
has answer: http://stackoverflow.com/a/47673156
possible better answer: http://stackoverflow.com/a/47673121

http://stackoverflow.com/q/47564068
has answer: http://stackoverflow.com/a/47567696
type: Question
tagged with: robotframework
answer count: 1
tagged with: testing
type: AnsweredQuestion
score: 0
has title: Testing Forms in Robot Framework
accepted answer: http://stackoverflow.com/a/47567696
has body: I need to write a test for a web service that makes a request like the following: curl -X POST -v -F 'id=1234' -F 'name=blah.png' -F 'contentType=image/png' -F 'file=@somefile.png' path/to/some/endpoint The documentation: robot request documentation , doesn't suggest that it has a method to mock forms. I'm I missing something or do I need to write some python code outside of the robot request library to make a request like this? Thanks!
tagged with: python

http://stackoverflow.com/a/47680866
has comment: http://stackoverflow.com/comment/82326917
accepted answer of: http://stackoverflow.com/q/47624829
has comment: http://stackoverflow.com/comment/82326588
has body: You forget to include all source files: sources = glob.glob('ext/*.c') + glob.glob('src/*.c') you could see c extension build detail with setup.py build -fv: $ python setup.py build -fv ... clang -bundle -undefined dynamic_lookup build/temp.macosx-10.13-x86_64-3.6/ext/euler_py.o build/temp.macosx-10.13-x86_64-3.6/src/euler.o build/temp.macosx-10.13-x86_64-3.6/src/helpers.o -o build/lib.macosx-10.13-x86_64-3.6/euler_py.cpython-36m-darwin.so now helpers.o and euler.o properly linked.
type: Answer
answers question: http://stackoverflow.com/q/47624829
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/82326339
has comment: http://stackoverflow.com/comment/82325097
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82326466
has comment: http://stackoverflow.com/comment/82327014

http://stackoverflow.com/comment/82321293
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47680901
has text: yes your are right i should put it in bool()
score: 0

http://stackoverflow.com/a/47576369
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47576276
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82299918
has comment: http://stackoverflow.com/comment/82275852
has comment: http://stackoverflow.com/comment/82113367
has comment: http://stackoverflow.com/comment/82113929
type: Answer
accepted answer of: http://stackoverflow.com/q/47576276
has body: An easy way to deal with this problem is to use Selenium web browser, which can be controlled with python. That way, it will work just as your web browser and will manage all cookies and everything for you. With it you can also display javascript. Check the Selenium Starter Guide
has comment: http://stackoverflow.com/comment/96896583
has comment: http://stackoverflow.com/comment/82305772

http://stackoverflow.com/comment/82041889
type: Comment
has text: Ok, is Python installed? If not, install it. If it already is, maybe you're missing a '-dev' package of some sort related to Python...
score: 0
comment on: http://stackoverflow.com/q/47542282
type: QuestionComment

http://stackoverflow.com/comment/82171904
type: Comment
comment on: http://stackoverflow.com/a/47590965
has text: i'm extracting it directly on my mac os x!
type: AnswerComment
score: 0

http://stackoverflow.com/a/47660624
has body: Try converting class name to a CSS selector. With a CSS selector, a class named x-form-text x-form-field x-form-num-field turns into .x-form-text.x-form-field.x-form-num-field So basically just replace spaces with dots and you're good to go.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82281886
type: Answer
answers question: http://stackoverflow.com/q/47660523
has comment: http://stackoverflow.com/comment/82281800
has comment: http://stackoverflow.com/comment/82282390
downvote count: 0
has comment: http://stackoverflow.com/comment/82281517
has comment: http://stackoverflow.com/comment/82282247
has comment: http://stackoverflow.com/comment/82282210

http://stackoverflow.com/comment/138193594
has text: if you passed parameter as null, you can add null check control in your PythonLiteralOption class.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47730333
type: Comment

http://stackoverflow.com/q/47545699
tagged with: python
has body: I've looked all over Stackoverflow, for an answer to this question, but can't seem to find it. I am starting out in Python and I am attempting to make a simple quiz game. I want the player to be able to type the name of the menu they want to goto. I have this so far: print("Hello, and welcome to the Python Quiz.") print("[START]") print("[HELP]") print("[ABOUT]") print("[EXIT]") menu = input("Type name of menu to navigate to corresponding menu. ") if menu == "START": ........... What comes next?
has comment: http://stackoverflow.com/comment/82048280
score: -1
has comment: http://stackoverflow.com/comment/82048746
has comment: http://stackoverflow.com/comment/82079578
linked to: http://stackoverflow.com/q/19964603
has comment: http://stackoverflow.com/comment/82048224
has title: a Python version of batch-file's GOTO command?
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82068576
upvote count: 1
duplicate of: http://stackoverflow.com/q/19964603
has comment: http://stackoverflow.com/comment/82048681
favorite count: 0
has comment: http://stackoverflow.com/comment/82048652
type: Question
linked to: http://stackoverflow.com/q/438844
has answer: http://stackoverflow.com/a/47545771
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82048677
has comment: http://stackoverflow.com/comment/82048700

windows
tags question: http://stackoverflow.com/q/47590137
tags question: http://stackoverflow.com/q/47650886
tags question: http://stackoverflow.com/q/47583281
tags question: http://stackoverflow.com/q/47587088
tags question: http://stackoverflow.com/q/47561142
tags question: http://stackoverflow.com/q/47542493
tags question: http://stackoverflow.com/q/47661042
tags question: http://stackoverflow.com/q/47630802
tags question: http://stackoverflow.com/q/47686313
type: Tag
tags question: http://stackoverflow.com/q/47556899
tags question: http://stackoverflow.com/q/47600301
tags question: http://stackoverflow.com/q/47659570
tags question: http://stackoverflow.com/q/47623713
tags question: http://stackoverflow.com/q/47596952
tags question: http://stackoverflow.com/q/47605034
tags question: http://stackoverflow.com/q/47556831
tags question: http://stackoverflow.com/q/47631941
tags question: http://stackoverflow.com/q/47579641
tags question: http://stackoverflow.com/q/47602800
tags question: http://stackoverflow.com/q/47660525
tags question: http://stackoverflow.com/q/47590779
tags question: http://stackoverflow.com/q/47599936
tags question: http://stackoverflow.com/q/47575934
tags question: http://stackoverflow.com/q/47694335
tags question: http://stackoverflow.com/q/47550043
tags question: http://stackoverflow.com/q/47585686
tags question: http://stackoverflow.com/q/47637584
tag name: windows
tags question: http://stackoverflow.com/q/47562387
tags question: http://stackoverflow.com/q/47543734
tags question: http://stackoverflow.com/q/47663498
tags question: http://stackoverflow.com/q/47659478
tags question: http://stackoverflow.com/q/47555345
tags question: http://stackoverflow.com/q/47693984
tags question: http://stackoverflow.com/q/47592367
tags question: http://stackoverflow.com/q/47609513
tags question: http://stackoverflow.com/q/47693631

http://stackoverflow.com/a/49113180
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47592566
has body: Well i found myself working with Stanford POS Tagger recently (got a similar warning) but still the tagger is still working. The thing is, this is a warning telling you that they will change/remove the StanfordNERTagger class (more information about the warning). What i advise you to do is to maintain your code with venv or just copy the module (that's what i did) for example in order to keep your nltk module the way it is (avoid updating therefore sticking with this class). Hope this helps you.

http://stackoverflow.com/q/47646097
has comment: http://stackoverflow.com/comment/82250766
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/47646583
has comment: http://stackoverflow.com/comment/82250833
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82251341
linked to: http://stackoverflow.com/q/43069712
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47646583
has title: How to implement logout in django in template?
has comment: http://stackoverflow.com/comment/82250774
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: This is my views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import os # Create your views here. @csrf_exempt def index(request): if('loggedIn' in request.session): id = request.session['uid']; return render(request,"index.html",{'uid':id}); else: return render(request,"index.html",{}); urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ] This is the first time I am doing a Django project. I was able to log in and now see the index page. Now I have a logout button as Logout So, what can I need to do to log out from the system.. Please I am not getting idea behind the same.. It will be great If, somebody helped me.
downvote count: 1
score: -1
favorite count: 0

http://stackoverflow.com/q/47574672
has title: Writing sections of a file to two other files
tagged with: file
has comment: http://stackoverflow.com/comment/82106236
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47575040
has body: So I've got a file which contains combined instances (list of numbers) for a program i'm writing. I then proceed to put all the lines with '@' to both training and testing files. Now I want to put 28,709 instances to my training file and then the rest of the file's instances to the testing file. When I do this, with this code: import itertools # Splits the training and testing instances # with the newly reduced attributes training = open('training.txt', 'w') testing = open('testing.txt', 'w') linecount = 0 with open('combined.txt', 'r') as f: for l in f: if not l.startswith('@'): break else: training.write(l) testing.write(l) linecount += 1 with open('combined.txt', 'r') as f: newcount = 0 for l in f: while(newcount &lt; linecount): f.next() newcount += 1 if linecount &gt; (linecount + 28709): testing.write(l) else: training.write(l) linecount += 1 '''# Write 28,709 instances to training set for l in itertools.islice(f, linecount, linecount + 28709): training.write(l) # Write rest of instances to testing set for i in xrange(linecount + 28710): f.next() for l in f: testing.write(l)''' .. It doesn't do all the instances to the training set and doesn't output anything testing set. The original combined file can be found here (too big to paste here): https://gist.githubusercontent.com/ryankshah/618fde939a54c5eb8642135ab1f4514c/raw/a5a11c0fc301a6724b9af4c413d76b96ffa9859c/combined.txt EDIT: All the @ symbol lines should be in both. Then the first 28709 lines after the last '@' should be in the training file and the rest in the test file Thanks!
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47575040
answer count: 1
has comment: http://stackoverflow.com/comment/82106349
type: AnsweredQuestion

http://stackoverflow.com/a/47565589
has comment: http://stackoverflow.com/comment/82089247
answers question: http://stackoverflow.com/q/47565559
type: Answer
has body: You must convert your input to int: import time import random code = random.randint(100,1000) print('This is your secret code! PLEASE WRITE THIS DOWN!') print(code) tester = 1 while tester == 1: code1 = int(input('What is your name, phone number, and email?\n')) print('code', code1) if code == code1: print('Blah') time.sleep(5) tester = 2 else: print('fail') tester = 1
has comment: http://stackoverflow.com/comment/82089252
has comment: http://stackoverflow.com/comment/82089191
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82089209

http://stackoverflow.com/a/47632987
has body: Don't rely on the GC to clean/close the file descriptor. Use a context manager instead. You also don't need to provide the mode 'r' since it is the default for open. with open('data.json') as f: data = json.load(f)
type: Answer
upvote count: 14
has comment: http://stackoverflow.com/comment/82224068
downvote count: 0
score: 14
has comment: http://stackoverflow.com/comment/82224051
answers question: http://stackoverflow.com/q/47632855

http://stackoverflow.com/q/47675696
tagged with: encoding
has answer: http://stackoverflow.com/a/47864942
type: UnansweredQuestion
has title: Extract exactly Public key as "Decimal" in PEM format in python
tagged with: python
tagged with: pem
tagged with: openssl
downvote count: 0
tagged with: public-key
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: I am trying to reach exact point of in PEM public key's decimal format. Not in Pem. First of all i get my PEM certificate with using from socket import socket import ssl from OpenSSL import SSL import string import traceback import json import re for i in file_content: final_list.append(i.strip()) file = open("SSL_out_put.json","w") Temp_Priv_Key_list = [] counter = 1 for i in final_list[:4047]: print counter print i counter = counter + 1 try: x = ssl.get_server_certificate((i, 443)) Temp_Priv_Key_list.append({ 'counter' : counter, 'i' : i, 'x' : x }) content = json.dumps(Temp_Priv_Key_list, indent=3) file.write(content) Temp_Priv_Key_list=[] except Exception , err: pass print Exception , err file.close() after that i used "from pyasn1_modules import pem, rfc2459" to extract the publick key. This will give binary representation for the public key. after converting decimal i reilze that this is not i want to use. Note that in my experiance pyasc1 is not working correctly. After lots of research i found this code in here to extract public key BUT still in PEM format. from cryptography import x509 from cryptography.hazmat.backends import default_backend with open("cert.pem", "rb") as f: cert = f.read() cert = str(cert) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) key_data = (OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM,x509.get_pubkey())) print key_data Now i have my Publick key as Pem format still. After some other research i found this but only giving this output. Still Can t extract the publick key nither decimal nor binary format. from Crypto.PublicKey import RSA from base64 import b64decode from Crypto.Util import asn1 with open("public_key.pem", "rb") as f: cert = f.read() #print cert keyDER = b64decode(cert) keyPub = RSA.importKey(keyDER) print keyPub} this code will give you the out put of &lt;_RSAobj @0x7f65559da320 n(2048),e> This is my first question. Sorry if i don t asking proper. My brain is full of all kind of st…

http://stackoverflow.com/q/47679599
tagged with: qwebengineview
tagged with: pyqt5
has title: Cannot load HTML file with QWebEngineView.setHtml()
score: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: qt
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47679945
has body: The solution of my problem is probably very simple but yet out of my understanding. I am trying to load an HTML file into a QWebEngineView with PyQt5. The way I am doing it is: self.webView = QtWebEngineWidgets.QWebEngineView(self.splitter) html = r"C:\DATI\git\webgis\map.html" self.webView.setHtml(html) The only thing I get is a string representing the path and name of my HTML file: C:\DATI\git\webgis\map.html My map.html looks like this: Simple Map Strangely (to me at least), if I do self.webView.setHtml(" ciao "), this will render the HTML properly. What am I missing?
has answer: http://stackoverflow.com/a/47679945
upvote count: 2
tagged with: pyqt
type: AnsweredQuestion

http://stackoverflow.com/comment/82136432
comment on: http://stackoverflow.com/a/47589536
score: 1
type: Comment
type: AnswerComment
has text: Uh.. that makes sense. I'd rather not overwrite the file if possible and keep an ever growing list of data. Is that possible? Hmm

http://stackoverflow.com/comment/82184425
type: AnswerComment
score: 1
has text: Note that this will also remove apostrophes and hyphens inside words, which the OP may not want.
type: Comment
comment on: http://stackoverflow.com/a/47613039

http://stackoverflow.com/comment/82125142
type: QuestionComment
has text: Updated Title as requested in comments
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47582344

http://stackoverflow.com/q/47659249
has answer: http://stackoverflow.com/a/47780264
tagged with: bearing
tagged with: python
has title: Calculate cardinal direction from GPS coordinates in Python
tagged with: gps
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47659648
has answer: http://stackoverflow.com/a/66715348
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47659648
tagged with: coordinates
favorite count: 0
has body: How can I calculate the cardinal direction of a second point of geo coordinates in Python? I need to know distance and direction of two different locations. Example : work : coord 41.4107628,2.1745004 home : coord 41.4126728,2.1704725 from geopy.distance import vincenty work = geopy.Point(41.4107628,2.1745004) home = geopy.Point(41.4126728,2.1704725) print(vincenty(home, work)) 0.398011015257 km I'd like to know in which directions the second point lies, ( ex.: North, North-West, etc) respect to the first one... Many thanks in advance
tagged with: directions
possible better answer: http://stackoverflow.com/a/47780264
type: Question
upvote count: 2

http://stackoverflow.com/a/51709530
accepted answer of: http://stackoverflow.com/q/47599575
score: 0
type: Answer
has body: RegexParser only results in non-overlapping chunks. I reached the following solution using NLTK's bigrams. First, I modified the grammar to match any 2 or more consecutive nouns. Then I create bigrams from the result. The code: import nltk grammar = "CONSEC_NOUNS: {&lt;NN&gt;{2,}}" # match 2 or more nouns cp = nltk.RegexpParser(grammar) result = cp.parse([('APPLE', 'NN'), ('BANANA', 'NN'), ('GRAPE', 'NN'), ('PEAR', 'NN'), ('GO', 'VB'), ('ORANGE', 'NN'), ('STRAWBERRY', 'NN'), ('MELON', 'NN')]) leaves = [chunk.leaves() for chunk in result if ((type(chunk) == nltk.tree.Tree) and chunk.label()=='CONSEC_NOUNS')] noun_bigram_groups = [list(nltk.bigrams([w for w, t in leaf])) for leaf in leaves] extract = [' '.join(nouns) for group in noun_bigram_groups for nouns in group] print(extract) The output is: ['APPLE BANANA', 'BANANA GRAPE', 'GRAPE PEAR', 'ORANGE STRAWBERRY', 'STRAWBERRY MELON']
answers question: http://stackoverflow.com/q/47599575
type: AcceptedAnswer

http://stackoverflow.com/q/47660136
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47660237
answer count: 2
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/82279233
downvote count: 2
has body: We are acquiring data from an Arduino strain gauge through the serial port of the Raspberry Pi and Python. We have it so it will read all the data do the necessary calculations and it will print to a text file however if there is a power failure the data gathered is lost. This is what we are trying to figure out how to fix or not have happen. import serial ardserial = serial.Serial('/dev/ttyACM0',9600) counter = 1 def strain(): a=int(adserial.readlines()) b=(str(a*(5/16)/166)) c=float(b) with open('textfile1.txt','a+') as text_file: text_file.write('Strain Value: ' + str(c) + '\n') while counter &gt; 0: strain() We have it so it will write to the txt file correctly and it will save all the data if we kill the program but we also expected it to save all the data if the power was pulled to the Raspberry Pi. It does not do this. I was almost 100% sure that I have done it in the past where if the power was killed it would have the saved data but I can't for the life of me figure it out. Any help would be... well... helpful thanks.
tagged with: python
accepted answer: http://stackoverflow.com/a/47660237
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82279135
has title: Saving python file in event of power failure
has answer: http://stackoverflow.com/a/77643865
possible better answer: http://stackoverflow.com/a/77643865
has comment: http://stackoverflow.com/comment/82284257

http://stackoverflow.com/comment/82094893
type: Comment
has text: Thank you Warren! This actually worked together with specifying usecols[0,1,2]. And yes, it is on a Windows PC
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47561983

http://stackoverflow.com/q/47636448
has comment: http://stackoverflow.com/comment/82231527
tagged with: python
has comment: http://stackoverflow.com/comment/82233000
score: 0
answer count: 0
tagged with: subprocess
has title: Executing offlineimap through a python script on Windows (through cygwin terminal)
tagged with: shell
has comment: http://stackoverflow.com/comment/82231142
type: Question
has body: I am currently working on a python script to automatically parse a large amount of emails created by a registration form. Due to constraints outside my control, the way I chose to do this is to mirror all mails through offlineimap, run a script that processes all mails and files the relevant info into the right places and then run offlineimap again to move all processed mail into a different folders. Being on Windows(7), I run offlineimap through the Cygwin Terminal. In order to allow not-so-tech-versed colleagues use my script, I wanted to include both runs of offlineimap into the script using: import subprocess subprocess.run("offlineimap", shell=True, timeout=20) I get as a result: CompletedProcess(args='offlineimap', returncode=1) Sadly I'm rather new to Python and the subprocess.run command appears to be so new that google didn't yield too many examples. But the problem appears to be that offlineimap is run in the Windows command shell and it fails. So the solutions to my problem would be either: a) utilize the cygwin terminal through python b) run offlineimap through the windows command shell Sadly the documentation of offlineimap only mentions Windows in passing and the tool seems to be written to be run on linux machines. So I'm not holding my breath for option b) but any advise would be appreciated.
has comment: http://stackoverflow.com/comment/82231310
type: UnansweredQuestion
tagged with: cygwin

http://stackoverflow.com/a/47674939
score: 2
has body: From Numpy 11, It's not compatible with the new default behaviour : (boolean-indexing-changes) : Boolean indexing changes. ... ... Boolean indexes must match the dimension of the axis that they index. ... Internals have been optimized, the docs not yet ....
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47669683
answers question: http://stackoverflow.com/q/47669683
type: Answer
upvote count: 2

http://stackoverflow.com/comment/82254998
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160484/discussion-between-jezrael-and-jytinjalmon).
comment on: http://stackoverflow.com/q/47647649
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47628172
tagged with: python
linked to: http://stackoverflow.com/q/588004
tagged with: floating-point
possible better answer: http://stackoverflow.com/a/47628207
linked to: http://stackoverflow.com/q/12439753
has title: Python hyper parameter for rounding float numbers
tagged with: precision
type: Question
has answer: http://stackoverflow.com/a/47628207
upvote count: 2
has body: This question must be an easy one but I couldn't find anything about it here. Is there a way in python to define or use 1 command line so that every float number across the script will be rounded by X digists. For example if I define: max_float_digits = 4 and the program wants to outputs or print the following number 5.1355895682, all I will see is 5.1356 This necessity rises when some module return this value to my script: [('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664), ('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618), ('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347), ('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996), ('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993), ('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472), ('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117)] Instead of trying to access each value and round them I'd like a 1 command line that will round them all for me.
downvote count: 0
has comment: http://stackoverflow.com/comment/82213910
has comment: http://stackoverflow.com/comment/82214026
favorite count: 0
has comment: http://stackoverflow.com/comment/82214049
has answer: http://stackoverflow.com/a/47628370
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82215498
answer count: 3
accepted answer: http://stackoverflow.com/a/47628984
has answer: http://stackoverflow.com/a/47628984

http://stackoverflow.com/q/47557116
favorite count: 0
type: Question
has body: Really basic question pyspark/hive question: How do I append to an existing table? My attempt is below from pyspark import SparkContext, SparkConf from pyspark.sql import HiveContext conf_init = SparkConf().setAppName('pyspark2') sc = SparkContext(conf = conf_init) hive_cxt = HiveContext(sc) import pandas as pd df = pd.DataFrame({'a':[0,0], 'b':[0,0]}) sdf = hive_cxt.createDataFrame(df) sdf.write.mode('overwrite').saveAsTable('database.table') #this line works df = pd.DataFrame({'a':[1,1,1], 'b':[2,2,2]}) sdf = hive_cxt.createDataFrame(df) sdf.write.mode('append').saveAsTable('database.table') #this line does not work #sdf.write.insertInto('database.table',overwrite = False) #this line does not work Thanks! Sam
has answer: http://stackoverflow.com/a/61880221
accepted answer: http://stackoverflow.com/a/47577619
has title: PySpark/HIVE: append to an existing table
has comment: http://stackoverflow.com/comment/115976720
has comment: http://stackoverflow.com/comment/82071932
downvote count: 0
tagged with: pyspark
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/82074290
upvote count: 6
has comment: http://stackoverflow.com/comment/82075551
possible better answer: http://stackoverflow.com/a/61880221
tagged with: hive
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82072315
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/82079676
has answer: http://stackoverflow.com/a/47577619

http://stackoverflow.com/comment/82079556
type: Comment
comment on: http://stackoverflow.com/a/47559957
has text: @JustinBeland If this is the issue and the `crypto` package is installed, you will have to uninstall `crypto` and `pycrypto` (if still installed incorrectly) and then reinstall `pycrypto`. If `pycrypto` is installed while `crypto` is around, the `pycrypto`'s installation will end up in `crypto`'s `crypto` directory instead of the correct-case `Crypto`.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47618569
duplicate of: http://stackoverflow.com/q/8136788
tagged with: utf-8
tagged with: latin
type: Question
linked to: http://stackoverflow.com/q/8136788
answer count: 0
has comment: http://stackoverflow.com/comment/82195612
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82195556
tagged with: python
has comment: http://stackoverflow.com/comment/82195311
score: 0
tagged with: pandas
has body: I am writing a script which parses an apache log file into a pandas table. Now I recognized that in the log file the text is sometimes like this / with utf8 values in it: Bern,%20Bahnhof For example one log file text line: IP - - timestamp "GET /v1/connections?from=Bern,%20Bahnhof&amp;to=Luzern HTTP/1.1" httpstatus bytes -" My current code to open the log files: cols = ['ip','l','userid','timestamp','tz','fullrequest','status','bytes','referer','useragent'] df = pd.read_csv(path + file, delim_whitespace=True, names=cols, error_bad_lines=False, encoding='utf8').drop('l', 1) df = df.drop('userid', 1) Is there a way to parse the log files into pandas, so that these strange chars are converted into latin chars? So that in the end we have somthing like this: Bern, Bahnhof
has title: How to read text file into pandas and convert utf8 chars to string / latin?

http://stackoverflow.com/comment/82332575
has text: @chappie, I can't say why your platform stops moving while the player is jumping as I've not seen the code. Maybe `ontimer()` is still an option.
type: Comment
comment on: http://stackoverflow.com/a/47682726
score: 0
type: AnswerComment

http://stackoverflow.com/q/47562280
upvote count: 0
accepted answer: http://stackoverflow.com/a/47562364
downvote count: 2
has comment: http://stackoverflow.com/comment/82082472
has title: cleaning list in python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47562320
score: -2
has answer: http://stackoverflow.com/a/47562326
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47562320
has body: I have several list they have 2 values - one or more words and score, [(deployment appears', 4.0), ('times bigger', 4.0), ('data forced', 4.0), ('washington media', 4.0), ('barely understood', 4.0), ('american public', 4.0), ('country', 4.0), ('house', 4.0)] How can I create a list that has only words - for example, [('deployment appears'), ('times bigger'), ('data forced'), ('washington media'), ('barely understood'), ('american public'), ('accurate accounting'), ('white house')]
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/47562364

http://stackoverflow.com/q/47621187
possible better answer: http://stackoverflow.com/a/47621611
favorite count: 0
type: Question
answer count: 2
has title: pandas - aggregating on contents of dataframe
accepted answer: http://stackoverflow.com/a/47621240
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47621240
has answer: http://stackoverflow.com/a/47621611
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: I have a pandas dataframe which looks like this: Lane PropA PropB PropC Sample NameA R1 PASS FAIL WARN NameB R2 FAIL FAIL PASS NameC R1 WARN PASS PASS NameD R2 PASS PASS WARN I have as a goal to produce a bar plot that for each Prop shows how many of the Samples have PASS, WARN or FAIL as a value. Thus I need to get out a dataframe where the contents are like this instead: PASS WARN FAIL Prop PropA 3 2 1 PropB 2 5 3 PropC 2 5 1 How to I get from the dataframe above to the one below? Thanks!

http://stackoverflow.com/comment/82288999
type: Comment
type: QuestionComment
has text: Cool, I'll make the comment an answer then.
comment on: http://stackoverflow.com/q/47637584
score: 0

http://stackoverflow.com/q/47626770
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/47626802
tagged with: list
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47626807
answer count: 3
accepted answer: http://stackoverflow.com/a/47626802
possible better answer: http://stackoverflow.com/a/47626778
has title: Sorting Python list with exception
has answer: http://stackoverflow.com/a/47626778
type: Question
has body: How can I sort a python list alphabetically, taking into consideration the numbering at the back of the list items. See example below and code used to sort. Note that it is not possible to insert a zero into the code if the number is below 10. original list: ['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7', 'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9', 'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14', 'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10', 'drawing-n-17'] Sorted list: ['drawing-n-1', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9'] Desired List output: ['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17'] Code: dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")] print dwg_number_keys print sorted(dwg_number_keys, key=str.lower)

http://stackoverflow.com/q/47693771
favorite count: 0
has body: I have dataframe 0 1 2 12 34 23 10 12 0 Desire output upd_string 12, 34, 23 10, 12, 0 I try df_upd = pd.DataFrame() df_upd['upd_string'] = df[df.columns.values.tolist()].apply(str) But it returns ValueError: no results
type: Question
type: AnsweredQuestion
has title: Pandas: convert all columns in dataframe to string
tagged with: pandas
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47693797
has answer: http://stackoverflow.com/a/47693797
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/113217315
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47562412
has text: There is an error in the exampe: when calling Fitter.__init__ it expects a parameter
type: AnswerComment

http://stackoverflow.com/comment/82099162
has text: The exec function is powerful, but it is a big security risk. I would not recommend using it as a beginner.
type: AnswerComment
comment on: http://stackoverflow.com/a/47570806
score: 0
type: Comment

http://stackoverflow.com/q/47637241
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82235155
answer count: 0
type: UnansweredQuestion
has title: Use tensor flow predictions and convert that to image
tagged with: python
has body: I'm using tensorflow to run some inferences on a trained model. Now, I get the result back from my tensorflow, def load_graph(): ''' This method loads the graph ''' print 'load graphs' pb_graphs = ['/Users/pm/Downloads/frozen_graph.pb'] graphs = [] for each in pb_graphs: with tf.gfile.GFile(each, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def( graph_def, input_map=None, return_elements=None, name="" ) graphs.append(graph) oos_graph = graphs[0] print 'graph loaded' return oos_graph def run_inference(graph): sess = tf.Session(graph=graph, config=tf.ConfigProto(log_device_placement=False)) # (1892, 11776),(1892, 12288),(1892, 12800),(1892, 13312),(1892, 9728)]: for each in [(1892, 11264)]: y,x = each print y,x y1 = y + 1024 x1 = x + 1024 pano_images = pano_img[y:y+1024,x:x+1024] x_batch = pano_images.astype('float32') pred_boxes = graph.get_tensor_by_name("decoder/cat:0") pred_confs = graph.get_tensor_by_name("decoder/shape:0") x = graph.get_tensor_by_name("x_in:0") feed_dict_testing = {x: x_batch} t1 = datetime.now() np_pred_confs, np_pred_boxes = sess.run([pred_confs, pred_boxes], feed_dict=feed_dict_testing) t2 = datetime.now() delta = t2 - t1 print 'time taken in seconds == ', delta.total_seconds() print 'np_pred_boxes ==', np_pred_boxes.shape print 'np_pred_confs ==', np_pred_confs.shape print 'np_pred_boxes ==', type(np_pred_boxes.shape) print 'np_pred_confs ==', type(np_pred_confs.shape) with sess.as_default(): img = Image.fromarray(pred_boxes.eval()) img.save('/Users/pm/Downloads/tf_image.png') I want take the pred_boxes and generate a image and see what tensorflow has predicted. Using the below code to convert the tensorflow prediction to image ie; convert it to numpy array and generate a image. but it does not work. Read that I can use a eval() function to convert the tensor to numpy array. tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value f…
score: 0
has comment: http://stackoverflow.com/comment/82233134
has comment: http://stackoverflow.com/comment/82237131
tagged with: tensorflow

http://stackoverflow.com/comment/82374664
comment on: http://stackoverflow.com/q/47657406
type: Comment
type: QuestionComment
has text: @SwatiSingh What does `type(category)` return before you convert it into list?
score: 0

http://stackoverflow.com/a/47658644
has body: I just figure it out that normalization = weighted_spread.sum() should be normalization = W.sum() . Mathematical problem.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47658095

http://stackoverflow.com/a/54667233
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/47668000
has body: I think that the best way for you to get started is to download PyLucene's tarball (version of you choice): https://www.apache.org/dist/lucene/pylucene/ Inside you will find a test3/ folder (for python3, else test2/ for python2) with python tests. These cover common operations such as indexing, reading, searching and much more. I found these to be extremely helpful, given the terrible lack of documentation around Pylucene. Checkout the test_Pylucene.py in particular. Note This is also a very good way to quickly grasp the changes and adapt your code across releases if the Changelog is not intuitive enough for you. (Why I'm not providing code in this answer: The problem with providing code snippets on SO's answers for PyLucene is that these quickly become obsolete as soon as a new version is released, as we can see on most of the already existing ones.)
type: Answer

http://stackoverflow.com/comment/82215037
has text: Thank you for that response.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47596752
score: 0

http://stackoverflow.com/comment/82229742
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47635949
has text: You initialize `stocks` only once.
type: Comment

http://stackoverflow.com/a/47600236
answers question: http://stackoverflow.com/q/47598556
has body: You have almost the same problem as in the post you linked, but instead of simply removing the secondary join from the primary and letting SQLAlchemy figure it out you need to define the secondary instead of the primary – and let SQLA figure the primary out for you: tags = db.relationship( "Tag", secondaryjoin="and_(Tag.id == PostToTags.tag_id, Tag.type == 'post')", secondary='post_to_tags', )
accepted answer of: http://stackoverflow.com/q/47598556
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/75481910
score: 3
upvote count: 3
downvote count: 0
type: Answer
has body: Try this def my_function(**kwargs): for key, value in kwargs.items(): locals()[key] = value print(f"Local variable 'name' is {name}") print(f"Local variable 'age' is {age}") my_function(name="John", age=30)
answers question: http://stackoverflow.com/q/47552107

http://stackoverflow.com/q/47584642
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47585387
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/47585387
has comment: http://stackoverflow.com/comment/82131450
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
has title: How to combine two differently multi-indexed pandas dataframes by multiplying column by column
has body: I have two dataframes that I'm trying to combine. They each have a multi-index, but those indices have no overlapping levels. The dfs are each the same width. df1 v1 v2 v3 v4 v5 location year A 1990 1 3 2 1 4 2000 2 5 0 3 1 B 1990 6 2 1 2 1 2000 3 4 5 0 0 df2 v1 v2 v3 v4 v5 age sex 5 M 0 0 1 0 1 F 1 0 1 1 1 10 M 1 0 0 0 0 F 0 1 1 0 0 I want to make a new dataframe that has entries for every combination of the two indices, with values equal to the product of the values in corresponding columns: result v1 v2 v3 v4 v5 location year age sex A 1990 5 M 0 0 2 0 4 F 1 0 2 1 4 10 M 1 0 0 0 0 F 0 3 2 0 0 2000 5 M 0 0 0 0 1 F 2 0 0 3 1 10 M 2 0 0 0 0 F 0 5 0 0 0 B 1990 5 M 0 0 1 0 1 . . . . etc I think I could join the dfs and then multiply column by column, but I'm wondering if there's a way to do it more automatically, since pandas built in multiplication is so much faster. Thanks!

http://stackoverflow.com/q/47622775
tagged with: callable-object
has comment: http://stackoverflow.com/comment/82203412
favorite count: 0
has comment: http://stackoverflow.com/comment/82244677
has title: Error str not callable
duplicate of: http://stackoverflow.com/q/6039605
score: 1
has comment: http://stackoverflow.com/comment/82203736
has comment: http://stackoverflow.com/comment/82203617
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82203631
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82203923
downvote count: 0
upvote count: 1
has body: Here is a sample of code (python 3.6): n = 2 x = 2**n Q = str(x) print(q) This yields an error "str object is not callable". But I didn't understand why? I am working with much larger numbers (integers), and I need to convert them to a string before I can work with them. How can I do that?
tagged with: python
linked to: http://stackoverflow.com/q/6039605
tagged with: string

http://stackoverflow.com/q/47663745
has title: How to access and print dictionary values that contain nested lists?
has answer: http://stackoverflow.com/a/47664029
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82286914
possible better answer: http://stackoverflow.com/a/47664044
has answer: http://stackoverflow.com/a/47664213
has answer: http://stackoverflow.com/a/47664044
type: AnsweredQuestion
answer count: 3
has body: I'm learning Python and am a bit stuck with the concept of dictionaries and nested lists. The lab I'm currently working on calls for us to create a dict with some keys having just a single list of values and other keys having two or more lists associated. The code below properly prints the list elements for the key that has multiple lists, but if I change the get statement to a key with a single list I just get the first two digits of the string. my_dict = {1: ['test', 'values'], 2: [['test2', 'value2'], ['test3', 'value3']], 3: ['test4', 'value4']} for item in my_dict.get(2): print('%s, %s' %(item[0], item[1])) Would someone explain how to access list values from the dictionary regardless of whether the key has a single list, or multiple lists? Ultimately the output if key 1 or 3 is used would be test, values or test4, value4 If key 2 is selected the output would be test2, value2 test3, value3
downvote count: 3
has comment: http://stackoverflow.com/comment/82287126
has comment: http://stackoverflow.com/comment/82286956
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82286879
accepted answer: http://stackoverflow.com/a/47664029
upvote count: 2

http://stackoverflow.com/comment/82269656
has text: or maybe an example of your textfile format
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47655752
score: 0

http://stackoverflow.com/comment/82198224
type: AnswerComment
has text: @StefanPochmann True about the docs link, changed that. Even though little about `dict.pop` has changed from 2 to 3 :)
score: 0
comment on: http://stackoverflow.com/a/47619258
type: Comment

http://stackoverflow.com/a/47672680
type: Answer
has body: This is probably what you want: dict={"Data": ["john", "vincin","tenzin"]} dictlist=[] for key, value in dict.items(): dictlist.extend(value) print(dictlist[0]) Note 1: don't use keyword dict as variable name Note 2: this is even more concise: dictlist = sum(dict.values(),[])
downvote count: 0
answers question: http://stackoverflow.com/q/47672616
score: 1
upvote count: 1

http://stackoverflow.com/a/47644139
answers question: http://stackoverflow.com/q/47644077
type: Answer
score: 0
has body: U already made it just add a line break outside both loops and your good to go: l = [[2,3],[5,6],[4,8]] for item in l: print(item[0], end = ' ') print('\n') #take note this needs to be outside both loops for obj in l: print(obj[1], end = ' ') However if you just want it to be on the next line immediately, l = [[2,3],[5,6],[4,8]] for item in l: print(item[0], end = ' ') print() #take note this needs to be outside both loops for obj in l: print(obj[1], end = ' ')

http://stackoverflow.com/q/47585318
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47594740
accepted answer: http://stackoverflow.com/a/47594740
favorite count: 0
type: AnsweredQuestion
tagged with: pyside
tagged with: python
has body: My tool loops through a few thousand images and loads thumbnails of the images into my listview as seen below. However my application freezes until all the images are processed. I was wondering if there was a way i could populate the listview with images as they have been loaded, preventing the UI from freezing and letting the user go about using the application while the images are populated? This is all done us python and pyside. Code: import os import sys from PySide import QtGui, QtCore class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() self.resize(800, 400) self.setWindowTitle('Image Viewer') self.image_dir = "C:/Users/JokerMartini-Asus/Desktop/textures/thumbs" self.ui_image_viewer = QtGui.QListView() self.ui_image_viewer.setViewMode(QtGui.QListView.IconMode) self.ui_image_viewer.setResizeMode(QtGui.QListView.Adjust) self.ui_image_viewer.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_image_viewer.setIconSize(QtCore.QSize(300,300)) self.ui_image_viewer.setMovement(QtGui.QListView.Static) self.ui_image_viewer.setModel(QtGui.QStandardItemModel()) for img in os.listdir(self.image_dir): img_path = os.path.join(self.image_dir, img) pixmap = QtGui.QPixmap(img_path) name = os.path.splitext(os.path.basename(img_path))[0] item = QtGui.QStandardItem(QtGui.QIcon(pixmap), name) self.ui_image_viewer.model().appendRow(item) # Layout grid = QtGui.QVBoxLayout() grid.setContentsMargins(10,10,10,10) grid.addWidget(self.ui_image_viewer) main_widget = QtGui.QWidget() main_widget.setLayout(grid) self.setCentralWidget(main_widget) self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
has title: Populate QListview with large data set in the background
type: Question
score: 2

http://stackoverflow.com/comment/82189868
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47615323
has text: @guillermochamorro it doesn't raise error, everything is ok, no warm
score: 0

http://stackoverflow.com/comment/82068327
has text: @ElisByberi 1 hour
comment on: http://stackoverflow.com/q/47555670
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47559644
has title: Getting a Name Error message in python
tagged with: python
score: -1
has body: I have scipy imported in anaconda and i called: from scipy import misc and called: data = misc.imread(/Users/Desktop...) to call the image from you desktop but i am getting the error message: NameError: name 'misc' is not defined
has comment: http://stackoverflow.com/comment/82077110
type: Question
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47559711
answer count: 1
downvote count: 1
tagged with: scipy
favorite count: 0
tagged with: anaconda

http://stackoverflow.com/comment/89004258
score: 0
has text: Did you find a solution for this?
comment on: http://stackoverflow.com/q/47556847
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47684386
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47684053
has body: Here is an example applied with your data from Select data frame by dict passing in parameters or comprehension list python pandas import pandas as pd df = pd.DataFrame(dict(value=[100,200],direction=['&gt;','&lt;'])) my_filter = {"value":100, "direction": "&gt;"} # Apply mask = (df[list(my_filter)] == pd.Series(my_filter)).all(axis=1) df[mask]
type: Answer

http://stackoverflow.com/comment/130037356
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47577259
has text: `df.loc[df.A == 7, 'B'].iloc[0]` <- select the value. I figured the result wasn't necessarily a single integer value. ^^
type: Comment

http://stackoverflow.com/q/47586186
has comment: http://stackoverflow.com/comment/82130365
has body: I'm trying to change the dataframe printout so that it starts numbering the first dataframe entry at 40 instead of 0. import pandas as pd import numpy as np import glob import datetime as dt import math principle = 50000 # Amount initially invested rate_of_return = .076 # Return on investment or the interest rate years = 26 # Assuming starting at age 40 and end at age 65 roi_list = [] for i in range(years): roi_list.append(principle) principle = principle*(math.exp(rate_of_return)) df = pd.DataFrame(roi_list) # Creates a dataframe containing the roi_list values print(df)
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47586255
has comment: http://stackoverflow.com/comment/82130313
has title: Python - Changing dataframe order values
has answer: http://stackoverflow.com/a/47586365
possible better answer: http://stackoverflow.com/a/47586322
type: Question
has answer: http://stackoverflow.com/a/47586322
has comment: http://stackoverflow.com/comment/82130255
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47586248
has answer: http://stackoverflow.com/a/47586248
answer count: 4

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

http://stackoverflow.com/a/47608113
answers question: http://stackoverflow.com/q/47608018
downvote count: 0
score: 6
type: Answer
upvote count: 6
has body: Tesseract will search in /usr/share/tessdata first. If you want tesseract to search somewhere else, you can do one of the following set the environment variable TESSDATA_PREFIX to the path where you put your data. call tesseract with --tessdata-dir=&lt;pathToYourData&gt;

http://stackoverflow.com/q/47567399
has title: Retrieving selected cells on a given grid using Python
score: -2
has body: I have a grid on which user clicks and selects a range A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 A4 B4 C4 D4 E4 F4 G4 H4 I4 J4 K4 L4 A5 B5 C5 D5 E5 F5 G5 H5 I5 J5 K5 L5 A6 B6 C6 D6 E6 F6 G6 H6 I6 J6 K6 L6 A7 B7 C7 D7 E7 F7 G7 H7 I7 J7 K7 L7 A8 B8 C8 D8 E8 F8 G8 H8 I8 J8 K8 L8 A9 B9 C9 D9 E9 F9 G9 H9 I9 J9 K9 L9 The user selection is always a rectangle or a square. For example, if the user select's a rectangle J8-L9, the the only data that is returned is J8:L9. In this case the user has selected six boxes in the grid viz J8,K8, L8, J9, K9 and L9. These are the six boxes that I want to retrieve as a result. On other instances, the user might just select A4:C4, which essentially has only one row, but has three cells. How could I retrieve all the cells that is within the range using Python?
answer count: 1
tagged with: python
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/47567585
accepted answer: http://stackoverflow.com/a/47567585
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82092463

http://stackoverflow.com/a/47610246
score: 0
has body: While urban's answer gives great context and general tips... ... to answer your precise question. You can simply add a date call to every call of your one-liner, e.g. op=os.system("date &amp;&amp; ps -raxxxo pid,%cpu,%mem,vsize,time,command | grep -E 'java|gui' ") or op=os.system("date +%s &amp;&amp; ps -raxxxo pid,%cpu,%mem,vsize,time,command | grep -E 'java|gui' ") for less readable, but more distinct output.
type: Answer
answers question: http://stackoverflow.com/q/47609685
has comment: http://stackoverflow.com/comment/82182082

http://stackoverflow.com/q/47696226
has answer: http://stackoverflow.com/a/47700734
downvote count: 0
has comment: http://stackoverflow.com/comment/82384973
has comment: http://stackoverflow.com/comment/82352236
has comment: http://stackoverflow.com/comment/82382733
has comment: http://stackoverflow.com/comment/82383318
favorite count: 0
has comment: http://stackoverflow.com/comment/82384421
has answer: http://stackoverflow.com/a/47712952
has body: I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function. So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now. #credit to Markus Deserno from MPI #https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf def eq_points(N_count, r): points = [] a = 4*np.pi*r**2/N_count d = np.sqrt(a) M_theta = int(np.pi/d) d_theta = np.pi/M_theta d_phi = a/d_theta for m in range(M_theta): theta = np.pi*(m+0.5)/M_theta M_phi = int(2*np.pi*np.sin(theta)/d_phi) for n in range(M_phi): phi = 2*np.pi*n/M_phi points.append(np.array([r*np.sin(theta)*np.cos(phi), r*np.sin(theta)*np.sin(phi), r*np.cos(theta)])) omega = 4*np.pi/N_count return np.array(points), omega #starting plotting sequence fig = plt.figure() ax = fig.add_subplot(111, projection='3d') points, omega = eq_points(400, 1.) ax.scatter(points[:,0], points[:,1], points[:,2]) ax.scatter(0., 0., 0., c="r") ax.set_xlabel(r'$x$ axis') ax.set_ylabel(r'$y$ axis') ax.set_zlabel(r'$Z$ axis') plt.savefig("./sphere.png", format="png", dpi=300) plt.clf() The result is a sphere shown in the following figure. The blue points mark the data from the points array, while the red point is the origin. I would like to get something like this taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot. So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live d…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82367755
has comment: http://stackoverflow.com/comment/82352394
upvote count: 5
has title: How can I plot the surface of a structure which is given by vectors in python?
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/47712952
linked to: http://stackoverflow.com/q/44025403
has comment: http://stackoverflow.com/comment/82352140
type: Question
has comment: http://stackoverflow.com/comment/82352058
has comment: http://stackoverflow.com/comment/82352471
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/47700734

http://stackoverflow.com/comment/82326755
score: 0
has text: now I'm really not sure that I understand you correctly. Can you provide this fragment of code?
type: Comment
comment on: http://stackoverflow.com/a/47682435
type: AnswerComment

http://stackoverflow.com/a/47583809
answers question: http://stackoverflow.com/q/47561327
has body: How about this answer? 1. How to retrieve expiration time In order to retrieve the expiration time of access token, you can use tokeninfo which is one of Google APIs. Endpoint : GET https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=### access token ### curl sample : curl -L https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=### access token ### You are not required to authorize to use this. Response : { "azp": "#####", "aud": "#####", "scope": "#####", "exp": "1234567890", "expires_in": "3600", "access_type": "offline" } You can retrieve the expiration time. exp means the expiration time of access token. expires_in means the remaining time of access token. 2. How to update the access token You can retrieve new access token using refresh token. The expiration time is reset. When you retrieve access token, you already have the refresh token. If you have it, you can use it. If you have no refresh token, you can see how to retrieve it at here. I remembered that I had answered about this before. References : tokeninfo In this document, the query is id_token. In the case of access token, please use access_token. refresh token If this was not useful for you, I'm sorry.
score: 0
type: Answer

http://stackoverflow.com/comment/82220890
comment on: http://stackoverflow.com/q/47631539
type: Comment
has text: have you checked that the line `file = filename` does run? I would suggest an initial value for file, assign it before the `for filename in possibleFiles:` loop, and check if it changed after the loop
score: 0
type: QuestionComment

http://stackoverflow.com/q/47608374
score: 0
has body: I have the following problem and can't seem to find an answer for it, even though I assume it's fairly straight forward... I am trying to pass a string in Python/flask from one function to another. Without flask this works and prints my text. [...] def sample(args): with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f: saved_args = cPickle.load(f) with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f: chars, vocab = cPickle.load(f) model = Model(saved_args, training=False) with tf.Session() as sess: tf.global_variables_initializer().run() saver = tf.train.Saver(tf.global_variables()) ckpt = tf.train.get_checkpoint_state(args.save_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) text = model.sample(sess, chars, vocab, args.n, args.prime, args.sample).encode('utf-8') printer(text) def printer(text): print(text) This works fine and prints my string. If I try to implement flask I get an Internal Servor Error on 127.0.0.1:5000/text def sample(args): with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f: saved_args = cPickle.load(f) with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f: chars, vocab = cPickle.load(f) model = Model(saved_args, training=False) with tf.Session() as sess: tf.global_variables_initializer().run() saver = tf.train.Saver(tf.global_variables()) ckpt = tf.train.get_checkpoint_state(args.save_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) text = model.sample(sess, chars, vocab, args.n, args.prime, args.sample).encode('utf-8') printer(text) @app.route('/text') def printer(text): return(text) If I just try to display some text without passing a string it works fine. I'm completely new to python and flask, I would greatly appreciate any help! here's the Traceback from the Terminal: [2017-12-02 15:47:06,244] ERROR in app: Exception on /text [GET] Traceback (most recent call last): File "/Users/marcel/tensorflow/lib…
has title: Passing string in flask
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: string
type: Question
has answer: http://stackoverflow.com/a/47608484
has comment: http://stackoverflow.com/comment/82175267
tagged with: python
tagged with: parameter-passing
tagged with: flask
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47608484

http://stackoverflow.com/comment/82257282
has text: If `high_ = low_ + 1`, the loop runs once. Do you really want the same result when they're equal?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47649453
score: 3

http://stackoverflow.com/a/47656321
accepted answer of: http://stackoverflow.com/q/47656152
score: 9
answers question: http://stackoverflow.com/q/47656152
type: AcceptedAnswer
downvote count: 0
upvote count: 9
has body: Virtual events need to be surrounded by &lt;&lt; and &gt;&gt;. Just replace 'MyEvent' by '&lt;&lt;MyEvent&gt;&gt;' and your custom event should work.
type: Answer

http://stackoverflow.com/q/47621886
has answer: http://stackoverflow.com/a/47688802
has body: I'm trying to slice into a DataFrame that has a MultiIndex composed of an IntervalIndex and a regular Index. Example code: from pandas import Interval as ntv df = pd.DataFrame.from_records([ {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1}, {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0} ], index=('ntv', 'id')) Looks like this: E var1 ntv id (0, 10] 1 1 0.1 (0, 12] 2 0 0.5 What I would like to do is to slice into the DataFrame at a specific value and return all rows that has an interval that contains the value. Ex: df.loc[4] should return (trivially) E var1 id 1 1 0.1 2 0 0.5 The problem is I keep getting a TypeError about the index, and the docs show a similar operation (but on a single-level index) that does produce what I'm looking for. TypeError: only integer scalar arrays can be converted to a scalar index I've tried many things, nothing seems to work normally. I could include the id column inside the dataframe, but I'd rather keep my index unique, and I would constantly be calling set_index('id'). I feel like either a) I'm missing something about MultiIndexes or b) there is a bug / ambiguity with using an IntervalIndex in a MultiIndex.
type: AnsweredQuestion
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/47721151
has answer: http://stackoverflow.com/a/47623003
favorite count: 0
has title: How can I properly use a Pandas Dataframe with a multiindex that includes Intervals?
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
answer count: 5
has answer: http://stackoverflow.com/a/47687223
possible better answer: http://stackoverflow.com/a/47688290
accepted answer: http://stackoverflow.com/a/47688802
upvote count: 6
has answer: http://stackoverflow.com/a/47688290

http://stackoverflow.com/a/53438427
downvote count: 0
answers question: http://stackoverflow.com/q/47646154
type: Answer
score: 2
upvote count: 2
has body: however the size of the pen stays the same no matter what value i enter And well it should as you are in fact working with two different turtles: t = turtle.Pen() turtle.bgcolor("black") turtle.pensize(800) ... t.forward(120) You are making the mistake of mixing the functional interface to turtle with the object-oriented interface to turtle. You created your own turtle t, but you changed the pen size of the default turtle. If you want to change your turtle's pen size, you do: t.pensize(800) This is a common error so I recommend that Python turtle programmers use this import: from turtle import Screen, Turtle It loads the object-oriented code but blocks out the functional interface. Once that's fixed, then you need to address the issue raised by @jasonharper in the comments that calling reset() undoes pensize() and really isn't needed at this point in the program. Your code rewritten accordingly: from turtle import Screen, Turtle, mainloop screen = Screen() screen.bgcolor('black') t = Turtle() t.pensize(8) t.color("green") t.penup() t.setx(-450) t.pendown() t.left(90) t.forward(120) t.penup() t.right(90) t.forward(90) t.right(90) t.pendown() t.forward(120) t.left(90) t.forward(20) mainloop() # screen.mainloop() for Python 3

http://stackoverflow.com/comment/82126713
type: AnswerComment
comment on: http://stackoverflow.com/a/47581564
type: Comment
has text: A dictionary would be much slower than a simple array.
score: 0

http://stackoverflow.com/comment/82972490
type: AnswerComment
comment on: http://stackoverflow.com/a/47947420
has text: thanks, but that doesn't seem to help the situation. i've updated the question with a better working example.
type: Comment
score: 0

http://stackoverflow.com/comment/82354017
comment on: http://stackoverflow.com/a/47682435
has text: and what is the result of `Path(get_target(project_settings.user_home, 'Desktop',project_settings.avidshare_folder)).exists()`? `False`, right?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47619755
score: 0
has body: i have a "simulated surgery" in python to program but dont know how. Here is my code: class Surgery: def __init__(self): self.waitingroom = [] self.office = [] def enter_surgery(self, p): self.waitingroom.append(p) def call_next_patient(self): self.office.append self.waitingroom.remove def in_treatment(self): if self.office == []: return None else: return self.office def treatment_done(self): self.office.remove As you can see i want to move the patient in "call_next_patient" from the waitingroom to the office, but with "self" it is not global. without self it tells me that waitingroom is not defindet. how can i manage it?
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82197500
favorite count: 0
type: Question
has title: "move" an object between lists in classes
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47619805
tagged with: python
has comment: http://stackoverflow.com/comment/82197864

http://stackoverflow.com/comment/82351496
type: Comment
type: QuestionComment
score: 0
has text: If you have the name of the data frame externally, you do `dic[df_name]`. No, you can't query the name of the data frame every time since its a value and requires a key to access it. This would be the same limitation that you'd run into with SuperMongo style dynamic variables, since you wouldn't be able to get the name without already having the name. The problem isn't the dictionary solution, it's your reliance on `name(df)` as the key to dictionary. Just make the key based on something other than the data frame.
comment on: http://stackoverflow.com/q/47675185

http://stackoverflow.com/q/47603880
score: -3
tagged with: python
tagged with: dictionary
has title: What's faster in this case: searching a list or dict?
has answer: http://stackoverflow.com/a/47603913
has comment: http://stackoverflow.com/comment/82166630
accepted answer: http://stackoverflow.com/a/47603913
has comment: http://stackoverflow.com/comment/82166705
type: AnsweredQuestion
upvote count: 0
answer count: 1
has body: Say I have a text, 50,000 words, and I want to check every word in the text to see if it's been encountered yet. Would it be faster to: a) double_checker = [] for word in text: if word not in double_checker: double_checker.append(word) [perform operations] b) double_checker = {'a':[], 'b':[], 'c':[], 'd':[], 'e':[], 'f':[], 'g':[], 'h':[], 'i':[], 'j':[], 'k':[], 'l':[], 'm':[], 'n':[], 'o':[], 'p':[], 'q':[], 'r':[], 's':[], 't':[], 'u':[], 'v':[], 'w':[], 'x':[], 'y':[], 'z':[]} for word in text: if word not in double_checker[word[0].lower()]: double_checker[word[0].lower()].append(word) [perform operations] I'll be testing this myself, but my code takes about an hour to run so I was wondering if there were a theoretical calculation. I know the list is O(N) and a dict works off a faster hash, but the dict method has to also search through lists roughly 1/26th the size (obviously there will be more 'e' entries than 'z') AND access the 0th element of every word twice. For what I'm doing it isn't feasible to pre-sort. Any thoughts are appreciated.
downvote count: 3
has comment: http://stackoverflow.com/comment/82169520
has comment: http://stackoverflow.com/comment/82166634
has comment: http://stackoverflow.com/comment/82166673
favorite count: 0
type: Question
tagged with: performance

http://stackoverflow.com/q/47628477
tagged with: sql-server
answer count: 2
has comment: http://stackoverflow.com/comment/82235429
tagged with: mod-wsgi
upvote count: 0
linked to: http://stackoverflow.com/q/47587961
linked to: http://stackoverflow.com/q/47573523
accepted answer: http://stackoverflow.com/a/47668833
tagged with: github
downvote count: 1
has answer: http://stackoverflow.com/a/47668833
favorite count: 0
has answer: http://stackoverflow.com/a/47661995
type: Question
has comment: http://stackoverflow.com/comment/82261557
linked to: http://stackoverflow.com/q/47571249
has body: Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser As I'm new to Python Web Programming I need to code by clicking submit button that should retrive all the tables in the person database to the Web Browser via localhost. What should be the server configuration to run with localhost: Apache HTTP Server (or) WSGI module (or) Any Other Module/Server (pls Specify) Check this below links that I have configured: By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server Importing pyodbc results as Internal server error in Apache HTTP Server What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database I had tried with Apache HTTP Server with one command import pyodbc results in 500 Internal Server Error. But rest of the things worked fine with POST as well as in Python Shell. I had coded this way. Kindly had anyone worked with Web Server via localhost let me know what should we need to add/modify with the below code index.html &lt;form action="/cgi-bin/hello_get.py" method="post"&gt; Click the submmit button to retrive all the tables &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; hello_get.py import pyodbc cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};" "Server=DESKTOP-C6RS3DO;" "Database=demo2016;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute('SELECT * FROM person') print("Content-Type: text/html") print("") print("&lt;html&gt;&lt;head&gt;") print("") print("&lt;/head&gt;&lt;body&gt;") for row in cursor: print('row = %r' % (row,)) print("Hello from Python.") print("&lt;/body&gt;&lt;/html&gt;") cursor.close() cnxn.close() Do I need any extra modules and code from the above code? error.log [cgi:error] [pid 9344:tid 1264] [client ::1:52332] AH01215: End of script output before headers: hello_get.py, referer: http://localhost/index.html Traceback (most recent call last):\r: C:/Apache24/htdocs/hello_get.py, r…
tagged with: python
possible better answer: http://stackoverflow.com/a/47661995
score: -1
tagged with: pyodbc
has title: Initialization Configuration issues to integrate pyodbc with MSSQL Server via Web Browser
linked to: http://stackoverflow.com/q/47670856
type: AnsweredQuestion

http://stackoverflow.com/comment/82334433
comment on: http://stackoverflow.com/a/47667680
score: 0
type: AnswerComment
has text: If you can add a small snippet of your dataframe that illustrates your point, I can probably find a way around the problem. I am afraid I am misunderstanding the problem at the moment.
type: Comment

http://stackoverflow.com/comment/82330901
has text: Maybe see if you can convert to CSV (see https://stackoverflow.com/questions/10538162/convert-ssms-rpt-output-file-to-txt-csv) and then use `pd.read_csv`...
comment on: http://stackoverflow.com/q/47685206
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47602514
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82186550
type: Question
has comment: http://stackoverflow.com/comment/82163853
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47602603
has comment: http://stackoverflow.com/comment/82163787
has comment: http://stackoverflow.com/comment/82163914
tagged with: python
tagged with: linear-algebra
tagged with: scipy
has title: Solving Least squares in numpy/scipy?
has comment: http://stackoverflow.com/comment/82163803
has body: Lucas Kanade Implementation I am trying to implement the Lucas Kanade algorithm for some project without using any library. I am following this guide from opencv. I am stuck in translating least square equation which is below. I am not sure below code is correct method to compute equation? My Code inv(X)*np.matrix(T) where X = T = If yes please acknowledge me. If not please provide show how to do it using numpy or scipy. I am not sure how to validate the correctness of least square. Otherwise I would not have asked this question
score: 2
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/47602603

http://stackoverflow.com/comment/82343216
comment on: http://stackoverflow.com/q/47692106
has text: dont use double quotes again, just this `with open(r'PressReader\{}-Page-{}.png'.format(name, page), 'wb') as f:`
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47617902
has answer: http://stackoverflow.com/a/47618244
linked to: http://stackoverflow.com/q/47479965
answer count: 1
tagged with: user-interface
has title: Python - Tkinter CheckButton Issue
type: Question
has body: This is a part of my GUI program that I'm having a problem with and hoping someone could help me. What I'm trying to do is, when you click the check button, it should show the price on the text widget but when I click the check button it gives me an error: File "E:\Phython\Theater.py", line 147, in update_text if self.matinee_price.get(): AttributeError: 'Checkbutton' object has no attribute 'get' def matinee_pricing(self): #Purchase Label self.theater_label = tkinter.Label(text='Purchase Theater Seats Here', font=('Verdana', 15, 'bold')) self.theater_label.grid(row=2, column=10) #Checkbutton self.matinee_price = BooleanVar() self.matinee_price = tkinter.Checkbutton(text = '101 \nthru \n105', font=('Verdana', 10), bg='light pink', height=5, width=10,\ variable = self.matinee_price, command = self.update_text) self.matinee_price.grid(row=5, column=9) self.result = tkinter.Text(width=10, height=1, wrap = WORD) self.result.grid(row=20, column=10) def update_text(self): price = '' if self.matinee_price.get(): price += '$50' self.result.delete(0.0, END) self.result.insert(0.0, price)
score: 0
has comment: http://stackoverflow.com/comment/82196427
tagged with: python
accepted answer: http://stackoverflow.com/a/47618244
type: AnsweredQuestion
tagged with: tkinter

http://stackoverflow.com/a/47555063
answers question: http://stackoverflow.com/q/47552735
score: 0
has body: You cannot add a widget to a text input because it is not a layout. You should add your text input to a layout then add your bubble to this layout. Try this: from kivy.app import App from kivy.uix.bubble import Bubble from kivy.uix.textinput import TextInput from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout Builder.load_string(''' &lt;NumericKeyboard&gt; size_hint: (None, None) size: (160, 120) pos_hint: {'center_x': .5, 'y': .6} BubbleButton: text: 'Cut' BubbleButton: text: 'Copy' BubbleButton: text: 'Paste' ''') class NumericKeyboard(Bubble): pass class CustomTextInputLayout(FloatLayout): def __init__(self, **kwargs): super(CustomTextInputLayout, self).__init__(**kwargs) self.add_widget(CustomTextInput(self)) class CustomTextInput(TextInput): def __init__(self, layout,**kwargs): super(CustomTextInput, self).__init__(**kwargs) self.layout = layout def on_focus(self, instance, value): self.bubb = NumericKeyboard() self.layout.add_widget(self.bubb) class MyTestApp(App): def build(self): return CustomTextInputLayout() if __name__ == '__main__': MyTestApp().run()
type: Answer

http://stackoverflow.com/q/47562040
has title: Matplotlib y-tick labels not showing
has comment: http://stackoverflow.com/comment/82084400
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82129064
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82152934
answer count: 1
has comment: http://stackoverflow.com/comment/82110981
has comment: http://stackoverflow.com/comment/82110828
has comment: http://stackoverflow.com/comment/82083846
favorite count: 0
type: Question
type: AnsweredQuestion
has body: For some reason the y-tick and y-tick labels aren't showing up on my plot. The variable data is a pandas dataframe: rfr_scatter = pd.DataFrame({'Actual':y_test, 'Model Predicted':rfr_predictions}) import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import matplotlib.animation as animation from matplotlib import style from matplotlib import pyplot as plt import numpy as np import pandas as pd import tkinter as tk from tkinter import * def ScatterPlotter(notebooktab, data, test, pred): f = Figure(figsize=(7,5), dpi=100) ax1 = f.add_subplot(111, title="Model Performance") for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] + ax1.get_xticklabels() + ax1.get_yticklabels()): item.set_fontsize(8) item.set_color('black') markersize = 0.8 alpha = 0.05 line = np.arange(min(test), min(test) + 35, 5) data.plot.scatter(x='Actual', y='Model Predicted', ax=ax1, s=markersize, alpha=alpha) ax1.set_xlim((min(test),max(test))) ax1.set_ylim((pred.min(),pred.max())) ax1.plot(line,line,clr_red,'--', label = "Perfect") canvas = FigureCanvasTkAgg(f, notebooktab) canvas.show() canvas.get_tk_widget().pack() And i get this: I have tried setting the yticks to visible, with no luck. I'm probably missing something simple... EDIT: removing ax1.set_ylim((pred.min(),pred.max())) gives me a couple marks on the graph, it almost looks like the label is over the text, or the text isn't finishing rendering.
has answer: http://stackoverflow.com/a/47715993
score: 1
accepted answer: http://stackoverflow.com/a/47715993
has comment: http://stackoverflow.com/comment/82090790
has comment: http://stackoverflow.com/comment/82082512
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/82083555

http://stackoverflow.com/q/47585421
score: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1265665
has comment: http://stackoverflow.com/comment/82128800
has comment: http://stackoverflow.com/comment/82128763
has answer: http://stackoverflow.com/a/47585507
has comment: http://stackoverflow.com/comment/82128736
has comment: http://stackoverflow.com/comment/82128692
has body: I tried: tokens = [t.strip() for t in re.split(r'((?:-?\d+)|[+\-*/()])', exp)] return [t for t in tokens if t != ''] But it gets the wrong result: Expected :[3, '+', -4, '*', 5] Actual :['3', '+', '-4', '*', '5']
tagged with: python
has comment: http://stackoverflow.com/comment/82128829
has title: Break a math expression up into a list of its parts, separating the numbers from the operators
linked to: http://stackoverflow.com/q/4289331
type: Question
has answer: http://stackoverflow.com/a/47585443
answer count: 2
has comment: http://stackoverflow.com/comment/82129426

http://stackoverflow.com/q/47633511
downvote count: 0
tagged with: pickle
has title: What does __flags__ in python type used for
tagged with: python
has body: I have been read pickle source code recently. The following code in copy_reg make me confused: _HEAPTYPE = 1&lt;&lt;9 def _reduce_ex(self, proto): assert proto &lt; 2 for base in self.__class__.__mro__: if hasattr(base, '__flags__') and not base.__flags__ &amp; _HEAPTYPE: break else: base = object # not really reachable if base is object: state = None So what does __flags__ using for? I found it is defined in type object: type.__flags__ = 2148423147 I was tried to search it in the official doc, but nothing was found. But interesting thing is that __class__.__flags__ &amp; _HEAPTYPE is always 0 when the __class__ is python internal type. And the result will be 1 when __class__ is a subclass of python internal type. Can anyone help me to solve this puzzle?
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47638020
has answer: http://stackoverflow.com/a/47638050
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47638020
accepted answer: http://stackoverflow.com/a/47638050
upvote count: 2
tagged with: cpython

http://stackoverflow.com/comment/82106983
has text: Try "Menu > Product > Clean"
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47572872
score: 0

http://stackoverflow.com/q/47682695
downvote count: 3
has comment: http://stackoverflow.com/comment/82324713
score: -3
accepted answer: http://stackoverflow.com/a/47682925
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82324699
has answer: http://stackoverflow.com/a/47682925
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/47682774
tagged with: python
has answer: http://stackoverflow.com/a/47682774
has comment: http://stackoverflow.com/comment/82324624
has title: Set python variables to operators?
has comment: http://stackoverflow.com/comment/82324741
has body: Python, Operators set to variables? I am making a calculator and I want the user to be able to enter words like add to +. Is there any way to set python variables to operands. e.g. operands = { "add": + } etc. Is there any way to do this without modules. But if not possible is there a module?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82324643
has comment: http://stackoverflow.com/comment/82324625
has comment: http://stackoverflow.com/comment/82324728
tagged with: math

http://stackoverflow.com/q/47545841
has comment: http://stackoverflow.com/comment/82048457
type: AnsweredQuestion
tagged with: terminal
linked to: http://stackoverflow.com/q/89228
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82048465
has comment: http://stackoverflow.com/comment/82050437
has comment: http://stackoverflow.com/comment/82048604
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82048588
has answer: http://stackoverflow.com/a/47545913
answer count: 2
tagged with: subprocess
upvote count: 0
accepted answer: http://stackoverflow.com/a/47545871
has answer: http://stackoverflow.com/a/47545871
has body: Here's a custom key binding I have in ST3: { "keys": ["super+shift+e"], "command": "open_dir", "args": {"dir": "$file_path", "file": "$file_name"} } I would like to edit/view the command functions referenced in this JSON key binding (e.g. open_dir, which opens Finder). I want to see the code behind open_dir to see how it works. The JSON file of this key binding is Default (OSX).sublime-keymap. I've done file searches in ~/Library/Application Support/Sublime Text 3/ as well as in Applications/Sublime Text/ for command names such as open_dir but I still can't find the code of the commands that the JSON script is referencing. Is there a way to find and view the commands that the JSON script is referencing? EDIT: Thanks and apologies to those who commented before I made this edit. I've changed the title and the question text pretty heavily to try to be clearer since the post got put on hold.
possible better answer: http://stackoverflow.com/a/47545913
downvote count: 1
has comment: http://stackoverflow.com/comment/82050115
has title: Edit/view the command functions referenced by the key binding JSON script in Sublime Text 3

http://stackoverflow.com/q/47674185
tagged with: python
has comment: http://stackoverflow.com/comment/82892979
upvote count: 11
favorite count: 0
type: Question
tagged with: jenkins
has comment: http://stackoverflow.com/comment/82605556
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82309815
has title: py.test: Show local variables in Jenkins
answer count: 1
downvote count: 0
tagged with: django
score: 11
has answer: http://stackoverflow.com/a/47711092
has comment: http://stackoverflow.com/comment/82310518
has comment: http://stackoverflow.com/comment/82310629
has comment: http://stackoverflow.com/comment/82882372
tagged with: sentry
has body: Up to now we call py.test via Jenkins. If a test fails, we see the usual stacktrace like this Traceback (most recent call last): File "/home/u/src/foo/bar/tests/test_x.py", line 36, in test_schema_migrations errors, out)) AssertionError: Unknown output: ["Migrations for 'blue':", ...] It would be really great, if I could see local variables like in the django debug page (See https://djangobook.com/wp-content/uploads/figure2_3a.png). .... But they should only be visible if I want to see them. I guess this means I need a different format than text. Maybe HTML? Is there a way to enable this? I never used the tool Sentry. But AFAIK this can display nice tracebacks with local variables.
tagged with: pytest
has comment: http://stackoverflow.com/comment/82881125
has comment: http://stackoverflow.com/comment/82307799
has comment: http://stackoverflow.com/comment/82881011
has comment: http://stackoverflow.com/comment/82311395

http://stackoverflow.com/comment/82350674
has text: Seems like javascript changes data source, you will have to extract data from json but looking at the amount of jsons in the source code it won't be easy.
comment on: http://stackoverflow.com/q/47686042
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82260468
comment on: http://stackoverflow.com/a/47595016
type: Comment
has text: @thangaraj1980 Please accept the answer if it works. That will help others with same issue.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82197600
has text: Since the `Label` class does work, doesn't that imply there's already an unique field in `Photo`? How can `Label` work while `Material` can't?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47616045
type: Comment

indexing
tags question: http://stackoverflow.com/q/47600468
tags question: http://stackoverflow.com/q/47572640
tag name: indexing
tags question: http://stackoverflow.com/q/47543572
tags question: http://stackoverflow.com/q/47587278
type: Tag
tags question: http://stackoverflow.com/q/47663635
tags question: http://stackoverflow.com/q/47669683
tags question: http://stackoverflow.com/q/47553404
tags question: http://stackoverflow.com/q/47639215
tags question: http://stackoverflow.com/q/47696706
tags question: http://stackoverflow.com/q/47579250
tags question: http://stackoverflow.com/q/47666687
tags question: http://stackoverflow.com/q/47601936
tags question: http://stackoverflow.com/q/47660726
tags question: http://stackoverflow.com/q/47695333
tags question: http://stackoverflow.com/q/47584961
tags question: http://stackoverflow.com/q/47642398
tags question: http://stackoverflow.com/q/47585362

http://stackoverflow.com/q/47588591
answer count: 2
has title: JPG encoding in python sent via socket to C# and decode
has comment: http://stackoverflow.com/comment/82134616
has body: I want to sent my processed image from python backend to C# frontend. So i encode it using JPG encoder and sent. When i receive it and decoding it using jpegdecoder in C#, it throw the exception. Where size of received bytes are equal to the bytes sent after encoding. Could anyone guide me how i decode this image and display it. code in Python Server Side encoding Image JPG while True: conn, addr = s.accept() print ('connected to : ' + addr[0] +" :"+ str(addr[1])) vidcap = cv2.VideoCapture(videoPath) total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) conn.setblocking(0) for mm in range(0,total_frames ,1): try: dataClient = str(conn.recv(4096).decode('UTF-8')) conn.send(str.encode(dataClient)) conn.close() kk=2 break except socket.error: ret,img= vidcap.read() image = cv2.resize(img, (640, 480)) ############################################# encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),100] result,enData=cv2.imencode('.jpg',image,encode_param) conn.send(enData) ############################################# Code in C# Client side decoding Image JPG const int PORT_NO = 6666; //const string SERVER_IP = "210.107.232.138"; // 210.107.232.138 127.0.0.1 string SERVER_IP = IpAddress.Text; client = new TcpClient(SERVER_IP, PORT_NO); nwStream = client.GetStream(); bytesToRead = new byte[client.ReceiveBufferSize]; bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize); ///////////////////////////////////// MemoryStream ms = new MemoryStream(bytesRead); JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); //line 129 BitmapSource bitmapSource = decoder.Frames[0]; ///////////////////////////////////// var src = new System.Windows.Media.Imaging.FormatConvertedBitmap(); src.BeginInit(); src.Source = bitmapSource; src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32; src.EndInit(); //copy to bitmap Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelF…
has comment: http://stackoverflow.com/comment/82134707
tagged with: stream
accepted answer: http://stackoverflow.com/a/47588835
tagged with: http://stackoverflow.com/tag/jpeg
has answer: http://stackoverflow.com/a/47588835
has comment: http://stackoverflow.com/comment/82134574
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/82134789
has comment: http://stackoverflow.com/comment/82134621
has comment: http://stackoverflow.com/comment/82134346
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/82134593
possible better answer: http://stackoverflow.com/a/47588833
has comment: http://stackoverflow.com/comment/82134530
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47588833

http://stackoverflow.com/q/47676721
tagged with: python
has title: Register an internal package on Pypi
type: AnsweredQuestion
score: 20
upvote count: 20
possible better answer: http://stackoverflow.com/a/47724121
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47724121
tagged with: pypi
has answer: http://stackoverflow.com/a/47723309
favorite count: 0
accepted answer: http://stackoverflow.com/a/47723309
type: Question
has body: I read somewhere that if you make an internal Python package for proprietary work, you should still register the name on PyPi to avoid potential future dependency issues. How do I do this without posting my code publicly? This package contains code to be used internally at my work. Should I make an empty python package using the name I want to reserve and upload that to PyPi? And then install my package at work using git instead of PyPi? Uploading an empty package seems like a silly thing to do that would just annoy other people. But I can't find a way to just register the name.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82408831
tagged with: package

http://stackoverflow.com/a/47678045
has body: The function is obsolete. it returns: True if the array is Fortran contiguous BUT not C contiguous. In [421]: np.isfortran(a1) Out[421]: False In [422]: a1.flags Out[422]: C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False Your array is fortran contiguous AND C contiguous.
type: Answer
answers question: http://stackoverflow.com/q/47677654
downvote count: 0
score: 1
upvote count: 1

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

http://stackoverflow.com/q/47686851
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/47686916
score: 0
has body: I want use the date format in list2 to list 1 list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28'] list2 = ['1628 4 19 21:10:32', '1752 6 15 20:05:36', '1775 4 18 09:15:56', '1865 4 14 14:54:36', '1876 5 10 15:36:27', '1879 10 22 03:45:15', '2010 9 29 04:46:28'] Just replace the zero in single number months with space
has title: Replace a char which in the string with another char
type: Question
tagged with: format
answer count: 2
has answer: http://stackoverflow.com/a/47686982
type: UnansweredQuestion

http://stackoverflow.com/comment/82140383
type: Comment
type: QuestionComment
score: 0
has text: Is that the correct sort order? For example try `sorted(['player_1', 'player_2', 'player_10'])`
comment on: http://stackoverflow.com/q/47591430

http://stackoverflow.com/comment/82249487
type: AnswerComment
comment on: http://stackoverflow.com/a/47644129
has text: Done :) Thanks again
type: Comment
score: 0

http://stackoverflow.com/q/47675368
has comment: http://stackoverflow.com/comment/82337051
downvote count: 1
tagged with: aws-lambda
favorite count: 0
has answer: http://stackoverflow.com/a/47688500
type: Question
tagged with: alexa-skills-kit
has title: How to build Python Lambda for Alexa skill with sequence of statements?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82310460
tagged with: python
score: -1
has body: I am building Alexa skill for my application. When your ask's 'what is my account status?' this intent return sequence of statements related to user's account. API gives following response response = [{ .. text: 'Total orders are 41, Delivered 28' .. }, { .. text: 'Today orders are 12, Delivered 2' .. }, {}] How to build response sequence based on API response? With this intent, I get the response from API with set statements Alexa should prompt each statement one by one. If the user said 'next' in between any of the statement while Alexa prompting then it goes to next statement in the response array.
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/47692000

http://stackoverflow.com/q/47549202
has title: AssertTrue missing 1 required positional argument
tagged with: python
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/82065660
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/47552349
type: AnsweredQuestion
score: 0
tagged with: typeerror
tagged with: assert
has body: I am trying to assert the presence of an element and I can make it work but now in the way that I would like. I have a common functions file: - from selenium.common.exceptions import NoSuchElementException def is_element_present_common(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException as e: return False return True ...and my main file: - import unittest from Common import common_functions, initialisation, login from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec from selenium.common.exceptions import NoSuchElementException class QuickTestPlanLogin(unittest.TestCase): def setUp(self): self.driver = initialisation.start_webdriver() self.driver = initialisation.start_sap(self.driver) def tearDown(self): self.driver.close() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException as e: return False return True def test_login(self): wait = initialisation.wait_for(self.driver) self.driver = login.default_login(self.driver, "username", "password") # self.assertTrue(self.is_element_present(By.ID, "my-projects-table_info")) # self.assertTrue(common_functions.is_element_present_common(By.ID, "my-projects-table_info")) There are two assert statements. If I run the first one it works fine, but it is calling the is_element_present function which I do not want. I would like to call the is_element_present_common function from the common_functions file. Every time I run the second assert statement I get the following error: - TypeError: is_element_present() missing 1 required positional argument: 'what' I know I am missing something very simple....
answer count: 1
has comment: http://stackoverflow.com/comment/82065203
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82067083
upvote count: 2
has answer: http://stackoverflow.com/a/47552349
downvote count: 2
has comment: http://stackoverflow.com/comment/82055567

http://stackoverflow.com/q/47609294
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82233697
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82179481
type: UnansweredQuestion
has body: I have data sets which are csv files. Some of them have comment lines with meta data which are not necessarily the first line. At this point i import them with numpy.genfromtxt which works great. However, i would like to be able to import the comment lines as well to scan them for certain criterias. Is there a simple way to do this? As an example: ''' Beginning of File ''' ' comment tag ' ' Name of colums' ' comment tag '' Something i don't care about ' ' comment tag '' Something i care about ' ' Data ' ''' End of file ''' And then i would like to do something like this: if ' Something i care about ' == ' criteria': do_something
has comment: http://stackoverflow.com/comment/82236751
tagged with: python
has title: Import comments from numpy.genfromtxt()

http://stackoverflow.com/comment/82274584
has text: Can you provide the structure for TABLE1 and TABLE2 and the contents of TABLE1?
comment on: http://stackoverflow.com/q/47625172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47643397
has comment: http://stackoverflow.com/comment/82277794
upvote count: 1
tagged with: scrapy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82246249
has title: scrapy pipeline process_item not working (yet another not working)
type: UnansweredQuestion
tagged with: python
has body: item not working question . but i have tried my very best on doing research, still i have to raise a questions. i have simplified the code as below. to make it short, i want to get the details of some products from a web site, i have to use splash to make myself able to read some css. I have registered an item and two db classes, my plan was to store products in product table and their image paths in another . However, at the end the images were downloaded but the item pipeline has not been triggered. in my pipeline, i can only obtain two prints, --> pipeline inited: end init Though i can get the picture but i cannot get my message print( "pipeline" + image_url) most importantly pipeline.py ============= from sqlalchemy.orm import sessionmaker from scrapy.exceptions import DropItem from itembot.database.models import Products, db_connect, create_products_table from scrapy.pipelines.images import ImagesPipeline class ImagesPipeline(ImagesPipeline): def get_media_requests(self, item, info): for image_url in item["image_urls"]: print("pipeline" + image_url) yield scrapy.Request(image_url) def item_completed(self, results, item, info): image_paths = [x["path"] for ok, x in results if ok] print("imagepath" + image_paths) if not image_paths: raise DropItem("Item contains no images") item["image_paths"] = image_paths return item class ItembotPipeline(object): def __init__(self): print("pipeline inited: " ) engine = db_connect() create_products_table(engine) self.Session = sessionmaker(bind=engine) print("end init") def process_item(self, item, spider): print("pipeline Entered : ",item ) print("pipeline Entered : item is products ",item ) products = Products(**item) try: session = self.Session() print("pipeline adding : ",item ) session.add(products) session.commit() print("pipeline commited : ",item ) session.refresh(products) item[id] = products[id] yield item[id] except: session.rollback() raise finally: session.close() if(products[id] is not None): print("pipeline 2if: …
score: 1
has answer: http://stackoverflow.com/a/47643869
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47677654
has answer: http://stackoverflow.com/a/47678066
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82314723
tagged with: fortran
has body: I need a numpy array with 3-rows and 1 Column (for pyCGNS when creating a Zone). And This Must be true when asking if it is NPY.isfortran(X). I tried several ways, but none worked. e.g. a1 = NPY.zeros((3,1),order='F') print NPY.isfortran(a1) -&gt;False
tagged with: arrays
has title: Creating a Column-Vector in Python Numpy in Fortran order
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47678045
possible better answer: http://stackoverflow.com/a/47678045
has answer: http://stackoverflow.com/a/48306111
accepted answer: http://stackoverflow.com/a/48306111

http://stackoverflow.com/a/47547675
answers question: http://stackoverflow.com/q/47543112
has comment: http://stackoverflow.com/comment/82088634
score: 0
has body: Although your question mentions models, in the comments you talk about form fields. You should not be doing any of this, but add the fields in the form's __init__ method. self.fields['whatever'] = forms.CharField(...)
type: Answer

http://stackoverflow.com/q/47595828
type: Question
has answer: http://stackoverflow.com/a/47596151
tagged with: numpy
tagged with: performance
accepted answer: http://stackoverflow.com/a/47596251
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/47596456
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47596151
has title: Fill next column until it reaches zero in numpy matrix or pandas dataframe
has answer: http://stackoverflow.com/a/47596251
has body: Imagine a table with known dimensions. The first column holds numbers and the rest of the rows are 0. I would like the fill the rows based on the value in the first column by subtracting 1 and stop in the column where the value is 0. I would like this to be as efficient as possible The code I have now uses ndarrays and a loop : test = np.zeros([3,360]) test[:,0] = [1,180,360] for j in range(1,360): test[:,j] = test[:,j-1]-1 test[np.where(test&lt;0)] = 0 Is there a more efficient/pythonic way ? E.g. avoiding the for-loop ?

http://stackoverflow.com/comment/82321080
type: Comment
type: QuestionComment
score: 0
has text: Sounds like you are looking for [`itertools combinations`](https://docs.python.org/3.5/library/itertools.html#itertools.combinations)
comment on: http://stackoverflow.com/q/47678290

http://stackoverflow.com/a/74571506
answers question: http://stackoverflow.com/q/47692155
has body: import numpy as np import pandas as pd ## Let's create 5000 rows and 4 different columns arr_random = np.random.default_rng().uniform(low=5,high=10,size=[5000,4]) arr_random ## Creating the dataframe df = pd.DataFrame(arr_random, columns=["A","B","C","D"])
type: Answer
score: 0

http://stackoverflow.com/comment/82152898
type: Comment
comment on: http://stackoverflow.com/q/47597203
has text: I tried `im = scipy.misc.imread(im_name, flatten = True)`. But as I stated above the fact that these png have color maps stored along with them seems to cause the problem. (In Matlab however it works)
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82673911
type: Comment
comment on: http://stackoverflow.com/a/47655395
type: AnswerComment
score: 0
has text: Appreciate the response! But have you tried the following? Add the following item to cart: http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w and go to the check out page: https://www.supremenewyork.com/checkout, there is a terms and conditions checkbox that I’m attempting to check off with Browser’s splinter. Because I made the attempt but still doesn't work.

http://stackoverflow.com/a/47584045
type: Answer
has comment: http://stackoverflow.com/comment/82147845
has body: I guess tsplot is deprecated because people tend to think it would be useful for plotting timeseries - which isn't the case. Of course you may use it, see e.g. this question, but I would recommend simply plotting the data as a line plot: ax = df.plot(x="Date", y="count") ax.figure.autofmt_xdate()
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82148611
has comment: http://stackoverflow.com/comment/82147374
accepted answer of: http://stackoverflow.com/q/47578622
has comment: http://stackoverflow.com/comment/82148208
answers question: http://stackoverflow.com/q/47578622

http://stackoverflow.com/q/47605073
type: Question
linked to: http://stackoverflow.com/q/8382196
accepted answer: http://stackoverflow.com/a/47605263
has comment: http://stackoverflow.com/comment/82168815
answer count: 1
tagged with: scroll
has answer: http://stackoverflow.com/a/47605263
tagged with: django
tagged with: javascript
tagged with: python
upvote count: 7
has title: How to load more content in Django application?
score: 6
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
has body: I have developed a template for viewing the group list in my Django application. What I came to know is that, after more groups, the page is scrolling down. I am unable to see all the names of the groups. Also, I want to view only 4 group names at the start and then after clicking the load more button, the next 4 groups show up. I am unable to do this. {% extends "groups/group_base.html" %} {% block pregroup %} {% if user.is_authenticated %} Welcome back @{{user.username }} {% endif %} Groups Welcome to the Groups Page! Select a Group with a shared interest! {% if user.is_authenticated %} Create New Group! {% endif %} {% endblock %} {% block group_content %} {% for group in object_list %} {{ group.name }} {{ group.members.count }} member {{ group.posts.count }} post {% endfor %} {% endblock %} I want to add a scrolling option to this page. How to do that? Pagination could be a solution. But I want to load the list on the same page itself.

http://stackoverflow.com/a/47642989
has comment: http://stackoverflow.com/comment/82244945
answers question: http://stackoverflow.com/q/47642767
score: 3
upvote count: 3
downvote count: 0
has body: tf.map_fn() enables you to map an arbitrary TensorFlow subcomputation across the elements of a vector (or the slices of a higher-dimensional tensor). For example: a = tf.constant([1.0, -1.0, 2.0, -2.0]) def f(elem): return tf.where(elem &gt; 0, tf.log(elem), -10.0) # Alternatively, if the computation is more expensive than `tf.log()`, use # `tf.cond()` to ensure that only one branch is executed: # return tf.where(elem &gt; 0, lambda: tf.log(elem), lambda: -10.0) result = tf.map_fn(f, a)
has comment: http://stackoverflow.com/comment/82244869
accepted answer of: http://stackoverflow.com/q/47642767
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47679139
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82318774
has comment: http://stackoverflow.com/comment/82320290
type: Question
has comment: http://stackoverflow.com/comment/82319355
has title: PyMdown Snippets extension not working
score: 0
has comment: http://stackoverflow.com/comment/82317639
tagged with: python
has body: I have I markdown file named "file.md" with the following content: #hello world Than I am trying to run the code: echo '--8&lt;-- "file.md"' | /usr/bin/python3 -m markdown -q -o html5 --noisy -x pymdownx.snippets Resulting in this: &lt;p&gt;--8&amp;lt;-- "file.md"&lt;/p&gt; When it should echo: &lt;h1&gt;hello world&lt;/h1&gt; The project page is at https://facelessuser.github.io/pymdown-extensions/extensions/snippets/ I also tried the syntax: --8&lt;-- filename.md filename2.md --8&lt;-- But with similar results. Any light? Edit: I was able to make it work like this: Worked at the same directory: rgr@atpc: ls agenda.md file.md home in teste rgr@atpc: cat file.md #hello world rgr@atpc: echo '--8&lt;-- "file.md"' | /usr/bin/python3 -m markdown -q -o html5 --noisy -x pymdownx.snippets Successfuly imported extension module "pymdownx.snippets". Successfully loaded extension "pymdownx.snippets.SnippetExtension". &lt;h1&gt;hello world&lt;/h1&gt;rgr@atpc:
tagged with: markdown
has comment: http://stackoverflow.com/comment/82317486
answer count: 0
has comment: http://stackoverflow.com/comment/82319303

http://stackoverflow.com/comment/82332486
type: Comment
has text: @CharlesD., I've updated my example accordingly. You'll need to click on the turtle itself, not just somewhere on the screen, to drag it around.
comment on: http://stackoverflow.com/a/47686209
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82155067
comment on: http://stackoverflow.com/a/47598041
type: AnswerComment
has text: Thank you Akshay Bahadur for finding that link
score: 0
type: Comment

http://stackoverflow.com/comment/82193232
type: Comment
type: QuestionComment
has text: How could `lower<0`, for example, ever be true? Given that you start at `lower=0` and only ever increase it, that seems... unlikely.
score: 4
comment on: http://stackoverflow.com/q/47617506

python-multiprocessing
tags question: http://stackoverflow.com/q/47593255
tags question: http://stackoverflow.com/q/47672076
tags question: http://stackoverflow.com/q/47689297
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/47662040
tags question: http://stackoverflow.com/q/47691542
tags question: http://stackoverflow.com/q/47566763
tags question: http://stackoverflow.com/q/47588655
tags question: http://stackoverflow.com/q/47586645
type: Tag
tags question: http://stackoverflow.com/q/47544183
tags question: http://stackoverflow.com/q/47618427
tags question: http://stackoverflow.com/q/47653665
tags question: http://stackoverflow.com/q/47548722
tags question: http://stackoverflow.com/q/47647021
tags question: http://stackoverflow.com/q/47692460
tags question: http://stackoverflow.com/q/47640541
tags question: http://stackoverflow.com/q/47644554

http://stackoverflow.com/comment/82268697
score: 0
type: QuestionComment
has text: Does each entry always start with `name`?
comment on: http://stackoverflow.com/q/47655232
type: Comment

http://stackoverflow.com/comment/82125365
comment on: http://stackoverflow.com/a/47564499
type: Comment
score: 0
type: AnswerComment
has text: I got it. Thanks!

http://stackoverflow.com/a/47627975
type: Answer
has body: Your lists need to be objects that implement a custom cmp function like so: class MyObject(): ... ... def __cmp__(self, other): ... return cmp(self.val, other.val) ...
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82213613
upvote count: 1
answers question: http://stackoverflow.com/q/47627896

http://stackoverflow.com/q/47682662
has comment: http://stackoverflow.com/comment/82324823
has answer: http://stackoverflow.com/a/47682907
tagged with: pygame
has comment: http://stackoverflow.com/comment/82327356
has comment: http://stackoverflow.com/comment/82324925
type: Question
has title: In Pygame, how to give different attributes to a circle in a while loop?
accepted answer: http://stackoverflow.com/a/47682907
tagged with: arrays
answer count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82324782
has body: I am creating a NBA simulator similar to Haxball, in which each circle should have a user name and be its own thing so that during the running of the program an indiviual circle could have its own attributes changed e.g a player gets slower but not everyone does. I have used a few lines in the teams class to create the Player and put them in a team1players list. This does work in creating 5 circles all in different co-ords. However I need the playername attribute (from the Player class) to change for each circle as only certain players play certain positions. I have tried to use self.composition in the for loop but it wont allow me to use a dictionary as an int. I need each player created to be a different playername - with the playername deriving from the composition dictionary containing all positions. So far I have added 1 name (Jose Calderon) to the point guard slot in the composition and I have tried to use the point guard list in the creation of the circle however this results in all players being named Jose Calderon as opposed to just team1players[0] (being the point guard) called Jose. Below is the section of code I need help with - there is plenty of other flaws but this is a basic prototype: self.team1players = [] for i in range(numPlayers): self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30)) self.team2players = []# for i in range(numPlayers): self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30)) Below is the full code as it will probably be needed for anyone to understand what is happening. Its a bit messy at the minute, sorry. :'( import pygame import random import math pygame.init()#initialising python (width, height) = (940,500)#variables for screen screen = pygame.display.set_mode((width, height)) #sets the screen size as "screen" pygame.display.set_caption('Basketball Simulator…
type: AnsweredQuestion
score: 0
tagged with: list

http://stackoverflow.com/q/47545489
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82052382
has comment: http://stackoverflow.com/comment/82051028
type: UnansweredQuestion
has title: Image resizing changes color and texture
tagged with: scikit-image
tagged with: python
has comment: http://stackoverflow.com/comment/82066132
has body: I'm cutting up a large image in to smaller overlapping patches, and this 500x500x3 gray square is part of the background. I'm loading the image into numpy, attempting to scale it down by to 100x100x3, and then saving the image using the following code: import numpy as np from scipy import misc import skimage.transform from matplotlib.image import imread im = imread(originalPath) arr = np.array(im) resized = skimage.transform.resize(arr,(100,100,3)) misc.imsave("resized.tif", resized) The saved image is the correct size, but becomes purple and pink rather than the original gray. I've also tried other rescaling methods including skimage.transform.downscale_local_mean(arr, (5,5,1)) skimage.measure.block_reduce(arr, block_size=(5,5,1), func=np.mean) and they all produce slightly varying versions of the same purple-ish square. I have one main question and one side question: How do I rescale to have a square with accurate colors? Am I using the correct rescaling method?
tagged with: numpy
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/q/47617930
tagged with: data-science
type: AnsweredQuestion
has body: model = Sequential() model.add(keras.layers.InputLayer(input_shape=input_shape)) model.add(keras.layers.convolutional.Conv2D(filters, filtersize, strides=(1, 1), padding='valid', data_format="channels_last", activation='relu')) model.summary() and output summary is : _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_10 (InputLayer) (None, 300, 300, 3) 0 _________________________________________________________________ conv2d_16 (Conv2D) (None, 296, 296, 10) 760 _________________________________________________________________ max_pooling2d_13 (MaxPooling (None, 296, 148, 5) 0 _________________________________________________________________ Above for conv2d_16 layer 10 is depth where as Maxpooling layer 5, how does it possible?
tagged with: keras-layer
accepted answer: http://stackoverflow.com/a/47618794
has comment: http://stackoverflow.com/comment/82195650
tagged with: deep-learning
tagged with: python
score: -3
favorite count: 0
type: Question
downvote count: 4
has title: The depth of pooling layer and prior convolution layer should same. But it is not same, kindly let me know the solutions
answer count: 1
has answer: http://stackoverflow.com/a/47618794
upvote count: 1
tagged with: keras

http://stackoverflow.com/comment/82220638
score: 0
has text: I love the title!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47631266

http://stackoverflow.com/a/47695718
answers question: http://stackoverflow.com/q/47695014
has body: bug fixed. assuming you have a dict with each key mapping to a list of numpy.int64. Setup d = {'key2':[np.int64(v) for v in xrange(10)]} Trials %timeit -n 1000 d['key2'] = map(int, d['key2']) 1000 loops, best of 3: 1.5 µs per loop %timeit -n 1000 d['key2'] = [int(v) for v in d['key2']] 1000 loops, best of 3: 2.0 µs per loop %timeit -n 1000 d['key2'] = [np.asscalar(v) for v in np.array(d['key2'])] 1000 loops, best of 3: 11.6 µs per loop updated with your current codes: integer_columns = ["col1","col2","col3","col4"] # assuming you have a list of list here for col in integer_columns: x = np.array(col) config_data[col] = [np.asscalar(v) for v in x] # &gt;&gt;&gt; type(integer_columns[0][1]) # &gt;&gt;&gt; int numpy.asscalar is a function in numpy for converting numpy types to native python types. here's good answer explaining it. So there's definitely other ways of doing it, it depends on your particular scenario for a certain solution.
score: 0
type: Answer

http://stackoverflow.com/comment/82163716
has text: `command=` expects function name (callback) like `self.plot` - if you use `self.plot()` then it executes functions `self.plot()` and it assigns to `command=` value returned from `self.plot()`
score: 0
comment on: http://stackoverflow.com/q/47602364
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47615037
downvote count: 0
tagged with: geolocation
answer count: 1
tagged with: twitter
upvote count: 1
tagged with: folium
favorite count: 0
type: Question
tagged with: geospatial
has title: AttributeError: 'Map' object has no attribute 'circle_marker'
tagged with: python
accepted answer: http://stackoverflow.com/a/47615115
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47615115
score: 1
has body: How should I fix this? Basically, I want to create a map of tweets based on their geo information. All the tweets I have collected are within the USA and also have geo info. Traceback (most recent call last): File "tweet_map.py", line 19, in &lt;module&gt; tweet_map.circle_marker(location=geo, radius=250) AttributeError: 'Map' object has no attribute 'circle_marker' Here's the code: #create a map of tweets using Folium import folium, pandas, ast # get geo data only from rows with non-empty values locations = pandas.read_csv('./usa_tweets.csv', usecols=[3]).dropna() geos = [] for location in locations.values: # add to geos array an evaluated python literal syntax of the data geos.append(ast.literal_eval(location[0])['coordinates']) # initialize and create map tweet_map = folium.Map(location=[52.8, -2], tiles='Mapbox Bright', zoom_start=7) # add markers for geo in geos: tweet_map.circle_marker(location=geo, radius=250) tweet_map.create

http://stackoverflow.com/comment/82073791
type: Comment
type: QuestionComment
score: 0
has text: I know. But before getting into Scrapy, I'd like to first learn the basics :)
comment on: http://stackoverflow.com/q/47557989

http://stackoverflow.com/a/47550612
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47550405
has body: If you want to just get the 2.2 and 3.3 values, you can go without regexps: data = [u'1111 aaaa 20 0 250m 149m 113m S 0.0 2.2 532:09.83 bbbb', u' 5555 cccc 20 0 218m 121m 91m S 0.0 3.3 288:50.20 dddd'] print([item.split()[9] for item in data]) # yields [u'2.2', u'3.3'] By default split splits by whitespace. And your 2.2 and 3.3 numbers happen to be 10th in each of the blobs. Python uses 0-indexing of lists, so 10th in human terms becomes 9.
answers question: http://stackoverflow.com/q/47550405
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82140303
comment on: http://stackoverflow.com/q/47590982
type: QuestionComment
has text: I just need get use more than 1 database and their objects in one connection. In your example its different from me question. Anyway thanks!
score: 0
type: Comment

http://stackoverflow.com/q/47561251
has body: I have a raw hexadecimal representation of and image like this: "FF00FF00FF00" Every 2 letters represent the color of one pixel, in this example it is 6 pixels white -black -white - black -white - black, 2x3 pixels (width x height). I want to convert this into an html re-presentable image. I was wondering what the best solution for this would be? I was thinking of converting the HEX string one by one into base64 and then use a &lt;img&gt; tag to display it on an html page. I was using python to convert it: encoded = HEX_STRING.decode("hex").encode("base64") Converting it pixel by pixel would give me this /wAA/wAA/wAA. Then I would add this as a src to an image tag: &lt;img src='data:image/png;base64,iVBORw0KGgo/wAA/wAA/wAA' alt='img'&gt; This doesn't work. The only other way I could think of is drawing an image pixel by pixel with html canvas. I'm wondering if there is an easier solution?
has comment: http://stackoverflow.com/comment/82082960
has answer: http://stackoverflow.com/a/47562358
type: Question
has comment: http://stackoverflow.com/comment/82080860
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/82082811
has title: How to convert a raw hexadecimal image to a html img
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47561725
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/47625296
has comment: http://stackoverflow.com/comment/82212879
has body: You would need to iterate through the list as the key that you are using to evaluate condition is in the sub list. mylist = [["hello","son", 52],["welcome","home",65],["good","work",6]] name = 'hello' # 'son' would also work for i, sub_list in enumerate(mylist): if name in sub_list: del mylist[i] print(name + " deleted") break print(mylist) For a given example, where you want to specify bunch of properties for a name; I would have considered using dictionary with name as key.
type: Answer
answers question: http://stackoverflow.com/q/47625162
score: 0
has comment: http://stackoverflow.com/comment/82211496

http://stackoverflow.com/q/47632015
type: UnansweredQuestion
tagged with: python
tagged with: novaclient
has title: openstack API python - no module named version
has body: I'm trying to instanciate VM on openstack using the NovaClient API in python. More precisely with mq-rabbit celery tasks. Unfortunatly I got this error : from novaclient import client File "/usr/local/lib/python2.7/dist-packages/novaclient/__init__.py", line 15, in &lt;module&gt; import pbr.version ImportError: No module named version I already tested with a simple python file and it works, my VM was created but when I try to do this throught a celery tash I got the error above... My version is the latest python-novaclient-6.0.2, but as our servers are in version 2 I use the version 2 API. Here is my code in my celery task, who works when I test in python shell : loader = loading.get_plugin_loader('password') auth = loader.load_from_options(auth_url=auth_url, username=username, password=password, project_name=tenant_name) sess = session.Session(auth=auth) nova = client.Client('2', session=sess) #API version and session
tagged with: python-2.7
score: 0
tagged with: openstack-nova
answer count: 1
tagged with: openstack
type: Question
has comment: http://stackoverflow.com/comment/82221736
has answer: http://stackoverflow.com/a/47632328

http://stackoverflow.com/comment/82111789
has text: You assuming the increment of C are 1 ?
comment on: http://stackoverflow.com/a/47577370
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47549613
has body: Use a custom key function for itertools.groupby(iterable, key=None) as shown below (the initial input string was extended): import re, itertools s = "90.80.19 90.43.19 908019 92.11.15 90.80.19 930000 921115" matches = re.findall(r'\d\d\.?\d\d\.?\d\d', s) result = [ list(g) for k,g in itertools.groupby(sorted(matches), key=lambda x: x.replace('.', '') or x) ] print(result) The output: [['90.43.19'], ['90.80.19', '90.80.19', '908019'], ['92.11.15', '921115'], ['930000']]
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47549264
accepted answer of: http://stackoverflow.com/q/47549264

http://stackoverflow.com/comment/82110672
type: QuestionComment
comment on: http://stackoverflow.com/q/47576632
has text: What I wrote so far is: `df.apply(lambda x: df[(df.B == x.B) & (~df.C.eq(x.C))].min().C - x.C, axis=1)' This works as required, however I have two issuse: checking that df.C == x.C just works in this example (so how do I exclude my current elements really without just checking for one column), plus apply is slow right? Any better ways?
score: 0
type: Comment

http://stackoverflow.com/q/47653159
tagged with: visual-studio-2015
tagged with: c++
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82291104
has answer: http://stackoverflow.com/a/47673903
answer count: 1
tagged with: include
type: Question
tagged with: debugging
accepted answer: http://stackoverflow.com/a/47673903
has body: I would like to run a Python script that uses a library that only works with Python2.7 in a c++ Program. I run this in Release mode because i don't have python27_d.lib under VS 2015. PyObject *pName, *pModule, *pDict, *pFunc, *pValue; Py_Initialize(); std::string name = "C:/pathToProgamm/pythonHTTPS.py" pName = PyString_fromString(name.c_strg()); pModule = Pyimport_Import(pName); pDict = PyModule_GetDict(pModule); Here I get the error python27.pdb not loaded I tried to solve it by changing to "Only specified modules" (from "All modules, unless excluded") under Debugging->Symbols in VS 2015 but then I get Symbol loading for python27.dll was skipped because it is not specified in the included modules list. I also tried to download the pdb file and point to it but this also doesn't work. What I want to do is that: if (pName = PyString_FromString(name_i.c_str())) { if (pModule = PyImport_Import(pName)) { if (pDict = PyModule_GetDict(pModule)) { if (pFunc = PyDict_GetItemString(pDict, NULL)) { std::cout &lt;&lt; "success" &lt;&lt; std::endl; } else { std::cout &lt;&lt; "failed pFunc" &lt;&lt; std::endl; return; } } else { std::cout &lt;&lt; "failed pDict" &lt;&lt; std::endl; return; } } else { std::cout &lt;&lt; "failed pModule" &lt;&lt; std::endl; return; } } else { std::cout &lt;&lt; "failed pName" &lt;&lt; std::endl; return; } but the result of this is --> failed pModule so the error is in pModule=Pyimport_import(pName); could anybody tell me why this fails and how to get the debugging running for my python version (2.7.14)
tagged with: python
has title: Running Python2.7 script in C++ using #include "Python.h"

http://stackoverflow.com/comment/82140204
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47591502
has text: `/opt` is enough . https://askubuntu.com/a/195658/159179
score: 1

http://stackoverflow.com/q/47649044
favorite count: 0
has body: I have to make a function whose purpose is taking in parameter a list. Such as this one : ['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000'] And return a list similar to this : data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}] So I made that function : def my_function(list_in_question, my_config_list =[], prev_list = []): """ """ enumerated_list = list(enumerate(list_in_question)) if not '=' in enumerated_list[0][1]: main_key = enumerated_list[0][1]# référencé avant assignement pre_dict = {main_key : {}} for i in enumerated_list[1:]: if '=' in i[1] : splitted = i[1].split('=') prev_list.append({splitted[0] : splitted[1]}) elif not '=' in i[1] and i[1] != main_key: for j in prev_list: pre_dict[main_key].update(j) my_config_list.append(pre_dict) return my_function(list_in_question[i[0]:]) elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]: return my_config_list else: print("The format of the file containig the data in not adequate !") But I don't understand why when I execute it this way : new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' m…
linked to: http://stackoverflow.com/q/9884132
answer count: 4
type: Question
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/47650360
tagged with: function
has comment: http://stackoverflow.com/comment/82256699
has answer: http://stackoverflow.com/a/47649957
has answer: http://stackoverflow.com/a/47649756
downvote count: 0
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/23286254
has answer: http://stackoverflow.com/a/47650255
tagged with: list
possible better answer: http://stackoverflow.com/a/47649957
has title: Function that transforms a list in a list of dictionary
accepted answer: http://stackoverflow.com/a/47649756
type: AnsweredQuestion
tagged with: loops

http://stackoverflow.com/q/47680369
answer count: 1
tagged with: flask
type: Question
has body: Edit: After moving stuff around and renaming things, I'm revising this post to reflect my current issue. I'm unable to access the endpoints in the files inside my views folder. I thought importing them explicitly in test_example.py or having them already imported in __init__.py would do the trick. Here's the error when running pytest: rv = self._partial_build(endpoint, values, method, append_unknown) if rv is None: &gt; raise BuildError(endpoint, values, method, self) E werkzeug.routing.BuildError: Could not build url for endpoint '/api/create_booth'. Did you mean 'static' instead? Also, I tried substituting url_for('some_endpoint') with url_for('some_endpoint', _external=True) -- had no effect. Here's my directory structure and the simplified contents of the relevant files: directory structure server/ my_app/ __init__.py views/ __init__.py some_views.py test/ __init__.py conftest.py test_example.py __init__.py: from flask import Flask def create_app(): app = Flask(__name__) return app app = create_app() from views.some_view import * if __name__ == '__main__': app.run(debug=True) conftest.py import pytest from my_app import create_app @pytest.fixture def app(): app = create_app() return app test_example.py from flask import url_for from my_app.views.some_views import some_endpoint def test_some_endpoint(client): assert client.post(url_for('some_endpoint'), data=json.dumps(dict(some_attr='some_value')), content_type='application/json').status_code == 200 some_views.py from my_app import app @app.route('/api/some_endpoint/', methods=['POST']) def some_endpoint(): return "success" I'm running pytest-flask-0.10.0, Python 3.4.3, and Flask 0.12.2
accepted answer: http://stackoverflow.com/a/47686020
tagged with: python
has title: pytest-flask -- can not access application's endpoints from test client function
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47686020

http://stackoverflow.com/comment/82108079
has text: is it faster to do that vs doing the pd.merge(how=left) and then removing the Nan ?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47575580

http://stackoverflow.com/comment/82194789
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47609547
type: Comment
has text: Thanks for the fast and helpful response man, it was indeed the right solution, you can check my original post to see how i changed my code.

http://stackoverflow.com/a/47595169
answers question: http://stackoverflow.com/q/47595050
accepted answer of: http://stackoverflow.com/q/47595050
type: Answer
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: You can bind a function to &lt;Enter&gt; to trigger a function when the mouse enters a widget, and you can bind to &lt;Leave&gt; to trigger when it leaves. The &lt;Enter&gt; binding can run a function that starts updating the label periodically using after. The &lt;Leave&gt; binding can set a flag that the update function checks in order to know to stop updating. There are many questions and answers on this site about using after to do something periodically. For example, How to use the after method to make a callback run periodically?

http://stackoverflow.com/q/47605199
has body: I have been having problems using the .replace() method and for loop. My code below: K=int(input("How many times do you want to input? ")) print("K&gt; "+str(K)) my_list=['A'] count=0 while count&lt;K: letter.replace('A','B').replace('B','B'+'A') for letter in my_list print(my_list) count=count+1 The letter.replace() results in an invalid syntax error and I was wondering how to resolve this. I also have been having problems replacing the 'A' with 'B'. Would implementing the for loop work?
has comment: http://stackoverflow.com/comment/82169122
has title: Invalid syntax in Python code (.replace() and for loop)
tagged with: python
has answer: http://stackoverflow.com/a/47605519
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/82169368
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82169072
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82169171

http://stackoverflow.com/comment/82091642
type: AnswerComment
comment on: http://stackoverflow.com/a/47566118
has text: Good point. The OP doesn't seem as comfortable with Python though, so the above code was meant to be easily readable/understood at the expense of conciseness.
score: 0
type: Comment

http://stackoverflow.com/comment/82334549
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47687536
type: Comment
has text: Nothing is changed at all for my csv actually

http://stackoverflow.com/comment/85825544
score: 0
type: AnswerComment
has text: Is there a new update on when the pyomo5 expression will be on master?
comment on: http://stackoverflow.com/a/47679461
type: Comment

http://stackoverflow.com/q/47576975
favorite count: 0
type: Question
tagged with: numpy
has title: Fitting Sersic profile on data points with error bars in python
has comment: http://stackoverflow.com/comment/82257772
has body: I have a set of data which I like to fit a 1D-Sersic profile (a function already defined in astropy) I can easily fit the data if I simply consider the data points without any error bars as below: import numpy as np from astropy.modeling import models, fitting from astropy.modeling.models import Sersic1D ## data_LARS02 =np.loadtxt('/Users/a/data.asc') ## r_l02 = data[:,0] flux_l02 = data[:,1] ###########################################Fitting sers_l02_init = Sersic1D(amplitude=5e40, r_eff=1, n=2) fit_sers_l02 = fitting.LevMarLSQFitter() Sers_l02 = fit_sers_l02(sers_l02_init,r_l02,flux_l02) ##### The code works and everything is fine. However, I noticed there is a problem with the fit due to neglecting the error bars. Thus, I decided to include the error bars. But I do not know how to implement it. Do you have any suggestions?
has comment: http://stackoverflow.com/comment/82435762
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78199421
tagged with: python
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/82421031
score: 1
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/82327675
comment on: http://stackoverflow.com/a/47683673
has text: Thank you very much for your reply - learning that constraints are not enforced at all steps is very useful to know. I have also considered bounds, but I couldn't find a way out with them either. The term of which I have to take the sqrt (and also the log) in the objective function is a complicated nonlinear function of 6 variables. According to scipy docs, bounds only apply to the variables we are optimizing. I thought of something like catching the exception in case of MathError in f and just pass before return, but that seems very shallow.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47567397
possible better answer: http://stackoverflow.com/a/47568943
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47567514
has title: How can I remove the duplicate links from this Python code?
score: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47568943
has body: How can I remove the duplicate links from this Python code? import requests from bs4 import BeautifulSoup, SoupStrainer import bs4 search_link = "https://www.census.gov/data/tables/2016/demo/popest/state-total.html" r = requests.get(search_link) soup = BeautifulSoup(r.text, 'html.parser') results = soup.find_all('a') file = open('testfile.txt','w') for link in results: S=link.get('href') file.write("%s \n" % S) file.close() print(len(results)) import csv for link in results: S=link.get('href') csvRow = [S] csvfile = "data.csv" with open(csvfile, "a") as fp: wr = csv.writer(fp, dialect='excel') wr.writerow(csvRow )
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47567514

http://stackoverflow.com/comment/82286040
has text: I see. I thought `linspace` was hitting 0 and 1
comment on: http://stackoverflow.com/a/47662677
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47624935
has comment: http://stackoverflow.com/comment/82230011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82231939
has title: Check PEP8 in data structure
upvote count: 1
tagged with: python
answer count: 0
has body: I am using pycodestyle for checking code style, but I realized in this code: # -*- coding: utf-8 -*- class Button: def __init__(self, foo, bar, text="empty"): print foo print bar print text # Not valid button = Button(1, 2, text="Player 1") # Valid buttons = [Button(6, 7, text="Player 2")] In PEP8 about indentation says that the ideal would be this: button = Button(foo, bar, text="Player 1") Or: button = Button( 1, 2, text="Player 1") However I do not understand why this is valid: buttons = [Button(6, 7, text="Player 2")] Is it because of the data structure or is it a pycodestyle bug?
score: 1
tagged with: pep8
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/47674588
downvote count: 0
tagged with: python
score: 4
has body: I have a place holder for input: Y = tf.placeholder(dtype=tf.float32, shape=(None, n_outputs)) Now I want to create a constant the same shape the Y: w = Y.get_shape() zero = tf.constant(np.zeros(w), dtype=tf.float32) Error return: __index__ returned non-int (type NoneType)
linked to: http://stackoverflow.com/q/35853483
type: AnsweredQuestion
has title: tensorflow: how create an const tensor the same shape as a placeholder
answer count: 3
has answer: http://stackoverflow.com/a/64773879
has answer: http://stackoverflow.com/a/47675047
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/47722248
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47722248
tagged with: tensor
possible better answer: http://stackoverflow.com/a/64773879

http://stackoverflow.com/comment/82319987
type: QuestionComment
comment on: http://stackoverflow.com/q/47680073
has text: list1 = [x for x in list1 if x not in list2] No need for any of this set stuff... It doesn't help in a situation like this where you want to maintain the order.
score: 0
type: Comment

http://stackoverflow.com/comment/82326009
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47683108
score: 0
has text: Essentially setup your `setup.py` file to include a `data_files` list and python should package them up with the distributed package (such as when you turn it into a `wheel`. It'll work locally as well assuming the directory structure doesn't change any during the distribution.

http://stackoverflow.com/q/47633468
upvote count: 1
has comment: http://stackoverflow.com/comment/82226188
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47634487
has body: I have a dataset containing monthly observations of a time-series. What I want to do is transform the datetime to year/quarter format and then extract the first value DATE[0] as the previous quarter. For example 2006-10-31 belongs to 4Q of 2006. But I want to change it to 2006Q3. For the extraction of the subsequent values I will just use the last value from each quarter. So, for 2006Q4 I will keep BBGN, SSD, and QQ4567 values only from DATE[2]. Similarly, for 2007Q1 I will keep only DATE[5] values, and so forth. Original dataset: DATE BBGN SSD QQ4567 0 2006-10-31 00:00:00 1.210 22.022 9726.550 1 2006-11-30 00:00:00 1.270 22.060 9891.008 2 2006-12-31 00:00:00 1.300 22.080 10055.466 3 2007-01-31 00:00:00 1.330 22.099 10219.924 4 2007-02-28 00:00:00 1.393 22.110 10350.406 5 2007-03-31 00:00:00 1.440 22.125 10480.888 After processing the DATE DATE BBGN SSD QQ4567 0 2006Q3 1.210 22.022 9726.550 2 2006Q4 1.300 22.080 10055.466 5 2007Q1 1.440 22.125 10480.888 The steps I have taken so far are: Turn the values from the yyyy-mm-dd hh format to yyyyQQ format DF['DATE'] = pd.to_datetime(DF['DATE']).dt.to_period('Q') and I get this DATE BBGN SSD QQ4567 0 2006Q4 1.210 22.022 9726.550 1 2006Q4 1.270 22.060 9891.008 2 2006Q4 1.300 22.080 10055.466 3 2007Q1 1.330 22.099 10219.924 4 2007Q1 1.393 22.110 10350.406 5 2007Q1 1.440 22.125 10480.888 The next step is to extract the last values from each quarter. But because I always want to keep the first row I will exclude DATE[0] from the function. quarterDF = DF.iloc[1:,].drop_duplicates(subset='DATE', keep='last') Now, my question is how can I change the value in DATE[0] to always be the previous quarter. So, from 2006Q4 to be 2006Q3. Also, how this will work if DATE[0] is 2007Q1, can I change it to 2006Q4?
has title: Change year/quarter date format to previous period in python
has comment: http://stackoverflow.com/comment/82225616
has answer: http://stackoverflow.com/a/47634487
possible better answer: http://stackoverflow.com/a/47634653
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/47634653
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 1
downvote count: 0

http://stackoverflow.com/comment/82086098
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47563742
has text: It shows the same [error](https://gyazo.com/f301e084de15f315f743d8095c57888f)...shall we move this to a chat?
score: 0

http://stackoverflow.com/comment/82343570
score: 0
type: Comment
has text: I add sample data, for me it working nice. `f['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata')` does not work too?
comment on: http://stackoverflow.com/a/47691984
type: AnswerComment

http://stackoverflow.com/comment/82246893
has text: Add an extra `print()` in-between your for-loops
type: QuestionComment
comment on: http://stackoverflow.com/q/47644077
score: 0
type: Comment

http://stackoverflow.com/a/47637391
downvote count: 0
type: Answer
score: 16
upvote count: 16
has body: When using tf.feature_columns, the data you feed in your input_fn should have the same keys as the feature columns previously created. So, the x of your train_input_fn should be a dictionary, with keys named after the feature_columns. A mock example : x = {"policy_state": np.array(['AL','AL','AL','AL','AL']), "modern_classic_ind": np.array(['0','0','0','0','0']), "h_plus_ind": np.array(['0','0','0','0','0']),}
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47635507
answers question: http://stackoverflow.com/q/47635507

http://stackoverflow.com/a/47638218
has comment: http://stackoverflow.com/comment/82235290
has comment: http://stackoverflow.com/comment/82235225
type: Answer
has comment: http://stackoverflow.com/comment/82236087
has comment: http://stackoverflow.com/comment/82235946
has comment: http://stackoverflow.com/comment/82234835
answers question: http://stackoverflow.com/q/47638137
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82234713
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82234865
has body: Try below XPath //*[@class="maintitle"]/*[contains(@class, "main-wrap")]//*[@id="myid"]/*[contains(@class="h1")]//bold If you need tool that can convert CSS to XPath for you, you can try lxml: from cssselect import GenericTranslator from lxml.etree import XPath css_selector = """[class="maintitle"] &gt; .main-wrap #myid &gt; .h1 bold""" print(XPath(GenericTranslator().css_to_xpath(css_selector))) Output (looks weird, but...): descendant-or-self::*[@class = 'maintitle']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' main-wrap ')]/descendant-or-self::*/*[@id = 'myid']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' h1 ')]/descendant-or-self::*/bold Note that you might also need to add // at the beggining as: print("//" + str(XPath(GenericTranslator().css_to_xpath(css_selector))))
accepted answer of: http://stackoverflow.com/q/47638137
has comment: http://stackoverflow.com/comment/82235387
has comment: http://stackoverflow.com/comment/82235850

http://stackoverflow.com/comment/82058527
comment on: http://stackoverflow.com/q/47549965
score: 1
has text: So physically loading everything into RAM should be possible. Your actual problem may be somewhere else. You should post the code you currently have, otherwise it will be hard to say more.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82557071
type: QuestionComment
score: 0
has text: Did you have the chance to try the code I posted you?
comment on: http://stackoverflow.com/q/47586721
type: Comment

http://stackoverflow.com/comment/82332239
comment on: http://stackoverflow.com/a/47686253
score: 0
has text: so what is the += b? just keep adding the value to the key if the key is in d1?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47577301
tagged with: twitter
type: Question
has title: How can i use split function in python to split parts of text and save them to a different file?
tagged with: split
accepted answer: http://stackoverflow.com/a/47578363
tagged with: function
has answer: http://stackoverflow.com/a/47578363
tagged with: python
has comment: http://stackoverflow.com/comment/82112983
has comment: http://stackoverflow.com/comment/82113179
has comment: http://stackoverflow.com/comment/82111925
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82112896
has comment: http://stackoverflow.com/comment/82113287
has body: Hello i have a problem using the split function in python with no success. I collected some tweets using a crawler and i need to split some parts of each tweets to a different .json file specifically the ID and #(hashtag). I been using the split function with no success what i am doing wrong? I want to save to a different .json file what is after "id" and "text" The text looks like this: {"created_at":"Fri Oct 20 16:35:36 +0000 2017","id":921414607302025216,"id_str":"921414607302025216","text":"@IdrisAhmed16 loooooool who said I was indirecting you?? def on_data(self, data): try: #print data with open('Bologna_streams.json', 'r') as f: for line in f: tweet = data.spit(',"text":"')[1].split('",""source"')[0] print (tweet) saveThis = str(time.time()) + '::' +tweet saveFile = open('Bologna_text_preprocessing.json', 'w') json.dump(data) saveFile.write(saveThis) saveFile.write(tweet) saveFile.write('\n') saveFile.close() f.close() return True except BaseException as e: print("Error on_data: %s" % str(e)) time.sleep(5) def on_error(self, status): print (status)
tagged with: http://stackoverflow.com/tag/json
answer count: 1

http://stackoverflow.com/comment/82110837
has text: `chdtri(1, np.exp(-pd.Series([0.5, 0.1, 0.99]) * np.log(10)))` worked :) Note to self from ten years ago: study more maths.
comment on: http://stackoverflow.com/a/47575732
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47641998
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47641925
type: Answer
has body: There might be a better way but here is one, df['DryDay'] = ((df['DryDay'] == 1) &amp; ((df['DryDay'].shift() == 1) | (df['DryDay'].shift(-1) == 1))).astype(int) Date DryDay 0 2009-05-07 0 1 2009-05-08 0 2 2009-05-09 1 3 2009-05-10 1 4 2009-05-11 1 5 2009-05-12 1 6 2009-05-13 1 7 2009-05-14 0 8 2009-05-15 0 9 2009-05-16 0 10 2009-05-17 0 11 2009-05-18 0 12 2009-05-20 0 13 2009-05-21 0 14 2009-05-22 0 15 2009-05-23 1 16 2009-05-24 1 17 2009-05-25 1 18 2009-05-26 0 19 2009-05-27 0 20 2009-05-28 1 21 2009-05-29 1 22 2009-05-30 0
score: 0
accepted answer of: http://stackoverflow.com/q/47641925
has comment: http://stackoverflow.com/comment/82256760

http://stackoverflow.com/comment/82176283
has text: THanks for your detailed information, What happens if the output from the task1 needs to be processed into task2..Task2 is dependant on task1 results..So basically, task1 will send 2 outputs - 1) the result the task2 needs 2) error code to say if task1 is processed successfully or not..
type: Comment
comment on: http://stackoverflow.com/a/47606035
type: AnswerComment
score: 0

http://stackoverflow.com/q/47558225
tagged with: paramiko
has body: I've used paramiko's exec_command with ls succesfully until I tried it with a list of files as an argument. My function is: def jz_orion_ssh_sout_list(cmd): with paramiko.SSHClient() as ssh: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(orion['host'], username=orion['username'], password=orion['password']) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd) sout = ssh_stdout.readlines() serr = ssh_stderr.readlines() return sout When cmd='ls -l /my/path/file.txt' it works fine, but when cmd='ls -l /my/path/file1.txt file2.txt file3.txt', it only returns file1.txt. The latter cmd run directly on the target server returns all 3 files. How to make it work in paramiko? PS. I've found another syntax which works in paramiko: cmd='ls -l /my/path/{file1.txt,file2.txt,file3.txt}' but still I'd like to know what causes the failure with beforementioned one.
type: AnsweredQuestion
tagged with: bash
tagged with: ls
has title: paramiko ls with several files output truncated
score: 3
upvote count: 3
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47561925
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47561925
has comment: http://stackoverflow.com/comment/82081402
tagged with: python

http://stackoverflow.com/comment/82325509
score: 0
comment on: http://stackoverflow.com/q/47682885
type: QuestionComment
has text: @MadPhysicist I just use `partitioned_image = partition(image, 20)`. I did wonder about remainders, although given that my upper corresponds to the (i + 1) step ahead I fail to see how this would screw it up.
type: Comment

http://stackoverflow.com/comment/82135146
score: 0
has text: no problem, bro
comment on: http://stackoverflow.com/q/47586948
type: Comment
type: QuestionComment

frequency-distribution
tag name: frequency-distribution
type: Tag
tags question: http://stackoverflow.com/q/47586089

http://stackoverflow.com/q/47582619
has comment: http://stackoverflow.com/comment/82122846
tagged with: python
tagged with: data-structures
tagged with: search
type: AnsweredQuestion
score: 0
has title: Mapping sets on labels data structure in Python
answer count: 2
has comment: http://stackoverflow.com/comment/82123038
has comment: http://stackoverflow.com/comment/82122875
possible better answer: http://stackoverflow.com/a/47582677
has comment: http://stackoverflow.com/comment/82123013
has answer: http://stackoverflow.com/a/47582677
has body: I have a set of keywords that looks like S = {'apples', 'bananas', 'grapes', 'lemons'}and I want to associate a label fruit to this set in order to classify them basing on the set membership function: return 'fruit' if x in S. I have many such sets and corresponding labels. The sets have empty intersections. Is there a data structure that may serve the best for such a purpose? The only idea coming to my mind is to loop over all sets and compute the membership function. Is it possible to implement something like inverted dictionary - knowing one of values gives a key?
accepted answer: http://stackoverflow.com/a/47582686
type: Question
has comment: http://stackoverflow.com/comment/82122997
has answer: http://stackoverflow.com/a/47582686

http://stackoverflow.com/comment/82510760
has text: ...Caching b/c date exists and max-age > 0
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47653924

http://stackoverflow.com/q/47660726
downvote count: 1
has answer: http://stackoverflow.com/a/47663888
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82284188
has answer: http://stackoverflow.com/a/47660778
possible better answer: http://stackoverflow.com/a/47660778
tagged with: arrays
has title: How to index a 1D numpy array as if it is a matrix with 1 row?
tagged with: python
has comment: http://stackoverflow.com/comment/82280588
tagged with: indexing
type: AnsweredQuestion
has body: I have a 1D numpy array like: a = np.array([1,2,3,4,5]) And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3): a[0,2] Traceback (most recent call last): File "&lt;ipython-input-34-2fc0526218b3&gt;", line 1, in &lt;module&gt; a[0,1] IndexError: too many indices for array I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.
score: 0
has answer: http://stackoverflow.com/a/47661045
has comment: http://stackoverflow.com/comment/82284226
has comment: http://stackoverflow.com/comment/82284343
answer count: 3
accepted answer: http://stackoverflow.com/a/47661045
upvote count: 1
has comment: http://stackoverflow.com/comment/82291138

http://stackoverflow.com/comment/82122993
type: QuestionComment
has text: maybe using the mapping function in some way?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47580716

http://stackoverflow.com/q/47596202
score: 1
has answer: http://stackoverflow.com/a/47645623
upvote count: 1
tagged with: calendar
possible better answer: http://stackoverflow.com/a/47596576
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47596576
answer count: 2
has body: Would anyone know how to make Python return a date format like this from the calendar function?: date = "20170714" Basically I am looking for some enhancements if its possible for the API request to gather hourly weather data.. My problem is the code needs to be re-ran for each day.. Its a little clunky and time consuming to rerun the script 365 times to get a years worth of weather data, but its the only way I know how. Can a loop with the calendar function automate things? from urllib.request import urlopen from pandas.io.json import json_normalize import json import pandas as pd api_key = "" date = "20170714" zip_code = "96345" response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json" % (api_key, date, zip_code)) json_data = response.read().decode('utf-8', 'replace') data = json.loads(json_data) for observation in data['history']['observations']: print("Date/Time: " + observation['date']['pretty']) print("Temperature: " + observation['tempi']) print("Humidity: " + observation['hum']) df = json_normalize(data['history']['observations']) df = df'date.pretty','tempi','hum' df['date.pretty'] = pd.to_datetime(df['date.pretty']) print(df) This simple calendar script can return every day in the month of December 2013, but its not in a format that weather underground API would understand... Ultimately I am hoping to create a loop where the API request can gather a months data, (or even an entire year at a time) with the calendar function Vs one day manual fashion.... Is this possible??! import calendar tc = calendar.TextCalendar(firstweekday=0) for i in tc.itermonthdays(2013,12): print(i) Thanks
downvote count: 0
linked to: http://stackoverflow.com/q/47874185
tagged with: python
tagged with: data-science
has title: Python 3 Calendar
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47645623
tagged with: api

http://stackoverflow.com/q/47591430
upvote count: 2
answer count: 5
has comment: http://stackoverflow.com/comment/82140529
has comment: http://stackoverflow.com/comment/82139895
tagged with: python
has comment: http://stackoverflow.com/comment/82140107
accepted answer: http://stackoverflow.com/a/47592283
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47592211
has comment: http://stackoverflow.com/comment/82140383
has comment: http://stackoverflow.com/comment/82140279
has answer: http://stackoverflow.com/a/47592283
score: 1
has title: Algorithm for data rearrangement in a Python dict
has comment: http://stackoverflow.com/comment/82139889
possible better answer: http://stackoverflow.com/a/47592127
downvote count: 1
has answer: http://stackoverflow.com/a/47592127
favorite count: 0
type: Question
has body: In Python, I have the following dict: players = {'player_1': 'data_a', 'player_2': 'data_b', 'player_3': 'data_c', 'player_4': 'data_d', 'player_5': 'data_e', 'player_6': 'data_f'} What's the most efficient way to rotate the dict? The desired algorithm should take the new 'player_1' as input, and the rearrange the dict accordingly. Example: algorithm('player_4') would return the following dict: {'player_1': 'data_d', 'player_2': 'data_e', 'player_3': 'data_f' 'player_4': 'data_a', 'player_5': 'data_b', 'player_6': 'data_c', } Edit When iterating through a dict, I use the build in sorted method. Because of this, it does not matter that python dict is not sorted OOTB. The data within the dict still needs to be rearranged. Edit 2: An example of where I use the sorted below. for player, data in sorted(players.items()): make_move(player, data) if is_interrupted(player): # The game was interrupted, and we need to start the next round with the player who was interrupted. # This is where I need to rearrange the dict!
has answer: http://stackoverflow.com/a/47592092
has answer: http://stackoverflow.com/a/47591909
has comment: http://stackoverflow.com/comment/82139954

http://stackoverflow.com/comment/82156543
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47584350
score: 0
has text: run in command line using `python.exe` (without `w` in name). It will display error in command line.

http://stackoverflow.com/comment/82085627
score: 0
comment on: http://stackoverflow.com/q/47557240
has text: You want that the comboboxes that are below cboRows can only be between 0 and the number selected by cboRows minus the ones chosen by the other comboboxes that are different from 0 since this is chosen by default. I am right?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47572800
has comment: http://stackoverflow.com/comment/123054672
score: 1
tagged with: python
tagged with: character-encoding
type: Question
has body: I have setup a pipenv project in /home/user/code/myproject/ using pipenv --three I have added myproject directory as project directory in PyCharm and have setup environment for PyCharm to use pipenv from File &gt; Default Settings &gt; Project Interpreter &gt; But when I run any command from within the console of PyCharm like pipenv install &lt;package-name&gt; It gives error as Traceback (most recent call last): File "/usr/local/bin/pipenv", line 11, in &lt;module&gt; sys.exit(cli()) File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 676, in main _verify_python3_env() File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/_unicodefun.py", line 118, in _verify_python3_env 'for mitigation steps.' + extra) RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult http://click.pocoo.org/python3/for mitigation steps. This system lists a couple of UTF-8 supporting locales that you can pick from. The following suitable locales where discovered: af_ZA.UTF-8, am_ET.UTF-8, be_BY.UTF-8, bg_BG.UTF-8, ca_ES.UTF-8, cs_CZ.UTF-8, da_DK.UTF-8, de_AT.UTF-8, de_CH.UTF-8, de_DE.UTF-8, el_GR.UTF-8, en_AU.UTF-8, en_CA.UTF-8, en_GB.UTF-8, en_IE.UTF-8, en_NZ.UTF-8, en_US.UTF-8, es_ES.UTF-8, et_EE.UTF-8, eu_ES.UTF-8, fi_FI.UTF-8, fr_BE.UTF-8, fr_CA.UTF-8, fr_CH.UTF-8, fr_FR.UTF-8, he_IL.UTF-8, hr_HR.UTF-8, hu_HU.UTF-8, hy_AM.UTF-8, is_IS.UTF-8, it_CH.UTF-8, it_IT.UTF-8, ja_JP.UTF-8, kk_KZ.UTF-8, ko_KR.UTF-8, lt_LT.UTF-8, nl_BE.UTF-8, nl_NL.UTF-8, no_NO.UTF-8, pl_PL.UTF-8, pt_BR.UTF-8, pt_PT.UTF-8, ro_RO.UTF-8, ru_RU.UTF-8, sk_SK.UTF-8, sl_SI.UTF-8, sr_YU.UTF-8, sv_SE.UTF-8, tr_TR.UTF-8, uk_UA.UTF-8, zh_CN.UTF-8, zh_HK.UTF-8, zh_TW.UTF-8 How to setup the encoding in PyCharm? Same is working fine from terminal directly. Edit 2 The Setting &gt; Edito…
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47573503
tagged with: pycharm
has title: Setting up the appropriate character encoding for a pipenv project in the pycharm console
has answer: http://stackoverflow.com/a/47573503
answer count: 1
linked to: http://stackoverflow.com/q/46251411
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86876701
linked to: http://stackoverflow.com/q/32234393
favorite count: 0
has comment: http://stackoverflow.com/comment/123053513
type: AnsweredQuestion
tagged with: pipenv

http://stackoverflow.com/comment/82254335
type: QuestionComment
has text: It should working nice, because `float64` for both `O` columns.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47647649

http://stackoverflow.com/comment/82297840
score: 0
type: AnswerComment
has text: I sense some problem with the input format. Try printing the row variable and update it. It should be easy to debug then. for row in f: print row and once you set columns_list, also print columns_list and you will know what all is happening.
type: Comment
comment on: http://stackoverflow.com/a/47669418

http://stackoverflow.com/q/47587448
downvote count: 0
tagged with: machine-learning
has title: Random Forest on Tensorflow at Google Cloud Datalab restarting kernel (Code not working)
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
has body: I am using the data from the following Kaggle competition to train Random Forest on Tensorflow - https://www.kaggle.com/c/santander-product-recommendation The code was working fine a day ago but now whenever I run the training code for the Random Forest: I get the following message (This is not an error message on the code but for the jupyter kernel): The kernel appears to have died. It will restart automatically. I am using the following code: import tensorflow as tf import numpy as np import pandas as pd import math import os from glob import glob import google.datalab.bigquery as bq print('Libraries Imported') trainingdata = bq.Query('SELECT * FROM `kagglesantander.training`') train_dataset = trainingdata.execute(output_options=bq.QueryOutput.dataframe()).result() print('Train Data Fetched') X = train_dataset.iloc[:,1:-1] y = train_dataset.iloc[:,-1] x_train = X.astype(np.float32).values y_train = y.astype(np.float32).values print('Data Prepared') params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams( num_classes=1, num_features=369, num_trees = 10).fill() print("Params =") print(vars(params)) # Remove previous checkpoints so that we can re-run this step if necessary. for f in glob("./ModelTrain/*"): os.remove(f) classifier = tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator( params, model_dir="./ModelTrain/") classifier.fit(x=x_train, y=y_train) print('Forest Trained') The error is happening due to the line: classifier.fit(x=x_train, y=y_train) As I tried the code without the line and it was working fine
type: UnansweredQuestion
tagged with: random-forest
tagged with: google-cloud-datalab
tagged with: python
answer count: 0
upvote count: 3

http://stackoverflow.com/comment/82159733
has text: `df.loc[df['Val1'] == 1]['Val2'].mean()` is probably a good start. Maybe look at grouping the values and you'll have your answer.
comment on: http://stackoverflow.com/q/47600529
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/82207700
type: Comment
type: AnswerComment
has text: Thanks, but would this work: if pygame.sprite.spritecollide(endpoint, self.image,True): print ("it works")
comment on: http://stackoverflow.com/a/47624869
score: 0

http://stackoverflow.com/comment/82334746
comment on: http://stackoverflow.com/q/47687656
score: 0
type: Comment
has text: Have your program `print(line)` right before the you `split` for every line. The last line it prints will be the problem line, and you can work out why it's happening.
type: QuestionComment

http://stackoverflow.com/a/47686265
has comment: http://stackoverflow.com/comment/82332177
score: 1
has comment: http://stackoverflow.com/comment/82332155
answers question: http://stackoverflow.com/q/47686224
has body: You can use the dict.get function to use a default value of 0 when the key is not found in d1: for key, val in d2.items(): d1[key] = d1.get(key, 0) + val
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/47604826
tagged with: k-means
tagged with: cluster-analysis
tagged with: python
accepted answer: http://stackoverflow.com/a/47606847
has body: As noted in the answer to this post about feature scaling, some(all?) implementations of KMeans are sensitive to the order of features data points. Based on the sklearn.cluster.KMeans documentation, n_init only changes the initial position of the centroid. This would mean that one must loop over a few shuffles of features data points to test if this is a problem. My questions are as follows: Is the scikit-learn implementation sensitive to the ordering as the post suggest? Does n_init take care of it for me? If I am to to it myself should I take the best based on minimum inertia or take an average as suggested here? Is there a good rule to know how many shuffle permutations is sufficient based on the number of data points? UPDATE: The question initially asked about feature(column) order which is not an issue. This was a misinterpretation of the term "objects" in the linked post. It has been updated to ask about the data points (rows) order.
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: scikit-learn
has title: Is sklearn.cluster.KMeans sensative to data point order?
has answer: http://stackoverflow.com/a/47606847
linked to: http://stackoverflow.com/q/20027645
favorite count: 0
type: Question

http://stackoverflow.com/q/47665784
tagged with: mysql
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47665818
score: 1
has body: I have this code in python querying an existing database: count = db.execute("SELECT COUNT (player_id) FROM players WHERE user_id = :id", id = session["user_id"]) for player in range(count): db.execute("INSERT INTO live_players (player_id) VALUES (:filler)", filler = 0) However, it doesn't run because 'count' isn't an int. I want SELECT COUNT to return 2, but instead it returns '[{'COUNT (player_id)': 2}]'. How could I remedy this?
upvote count: 1
has title: How to use SELECT COUNT sql to generate an int
tagged with: python

fedora
tags question: http://stackoverflow.com/q/47542282
tag name: fedora
type: Tag
tags question: http://stackoverflow.com/q/47614728
tags question: http://stackoverflow.com/q/47688474

http://stackoverflow.com/comment/82292331
has text: what 'i' ? the numbers list i used has the digit 1 (one)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47666514

http://stackoverflow.com/a/47579901
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: print(obj) just calls str(obj) and writes it to the sys.stdout. If you want to get hold of the same stringified representation, then you can just call str manually: my_string = str(dictionary) Source Additionally, str(obj) just calls obj.__str__(), so you can get the same behaviour if you do: my_string = dictionary.__str__() Interesting point: When you create your own class, you can actually override the default implementation of __str__ and define how you want your instance to be stringified/shown
answers question: http://stackoverflow.com/q/47579847

http://stackoverflow.com/q/47692213
has title: Reducing size of pyinstaller exe
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/47810133
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82594464
tagged with: pandas
has answer: http://stackoverflow.com/a/78915518
downvote count: 0
has comment: http://stackoverflow.com/comment/125701447
has answer: http://stackoverflow.com/a/47866840
tagged with: selenium
linked to: http://stackoverflow.com/q/62262398
linked to: http://stackoverflow.com/q/45722188
favorite count: 0
has comment: http://stackoverflow.com/comment/82594414
type: Question
upvote count: 81
has answer: http://stackoverflow.com/a/69059505
has comment: http://stackoverflow.com/comment/82667871
has answer: http://stackoverflow.com/a/47810359
has answer: http://stackoverflow.com/a/47810133
has comment: http://stackoverflow.com/comment/82667851
possible better answer: http://stackoverflow.com/a/47866840
tagged with: pyinstaller
has body: I have a simple pandas pyinstaller exe which is over 40MB. My exe example: import collections import csv import selenium import pandas print('hi') 40MB+ for this seems a bit overkill. How can I reduce this as much as possible? One method: pyinstaller --onefile --exclude matplotlib --exclude scipy --exclude pandas --exclude numpy.py This however is not practical considering how big the exclusion list would be. How do I select a folder for pyinstaller to get modules from and exclude everything else so I may have a small application? Spec file: a = Analysis(['123.py'], pathex=['C:\\Users\\AA\\ZZ'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='123', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) It's also worth mentioning. By default, Pyinstaller does not detect pandas. Add: hiddenimports = ['pandas._libs.tslibs.timedeltas'] To: C:\Users\&lt;NAME&gt;\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyInstaller\hooks A possible solution when using multiple executables, could be to link each executable to a separate folder or executable with all imports.
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/79241062
linked to: http://stackoverflow.com/q/47610050
score: 81

http://stackoverflow.com/a/47655660
accepted answer of: http://stackoverflow.com/q/47655454
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47655454
score: 5
has body: In general, in such cases you can always fire up your REPL and call help on trace_add to examine its docstring. &gt;&gt;&gt; from tkinter import StringVar &gt;&gt;&gt; help(StringVar.trace_add) For trace_add the following is stated: trace_add(self, mode, callback) Define a trace callback for the variable. Mode is one of "read", "write", "unset", or a list or tuple of such strings. Callback must be a function which is called when the variable is read, written or unset. Return the name of the callback. So, judging from that, 'wu' should now be ['write', 'unset'].

http://stackoverflow.com/q/47581768
has body: This should be an easy question but I really couldn't find a similar one.... I'm trying to scale each column of a data frame by subtracting the minimum of each column and divide by the scale. For R, I can do: apply(df,0,function(x) (x-min(x))/(max(x)-min(x))) The data frame are integers only: col1 col2 col3 1. 20 32 14 2. 15 33 67 3. 12 14 24 But pandas doesn't seem to do element wise division by default.
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47581842
tagged with: pandas
answer count: 1
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47581842
favorite count: 0
type: Question
tagged with: dataframe
has title: pandas element wise operation for each column
tagged with: python

http://stackoverflow.com/q/47621547
has title: Extract portion of a text from a web page
score: -5
accepted answer: http://stackoverflow.com/a/47621680
has body: Im trying to generate a list of getfile.do strings for a particular type of report - a "technical" report. The problem is that the report "type" is tagged at the end of the string, so the code should read the string and if the report tag checks out it should go back and extract the getfile.do (action). Here is a sample from the source webpage (WWW.SEDAR.COM) (there is a lot of unwanted stuff, but the below is one i do want. So if we read "Technical Report" in the code below, I want to extract the action information (so I can use it to download the document). The problem is that many of the page links are not relevant. FORM name="form1512323126173" action="/GetFile.do lang=EN&amp;docClass=24&amp;issuerNo=00021020&amp;issuerType=03&amp;projectNo=02627564&amp;d cId=4117642" method="post" target="AcceptTermsOfUse"P HREF="javascript:submitFiling(document.form1512323126173,'AcceptTermsOf use');"title="&amp;docClass=24&amp;issuerNo=00021020&amp;issuerType=03&amp;projectNo=026 7564&amp;docId=4117642"onmouseover="window.status='&amp;docClass=24&amp;issuerNo=000 1020&amp;issuerType=03&amp;projectNo=02627564&amp;docId=4117642';return true;"onmouseout="window.status='';return true;">Technical report (NI 43101) Below is an example, (on the same page) that Im not interested in: FORM name="form1512323126172" action="/GetFile.do lang=EN&amp;docClass=24&amp;issuerNo=00021020&amp;issuerType=03&amp;projectNo=02627564&amp;d cId=4117645" method="post" target="AcceptTermsOfUse"PA HREF="javascript:submitFiling(document.form1512323126172,'AcceptTermsOfU e');"title="&amp;docClass=24&amp;issuerNo=00021020&amp;issuerType=03&amp;projectNo=02627 64&amp;docId=4117645"onmouseover="window.status='&amp;docClass=24&amp;issuerNo=00021020&amp;issuerType=03&amp;projectNo=02627564&amp;docId=4117645';return true;" onmouseout="window.status='';return true;">Consent of qualified person(NI 43-101) So in conclusion from a web page scrape of the above, I would hope to see the output as follow: action="/GetFil…
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47621680
has comment: http://stackoverflow.com/comment/82201104
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82201498
upvote count: 0
answer count: 1
tagged with: javascript
favorite count: 0
type: Question

http://stackoverflow.com/comment/82057901
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47550126
type: QuestionComment
has text: The right way to leave `while(True)` loop is `break`. You should fix your codestyle so that one could understand what is going on and then use `break`.

http://stackoverflow.com/a/47694992
answers question: http://stackoverflow.com/q/47694795
has comment: http://stackoverflow.com/comment/82350127
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47694795
has body: you should indent the last 3 lines, so they're part of the iteration. It was only processing the last part after all the iterations were complete. for page in pages: response = get('http://www.sedar.com/FindCompanyDocuments.do?lang=EN&amp;page_no=' + page + '&amp;company_search=All+%28or+type+a+name%29&amp;document_selection=24&amp;industry_group=A&amp;FromDate=01&amp;FromMonth=01&amp;FromYear=2017&amp;ToDate=06&amp;ToMonth=12&amp;ToYear=2017&amp;Variable=DocType') page_html = BeautifulSoup(response.text, 'html.parser') for link in page_html.find_all('a'): print(link.get('title'))

http://stackoverflow.com/comment/82277907
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. Please provide examples of your input, your expected output, and your coding attempts so far..
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47659417

http://stackoverflow.com/comment/82206071
has text: Is there a `wsgi.py` file in `foodForThought`?
type: Comment
comment on: http://stackoverflow.com/q/47624099
score: 1
type: QuestionComment

http://stackoverflow.com/a/47650321
type: Answer
has comment: http://stackoverflow.com/comment/131183911
has comment: http://stackoverflow.com/comment/82339301
has body: Bendegúz Szatmári already answer the main question. I just want to let you know that use Process is not best idea in most of usage. Different process does not share memory with your program. You can not control them so easily as different thread. Here is simple example how you can Start end Stop different thread. from PyQt5 import QtWidgets from PyQt5.QtCore import * import sys import time class TTT(QThread): def __init__(self): super(TTT, self).__init__() self.quit_flag = False def run(self): while True: if not self.quit_flag: self.doSomething() time.sleep(1) else: break self.quit() self.wait() def doSomething(self): print('123') class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.btn = QtWidgets.QPushButton('run process') self.btn.clicked.connect(self.create_process) self.setCentralWidget(self.btn) def create_process(self): if self.btn.text() == "run process": print("Started") self.btn.setText("stop process") self.t = TTT() self.t.start() else: self.t.quit_flag = True print("Stop sent") self.t.wait() print("Stopped") self.btn.setText("run process") if __name__=="__main__": app=QtWidgets.QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_())
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/82314535
answers question: http://stackoverflow.com/q/47649159
upvote count: 6

http://stackoverflow.com/comment/82113634
type: AnswerComment
comment on: http://stackoverflow.com/a/47577661
has text: Hi @Amit Tripathi, sorry I missed a problem, how can I pass a list of `instance[i].call_method` to `multi_process `?
score: 0
type: Comment

http://stackoverflow.com/a/47682534
answers question: http://stackoverflow.com/q/47681761
has body: I would like recreate the df, you can add the reset_index() at the end pd.DataFrame(df.iloc[:,1:].values.reshape(8,2),index=['','ex_']*4+df.name.repeat(2),columns=['value1','value2']) Out[986]: value1 value2 name jim 0.400000 0.600000 ex_jim 0.700000 0.300000 tim 0.200000 0.800000 ex_tim 0.766667 0.233333 john 1.000000 0.000000 ex_john 0.500000 0.500000 paul 0.900000 0.100000 ex_paul 0.533333 0.466667
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82324481
has comment: http://stackoverflow.com/comment/82324877
type: Answer

http://stackoverflow.com/q/47587961
downvote count: 0
linked to: http://stackoverflow.com/q/47573523
upvote count: 1
has title: By adding one statement import pyodbc causes Internal Server Error in Apache HTTP Server
favorite count: 0
type: Question
tagged with: django-pyodbc
type: UnansweredQuestion
tagged with: django-pyodbc-azure
tagged with: apache
tagged with: python
tagged with: pyodbc
answer count: 0
has body: To run the normal school old python file in Apache Server. I had coded this way index.html First Name: Last Name: hello_get.py #!C:/Users/Desktop/AppData/Local/Programs/Python/Python36-32/python # Import modules for CGI handling import cgi, cgitb import pyodbc # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print("Content-Type:text/html\r\n\r\n") print(" ") print(" ") print(" Hello - Second CGI Program ") print(" ") print(" ") print(" Hello %s %s " % (first_name, last_name)) print(" ") print(" ") I have tried to run in python shell. It perfectly works Also in httpd.conf file: LoadModule pyodbc_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd" Results httpd: Syntax error on line 571 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error So How do I need to import pyodbc in .py file as well as how to load pyodbc module in Apache HTTP server? As @FlipperPA said to load mod_wsgi module in this link Click Here C:\>pip install mod_wsgi-4.5.22+ap24vc9-cp27-cp27m-win32.whl C:\Windows\system32>pip install htmlpy Collecting htmlpy Downloading htmlPy-2.0.3.tar.gz Installing collected packages: htmlpy Running setup.py install for htmlpy ... done Successfully installed htmlpy-2.0.3 Also in httpd.conf file: LoadFile "c:/users/desktop/appdata/local/programs/python/python36-32/python36.dll" LoadModule wsgi_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd" LoadModule pyodbc_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd" WSGIPythonHome "c:/users/vitriv-desktop/appdata/local/programs/python/python36-32" This is test_wsgi.py #!C:/Users/AppD…
score: 1

http://stackoverflow.com/comment/82076124
type: Comment
type: QuestionComment
score: 0
has text: Tom -- 1.) I do not know the difference between looping over the 'raw' lines and using the csv.reader function. I will look at some documentation 2.) Ok, The extra double quotes are coming from the sequential key... I will update that. I am new to programming, How can i remove the "\n" after each dictionary entry? Would not removing the trailing newline have negative effects later? I am curious and uneducated.
comment on: http://stackoverflow.com/q/47557614

http://stackoverflow.com/comment/107412898
has text: you may want deepcopy instead to avoid conflicts. https://docs.python.org/3/library/copy.html#copy.deepcopy
comment on: http://stackoverflow.com/a/47557217
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47684719
tagged with: django-forms
type: Question
accepted answer: http://stackoverflow.com/a/47685059
has body: I am trying to have users enter data in a django form and only allow ONE entry into the database per each time slot and day slot. Example: User fills out form to "sign up" to speak during 8:00am - 9:00am on Day 1 for schedule id 2. If a database entry already exists with the same TIMESLOT and DAYSLOT, I want to raise an error and prevent entry. Here is what I have so far, but the filter is spanning across the entire table rather than just filtering per schedule ID... models.py from django.db import models import datetime class Schedule(models.Model): title = models.CharField(max_length=250) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Agenda(models.Model): dayChoice = ( ('d1', "Day 1"), ('d2', "Day 2"), ('d3', "Day 3"), ('d4', "Day 4") ) fullName = models.CharField(max_length=250) startTime = models.TimeField(auto_now=False, blank=True, null=True) endTime = models.TimeField(auto_now=False, blank=True, null=True) approved = models.BooleanField(blank=True) daySlot = models.CharField(max_length=2, choices=dayChoice) sub_date = models.DateTimeField(auto_now=True) scheduler = models.ForeignKey(Schedule, on_delete=models.CASCADE) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.fullName views.py from django.shortcuts import render, redirect from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Schedule, Agenda from .forms import AgendaForm # Create your views here. def schedule_list(request): schedules = Schedule.objects.all() return render(request, 'adjenda/schedule_list.html', {'schedules': schedules}) def agenda_detail(request, pk): schedules = get_object_or_404(Schedule, pk=pk) agenda = Agenda.objects.filter(scheduler_id=pk).order_by('startTime') form = AgendaForm(request.POST) if request.method == "POST": form = AgendaForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author …
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
tagged with: django-views
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47685059
has title: Trying to prevent multiple form entries with identical field data (only allow first user to take timeslot)

http://stackoverflow.com/q/47548289
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: nearest-neighbor
favorite count: 0
has answer: http://stackoverflow.com/a/47568256
type: Question
tagged with: algorithm
tagged with: annoy
has body: Can I use spotify's "Annoy" package to query points within radius r https://github.com/tjrileywisc/annoy I coudn't find any relevant function call in the implementation on their github page. I have used Kd-tree using query ball point for such problem. But since annoy is faster and I have to query billions of points, I am wondering if its possible to using this package
tagged with: python
accepted answer: http://stackoverflow.com/a/47568256
has title: Querying the "Annoy" index for all the points within radius r

http://stackoverflow.com/comment/82333467
score: 0
has text: In the future, you should provide the error messages when something "doesn't work"; otherwise, your question is likely to be closed.
comment on: http://stackoverflow.com/q/47637070
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47644077
has body: I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong. l = [[2,3],[5,6],[4,8]] for item in l: print(item[0], end = ' ') for obj in l: print(obj[1], end = ' ')
tagged with: python
has title: Printing items from a list in Python
has answer: http://stackoverflow.com/a/47644378
score: 0
tagged with: list
tagged with: printing
has answer: http://stackoverflow.com/a/47644124
has answer: http://stackoverflow.com/a/47644163
answer count: 7
has answer: http://stackoverflow.com/a/47644139
has answer: http://stackoverflow.com/a/47644177
type: Question
has answer: http://stackoverflow.com/a/47644141
has answer: http://stackoverflow.com/a/47646768
has comment: http://stackoverflow.com/comment/82246893
type: UnansweredQuestion

http://stackoverflow.com/a/47653980
has comment: http://stackoverflow.com/comment/82268171
answers question: http://stackoverflow.com/q/47653668
has comment: http://stackoverflow.com/comment/82266885
has comment: http://stackoverflow.com/comment/82267281
accepted answer of: http://stackoverflow.com/q/47653668
type: Answer
has comment: http://stackoverflow.com/comment/82268558
has comment: http://stackoverflow.com/comment/82266727
has comment: http://stackoverflow.com/comment/82271464
has body: The conv2d operation sums over the channels of your input. Thus, initialising the kernel with ones will give you identical output channels, each of which is the sum over your input channels. Note that unless you set the bias_initializer to zero or set the use_bias parameter to False, the randomly-initialised bias will also affect your output. import tensorflow as tf import numpy as np with tf.Graph().as_default(): x = tf.placeholder(tf.float32, [None, 500, 500, 3]) y = tf.layers.conv2d(x, 3, 1, padding='same', use_bias=False, kernel_initializer=tf.ones_initializer()) sess = tf.Session() sess.run(tf.global_variables_initializer()) # Evaluate np.random.seed(1) _x = np.random.uniform(0, 1, (1, 500, 500, 3)) _y = sess.run(y, {x: _x}) # Check that the channels are identical np.testing.assert_allclose(_y[..., 0], _y[..., 1]) # Check that each channel is the sum over channels np.testing.assert_allclose(_y[..., 0], _x.sum(axis=-1), rtol=1e-5)
score: 0
has comment: http://stackoverflow.com/comment/82267451
has comment: http://stackoverflow.com/comment/82268335
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82267416

http://stackoverflow.com/q/47547169
has body: I am making a Twitter sentiment analysis. After cleaning the tweets, when I try to write tweets into .txt file from .csv it writes only first tweets in text file and repeats until the end. Consider the following code f = open('PanamaCase.csv', 'r') with f: reader = csv.DictReader(f) i=0 for row in reader: row=str(row['Tweets']) #print(type(row)) print(clean(row)) txt = open('cleanedTweets.txt','w') #line = 0 with txt: reader2 = csv.DictReader(f) for line in reader2: txt.write(clean(row) + "\n")
accepted answer: http://stackoverflow.com/a/47548549
tagged with: http://stackoverflow.com/tag/csv
tagged with: io
tagged with: python
has comment: http://stackoverflow.com/comment/82052761
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82051111
score: 0
has answer: http://stackoverflow.com/a/47548549
has comment: http://stackoverflow.com/comment/82050933
has comment: http://stackoverflow.com/comment/82051291
answer count: 1
has comment: http://stackoverflow.com/comment/82051532
has comment: http://stackoverflow.com/comment/82050852
has title: Repeat first line on whole text file using python
type: Question
has comment: http://stackoverflow.com/comment/82051009
has comment: http://stackoverflow.com/comment/82050961

dbus
type: Tag
tags question: http://stackoverflow.com/q/47668125
tag name: dbus
tags question: http://stackoverflow.com/q/47647200

http://stackoverflow.com/comment/82300051
comment on: http://stackoverflow.com/a/47670530
score: 0
type: Comment
has text: if I understand your answer correctly, when you call `@login_manager.user_loader`, it will automatically search for a user_id, and if not found, will clear its `session` variable ?
type: AnswerComment

http://stackoverflow.com/comment/82265986
has text: May I ask how to change the gender 0 and 1 into female and male?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47652065

http://stackoverflow.com/a/47634117
answers question: http://stackoverflow.com/q/47633919
has body: You can use the below code: Code: from nltk.stem import PorterStemmer stemmer = PorterStemmer() List = ['work','worked','working','play'] List = [stemmer.stem(token) for token in List] List1=[] for token in List: if token not in List1: List1.append(token) Output: ['work', 'play']
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82778790
has comment: http://stackoverflow.com/comment/82775028
has comment: http://stackoverflow.com/comment/82774847
has comment: http://stackoverflow.com/comment/82774706
type: Answer

http://stackoverflow.com/a/47737210
upvote count: 1
answers question: http://stackoverflow.com/q/47618944
has body: How about splitting a string of all the numbers at zero and finding the max length of the resultant elements. &gt;&gt;&gt; a_list = [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0] &gt;&gt;&gt; max(''.join(map(str, a_list)).split('0')) '1111' &gt;&gt;&gt; len(max(''.join(map(str, a_list)).split('0'))) 4 &gt;&gt;&gt; ones = [1, 1, 1] &gt;&gt;&gt; max(''.join(map(str, ones)).split('0')) '111' &gt;&gt;&gt; len(max(''.join(map(str, ones)).split('0'))) 3 Edit: I like Stefan Pochmann's answer in the comments here: len(max(bytes(a_list).split(b'\0')))
type: Answer
has comment: http://stackoverflow.com/comment/82934641
downvote count: 0
score: 1

http://stackoverflow.com/q/47613053
tagged with: python
has comment: http://stackoverflow.com/comment/82184507
has comment: http://stackoverflow.com/comment/82185862
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82184552
type: Question
has title: Python: how to install pymumps?
has comment: http://stackoverflow.com/comment/82185831
has comment: http://stackoverflow.com/comment/82186791
type: UnansweredQuestion
has body: I am trying to use pymumps. what i did: i am following the instructions here: https://pypi.python.org/pypi/PyMUMPS 1- i installed mpi4py 2- i installed mumps library using (not required. this is mumps library) apt-get instal libmumps-scotch-dev 3- i did settup of pymumps using: python setup.py install 4- i put the folder mumps( which contained the installation) inside my project as shown below so this should install pymumps locally. the folder mumps is as follows: Now it is time to test it in the python interpreter when i do import mumps i got this error: Traceback (most recent call last): File "", line 1, in File "/opt/scripts/mumps/init.py", line 2, in import _dmumps ModuleNotFoundError: No module named '_dmumps'
has comment: http://stackoverflow.com/comment/82184578
has comment: http://stackoverflow.com/comment/82185921

http://stackoverflow.com/comment/82202256
has text: Have you even tried your suggestion yourself? It gives `jinja2.exceptions.UndefinedError: '__main__.FooForm object' has no attribute 'bar_field' `
comment on: http://stackoverflow.com/a/47621952
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82095516
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47568835
type: QuestionComment
has text: This might be of use: https://stackoverflow.com/questions/477061/how-to-read-unicode-input-and-compare-unicode-strings-in-python. The trick is to try and determine the encoding used by your terminal, if using your application through such. That boils down to: you should always know your input's encoding.

http://stackoverflow.com/q/47615106
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47615260
score: 1
has answer: http://stackoverflow.com/a/47615260
tagged with: python
tagged with: kivy
has body: When I use DraggableImage class (a class which inherits DragBehavior and Image) with on_touch_up, once I dragged and dropped a image, the image cannot be dragged anymore. I don't know why this happens and how to fix. from kivy.app import App from kivy.uix.behaviors import DragBehavior from kivy.uix.image import Image class DraggableImage(DragBehavior, Image): def on_touch_up(self, touch): # without this (e.g. "pass" here), image is always draggable. print("This is test") class TestApp(App): def build(self): pass if __name__ == '__main__': TestApp().run() test.kv BoxLayout: DraggableImage: source: "example.png"
type: AnsweredQuestion
tagged with: python-3.x
answer count: 1
downvote count: 0
upvote count: 1
has title: DragBehavior only work for the first time with on_touch_up in Kivy

http://stackoverflow.com/q/47584738
type: Question
has body: I'm trying to use the Stanford Parser through NLTK, following the example here. I follow the first two lines of the example (with the necessary import) from nltk.parse.corenlp import CoreNLPDependencyParser dep_parser = CoreNLPDependencyParser(url='http://localhost:9000') parse, = dep_parser.raw_parse('The quick brown fox jumps over the lazy dog.') but I get an error saying: [...] Failed to establish a new connection: [Errno 61] Connection refused" I realize that it must be an issue with trying to connect to the url given as input to the constructor. dep_parser = CoreNLPDependencyParser(url='http://localhost:9000') What url should I be connecting to, if not this? If this is correct, what is the issue?
tagged with: stanford-nlp
tagged with: nltk
accepted answer: http://stackoverflow.com/a/50832258
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50832258
answer count: 1
has title: NLTK CoreNLPDependencyParser: Failed to establish connection
downvote count: 0
tagged with: nlp
favorite count: 0

http://stackoverflow.com/q/47639215
score: 0
possible better answer: http://stackoverflow.com/a/47639325
tagged with: range
tagged with: python
has answer: http://stackoverflow.com/a/47639325
tagged with: indexing
tagged with: recursion
type: Question
has comment: http://stackoverflow.com/comment/82236785
has title: "IndexError: list index out of range" While using recursion on lists
accepted answer: http://stackoverflow.com/a/47640499
has comment: http://stackoverflow.com/comment/82236908
has answer: http://stackoverflow.com/a/47640499
answer count: 2
tagged with: for-loop
type: AnsweredQuestion
has body: I'm a programming student and I have just recently started working in Python. I started with learning Rackett which has a very different approach. While trying to use recursion in combination with a for statement I ran into "IndexError: list index out of range". This is my code: def search_matching_pokemon(p, l): lp = [] for i in range(len(l) - 1): if p[-1] == l[i][0]: print ('Found one') poke = l.pop(i) lp = lp + [poke] print (f'List is now {lp}') search_matching_pokemon(poke, l) #problem with the range else: print ('Trying a different pokémon') return lp I think my function doesn't take the reduced list when recursing, at least not during the range(len(l) - 1) Help would be very much appreciated, thank you in advance.

attributeerror
tags question: http://stackoverflow.com/q/47585906
tags question: http://stackoverflow.com/q/47541125
tags question: http://stackoverflow.com/q/47551392
tag name: attributeerror
type: Tag
tags question: http://stackoverflow.com/q/47619074
tags question: http://stackoverflow.com/q/47557905
tags question: http://stackoverflow.com/q/47677241
tags question: http://stackoverflow.com/q/47595011
tags question: http://stackoverflow.com/q/47599527
tags question: http://stackoverflow.com/q/47574056

http://stackoverflow.com/comment/82282651
has text: Please include your output in your question, not as a link to a screenshot.
type: QuestionComment
comment on: http://stackoverflow.com/q/47661686
type: Comment
score: 0

http://stackoverflow.com/q/47564437
accepted answer: http://stackoverflow.com/a/47572638
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47572922
has answer: http://stackoverflow.com/a/47572638
has body: I'm new to protobuf. I need to serialize complex graph-like structure and share it between C++ and Python clients. I'm trying to apply protobuf because: It is language agnostic, has generators both for C++ and Python It is binary. I can't afford text formats because my data structure is quite large But Protobuf user guide says: Protocol Buffers are not designed to handle large messages. As a general rule of thumb, if you are dealing in messages larger than a megabyte each, it may be time to consider an alternate strategy. https://developers.google.com/protocol-buffers/docs/techniques#large-data I have graph-like structures that are sometimes up to 1 Gb in size, way above 1 Mb. Why protobuf is bad for serializing large datasets? What should I use instead?
has comment: http://stackoverflow.com/comment/129382366
type: AnsweredQuestion
tagged with: protocol-buffers
score: 39
upvote count: 39
favorite count: 0
tagged with: c++
type: Question
answer count: 2
has title: Why protobuf is bad for large data structures?
possible better answer: http://stackoverflow.com/a/47572922

http://stackoverflow.com/q/47570929
answer count: 1
has answer: http://stackoverflow.com/a/47571228
has body: I have a txt file as follows, #onetwothree.txt &gt;one QWERTYUIOP &gt;two ASDFGHJKL &gt;three ZXCVBNM ... and I want to split that txt file into several files as follows, #one.txt &gt;one QWERTYUIOP and #two.txt &gt;two ASDFGHJKL and #three.txt &gt;three ZXCVBNM here is the code I worte, import re with open("onetwothree.txt") as file: name=re.findall(r'\&gt;[^\n]+',file.read()) sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read()) . . . I know that there is something wrong in following part. sequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read()) I want to make a list using re.findall,enumerate and following list is what I want to get. &gt;&gt;&gt;print (seq) ["QWERTYUIOP","ASDFGHJKL","ZXCVBNM"] how can I fix this codesequence=re.findall(r'name[ind][^/n]+' for ind in enumerate(name), file.read()) right?
type: Question
tagged with: enumerate
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47571228
tagged with: python
tagged with: regex
has title: how to use enumerate with regex(findall) in python?

http://stackoverflow.com/comment/82129912
type: QuestionComment
comment on: http://stackoverflow.com/q/47585856
score: 0
has text: Your previous question told you to use load function by the way ... https://stackoverflow.com/questions/47579348/python-json-to-csv
type: Comment

http://stackoverflow.com/comment/101541149
type: Comment
type: QuestionComment
has text: You might be interested in [`mpu.datastructures.Interval`](https://mpu.readthedocs.io/en/latest/datastructures.html#mpu.datastructures.Interval)
comment on: http://stackoverflow.com/q/47664319
score: 0

http://stackoverflow.com/q/47691724
has title: half yearly colorbar in matplotlib and pandas
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/47694138
has body: I have a panda dataframe. I am making scatter plot and tried to categorize the data based on colorbar. I did it for monthly classification and quality classification as shown in the example code below. a = np.random.rand(366) b = np.random.rand(366)*0.4 index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366)) df = pd.DataFrame({'a':a,'b':b},index = index) plt.scatter(df['a'],df['b'],c = df.index.month) plt.colorbar() And also for quality: plt.scatter(df['a'],df['b'],c = df.index.quarter) plt.colorbar() My question: is there any way to categorize by half yearly. for example from the month 1-6 and 7-12 and also by month like: 10-3 and 4-9 Thank you and your help/suggestion will be highly appreciated.
favorite count: 0
accepted answer: http://stackoverflow.com/a/47693367
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47694138
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47693367
score: 2
type: AnsweredQuestion
tagged with: datetimeindex
tagged with: pandas

http://stackoverflow.com/a/47683831
has comment: http://stackoverflow.com/comment/82327474
answers question: http://stackoverflow.com/q/47683244
has comment: http://stackoverflow.com/comment/82327538
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47683244
score: 0
type: Answer
has body: Two problems: You are only handling addition of a complex object to a complex object, when you want to also be able to handle complex object + int. When adding in this order (int + custom type), you need to add a reflected addition method (__radd__) class complex: def __init__(self, a = 0, b = 0): self.__real = float(a) self.__imag = float(b) def __add__(self, other): if isinstance(other, complex): return complex(self.__real + other.__real, self.__imag + other.__imag) else: return complex(self.__real + other, self.__imag) def __radd__(self, other): return self + other N.B.: It is considered bad style to shadow built-in names (like complex).

http://stackoverflow.com/comment/82211184
score: 0
type: Comment
type: AnswerComment
has text: I don't understand why people down vote even if answer is correct , might not be the best but it serves the purpose
comment on: http://stackoverflow.com/a/47616202

http://stackoverflow.com/a/47614828
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82188245
has body: unicode is python 2.x method. If you are running Python 3.x, then all strings are unicode and that call is not needed. https://docs.python.org/3/howto/unicode.html
accepted answer of: http://stackoverflow.com/q/47614742
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47614742

http://stackoverflow.com/comment/82322717
type: AnswerComment
type: Comment
has text: Is Python telling you there's an error or is PyCharm telling you there's an error
comment on: http://stackoverflow.com/a/47678467
score: 0

http://stackoverflow.com/comment/82040784
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47541183
has text: And https://pythonnet.github.io/

http://stackoverflow.com/q/47692062
score: 1
has comment: http://stackoverflow.com/comment/82356573
tagged with: python
type: Question
has title: Determine the camera trigger delay of see3cam
has comment: http://stackoverflow.com/comment/82343883
answer count: 0
has comment: http://stackoverflow.com/comment/82345093
type: UnansweredQuestion
tagged with: opencv
downvote count: 0
tagged with: delay
upvote count: 1
tagged with: triggers
has comment: http://stackoverflow.com/comment/82392237
favorite count: 0
has body: I have an application where I need to take a picture at a very specific moment when another program gives the command. As the camera needs to be very light, I bought the see3cam_CU135 from e-con systems. I was planning on running the camera with python and having python wait for the command from the other program. The delay between triggering and the actual exposure is essential to know and so far, I haven't been very successful in finding out what it is. Here's my setup to figure out the delay: I run a separate script that acts as stopwatch, printing the clock of my system to my screen: import time while True: print(time.time()) time.sleep(0.001) Then I run my actual script that takes the picture of the output of the first script. import cv2 import time vc = cv2.VideoCapture(1) vc.set(cv2.CAP_PROP_FRAME_WIDTH,4208) vc.set(cv2.CAP_PROP_FRAME_HEIGHT,3120) vc.set(cv2.CAP_PROP_EXPOSURE,-2) if vc.isOpened(): # try to get the first frame t1=time.time() while int(time.time()) == int(t1): a=0 rval, frame = vc.read() print(t1) cv2.imwrite("photo.png", frame) else: rval = False vc.release() If I start the script at a time of, let's say 1512638235.3549826, the program should stay in the while loop until the next full second starts, 1512638236, and then trigger the picture, right? So the time on the picture minus the full second after t1 should give me the delay. So far so good, but here's what's weird: yesterday I ran it, and t1 was 1512579170.079795. So the script should wait almost a second, then trigger the picture. However, the picture of the stopwatch showed 1512579170.588795 (half a second before the trigger command would have been sent). Is it possible that vc.read does not actually trigger a frame, but just reads whatever frame is currently in the buffer of the camera and, therefore, returned an older frame? If so, how can I trigger a frame manually exactly when I want it? A second question I have here is the white balance issue with OpenCV. Apparently it is not possi…
has comment: http://stackoverflow.com/comment/82356699
tagged with: camera

http://stackoverflow.com/a/47611801
answers question: http://stackoverflow.com/q/47611720
score: 0
type: Answer
has body: You want to only have one while loop in which every requirement is checked. See the following code: valid_password = False while not valid_password: new_password = input("Please enter your new password: ") new_password2 = input("Please enter your new password again: ") if new_password != new_password2: print("The passwords don't match up.") continue elif len(new_password) &lt; 8: print("Your password must be longer") continue elif new_password.upper() == new_password or new_password.lower() == new_password: print("Your password must contain at least one lowercase and uppercase letter") continue else: print("Password Accepted!") valid_password = True Hope this helps!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47611720
has comment: http://stackoverflow.com/comment/82181869

http://stackoverflow.com/comment/82148972
type: AnswerComment
has text: I dont think so, because for Row 5 A = 2 and for Row 3 and 4 A = 1. 2.5 is from Row 0 - 2 where A = 0. Or am I missing sth?
type: Comment
comment on: http://stackoverflow.com/a/47594506
score: 0

http://stackoverflow.com/comment/82223435
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47632288
has text: I got database locked error, that’s why I’m looking for other solution.
score: 0

http://stackoverflow.com/q/47665760
favorite count: 0
has answer: http://stackoverflow.com/a/47666357
has answer: http://stackoverflow.com/a/74286115
type: Question
has answer: http://stackoverflow.com/a/66283705
tagged with: python-3.x
has title: No module named 'websocket'
has answer: http://stackoverflow.com/a/76998727
downvote count: 0
tagged with: websocket
has answer: http://stackoverflow.com/a/73229167
has answer: http://stackoverflow.com/a/68106107
upvote count: 17
has answer: http://stackoverflow.com/a/70208712
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76232091
possible better answer: http://stackoverflow.com/a/66328894
has comment: http://stackoverflow.com/comment/82294922
has body: I'm a fairly new to Python and I am trying to enter the following code: from websocket import create_connection as cc import json, time I want to look at BTC and LTC stocks in a live feed type-fashion but I keep getting this error: ModuleNotFoundError: No module named 'websocket' I've been looking around and it seems that a common solution is: pip install websocket that just didn't connect with me. Most sites say install this and just have the above code but I have no idea where to install it or what to do with it.
answer count: 10
tagged with: python
score: 17
accepted answer: http://stackoverflow.com/a/47666357
has answer: http://stackoverflow.com/a/66328894
has answer: http://stackoverflow.com/a/64993334

http://stackoverflow.com/q/47580866
has body: So I created a test dataset that looks like this INDEX YEAR_ID GAME_ID BAT_TEAM_ID INN_CT EVENT_CD INN_PA_CT wBB wHBP w1B 0 2016 1 ANN 1 1 0 0.691 0.721 0.878 1 2016 1 ANN 1 3 1 0.691 0.721 0.878 2 2016 1 ANN 2 3 0 0.691 0.721 0.878 3 2016 1 ANN 2 1 1 0.691 0.721 0.878 4 2016 1 CLE 2 2 0 0.691 0.721 0.878 5 2016 1 CLE 2 2 1 0.691 0.721 0.878 6 2016 2 KCA 1 1 0 0.691 0.721 0.878 7 2016 2 KCA 1 1 1 0.691 0.721 0.878 8 2016 2 KCA 1 3 2 0.691 0.721 0.878 9 2016 2 KCA 1 2 3 0.691 0.721 0.878 10 2016 2 TEX 1 1 0 0.691 0.721 0.878 11 2016 2 TEX 1 1 1 0.691 0.721 0.878 12 2016 2 TEX 1 2 2 0.691 0.721 0.878 13 2016 2 TEX 1 1 3 0.691 0.721 0.878 14 2016 2 KCA 2 2 0 0.691 0.721 0.878 15 2016 2 KCA 2 2 1 0.691 0.721 0.878 and I've defined a function to calculate some statistic: def woba(x): return ((((x['EVENT_CD'] == 1).sum() * x['wBB']) + ((x['EVENT_CD'] == 2).sum() * x['wHBP']) + ((x['EVENT_CD'] == 3).sum() * x['w1B'])) / (x['INN_PA_CT'].max())) stat = df.groupby(['BAT_TEAM_ID', 'GAME_ID', 'INN_CT']).apply(woba) stat = stat.reset_index(level = ['BAT_TEAM_ID', 'GAME_ID', 'INN_CT']) stat.columns = ['BAT_TEAM_ID', 'GAME_ID', 'INN_CT', 'wOBA'] and the function works, it returns the values I want, but for some reason there are duplicates in the result INDEX BAT_TEAM_ID GAME_ID INN_CT wOBA 0 ANN 1 1 1.569 1 ANN 1 1 1.569 2 ANN 1 2 1.569 3 ANN 1 2 1.569 4 CLE 1 2 1.442 5 CLE 1 2 1.442 6 KCA 2 1 0.993666667 7 KCA 2 1 0.993666667 8 KCA 2 1 0.993666667 9 KCA 2 1 0.993666667 14 KCA 2 2 1.442 15 KCA 2 2 1.442 10 TEX 2 1 0.931333333 11 TEX 2 1 0.931333333 12 TEX 2 1 0.931333333 13 TEX 2 1 0.931333333 when there should only be 6 rows. What went wrong, or how do I fix this?
has answer: http://stackoverflow.com/a/47581227
has comment: http://stackoverflow.com/comment/82119690
accepted answer: http://stackoverflow.com/a/47581227
tagged with: function
tagged with: duplicates
tagged with: python
has title: Python: Function Returning Duplicate Values
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82119563
has comment: http://stackoverflow.com/comment/82119693
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82119372
answer count: 1
has comment: http://stackoverflow.com/comment/82119920
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82119991

http://stackoverflow.com/a/60416658
score: -1
has body: to add automatic comma between each object and add brackets in file to make it complete json just write a simple jq query jq -s '.' file_name
answers question: http://stackoverflow.com/q/47675367
upvote count: 0
downvote count: 1
type: Answer

http://stackoverflow.com/a/67897715
has comment: http://stackoverflow.com/comment/120012434
has body: Install sqlite3 for nodejs using this command npm install https://github.com/mapbox/node-sqlite3/tarball/master
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47616490
type: Answer
score: 0

http://stackoverflow.com/q/47664509
type: UnansweredQuestion
has body: hi I am having trouble with this one problem Given a variable, polygon_sides, that is associated with a dictionary that maps names of polygons to number of sides, create a new dictionary that maps number of sides to polygon names, and associate it with a variable n_polygons. my current code for n_polygons in polygon_sides: polygon_sides={n_polygons[]:polygon_sides} the only error it gives me are syntax errors. do i have to rearrange the whole problem??
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82288305
score: -3
has comment: http://stackoverflow.com/comment/82288341
has answer: http://stackoverflow.com/a/47664550
answer count: 2
upvote count: 0
tagged with: polygons
has title: Polygons and keys
downvote count: 3
has answer: http://stackoverflow.com/a/47664577
favorite count: 0
type: Question

http://stackoverflow.com/comment/82061967
has text: @hspandher I updated.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47552490

http://stackoverflow.com/comment/82127470
type: QuestionComment
comment on: http://stackoverflow.com/q/47584852
score: 0
has text: what output did you expect ? Output is correct with code but it seems code is not correct with your expectation. Maybe put more `print()` inside to see what's going on in code.
type: Comment

http://stackoverflow.com/comment/82342831
comment on: http://stackoverflow.com/q/47691916
type: Comment
has text: You are deleting...and then trying to access?
score: 0
type: QuestionComment

http://stackoverflow.com/q/47598617
has answer: http://stackoverflow.com/a/47598721
upvote count: 1
has answer: http://stackoverflow.com/a/47598723
has comment: http://stackoverflow.com/comment/82155460
has answer: http://stackoverflow.com/a/47598780
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47598721
possible better answer: http://stackoverflow.com/a/47598723
has title: Why do we not need "else" in an if-statement if it contains "return"?
has body: I'm a beginner in Python, and I can't understand why we don't have to use else in cases like the one below: def find_element(p,t): i=0 while i&lt;len(p): if p[i]==t: return i i=i+1 return -1 In this code I thought I should use else return -1 if I wanted to return -1, but it seems that python understands this without else like in the code above.
tagged with: python
has comment: http://stackoverflow.com/comment/82155465
has comment: http://stackoverflow.com/comment/82155530
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/47598737

http://stackoverflow.com/a/48638340
answers question: http://stackoverflow.com/q/47574624
type: Answer
score: 0
has body: Did you configure HADOOP_CONF_DIR or YARN_CONF_DIR properly? This directory should contain client configs of hdfs and yarn service. So that spark application can get resources from Yarn and applications can perform read/write operation to HDFS. Kindly check the doc given below which gives you info about prerequisites to be followed for spark on yarn. https://spark.apache.org/docs/2.1.1/running-on-yarn.html If you deploy spark from cloudera manager or ambari server, All environment variables associated with the client configuration will be deployed by itself.

http://stackoverflow.com/a/47556546
has comment: http://stackoverflow.com/comment/99924649
has comment: http://stackoverflow.com/comment/92903458
has comment: http://stackoverflow.com/comment/94890376
accepted answer of: http://stackoverflow.com/q/47556025
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47556025
downvote count: 4
upvote count: 3
has comment: http://stackoverflow.com/comment/92298860
type: AcceptedAnswer
has body: Try: (Documentation) from pyspark.sql import Row newDf = sc.parallelize([Row(id='ID123')]).toDF() newDF.show()

http://stackoverflow.com/a/51856453
answers question: http://stackoverflow.com/q/47551733
accepted answer of: http://stackoverflow.com/q/47551733
type: AcceptedAnswer
score: 0
type: Answer
has body: Although noone answered I found a workaround which avoided the fsolve function and used interpolation instead. Luckily the initial guess is good enough that only a few y values are needed. If the initial guess knowledge is poor then this method is probably not appropriate. Do note this still has some issues but for my purposes it performs well... ystar = np.empty((A,B)) # empty array for the solutions num_ys = 20 #number of points to find where the solution is y0_u = y0 #just so the calculated initial guess isn't overwritten for i in range(Thetas.shape[1]): ys = np.linspace(-.05,.2,num_ys)[:,None]*np.ones((num_ys,Thetas.shape[0])) + y0_u vals = (np.squeeze(eta) - np.squeeze(m)*ys*np.sqrt(g*np.tanh(ys**2*depth)) - np.squeeze(md)*np.sqrt(g*np.tanh(depth*np.sqrt(ys**4+2*(ys**2)*kB*np.cos(Thetas[:,i]+phi_bi)+kB**2)))*(( ys**4+2*(ys**2)*kB*np.cos(Thetas[:,i]+phi_bi)+kB**2 )**0.25)) idxs_important = -1*(np.clip(np.vstack(((np.sign(vals[:-1]*vals[1:])-1),np.zeros((1,Thetas[:,i].size)))),-1,0) + np.clip(np.vstack((np.zeros((1,Thetas[:,i].size)),(np.sign(vals[:-1]*vals[1:]))-1)),-1,0)) ys_chosen = idxs_important*ys ys_chosen[ys_chosen==0] = 10000 sorted_ys_idx = np.argsort(ys_chosen.T, axis = 1) sorted_ys = ((ys_chosen.T)[np.arange(np.shape(ys_chosen.T)[0])[:,np.newaxis],sorted_ys_idx]).T sorted_vals = (((vals*idxs_important).T)[np.arange(np.shape(vals.T)[0])[:,np.newaxis],sorted_ys_idx]).T # interpolation bit x_id = 0 yposs = sorted_ys[:2,:] valposs = sorted_vals[:2,:] y = yposs[0,:] + (yposs[1,:] - yposs[0,:])*(x_id - valposs[0,:])/(valposs[1,:] - valposs[0,:]) ystar[:,i] = np.squeeze(y) y0_u=ystar[:,i]

dataframe
tags question: http://stackoverflow.com/q/47680315
tags question: http://stackoverflow.com/q/47542745
tags question: http://stackoverflow.com/q/47681016
tags question: http://stackoverflow.com/q/47592512
tags question: http://stackoverflow.com/q/47602655
tags question: http://stackoverflow.com/q/47622802
tags question: http://stackoverflow.com/q/47577016
tags question: http://stackoverflow.com/q/47670928
tags question: http://stackoverflow.com/q/47598343
tags question: http://stackoverflow.com/q/47691921
tags question: http://stackoverflow.com/q/47614865
tags question: http://stackoverflow.com/q/47571309
tags question: http://stackoverflow.com/q/47669609
tags question: http://stackoverflow.com/q/47689237
tags question: http://stackoverflow.com/q/47613827
tags question: http://stackoverflow.com/q/47635397
tags question: http://stackoverflow.com/q/47686559
tags question: http://stackoverflow.com/q/47696401
tags question: http://stackoverflow.com/q/47644434
tags question: http://stackoverflow.com/q/47617188
tags question: http://stackoverflow.com/q/47543572
tags question: http://stackoverflow.com/q/47661395
tags question: http://stackoverflow.com/q/47692155
tags question: http://stackoverflow.com/q/47678961
tags question: http://stackoverflow.com/q/47652102
tags question: http://stackoverflow.com/q/47684057
tags question: http://stackoverflow.com/q/47682621
tags question: http://stackoverflow.com/q/47614815
tags question: http://stackoverflow.com/q/47545052
tags question: http://stackoverflow.com/q/47661778
tags question: http://stackoverflow.com/q/47641736
tags question: http://stackoverflow.com/q/47647769
tags question: http://stackoverflow.com/q/47628924
tags question: http://stackoverflow.com/q/47597942
tags question: http://stackoverflow.com/q/47621671
tags question: http://stackoverflow.com/q/47543576
tags question: http://stackoverflow.com/q/47693021
tags question: http://stackoverflow.com/q/47618321
tags question: http://stackoverflow.com/q/47544790
tags question: http://stackoverflow.com/q/47571987
tags question: http://stackoverflow.com/q/47669376
tags question: http://stackoverflow.com/q/47625375
tags question: http://stackoverflow.com/q/47652839
tags question: http://stackoverflow.com/q/47576897
tags question: http://stackoverflow.com/q/47552206
tags question: http://stackoverflow.com/q/47697220
tags question: http://stackoverflow.com/q/47680732
tags question: http://stackoverflow.com/q/47598233
tags question: http://stackoverflow.com/q/47573519
tags question: http://stackoverflow.com/q/47621886
tags question: http://stackoverflow.com/q/47637696
tags question: http://stackoverflow.com/q/47689217
tags question: http://stackoverflow.com/q/47558535
tags question: http://stackoverflow.com/q/47678682
tags question: http://stackoverflow.com/q/47636441
tags question: http://stackoverflow.com/q/47574798
tags question: http://stackoverflow.com/q/47579274
tags question: http://stackoverflow.com/q/47565045
tags question: http://stackoverflow.com/q/47687872
tags question: http://stackoverflow.com/q/47590455
tags question: http://stackoverflow.com/q/47589034
tags question: http://stackoverflow.com/q/47649776
tags question: http://stackoverflow.com/q/47576025
tags question: http://stackoverflow.com/q/47659726
tags question: http://stackoverflow.com/q/47563510
tags question: http://stackoverflow.com/q/47551251
tags question: http://stackoverflow.com/q/47569284
tags question: http://stackoverflow.com/q/47579844
tags question: http://stackoverflow.com/q/47569496
tags question: http://stackoverflow.com/q/47675072
tags question: http://stackoverflow.com/q/47643804
tags question: http://stackoverflow.com/q/47616756
tags question: http://stackoverflow.com/q/47664952
tags question: http://stackoverflow.com/q/47681184
tags question: http://stackoverflow.com/q/47579207
tags question: http://stackoverflow.com/q/47655866
tags question: http://stackoverflow.com/q/47695453
tags question: http://stackoverflow.com/q/47602234
tags question: http://stackoverflow.com/q/47560533
tags question: http://stackoverflow.com/q/47681401

http://stackoverflow.com/comment/82305979
comment on: http://stackoverflow.com/a/47672437
has text: @Joey you should clearly state what your objective is. I am not sure why you want now to access a C1 value which does not comply with your initial requirements and, in consequence, you did not saved it in any container in the first place.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47665202
score: 3
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47637477
has body: For one time specifically in your application, you can use ALTracker.setMode("Head") or ALBasicAwareness.setTrackingMode("Head") For a global settings (robot behavior even when not running an app), you can add the following preference: domain: com.aldebaran.autonomouslife key: DefaultBasicAwarenessTrackingMode value: Head
answers question: http://stackoverflow.com/q/47637477

http://stackoverflow.com/comment/82090192
comment on: http://stackoverflow.com/q/47565885
score: 0
has text: Any solution which I can get User own ContentType Object? @SandeepBalagopal
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82166867
comment on: http://stackoverflow.com/a/47603990
score: 0
type: Comment
type: AnswerComment
has text: Yes, I know that, but I am just exercising my skills, and problem solving. I wondered if I could create a replica of the original function. Thanks for the comment tho! <3

http://stackoverflow.com/comment/82189400
has text: Thank you so much!
comment on: http://stackoverflow.com/a/47615499
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82108293
comment on: http://stackoverflow.com/q/47575407
type: Comment
has text: please fix your code in this question - it is not clear what this code does
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82183404
has text: The splitter is just a container for all the widgets you add to it -- each with its own layout, its own child widgets, etc. For example, add `print(splitter1.children())` to `make_tab1`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47611966
type: Comment

http://stackoverflow.com/a/53122318
score: 0
answers question: http://stackoverflow.com/q/47571849
type: Answer
has body: this is how a solve the problem pip install wheel you can remove the venv folder and restart like this python3 -m venv ./venv pip install wheel pip install flask this will solve the problem

http://stackoverflow.com/a/47601068
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47600975
downvote count: 0
has body: You want a loop: import sys def syracuse(n): syracuse_sequence = [n] while True: if n == 1: print(syracuse_sequence) return 0 elif n % 2 == 0: n /= 2 syracuse_sequence.append(round(n)) continue else: n = (n * 3 ) + 1 syracuse_sequence.append(round(n)) continue def main(argv): n = int(argv[1]) syracuse(n) if __name__ == "__main__": main(sys.argv) This will run the program until it gets to 1 (which I assume is what you want) This is what it outputs for 17: Hope this helps!
has comment: http://stackoverflow.com/comment/82160919
has comment: http://stackoverflow.com/comment/82161148
type: Answer
has comment: http://stackoverflow.com/comment/82160948
has comment: http://stackoverflow.com/comment/82161130

http://stackoverflow.com/q/47609537
has title: seasonal decompose in python
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/127286220
has answer: http://stackoverflow.com/a/47610117
favorite count: 0
type: Question
tagged with: time-series
downvote count: 0
score: 16
tagged with: machine-learning
tagged with: python
has body: I have a CSV file that contains the average temperature over almost 5 years. After decomposition using seasonal_decompose function from statsmodels.tsa.seasonal, I got the following results. Indeed, the results do not show any seasonal! However, I see a clear sin in the trend! I am wondering why is that and how can I correct it? Thank you. nresult = seasonal_decompose(nseries, model='additive', freq=1) nresult.plot() plt.show()
upvote count: 16
accepted answer: http://stackoverflow.com/a/47610117
type: AnsweredQuestion
tagged with: statsmodels

http://stackoverflow.com/a/49219529
type: Answer
has comment: http://stackoverflow.com/comment/85492336
has comment: http://stackoverflow.com/comment/85466176
has body: Here's how I did it. In models.py from django.template.defaultfilters import slugify from django.db import models from django.contrib.auth.models import User from pinax.badges.base import Badge, BadgeAwarded from pinax.badges.registry import badges class PointsBadge(Badge): slug = "points" levels = [ "Bronze", "Silver", "Gold", ] events = [ "points_awarded", ] multiple = False def award(self, **state): user = state["user"] points = user.profile.points if points &gt; 500: return BadgeAwarded(level=3) elif points &gt; 50: return BadgeAwarded(level=2) elif points &gt; 5: return BadgeAwarded(level=1) badges.register(PointsBadge) class Profile(models.Model): user = models.OneToOneField( User, on_delete = models.CASCADE ) points = models.IntegerField ( default = 0 ) def award_points (self, points): self.points += points self.save() In signals.py I create profile when user created @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) And then within my view request.user.profile.award_points(p.points) badges.possibly_award_badge("points_awarded", user=request.user)
score: 0
answers question: http://stackoverflow.com/q/47579491

http://stackoverflow.com/a/47644211
has body: Here is an example on how you can work with datetime: import datetime def add_minutes(t, incr): return t + datetime.timedelta(minutes=incr) # Create a datetime object t = datetime.datetime.now() # 2017-12-05 01:29... # Add minutes t2 = add_minutes(t,5) # Whenever you need to output use stftime: print(t2.strftime("%H:%M")) Prints: 01:34
has comment: http://stackoverflow.com/comment/82353470
has comment: http://stackoverflow.com/comment/82347186
has comment: http://stackoverflow.com/comment/82265692
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82324665
has comment: http://stackoverflow.com/comment/82288220
has comment: http://stackoverflow.com/comment/82264678
answers question: http://stackoverflow.com/q/47644135

http://stackoverflow.com/a/47595907
has body: Pandas uses xlrd to read in Excel files, and unfortunately xlrd does not parse the formatting used within the cell. The openpyxl package can handle string formatting, but only for the older .xls format. You will probably need to write a custom parser that looks at the underlying XML data. An .xlsx file is just a zip archive that contains a collection of xml files. The two that you need to look at are file.xlsx/xl/sharedStrings.xml file.xlsx/xl/worksheets/sheet1.xml (or whatever your sheet is named) The first file contains the string with their formatting. The second file contains the cells in the sheet and which string they reference. The strings are referenced by their order in the sharedStrings.xml. Here is a screen cap of an example excel sheet: Example sharedStrings.xml file: <?xml version="1.0" encoding="UTF-8"?> <r> <t>O</t> </r> <r> <vertAlign val="subscript"/><sz val="11"/><color theme="1"/><rFont val="Calibri"/><family val="2"/><scheme val="minor" /> <t>2</t> </r> <r> <vertAlign val="superscript"/><sz val="11"/><color theme="1"/><rFont val="Calibri"/><family val="2"/><scheme val="minor" /> <t>+</t> </r> <r> <t>H</t> </r> <r> <vertAlign val="subscript"/><sz val="11"/><color theme="1"/><rFont val="Calibri"/><family val="2"/><scheme val="minor" /> <t>2</t> </r> <r> <sz val="11"/><color theme="1"/><rFont val="Calibri"/><family val="2"/><scheme val="minor" /> <t>O</t> </r> <r> <t>O</t> </r> <r> <vertAlign val="superscript"/><sz val="11"/><color theme="1"/><rFont val="Calibri"/><family val="2"/><scheme val="minor" /> <t>2+</t> </r> Each element is a clump of text. The <r> elements are the a set of characters and formatting. The <t> elements are the actual characters, and the preceeding elements are the styling/formatting. You can distinguish when the superscript and subscript occur in <vertAlign> element. Example of sheet1.xml: <?xml version="1.0" encoding="UTF-8"?> <dimension ref="A1:A3" /> <selection activeCell="A4" sqref="A4" /> <sheetFormatPr defaultRowHeight…
has comment: http://stackoverflow.com/comment/82153299
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47584896
has comment: http://stackoverflow.com/comment/82152656

http://stackoverflow.com/comment/82339458
type: Comment
comment on: http://stackoverflow.com/q/47684732
score: 0
has text: possible duplicate of https://stackoverflow.com/questions/31797134/send-email-to-multiple-recipients-with-bcc-hidden-address-django-1-6
type: QuestionComment

http://stackoverflow.com/a/47638611
accepted answer of: http://stackoverflow.com/q/47638374
type: AcceptedAnswer
downvote count: 0
has body: I think in the middleware call method you should return the response. Please check the document for reference: Writing custom middleware The error seems to happen since you are not returning the response in the call() method.
answers question: http://stackoverflow.com/q/47638374
upvote count: 8
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/82238232

usb
tags question: http://stackoverflow.com/q/47551983
type: Tag
tag name: usb
tags question: http://stackoverflow.com/q/47628122
tags question: http://stackoverflow.com/q/47601411

http://stackoverflow.com/a/51983388
upvote count: 1
score: 1
has body: If you have automatic installs / docker install you need to ensure you add the following line to requirements.txt to ensure psycopg2 installs from source, rather than using the binary, or you'll continue to experience the above issue upon deployment. psycopg2&gt;=2.7,&lt;2.8 --no-binary psycopg2
type: Answer
answers question: http://stackoverflow.com/q/47614728
downvote count: 0

http://stackoverflow.com/comment/82170190
score: 1
type: Comment
has text: but in the same terminal if i try to import it it says `ModuleNotFoundError: No module named 'pytesser'`
type: AnswerComment
comment on: http://stackoverflow.com/a/47605715

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47659998
tag name: decision-tree

http://stackoverflow.com/comment/111008872
has text: yea, unfortunately, it looks like they didn't update the old version after backport, and the fix is only available starting 3.8. I will update the answer
comment on: http://stackoverflow.com/a/52140174
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82274804
type: QuestionComment
has text: https://www.howtoinstall.co/en/ubuntu/utopic/python-flask-babel
comment on: http://stackoverflow.com/q/47658112
score: 0
type: Comment

http://stackoverflow.com/comment/82226900
type: QuestionComment
type: Comment
has text: What is sparse about this? Just that you expect few `True` elements? It might be good if you gave a more complete example.
score: 0
comment on: http://stackoverflow.com/q/47631832

http://stackoverflow.com/a/47694099
type: Answer
has comment: http://stackoverflow.com/comment/82347404
score: 0
has body: If I am understanding your question correctly, you wish to write a function that can take any amount of vectors and return the sum? Then yes, you would need to use *args like so: def add_lists(*args): final_vector = [0, 0] for vector in args: final_vector[0] += vector[0] final_vector[1] += vector[1] return final_vector Basically, treat args as a list - containing all the arguments passed through when you call the function.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47694053
answers question: http://stackoverflow.com/q/47694053

http://stackoverflow.com/q/47644532
type: Question
score: 2
tagged with: string.format
tagged with: list
upvote count: 2
has title: In Python, is there a method to print lists into a string using .format notation?
answer count: 1
downvote count: 0
tagged with: string
favorite count: 0
tagged with: tuples
type: AnsweredQuestion
has body: A simple Madlibs exercise: STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s." WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun') WORD_values = [] for s in WORD_types: print "Please give {}.".format(s) s = raw_input() WORD_values.append(s) print STORY % tuple(WORD_values) It's there a way to accomplish that last line with .format notation? STORY = "This morning I woke up and felt {} because {} was going to finally {} over the big {} {}." WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun') WORD_values = [] for s in WORD_types: print "Please give {}.".format(s) s = raw_input() WORD_values.append(s) print STORY.format(WORD_values) This kicks back the following error: Traceback (most recent call last): File "Madlibs.py", line 12, in &lt;module&gt; print STORY.format(WORD_values) IndexError: tuple index out of range
accepted answer: http://stackoverflow.com/a/47644613
tagged with: python
has answer: http://stackoverflow.com/a/47644613

http://stackoverflow.com/q/47572366
has comment: http://stackoverflow.com/comment/82101865
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/82102380
has comment: http://stackoverflow.com/comment/82105336
answer count: 0
has comment: http://stackoverflow.com/comment/82104395
tagged with: pyqt
linked to: http://stackoverflow.com/q/43937066
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82102141
downvote count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/82101748
has title: Dynamic Subplots in Matplotlib GUI
duplicate of: http://stackoverflow.com/q/43937066
favorite count: 0
type: Question
has body: I want to embed matplotlib plots in a PyQt5 UI -- with a dynamic count of subplots. Is there an efficient way to do this without constantly deleting and constructing new axes? Originally I thought using gridspec would be the right thing to do, but I couldn't find a way to update nrows/ncols, other than constructing a new gridspec object. Example code: import sys from PyQt5 import QtWidgets from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class Plot(FigureCanvas): def __init__(self, parent=None, width=5.4, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.axes = [self.fig.add_subplot(211), self.fig.add_subplot(212)] self.fig.set_facecolor("none") self.fig.set_tight_layout(True) FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def update_subplot(self, count): [self.fig.delaxes(ax) for ax in self.axes] self.axes = [self.fig.add_subplot(count, 1, i+1) for i in range(count)] self.draw() class PlotWidget(QtWidgets.QWidget): def __init__(self): super(PlotWidget, self).__init__() self.initPlot() self.initUI() def initPlot(self): self.plot = Plot() def initUI(self): self.setGeometry(100, 100, 800, 600) grid = QtWidgets.QGridLayout(self) grid.addWidget(self.plot, 3, 0, 1, 2) btn1 = QtWidgets.QPushButton('1 Subplot ', self) btn1.clicked.connect(lambda: self.plot.update_subplot(1)) grid.addWidget(btn1, 5, 0) btn2 = QtWidgets.QPushButton('2 Subplots ', self) btn2.clicked.connect(lambda: self.plot.update_subplot(2)) grid.addWidget(btn2, 5, 1) self.show() app = QtWidgets.QApplication(sys.argv) window = PlotWidget() window.show() sys.exit(app.exec_())
score: 3

scope
tags question: http://stackoverflow.com/q/47642737
type: Tag
tags question: http://stackoverflow.com/q/47607071
tags question: http://stackoverflow.com/q/47544790
tag name: scope

http://stackoverflow.com/q/47689664
type: Question
tagged with: mongodb
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82338463
has body: My collection contains {name:'p1', age: 20} {name: 'p2', age: 21} {name: 'p3', age: 23} {name: 'p4', ag:41 } I want to group persons such that for any person in the group there exist another person int the group such that difference between their ages is at most 2. Here resulting group will contain expected result [{name:'p1' ...}, {name:'p2' ...}, {name: 'p3'}] since ages of p2 -p1 = 1 and p3-p2 = 2 p1,p2,p3 form a group
tagged with: python
has comment: http://stackoverflow.com/comment/82339695
has title: Grouping documents in MongoDB on special condition
score: 0
has comment: http://stackoverflow.com/comment/82339113
answer count: 1
tagged with: pymongo
has answer: http://stackoverflow.com/a/47745073

http://stackoverflow.com/a/47654617
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Simply with numpy module: import numpy as np x = np.array([[1, 5, 3, 4], [5, 10, 7, 8], [9, 9, 2, 12]]) print(np.min(x, 0)) # [1 5 2 4] print(np.max(x, 0)) # [ 9 10 7 12]
answers question: http://stackoverflow.com/q/47654162

http://stackoverflow.com/a/47808654
downvote count: 0
has body: When looking at a package level, you can define a function named setup in the __init__.py of that package. Calling the tests in this package, the setup function in the __init__.py is called once. Example setup - package - __init__.py - test1.py - test2.py See documentation section 'Test packages'.
upvote count: 8
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/47670547
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47670547

http://stackoverflow.com/comment/82351327
type: Comment
comment on: http://stackoverflow.com/a/47695485
type: AnswerComment
has text: @Dark - better here is `split`, but `partions` working too ;)
score: 0

http://stackoverflow.com/comment/82157921
has text: What is the point of using `subprocess`? Just import *MyWindow.py* and open the window normally.
comment on: http://stackoverflow.com/q/47596831
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82246497
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47643751
has text: This is not an answer, this should rather be a comment
score: 0

http://stackoverflow.com/a/47638058
downvote count: 0
has body: I think the reason maybe that you have an older version of PyTorch on your system. On my system, the pytorch version is 0.2.0, torch.nn has a module called Upsample. You can uninstall your current version of pytorch and reinstall it.
has comment: http://stackoverflow.com/comment/82247490
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47635918
accepted answer of: http://stackoverflow.com/q/47635918

http://stackoverflow.com/q/47627927
answer count: 1
has comment: http://stackoverflow.com/comment/82256376
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82213430
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/82213451
has answer: http://stackoverflow.com/a/47628084
tagged with: javascript
tagged with: python
has body: I have a pattern to search around web but im new to it and unable to verify it. Im looking for example [verify if any whitespace] [any of this char ':' '|' ';'] [verify if any whitespace] [[String a-zA-Z0-9-]+] Suppose Test String - " : hello129 " or ":hello129" or ";hello129" or "|hello129" or " | hello129" My attemps \s[:;|]\s[a-zA-Z0-9_.+-]+ (\w+\s\w+):(\w+\s\w+)[a-zA-Z0-9_.+-]+ Please suggest me possible solutions for this pattern in regex/regular expressions Thank you in advance :)
tagged with: regex
upvote count: 0
has title: Regex to include white space and then verify a character
downvote count: 3
has comment: http://stackoverflow.com/comment/82213509
has comment: http://stackoverflow.com/comment/82213406
has comment: http://stackoverflow.com/comment/82213469
has comment: http://stackoverflow.com/comment/82213448

http://stackoverflow.com/a/47635557
downvote count: 0
has comment: http://stackoverflow.com/comment/82231932
answers question: http://stackoverflow.com/q/47635397
upvote count: 5
has comment: http://stackoverflow.com/comment/82230193
type: Answer
has body: Use rank with reshape by stack and then unstack: df2 = (df1.set_index('weight', append=True) .stack() .rank(method='dense') .astype(int) .unstack() .reset_index(level=1)) print (df2) weight node1 node2 0 1 1 3 1 2 1 4 2 1 2 4 3 1 3 5
score: 5

http://stackoverflow.com/comment/82113039
type: AnswerComment
has text: Thanks, @furas. I've updated my answer to include that information.
comment on: http://stackoverflow.com/a/47574657
type: Comment
score: 0

http://stackoverflow.com/q/47675177
has comment: http://stackoverflow.com/comment/82309738
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82410400
has comment: http://stackoverflow.com/comment/121960038
has comment: http://stackoverflow.com/comment/82312082
has comment: http://stackoverflow.com/comment/82312097
linked to: http://stackoverflow.com/q/1074062
tagged with: python
has title: How to make Scons build object files in a separate folder
has comment: http://stackoverflow.com/comment/93622881
has comment: http://stackoverflow.com/comment/82310313
has comment: http://stackoverflow.com/comment/82310983
linked to: http://stackoverflow.com/q/3720142
downvote count: 0
upvote count: 1
score: 1
tagged with: scons
answer count: 1
has answer: http://stackoverflow.com/a/47724927
has comment: http://stackoverflow.com/comment/82310039
has comment: http://stackoverflow.com/comment/82310682
has body: I'm working on a project which we used to compile using make. Now we wanna use scons instead so I've created a Sconstruct file that seems to handle this just fine. Nevertheless, I'm greatly dissatisfied with the location where scons puts .o files (right next to my source files (.c), which is annoying) and i can't seem to understand how to make it create them in a specific folder during the build. I've tried several (quite a lot) "VariantDir()", "env.VariantDir()", "variant_dir=...", etc... calls but none have worked for me yet. All I'm asking for is an option that would enable me to choose the folder where .o files will go so that they don't end up mixed with my source files. Here's a taste of what I've done so far : ### Imports ### import os ### Environment de compilation ### # Dossier et nom du binaire binFolder = 'bin/' binName = 'sc.bin' # Outils de l'environnement env = DefaultEnvironment( tools = [ 'gcc', 'link' ], ) # Chaine de compilation env.PrependENVPath('PATH', os.path.abspath('path/to/cross/compiler')) prefix = 'cross-compiler-prefix' env['CC'] = prefix + env['CC'] ### Fichiers a compiler ### srcFiles = [ 'some', 'source', 'files' ] ### Dossiers a inclure (headers) ### includeFolders = [ 'some', 'include', 'folders' ] ### Flags de compilation ### compilationFlags = '-some -compilation -flags' ### Librairies externes ## libs = [ 'some', 'libraries' ] ### Regle de generation sc.bin ### sc_multi = env.Program( binFolder+binName, srcFiles, CDEFINES = {'SOME_MACRO':'SOME_VALUE'}, CPPPATH = includeFolders, CFLAGS = compilationFlags, LIBS = libs, ) # Par default, on genere la cible sc_multi Default(sc_multi) Alias('sc_multi', sc_multi) If anyone has insight, please share as I nearly don't have any hair left. Thx !
favorite count: 0
type: Question

http://stackoverflow.com/comment/82362989
type: Comment
has text: There were two other issues related to the fact that we were using processes instead of threads, and that there was a race condition. Updated the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47697551

http://stackoverflow.com/comment/82185867
comment on: http://stackoverflow.com/a/47613696
score: 0
type: AnswerComment
has text: sim=c*(sc.dot(Q.T,sim)) + (1-c)*I will this line change too in sparse multiplication ?
type: Comment

http://stackoverflow.com/q/47643606
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
tagged with: django
has body: I am trying to run around Django and Celery. I just using sample program and get stuck in Status of the Tasks. I am not sure, if I doing any wrong with configuration, but everything seems to follow all the steps. Also the Backend and Workers is working properly. In case, I want to get the status of the Q-tasks so that it's easy to identify whether the Job is "Running", "Success", or "Failure". But I end up with the status always "PENDING" and "SUCCESS" in case of Success. Sample Sum for Worker Worker Information Job Call Job 1st Check Status --> Always Pending Check Status from AsynChronization --> Also Always Pending or Success in Case of complete
linked to: http://stackoverflow.com/q/24518054
has answer: http://stackoverflow.com/a/51530540
tagged with: celery
favorite count: 0
type: Question
tagged with: celery-task
tagged with: django-celery
tagged with: python
has title: Python Celery Q Task Status Always Pending or Success

http://stackoverflow.com/q/47697797
has body: I already asked my problem: How to read two columns using python, but my goal is to draw a graph oX = f(oY). I tried with: import matplotlib.pyplot as plt from matplotlib import style import csv with open('file.csv') as f: reader = csv.reader(f) for row in reader: res = row[0].split() oX = res[0] oY = res[1] print (oX , oY) It does not work for me.
has comment: http://stackoverflow.com/comment/82356601
tagged with: matplotlib
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82368158
accepted answer: http://stackoverflow.com/a/47698288
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82355417
has title: Read two columns and draw the graph
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47698288
linked to: http://stackoverflow.com/q/47687701
linked to: http://stackoverflow.com/q/47269695
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/47613222
type: Answer
has body: The bottom "axes" (the "subplot" in the figure) is covering up the x-labels of the axes above. You can see them again by making the bottom axes smaller Use the line frame2=fig1.add_axes((.1,.1,.8,.1)). (notice that the .2 is now .1. Your code doesn't run self-contained, but this is probably roughly what you're after:
answers question: http://stackoverflow.com/q/47612702
score: 0

http://stackoverflow.com/a/47599499
type: Answer
has body: Your real use case should look like this: import subprocess import os.path a = subprocess.check_output([ './fasttext', 'print-sentence-vectors', os.path.expanduser('~/Vaiju/Project/all code and data/My Code/TrainedModels/wiki_unigrams.bin'), ], stdin=open('1fasttext.test.txt', 'r')) Note that each argument is passed as a separate list member; redirections are performed via Python (in this case, using stdin= instead of a &lt; redirection), and replacing expansions like ~ has to be done by Python (as, here, with os.path.expanduser()).
answers question: http://stackoverflow.com/q/47572190
score: 0

http://stackoverflow.com/q/47643956
tagged with: class
tagged with: reference
type: Question
has title: Python: Accessing class instance's `self` in decorator
answer count: 0
type: UnansweredQuestion
tagged with: decorator
has comment: http://stackoverflow.com/comment/82246597
linked to: http://stackoverflow.com/q/11731136
has body: I have this decorator which takes one argument by itself before it decorates a provided function. That decorator is then used to decorate a class method. Let's say we have the following code: from somewhere import dec class Something: def __init__(self, variable = 5): self.variable = variable @dec(need_to_access_instance_self_variable) def some_method(self, blahblah): # does something pass Everything works like a charm, except I'd like to pass self.variable as an argument to the decorator—and nothing hasn't worked for me so far. Is this even possible? I cannot seem to figure out the scoping. Any ideas how would that be achievable? Thank you!
score: 0
has comment: http://stackoverflow.com/comment/82246901
duplicate of: http://stackoverflow.com/q/11731136
tagged with: python
has comment: http://stackoverflow.com/comment/82246623
has comment: http://stackoverflow.com/comment/82246760
has comment: http://stackoverflow.com/comment/82246735

http://stackoverflow.com/comment/82324912
type: AnswerComment
has text: @JokerMartini. I've now tested it pretty thoroughly, and can confirm it all works exactly as expected. The only minor issue was some runtime errors when closing the app if there was a cached selection (which I've now fixed in the code example).
score: 0
comment on: http://stackoverflow.com/a/47681015
type: Comment

http://stackoverflow.com/q/47681842
has comment: http://stackoverflow.com/comment/82323038
has comment: http://stackoverflow.com/comment/82322793
tagged with: selenium
has comment: http://stackoverflow.com/comment/82359321
type: Question
has comment: http://stackoverflow.com/comment/82323449
tagged with: robotframework
has comment: http://stackoverflow.com/comment/82323538
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23703870
tagged with: python
has comment: http://stackoverflow.com/comment/82368725
tagged with: selenium-webdriver
has body: I am trying to extend the RobotFramework SeleniumLibray to override open_browser method. The problem is, I am not even sure which class I should override. Library https://github.com/robotframework/SeleniumLibrary/blob/master/src/SeleniumLibrary/init.py following code gives the error. if I extend the BrowserManagementKeywords class, I am not sure what should I pass as ctx in constructor argument. from SeleniumLibrary import SeleniumLibrary import env class DriverManager(SeleniumLibrary): def open_browser(self, url, alias=None, ff_profile_dir=None): browser = env.capabilities.get("browserName") remote_url = env.host desired_capabilities = env.capabilities return super(DriverManager, self).open_browser(url, browser, alias, remote_url, desired_capabilities, ff_profile_dir) DriverManager().open_browser("https://google.com") Error AttributeError: 'super' object has no attribute 'open_browser'
has comment: http://stackoverflow.com/comment/82323164
score: 0
has comment: http://stackoverflow.com/comment/82322873
answer count: 0
has comment: http://stackoverflow.com/comment/82408225
tagged with: selenium2library
has title: Extend RobotFramework SeleniumLibary

http://stackoverflow.com/comment/115399385
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47555613
score: 0
has text: The names are part of the [Unicode standard](https://www.unicode.org/Public/UCD/latest/ucd/NamesList.txt), also see the duplicate.

http://stackoverflow.com/a/47617114
type: Answer
has body: found the problem i needed to add import myPckg.module like i wrote "I just started to learn.." :-)
score: 0
accepted answer of: http://stackoverflow.com/q/47616499
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47616499

http://stackoverflow.com/comment/82051407
comment on: http://stackoverflow.com/q/47547298
type: Comment
type: QuestionComment
has text: `def checkInternet():`
score: 0

http://stackoverflow.com/comment/82129785
comment on: http://stackoverflow.com/q/47578003
score: 1
type: QuestionComment
has text: Python is strict on indentation and your code shows no indentation, which probably means it is not an accurate reflection of your code. Please ensure that your code displayed reflects your actual code. Also, please provide the output being displayed.
type: Comment

http://stackoverflow.com/q/47603148
favorite count: 0
has body: I'm coming from a Postgres background and am new to MariaDB (MySQL). When trying to save a DateTime into MariaDB, I'm getting this error. sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1292, "Incorrect datetime value: '2017-11-25 16:33:26+00:00' for column 'expires_at' at row 1") [SQL: 'INSERT INTO user (username, password, created_at, expires_at, expires_at_ms) VALUES (%s, %s, %s, %s, %s)'] [parameters: ('uuid1', '...', FakeDatetime(2017, 10, 25, 0, 0), FakeDatetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal()), 0)] According to the documentation, I should get around it if I used a TIMESTAMP field instead of DateTime. But this didn't help either. MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) The issue is this date '2017-11-25 16:33:26+00:00', which is presented like this: FakeDatetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal()) The fake data comes from @freeze_time("2017-10-25") in Python, and shouldn't matter in this context. Model in SqlAlchemy: class User(db.Model): __tablename__ = 'user' username = db.Column(db.String(36), primary_key=True) password = db.Column(db.String(100)) created_at = db.Column(db.TIMESTAMP()) expires_at = db.Column(db.TIMESTAMP()) expires_at_ms = db.Column(db.BigInteger()) Further analysis: from dateutil import parser as dt_parser expires_at = dt_parser.parse('Sat, 25 Nov 2017 16:33:26 GMT') This fails, because MySQL doesn't like tzinfo. datetime.datetime(2017, 11, 25, 16, 33, 26, tzinfo=tzlocal()) But expires_at = datetime.datetime.now() works. Because this is acceptable for MySQL: datetime.datetime(2017, 12, 2, 9, 44, 55, 392927)
type: Question
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82177089
tagged with: datetime
tagged with: python
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/82178804
answer count: 0
has title: How to save datetime with tzlocal() into MariaDB?
upvote count: 3
downvote count: 0
tagged with: mysql
tagged with: mariadb

http://stackoverflow.com/comment/82237260
type: Comment
has text: I stand corrected... eval() does work and it is a lot easier... noob mistake of calling maya's version of eval() as maya.cmds.eval() instead of python eval()... I need coffee
comment on: http://stackoverflow.com/a/47614377
type: AnswerComment
score: 0

http://stackoverflow.com/a/47659164
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47624420
type: Answer
has body: Do NOT install cx_freeze by "pip install cx_freeze", because an old Version will be installed, instead go to https://pypi.python.org/pypi/cx_Freeze and then download the right version. Use for example pip install cx_Freeze-6.0b1-cp36-cp36m-win_amd64.whl. Finally copy the file "tcl86t.dll" and "tk86t.dll" into the build folder
accepted answer of: http://stackoverflow.com/q/47624420

http://stackoverflow.com/comment/82163787
comment on: http://stackoverflow.com/q/47602514
type: Comment
has text: I am not sure how to validate the correctness of least square.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82212948
comment on: http://stackoverflow.com/a/47627569
has text: `set.Union( any iterator)` vs `set | set`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82340824
type: Comment
has text: Can you please post the code you wrote? You're more likely to get help if your question provides a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47690852

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

http://stackoverflow.com/comment/82441238
has text: FYI, it's use `pip` which is a tool provided with Python to manage packages
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47690770

http://stackoverflow.com/q/47621638
has comment: http://stackoverflow.com/comment/82201236
favorite count: 0
has comment: http://stackoverflow.com/comment/82201272
type: Question
tagged with: python-3.x
downvote count: 4
tagged with: tkinter
has title: Why does random keep selecting the same choice?
upvote count: 0
type: UnansweredQuestion
has body: I am trying to make a code that returns yes or no to the user, but the output is always yes. What should I change or add to make the answer change? from tkinter import * from tkinter import ttk import random list=["yes", "no"] #a list of answers answer=random.choice(list) #choosing an answer root=Tk(className="yes or no") lab=ttk.Label(root, text="what's your question" ) lab.pack() #ask user for input U=ttk.Entry(root) U.pack() def return_answer(): U.get() U.delete(0, END) U.insert(0,answer) B1=ttk.Button(root, text="ok",command=return_answer) B1.pack() root.mainloop()
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/82201174
has comment: http://stackoverflow.com/comment/82201287
has comment: http://stackoverflow.com/comment/82201218
has answer: http://stackoverflow.com/a/47621684
answer count: 1

http://stackoverflow.com/comment/82122938
score: 1
type: Comment
type: AnswerComment
has text: The fine print went right over my head. I appreciate the definitions. Thank you for your answer.
comment on: http://stackoverflow.com/a/47580342

http://stackoverflow.com/comment/82086106
has text: Can you show is what you've tried?
score: 0
comment on: http://stackoverflow.com/q/47563811
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47599436
has answer: http://stackoverflow.com/a/47602580
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/47602580
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82161783
has comment: http://stackoverflow.com/comment/82162578
accepted answer: http://stackoverflow.com/a/47681145
has comment: http://stackoverflow.com/comment/82162706
has title: Returning probabilities in a classification prediction in Keras?
tagged with: python
score: 12
upvote count: 12
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47681145
downvote count: 0
has comment: http://stackoverflow.com/comment/82162502
tagged with: neural-network
tagged with: machine-learning
has body: I am trying to make a simple proof-of-concept where I can see the probabilities of different classes for a given prediction. However, everything I try seems to only output the predicted class, even though I am using a softmax activation. I am new to machine learning, so I'm not sure if I am making a simple mistake or if this is a feature not available in Keras. I'm using Keras + TensorFlow. I have adapted one of the basic examples given by Keras for classifying the MNIST dataset. My code below is exactly the same as the example, except for a few (commented) extra lines that exports the model to a local file. '''Trains a simple deep NN on the MNIST dataset. Gets to 98.40% test accuracy after 20 epochs (there is *a lot* of margin for parameter tuning). 2 seconds per epoch on a K520 GPU. ''' from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import h5py # added import because it is required for model.save model_filepath = 'test_model.h5' # added filepath config batch_size = 128 num_classes = 10 epochs = 20 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Dense(512, activation='relu', input_shape=(784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer=RMSpr…
tagged with: keras
has comment: http://stackoverflow.com/comment/82162667

http://stackoverflow.com/q/47602097
has answer: http://stackoverflow.com/a/47602646
has answer: http://stackoverflow.com/a/47602170
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60723014
has comment: http://stackoverflow.com/comment/98042061
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/74375633
linked to: http://stackoverflow.com/q/46556220
has answer: http://stackoverflow.com/a/69315353
linked to: http://stackoverflow.com/q/40899021
upvote count: 34
score: 34
has answer: http://stackoverflow.com/a/47602249
tagged with: pandas-groupby
tagged with: pandas
has title: Pandas groupby to to_csv
downvote count: 0
answer count: 7
has body: Want to output a Pandas groupby dataframe to CSV. Tried various StackOverflow solutions but they have not worked. Python 3.6.1, Pandas 0.20.1 groupby result looks like: id month year count week 0 9066 82 32142 895 1 7679 84 30112 749 2 8368 126 42187 872 3 11038 102 34165 976 4 8815 117 34122 767 5 10979 163 50225 1252 6 8726 142 38159 996 7 5568 63 26143 582 Want a csv that looks like week count 0 895 1 749 2 872 3 976 4 767 5 1252 6 996 7 582 Current code: week_grouped = df.groupby('week') week_grouped.sum() #At this point you have the groupby result week_grouped.to_csv('week_grouped.csv') #Can't do this - .to_csv is not a df function. Read SO solutions: output groupby to csv file pandas week_grouped.drop_duplicates().to_csv('week_grouped.csv') Result: AttributeError: Cannot access callable attribute 'drop_duplicates' of 'DataFrameGroupBy' objects, try using the 'apply' method Python pandas - writing groupby output to file week_grouped.reset_index().to_csv('week_grouped.csv') Result: AttributeError: "Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method"
linked to: http://stackoverflow.com/q/35025917
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47602244

http://stackoverflow.com/a/47604843
has comment: http://stackoverflow.com/comment/82168342
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/82168400
has body: You can do this all with a "one-liner" using list comprehension and string functions join, split, strip, and no additional libraries. a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.'] b = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes'] c = ['.', 'this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes'] In [5]: [i.strip().split(' ') for i in ' '.join(a).split('.') if len(i) &gt; 0 ] Out[5]: [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']] In [8]: [i.strip().split(' ') for i in ' '.join(b).split('.') if len(i) &gt; 0 ] Out[8]: [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']] In [9]: In [8]: [i.strip().split(' ') for i in ' '.join(c).split('.') if len(i) &gt; 0 ] Out[9]: [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']] @Craig has a simpler update: [s.split() for s in ' '.join(a).split('.') if s]
downvote count: 0
answers question: http://stackoverflow.com/q/47604449
has comment: http://stackoverflow.com/comment/82175545
has comment: http://stackoverflow.com/comment/82183571
has comment: http://stackoverflow.com/comment/82175146

http://stackoverflow.com/a/47667697
answers question: http://stackoverflow.com/q/47631328
score: 0
type: Answer
has body: Finally, this problem has been solved by changing the match-clients dynamically through ssh and then rndc reload. This make the remote server only access to the specific view in which you want to update the zone using dnspython.

http://stackoverflow.com/q/47575064
has comment: http://stackoverflow.com/comment/82107013
has title: Python: How two group and reshape a list given specific order of keys
tagged with: list
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47575633
accepted answer: http://stackoverflow.com/a/47575933
type: Question
has answer: http://stackoverflow.com/a/47575933
tagged with: group-by
tagged with: python
possible better answer: http://stackoverflow.com/a/47575633
has body: This is my first question here, so sorry in advance that it might be not perfect. ;) I have a list of image names. Each of the images was taken in a specific mode. The modes are Q+,Q-,U+,U- (The Stokes parameter of an polarimetry image). So four images represent a full observation cycle. The list of files i have looks something like this. [['file_name1','Q+', some other info, ...], ['file_name2','Q+', some other info, ...], ['file_name3','Q+', some other info, ...], ['file_name4','Q-', some other info, ...], ['file_name5','Q-', some other info, ...], ['file_name6','Q-', some other info, ...], ['file_name7','U+', some other info, ...], ['file_name8','U+', some other info, ...], ['file_name9','U+', some other info, ...], ['file_name10','U-', some other info, ...], ['file_name11','U-', some other info, ...], ['file_name12','U-', some other info, ...]] My problem is, that i need to group the data in a specific way for further processing. In the end the data structure should look like this: [[['file_name1','Q+', ...], ['file_name4','Q-', ...], ['file_name7','U+', ...], ['file_name10','U-', ...]], [['file_name2','Q+', ...], ['file_name5','Q-', ...], ['file_name8','U+', ...], ['file_name11','U-', ...]], [['file_name3','Q+', ...], ['file_name6','Q-', ...], ['file_name9','U+', ...], ['file_name12','U-', ...]], ....] I found no solution yet... but i think that maybe the python groupby can do it.

http://stackoverflow.com/comment/82292401
comment on: http://stackoverflow.com/a/47666514
score: 0
has text: Please enter numbers separated by vertical bars '|' : 10.2|20|2|5|4|1|99|9|7 99 20 0 9 7 5 4 2 1 99 | 20 | 10.2 | 9 | 7 | 5 | 4 | 2 | 1 |
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82297224
comment on: http://stackoverflow.com/a/47669206
has text: @juanpa.arrivillaga thank you, i've updated answer.:)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47556339
answer count: 0
type: UnansweredQuestion
has title: FIle handling and delivery in a Django ELastic Load Balancer deployment
has comment: http://stackoverflow.com/comment/82071140
tagged with: django
tagged with: amazon-web-services
type: Question
score: 0
has body: So I have a Django app deployed in AWS Elastic Beanstalk that generates a web page and collects user data for various tables when the user loads the page, clicks a link, etc. All this data is currently recorded on an RDS database. At periodic intervals, the data for the day is collected (potentially several million rows) and stored in a series of CSV files. The data is then sent to an FTP server to be analysed later. There are also cleaning operations ran to delete data a few days old from the database as well. I'm thinking that I can potentially remove some overhead and complexity from the project by removing the DB aspect altogether. I shall instead write out the data to files located on the instance, gzip them and send the file over. A few potential issues occur to me though: If my load balancer scales up to more than one instance (currently just one), how can I make sure that each instance receives a command at X hour in the day to get the current file, zip it and send to the FTP? How can I uniquely identify which instance the file came from? They have a timestamp attached to the file name but is there an instance ID I can append to it? Is it possible to append to a file over SFTP?
has comment: http://stackoverflow.com/comment/82071789
has comment: http://stackoverflow.com/comment/82071448
tagged with: python
tagged with: amazon-elastic-beanstalk

http://stackoverflow.com/comment/82282892
has text: worked perfectly :) thank you @gonczor. Although not a duplicate question I believe, I found same solution here: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another-module
comment on: http://stackoverflow.com/a/47660995
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47669418
has comment: http://stackoverflow.com/comment/82297872
has comment: http://stackoverflow.com/comment/82298850
score: 0
has comment: http://stackoverflow.com/comment/82317643
has comment: http://stackoverflow.com/comment/82304826
has comment: http://stackoverflow.com/comment/82298584
has comment: http://stackoverflow.com/comment/82297840
has comment: http://stackoverflow.com/comment/82297731
has comment: http://stackoverflow.com/comment/82298667
has comment: http://stackoverflow.com/comment/82298306
has comment: http://stackoverflow.com/comment/82298742
type: Answer
has comment: http://stackoverflow.com/comment/82298257
has body: I am able to see a couple of errors in the code. for row in f: (1) for column in row.split(','): (2) i=(int(column)) Sum += i row_count += 1 (3) average = Sum / len(column) (1) When you split the row, what you get back is basically an array/list. In your case, it would be ['5', 'Ser15]. And instead of a for loop, you might want to change the code as follows: for row in f: columns_list = row.split(',') i=(int(columns_list[0])) Sum += i row_count += 1 average = Sum / row_count (2) Now you can't convert a list to an integer. What you might be interested in is i = int(column[0]) i.e. first number in the list i.e. first column of your CSV file. (3) You want to find the average of all rows, right? Souldn't it be average = Sum / row_count? def av(): with open("SciMedreport.csv","r") as f: average = 0 Sum = 0 row_count = 0 divisor = 0 for row in f: row_count += 1 if row_count%2 == 0: # if it doesn't work, try changing to 1 # print(row.split(',')) divisor += 1 # write rest of the code here, Sum += i etc. columns_list = row.split(',') i = int(columns_list[0]) Sum += i average = Sum / divisor
has comment: http://stackoverflow.com/comment/82298412
answers question: http://stackoverflow.com/q/47669297
has comment: http://stackoverflow.com/comment/82298475
has comment: http://stackoverflow.com/comment/82297931
has comment: http://stackoverflow.com/comment/82298329
has comment: http://stackoverflow.com/comment/82297790
has comment: http://stackoverflow.com/comment/82297880

pyke
tags question: http://stackoverflow.com/q/47558136
type: Tag
tag name: pyke

http://stackoverflow.com/comment/82337711
comment on: http://stackoverflow.com/a/47689264
score: 0
type: Comment
has text: This doesn't work with my actual data where `week` is: Name: week, Length: 1227, dtype: object. The output just returns 'OND' for all. Do I need to change the format of `week`? @jezrael
type: AnswerComment

http://stackoverflow.com/comment/82236268
type: QuestionComment
has text: @Accumulation it returns 0. And if you use 2017 it returns 1. Why?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47638585

http://stackoverflow.com/comment/82069008
comment on: http://stackoverflow.com/q/47555406
has text: """https://upload.wikimedia.org/wikipedia/en/b/b0/ Avatar-Teaser-Poster.jpg"""
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47612157
has title: no module cv on jupyter
tagged with: jupyter-notebook
score: -1
has comment: http://stackoverflow.com/comment/82203685
has comment: http://stackoverflow.com/comment/82185040
upvote count: 0
has body: I am working on Jupyter Notebook on my windows. I am trying to import module cv and cv2. import cv produces this error. ImportModuleError: No module cv Similarly for import cv2 it produces the error : ImportModuleError: No module cv Please help me solve this issue.
answer count: 1
downvote count: 1
favorite count: 0
tagged with: opencv
has answer: http://stackoverflow.com/a/47629148
type: Question
has comment: http://stackoverflow.com/comment/82185361
tagged with: python
tagged with: computer-vision
type: UnansweredQuestion

http://stackoverflow.com/q/47687414
has body: Various versions of this question have been asked before, and I'm not sure if I'm supposed to ask my question on one of the threads or start a new thread. Here goes: I have a pandas dataframe where there is a column (eg: speed) that I'm trying to plot, and then another column (eg: active) which is, for now, true/false. Depending on the value of active, I'd like to color the line plot. This thread seems to be the "right" solution, but I'm having an issue: seaborn or matplotlib line chart, line color depending on variable The OP and I are trying to achieve the same thing: Here's a broken plot/reproducer: Values=[3,4,6, 6,5,4, 3,2,3, 4,5,6] Colors=['red','red', 'red', 'blue','blue','blue', 'red', 'red', 'red', 'blue', 'blue', 'blue'] myf = pd.DataFrame({'speed': Values, 'colors': Colors}) grouped = myf.groupby('colors') fig, ax = plt.subplots(1) for key, group in grouped: group.plot(ax=ax, y="speed", label=key, color=key) The resultant plot has two issues: not only are the changed color lines not "connected", but the colors themselves connect "across" the end points: What I want to see is the change from red to blue and back look like it's all one contiguous line. Color line by third variable - Python seems to do the right thing, but I am not dealing with "linear" color data. I basically am assigning a set of line colors in a column. I could easily set the values of the color column to numericals: Colors=['1','1', '1', '2','2'...] if that makes generating the desired plot easier. There is a comment in the first thread: You could do it if you'll duplicate points when color changed, I've modified answer for that But I basically copied and pasted the answer, so I'm not sure that comment is entirely accurate.
tagged with: colors
linked to: http://stackoverflow.com/q/33560789
type: UnansweredQuestion
upvote count: 5
tagged with: matplotlib
has title: color line by "value"
tagged with: python
answer count: 2
score: 5
tagged with: pandas
has answer: http://stackoverflow.com/a/47688731
linked to: http://stackoverflow.com/q/17240694
downvote count: 0
linked to: http://stackoverflow.com/q/40348541
duplicate of: http://stackoverflow.com/q/17240694
tagged with: plot
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/36505587
has answer: http://stackoverflow.com/a/47688403

http://stackoverflow.com/comment/82267025
type: Comment
score: 0
has text: Thanks it did work certainly with the example in the question, but there was some kind of robustness issue, in my example it generated the error `ValueError: Boolean array expected for the condition, not float64`, I was investigating the cause of this when @dispayname posted his answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/47654154

http://stackoverflow.com/comment/82269199
comment on: http://stackoverflow.com/q/47630444
type: QuestionComment
has text: @dhanushka it is shape descriptor, bro. The image a will be convert to image b.
type: Comment
score: 0

http://stackoverflow.com/comment/82255977
has text: Add some details please
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47648761

http://stackoverflow.com/a/47674139
answers question: http://stackoverflow.com/q/47673088
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47673088
downvote count: 0
upvote count: 1
score: 1
has body: It seems you are using lxml library. If that is so, the below method should fetch you the full content. Use .text_content() instead of .text in the print statement. content=''' Farina sbiancata arricchita (farina sbiancata di grano, ferro ridotto, vitamine B3-B1-B2-B9), zucchero, agenti lievitanti E500ii-E541i-E341i, destrosio, latte scremato disidratato, olio di soia parzialmente idrogenato, sale, glutine di grano, colorante E170, estratto secco di sciroppo di granoturco, caseinati di sodio (latte), emulsionante E471, regolatore di acidità E270. Può contenere tracce di uova. Contiene OGM. Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine 10.9g, sale 2.6g. ''' from lxml.html import fromstring root = fromstring(content) for items in root.xpath("//div[contains(@class,'ingredients')]/p"): print(items.text_content()) #take a closer look at this .text_content() instead of .text.

http://stackoverflow.com/q/47604139
has answer: http://stackoverflow.com/a/47604221
type: AnsweredQuestion
has body: Given two dates, for example: December 1, 2017 June 1, 2018 I want to get this result: January 1, 2018 February 1, 2018 March 1, 2018 April 1, 2018 May 1, 2018 June 1, 2018 Moreover, I also want to modify the intervals. In the case above, the interval is monthly. I also want it to become quarterly and semi-annually. So, given December 1, 2017 and June 1, 2018, it will generate March 1, 2018 for semi-annual and so on... I also want it inclusive which means that the end date should also be included Is there a python package or function for this?
downvote count: 0
linked to: http://stackoverflow.com/q/22696662
linked to: http://stackoverflow.com/q/993358
score: 4
has comment: http://stackoverflow.com/comment/82167130
favorite count: 0
has answer: http://stackoverflow.com/a/47604385
possible better answer: http://stackoverflow.com/a/47604385
type: Question
has comment: http://stackoverflow.com/comment/82167174
answer count: 3
has title: python - Get all dates within an interval
has answer: http://stackoverflow.com/a/47604662
accepted answer: http://stackoverflow.com/a/47604662
tagged with: python
tagged with: date
upvote count: 4

http://stackoverflow.com/q/47558488
has comment: http://stackoverflow.com/comment/82075112
upvote count: 2
has comment: http://stackoverflow.com/comment/82075015
score: 1
has title: Unable to capture certain phone numbers with different pattern
linked to: http://stackoverflow.com/q/123559
has body: What should be the appropriate regular expression to capture all the phone numbers listed below? I tried with one and it partially does the work. However, I would like to get them all. Thanks for any suggestion or help. Here are the numbers along with my script I tried with: import re content=''' 415-555-1234 650-555-2345 (416)555-3456 202 555 4567 4035555678 1 416 555 9292 +1 416 555 9292 ''' for phone in re.findall(r'\+?1?\s?\(?\d*\)?[\s-]\d*[\s-]\d*',content): print(phone) The result I'm getting is: 415 -555-1234 650-555-2345 555-3456 202 555 4567 4035555678 1 416 555 9292 +1 416 555 9292
downvote count: 1
has comment: http://stackoverflow.com/comment/82075354
accepted answer: http://stackoverflow.com/a/47559087
favorite count: 0
has comment: http://stackoverflow.com/comment/82075613
has comment: http://stackoverflow.com/comment/82075224
possible better answer: http://stackoverflow.com/a/47559072
has comment: http://stackoverflow.com/comment/82075369
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47559087
tagged with: python
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/82074727
has comment: http://stackoverflow.com/comment/82075554
answer count: 2
has comment: http://stackoverflow.com/comment/82075780
has comment: http://stackoverflow.com/comment/82076002
has answer: http://stackoverflow.com/a/47559072

http://stackoverflow.com/comment/82245098
has text: Can you please post the error code you are running into?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47582179

http://stackoverflow.com/a/47559994
score: 0
has body: As @Ajax1234 noted your indentation in state_dict is off and you need to add return states Your function is state_dict but you're calling states_dict You need to switch random.choice(states_dict) to random.choice(states_dict()) If you fix 1 &amp; 3 you should be good to go.
answers question: http://stackoverflow.com/q/47559845
type: Answer

http://stackoverflow.com/q/47571061
has comment: http://stackoverflow.com/comment/82099485
has answer: http://stackoverflow.com/a/47571314
type: Question
has comment: http://stackoverflow.com/comment/82099690
has answer: http://stackoverflow.com/a/47571462
tagged with: python
has comment: http://stackoverflow.com/comment/82099828
accepted answer: http://stackoverflow.com/a/47571314
has body: **This is a practice application I have a text file containing a id &amp; a password. Each pair is on separate lines like so: P1 dogs P2 tree I then have 2 functions to allow the user the add another id/password or update the password by selecting an ID then the new password. (I have removed the save functionality so I don't create loads of pairs when testing) The question is how would I write a check function so that when the user is creating a new pair.. it checks if the id/password already exists. Then on the update password function, it only checks if the password exists? My code so far: #Keyword check def used_before_check(keyword, fname): for line in open(fname, 'r'): login_info = line.split() username_found = False for line in login_info: if keyword in line: username_found == True if username_found == True: return True else: return False # New password function def new_password(): print("\nCreate a new password") new_id_input = input("Please give your new password an ID: ") new_password_input = input("Please enter your new password: ") print("ID in use?", used_before_check(new_id_input, txt_file)) print("Password in use?", used_before_check(new_password_input, txt_file)) #Change password function def change_password(): print("\nChange password") id_input = input("Enter the ID of the password you'd like to change: ") password_input = input("Now enter the new password: ") print("password_input",used_before_check(password_input, txt_file))
has comment: http://stackoverflow.com/comment/82099590
has title: Python - how to read through text file for keyword
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47571305
possible better answer: http://stackoverflow.com/a/47571305
has comment: http://stackoverflow.com/comment/82099577

http://stackoverflow.com/a/47584134
downvote count: 0
has body: Just as with Python’s subclassing, it’s possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, this means that if multiple parents contain a Meta class, only the first one is going to be used, and all others will be ignored. https://docs.djangoproject.com/en/1.11/topics/db/models/#multiple-inheritance It's possible but it has some restrictions like ( overriding fields in parent class and meta classes ) and in Django ORM or the model way of classes is a bit different in architecture than regular python inheritance, read carefully what the documentation mentions and try to keep it simple. ... The main use-case where this is useful is for “mix-in” classes: adding a particular extra field or method to every class that inherits the mix-in. Try to keep your inheritance hierarchies as simple and straightforward as possible so that you won’t have to struggle to work out where a particular piece of information is coming from edited: added another quote :)
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47583766

http://stackoverflow.com/comment/82183969
has text: @MartijnPieters - thanks for pointing that out. I actually have everything indented correctly in my code, but I forgot to tab in some more on here after I pasted everything in. I've fixed the indentations.
score: 0
comment on: http://stackoverflow.com/q/47612803
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47643961
tagged with: input
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48599561
has answer: http://stackoverflow.com/a/48597955
tagged with: list
has title: Checking if inputted strings are equal to strings in list?
tagged with: function
answer count: 2
downvote count: 0
upvote count: 1
score: 1
tagged with: string
has body: I'm working on a project that involves building a simplified version of a calendar agent that asks the user for when they want to schedule an appointment and does it for them (if that slot is free). This is the code I have so far: def find_index(val, seq): for index in range(len(seq)): place = seq[index] if place == val: return index else: return int("-1") def find_val(val, seq): for ele in seq: if val == ele: return True else: return False def init_nested_list(size_outer, size_inner): cal = [] for outer_index in range(size_outer): nested_list = [] for inner_index in range(size_inner): nested_list.append("-") cal.append(nested_list) return cal def get_input(possible_vals, day_or_time_string): count = 0 if day_or_time_string == "day": answer = input("What day would you like your appointment? ") else: answer = input("What time would you like your appointment? ") answer = answer.strip() nested_list = find_val(answer, possible_vals) while answer in possible_vals: break else: count = count + 1 answer = input("Invalid entry. Please enter a valid day: ") if count == 3: print("This is getting silly - still not a valid entry") answer = input("Please do try to enter a valid day: ") count = 0 return answer def book_slot(cal,days_labels, times_labels, day, time): **ignore this function, haven't finished it yet** find_index(day, days_labels) def start_scheduler(cal, days_labels, times_labels): while True: day = get_input(days_labels, "day") time = get_input(times_labels, "time") book_slot( cal, days_labels, times_labels, day, time) print("--------------------------------- ") res = input("Did you want to book more appointments (type n for no, any other key for yes)? ") if res == "n": break days_labels= ["Monday","Tuesday","Wednesday","Thursday", "Friday"] times_labels = ["9","10","11","12","1","2","3","4","5"] calendar = init_nested_list(len(days_labels), len(times_labels)) print("Welcome to the acupuncture booking system. ") start_scheduler(calendar, days_labels, times_labels) T…
favorite count: 0
type: Question

http://stackoverflow.com/a/47801120
score: 27
upvote count: 28
accepted answer of: http://stackoverflow.com/q/47551251
answers question: http://stackoverflow.com/q/47551251
downvote count: 1
type: AcceptedAnswer
type: Answer
has body: The apply method itself passes each "group" of the groupby object as the first argument to the function. So it knows to associate 'Weight' and "Quantity" to a and b based on position. (eg they are the 2nd and 3rd arguments if you count the first "group" argument. df = pd.DataFrame(np.random.randint(0,11,(10,3)), columns = ['num1','num2','num3']) df['category'] = ['a','a','a','b','b','b','b','c','c','c'] df = df'category','num1','num2','num3' df category num1 num2 num3 0 a 2 5 2 1 a 5 5 2 2 a 7 3 4 3 b 10 9 1 4 b 4 7 6 5 b 0 5 2 6 b 7 7 5 7 c 2 2 1 8 c 4 3 2 9 c 1 4 6 gb = df.groupby('category') implicit argument is each "group" or in this case each category gb.apply(lambda grp: grp.sum()) The "grp" is the first argument to the lambda function notice I don't have to specify anything for it as it is already, automatically taken to be each group of the groupby object category num1 num2 num3 category a aaa 14 13 8 b bbbb 21 28 14 c ccc 7 9 9 So apply goes through each of these and performs a sum operation print(gb.groups) {'a': Int64Index([0, 1, 2], dtype='int64'), 'b': Int64Index([3, 4, 5, 6], dtype='int64'), 'c': Int64Index([7, 8, 9], dtype='int64')} print('1st GROUP:\n', df.loc[gb.groups['a']]) 1st GROUP: category num1 num2 num3 0 a 2 5 2 1 a 5 5 2 2 a 7 3 4 print('SUM of 1st group:\n', df.loc[gb.groups['a']].sum()) SUM of 1st group: category aaa num1 14 num2 13 num3 8 dtype: object Notice how this is the same as the first row of our previous operation So apply is implicitly passing each group to the function argument as the first argument. From the docs GroupBy.apply(func, *args, **kwargs) args, kwargs : tuple and dict Optional positional and keyword arguments to pass to func Additional Args passed in "*args" get passed after the implict group argument. so using your code gb.apply(lambda df,a,b: sum(df[a] * df[b]), 'num1', 'num2') category a 56 b 167 c 20 dtype: int64 here 'num1' and 'num2' are being passed as additional arguments to each call of the lambda func…

http://stackoverflow.com/a/47579404
upvote count: 1
has body: if we use while(driver.find_element_by_link_text("Txt link") == True): or while(driver.find_element_by_link_text("Txt link").is_displayed() == True): let say if element is not displayed, then? it will throw exception right? so go for WebDriverWait to wait for element. In Java, i use try/catch and place while in try if i expect some times that element may not available but still i need to move further.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47579314
downvote count: 0

http://stackoverflow.com/comment/82177682
has text: Always close any open files at the end of the program!
comment on: http://stackoverflow.com/q/47609662
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82049193
score: 0
has text: do you want all?
comment on: http://stackoverflow.com/q/47546162
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47661977
has comment: http://stackoverflow.com/comment/82313408
has comment: http://stackoverflow.com/comment/82314295
has body: I played a bit with this module and it seems it doesn't accept arbitrary "attributes" but only a certain set of predefined ones. Apparently 'frequency' is none of them. I picked a sample from the documentation and replaced your $edge-&gt;set_attribute( 'frequency', $frequency ); with $edge-&gt;set_attribute( 'label', $frequency ); as they often mention label in the examples. print $graph-&gt;as_ascii(); then printed: +--------------+ 2 +--------------+ | 14 | ---&gt; | million | +--------------+ +--------------+ +--------------+ 2 +--------------+ 2 +----------+ | digital | ---&gt; | humanities | ---&gt; | research | +--------------+ +--------------+ +----------+ +--------------+ 2 +--------------+ 3 +----------+ | participants | ---&gt; | may | ---&gt; | want | +--------------+ +--------------+ +----------+ ... Is that what you were after? Eventually I found the complete documentation for Graph::Easy. The Attributes section lists the allowed attributes. I'm pretty sure there is a way to have custom attributes because the module has a method get_custom_attributes.
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47661180
has comment: http://stackoverflow.com/comment/82320800
type: Answer

http://stackoverflow.com/a/47585366
has comment: http://stackoverflow.com/comment/82171806
has comment: http://stackoverflow.com/comment/82146144
has comment: http://stackoverflow.com/comment/82161737
type: Answer
has comment: http://stackoverflow.com/comment/82166613
has body: You got off lightly, you probably don't want to be working for a hedge fund where the quants don't understand basic algorithms :-) There is no way to process an arbitrarily-sized data structure in O(1) if, as in this case, you need to visit every element at least once. The best you can hope for is O(n) in this case, where n is the length of the string. Although, as an aside, a nominal O(n) algorithm will be O(1) for a fixed input size so, technically, they may have been correct here. However, that's not usually how people use complexity analysis. It appears to me you could have impressed them in a number of ways. First, by informing them that it's not possible to do it in O(1), unless you use the "suspect" reasoning given above. Second, by showing your elite skills by providing Pythonic code such as: inpStr = '123412345123456' # O(1) array creation. freq = [0] * 1000 # O(n) string processing. for val in [int(inpStr[pos:pos+3]) for pos in range(len(inpStr) - 2)]: freq[val] += 1 # O(1) output of relevant array values. print ([(num, freq[num]) for num in range(1000) if freq[num] &gt; 1]) This outputs: [(123, 3), (234, 3), (345, 2)] though you could, of course, modify the output format to anything you desire. And, finally, by telling them there's almost certainly no problem with an O(n) solution, since the code above delivers results for a one-million-digit string in well under half a second. It seems to scale quite linearly as well, since a 10,000,000-character string takes 3.5 seconds and a 100,000,000-character one takes 36 seconds. And, if they need better than that, there are ways to parallelise this sort of stuff that can greatly speed it up. Not within a single Python interpreter of course, due to the GIL, but you could split the string into something like (overlap indicated by vv is required to allow proper processing of the boundary areas): vv 123412 vv 123451 5123456 You can farm these out to separate workers and combine the results afterwards. The splitting o…
downvote count: 1
has comment: http://stackoverflow.com/comment/82173219
accepted answer of: http://stackoverflow.com/q/47581326
has comment: http://stackoverflow.com/comment/82173015
has comment: http://stackoverflow.com/comment/82145472
has comment: http://stackoverflow.com/comment/82209649
has comment: http://stackoverflow.com/comment/82209933
has comment: http://stackoverflow.com/comment/82167310
answers question: http://stackoverflow.com/q/47581326
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82171881
score: 171
has comment: http://stackoverflow.com/comment/82175446
has comment: http://stackoverflow.com/comment/82163575
upvote count: 172
has comment: http://stackoverflow.com/comment/82175528
has comment: http://stackoverflow.com/comment/82167504

http://stackoverflow.com/a/47634653
downvote count: 0
has body: Here is a pivot_table approach # Subtract the quarter from date save it in a column df['Q'] = df['DATE'] - pd.tseries.offsets.QuarterEnd() #0 2006-09-30 #1 2006-09-30 #2 2006-09-30 #3 2006-12-31 #4 2006-12-31 #5 2006-12-31 #Name: Q, dtype: datetime64[ns] # Drop and pivot for not including the columns ndf = df.drop(['DATE','Q'],1).pivot_table(index=pd.to_datetime(df['Q']).dt.to_period('Q'),aggfunc='last') BBGN QQ4567 SSD Qdate 2006Q3 1.30 10055.466 22.080 2006Q4 1.44 10480.888 22.125
upvote count: 1
answers question: http://stackoverflow.com/q/47633468
score: 1
type: Answer

http://stackoverflow.com/q/47582940
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/5946236
possible better answer: http://stackoverflow.com/a/47583054
upvote count: 3
has answer: http://stackoverflow.com/a/47583976
has answer: http://stackoverflow.com/a/47583054
has body: I was given two files. file1 contains a list of country names and their continent such as: Country,Continent China,Asia United States of America,North America Brazil,South America and file2 contains a list of country names and their population and areas, such as: Country|Population|Area China|1,339,190,000|9,596,960.00 United States of America|309,975,000|9,629,091.00 Brazil|193,364,000|8,511,965.00 I wanted to create two dictionaries, one for file1 and one for file2, then I wanted to combine all the values that has the same key. My final output should be something like this: China:[193364000, 8511965.00, Asia] Where the population is an integer and area is float I made two dictionaries, however I have no idea how to combine the values together. Here is my code: #first dictionary Continent = {} file2 = open("file2.txt", "r") for i in file2: file2 = i.strip parts2 = i.split(",") Continent[parts2[0]] = parts2[1] #Second dictionary Information = {} file1 = open("file1.txt", "r") for j in file1: file1 = j.strip part1 = j.split("|") #Strip "," off from the values so that it's an intger/float part1[1] = part1[1].replace(",", "") part1[2] = part1[2].replace(",", "") Information[part1[0]] = [part1[1], part1[2]]
accepted answer: http://stackoverflow.com/a/47583192
downvote count: 0
has comment: http://stackoverflow.com/comment/82123679
has answer: http://stackoverflow.com/a/47583192
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
tagged with: dictionary
answer count: 4
has comment: http://stackoverflow.com/comment/82124022
has comment: http://stackoverflow.com/comment/82123681
has title: How to combine values in two different dictionaries that have the same key in python
has answer: http://stackoverflow.com/a/47583055
has comment: http://stackoverflow.com/comment/82124086

http://stackoverflow.com/a/47658392
has comment: http://stackoverflow.com/comment/82284345
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47641318
has body: I think this is the almost the most efficient way to do what you want. I would use next() and a generator expression rather than a list, to avoid parsing the whole options list when it's not necessary: req_type = next(opt[1] for opt in pkt[DHCP].options if isinstance(opt, tuple) and opt[0] == 'message-type') Note that I've also added a check against the type of opt, as some are string objects. You could use a dict() but you would then have, again, to parse the whole options list. As a side note, the way DHCP options are handled in Scapy is a bit old and the correct way to do that now would probably be to use a PacketListField with cleaner methods to access the options.
type: Answer
accepted answer of: http://stackoverflow.com/q/47641318

http://stackoverflow.com/a/47659226
score: 0
has body: Based on dubbbdan idea, there is a code that works: my_max=16 def my_func(row,grouped_df1): if (grouped_df1.get_group(row['Group'])['Value']&gt;my_max).any(): return 1 else: return 0 SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]] for Sample in SampleList: grouped_df = Sample[0].groupby('Group') Sample[1]['Bad_Row'] = Sample[1].apply(lambda x: my_func(x,grouped_df), axis=1) Sample[1].drop(Sample[1][Sample[1]['Bad_Row']!=0].index, inplace=True) Sample[1].drop(['Bad_Row'], axis = 1, inplace = True)
answers question: http://stackoverflow.com/q/47657153
type: Answer

http://stackoverflow.com/q/47629598
has body: Question I tried to create a CNN where I am using images as labels, with values between 0 and 1. After some training my net has a loss of round about 23. Now I want to see the results. For this purpose I am using this python script: import caffe import numpy as np from PIL import Image net = caffe.Net('D:/caffe/net.prototxt', 'D:/caffe/net_iter_35000.caffemodel', caffe.TEST) # load input and configure preprocessing transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) transformer.set_mean('data', np.load('train_mean.npy').mean(1).mean(1)) transformer.set_transpose('data', (2,0,1)) transformer.set_channel_swap('data', (2,1,0)) transformer.set_raw_scale('data', 255.0) #note we can change the batch size on-the-fly #since we classify only one image, we change batch size from 10 to 1 net.blobs['data'].reshape(1,3,360,360) #load the image in the data layer im = caffe.io.load_image('train/img0.png') net.blobs['data'].data[...] = transformer.preprocess('data', im) #compute out = net.forward() result = out['conv7'][0][0] Now I am expecting the values of result to approximatly be between 0 and 1. But in reality result.max() returns 5.92 and result.min() returns -4315.5. Is there a mistake in the python script or are this values normal for a loss of 23? Additional Infos My train_test.prototxt: layer { name: "mynet" type: "Data" top: "data0" top: "label0" include { phase: TRAIN } transform_param { mean_file: "train_mean.binaryproto" scale: 0.00390625 } data_param { source: "train_lmdb" batch_size: 32 backend: LMDB } } layer { name: "mynetlabel" type: "Data" top: "data1" top: "label1" include { phase: TRAIN } transform_param { scale: 0.00390625 } data_param { source: "train_label_lmdb_2" batch_size: 32 backend: LMDB } } layer { name: "mnist" type: "Data" top: "data0" top: "label0" include { phase: TEST } transform_param { mean_file: "train_mean.binaryproto" scale: 0.00390625 } data_param { source: "val_lmdb" batch_size: 16 backend: LMDB } } layer { name: "mn…
tagged with: neural-network
tagged with: caffe
has answer: http://stackoverflow.com/a/47629881
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/39017998
has title: Caffe test net with images as labels
type: AnsweredQuestion
tagged with: deep-learning
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/39719915
accepted answer: http://stackoverflow.com/a/47629881

http://stackoverflow.com/comment/82297362
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47669206
type: AnswerComment
has text: no need to call set ;-) , see other answers. My guess would be that `loc.keys()` is faster because it returns a view unlike `set(loc)` which I presume has to copy the keys.

http://stackoverflow.com/q/47597358
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82167411
has comment: http://stackoverflow.com/comment/82164977
has comment: http://stackoverflow.com/comment/82222178
tagged with: python
tagged with: computer-vision
tagged with: opencv
score: 0
has title: Removal Background with Shadows on HUE
has comment: http://stackoverflow.com/comment/82190922
has comment: http://stackoverflow.com/comment/82167179
has comment: http://stackoverflow.com/comment/82157029
has comment: http://stackoverflow.com/comment/82153097
tagged with: image-processing
has comment: http://stackoverflow.com/comment/82161738
has body: I have an image of a leaf on a poorly white screen and need to find out just the leaf: The problem is that it contains greenish shadows, so simple color-based methods are not enough. Thus, I need some preprocessing to achieve an uniform background and to enhance important features. The goal is to delete undesired noise and distortions to apply an Expectation Maximization algorithm. I tried playing with OpenCV fastNlMeansDenoising, but it is not sufficient. UPDATE FOR CLARIFICATION When segmenting with color it is imperative to use the right color domains that exclude undesired noise. So we used Saturation and Value color components for leaf segmentation. This was useful for posterior segmentation using Expectation-Maximization (EM). I used OpenCV to convert the original images into the HSV domain. Then, using NumPy, I extracted the Saturation and Value components, which were fed to the EM algorithm. Once images were converted to HSV and the desired channels were extracted, I applied EM to the color domain in order to cluster the pixels into one of 2 possible groups: leaf and non-leaf groups. However, due to that greenish the EM is returning a wrong result.
has comment: http://stackoverflow.com/comment/82167440
type: Question
has comment: http://stackoverflow.com/comment/82167383

http://stackoverflow.com/q/47680732
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/47680845
answer count: 2
has answer: http://stackoverflow.com/a/47680845
score: 2
has comment: http://stackoverflow.com/comment/82321436
possible better answer: http://stackoverflow.com/a/57261050
downvote count: 2
linked to: http://stackoverflow.com/q/34682828
linked to: http://stackoverflow.com/q/40455457
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82320685
tagged with: pandas
linked to: http://stackoverflow.com/q/40885318
has body: I have a dataframe that contains school types and their locations. One of the columns is "Institude_Type" and the two school types are "Secondary (non-grammar) School" and "Secondary (grammar) School". I want to take all of the Secondary (non-grammar) School's information and put it into another dataframe - but I'm not sure how to do this. I want it to be an exact copy of the current DF, with all the same 8 columns. Just one with the grammar and the other with non grammar schools. Thanks in advance.
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/57261050
has comment: http://stackoverflow.com/comment/82320971
has title: Pandas - how do you create a new data frame based on another dataframe?
favorite count: 0

http://stackoverflow.com/q/47655871
has body: I'm trying to filter a table on a column that contain spaces. ... events = database_session.query(table) events.filter(table.column with space == 'xvalue') &lt; -- I want to do that ... There is for sure a simple way of doing that, but I can't seem to find it anywhere.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48686249
type: Question
type: AnsweredQuestion
answer count: 1
upvote count: 5
tagged with: python
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/48686249
has title: SQLAlchemy column name with space
score: 5

http://stackoverflow.com/q/47559551
answer count: 2
tagged with: nested-lists
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has title: Removing sublists contained within a list
linked to: http://stackoverflow.com/q/1207406
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/1207406
has answer: http://stackoverflow.com/a/47559643
has answer: http://stackoverflow.com/a/47559575
duplicate of: http://stackoverflow.com/q/6500888
tagged with: python
has body: I'm trying to remove all elements within a list except those that are integers. I am able to remove strings and booleans but I am unable to remove lists given the code below. messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] for idx, val in enumerate(messy_list): if type(val) != int: messy_list.pop(idx) print(messy_list)
type: Question
tagged with: list

http://stackoverflow.com/a/47602944
upvote count: 6
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47602800
has body: I do not think it is possible to get the list of COM objects directly from python, however you can run the following code (and indeed run it from inside python) in Powershell: Get-ChildItem HKLM:\Software\Classes -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -match '^\w+\.\w+$' -and (Test-Path -Path "$($_.PSPath)\CLSID") } | Select-Object -ExpandProperty PSChildName This will output a list of all valid names of COM objects on your system sorted alphabetically, and the syntax is normally MainProgram.SubFunction. Some of the output on my machine: I hope this helps!
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47602800
score: 6

http://stackoverflow.com/a/47677162
type: Answer
has body: The whole point here: Java only knows signed types. This means: although the Java byte is also about 8 bits, the range is from -128 to 127. Unsigned bytes go from 0 to 255. That is all there is to this. The only thing that really matters is that you are consistent about how the values dealt with. See here for some further thoughts on this topic.
upvote count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82313902
answers question: http://stackoverflow.com/q/47677018

http://stackoverflow.com/comment/82241344
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47641332
type: QuestionComment
has text: Is there a reason you didn't want to export this data into a sql database style of setup? gaining access to foreign keys would make this problem trivial.

http://stackoverflow.com/comment/82257113
score: 5
comment on: http://stackoverflow.com/q/47649453
has text: what do you want to fix here exactly? what should it do when it is e.g., `for i in range(2, 2):`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82315301
type: AnswerComment
has text: I will see if I find a solution later on.
comment on: http://stackoverflow.com/a/47677014
type: Comment
score: 0

http://stackoverflow.com/q/47565958
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47566203
has answer: http://stackoverflow.com/a/47566203
has body: I am newbie to python and i'm assigned to create my own algorithm to solve linear regression without using any import. The problem is, when i try my program to calculate the error, it give the strange value (i compare it with calculation from microsoft excel). Here's my program: x=[1.,1.,2.,2.,2.,2.,2.,2.,2.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,3.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,4.,5.,5.,5.,5.,5.,5.,5.,5.,6.] y=[67.,62.,109.,83.,91.,88.,123.,100.,109.,137.,131.,122.,122.,118.,115.,131.,143.,142.,122.,140.,150.,140.,150,150.,140.,150.,130.,130.,138.,135.,146.,146.,145.,145.,144.,140.,150.,152.,157.,155.,153.,154.,158.,162.,161.,162.,165.,171.,162.,169.,167.,150.,170.,140.,140.,150.,150.,150.,160.,150.,150.,150.,150.,140.,160.,170.,160.,160.,170.,171.,188.,170.,150.,150.,160.,160.,180.,170.] sumx = 0 sumxdoubled = 0 sumxsquare = 0 sumxy = 0 meanx = 0 sumy = 0 sumerror = 0 n= 78 for i in range(78): sumxy = sumxy + (x[i] * y[i]) print("Total (x.y) : ",sumxy) for i in range(78): sumx = sumx + x[i] print("Total x : ",sumx) for i in range(78): sumxsquare = sumxsquare + (x[i] ** 2) print("Total (x^2) : ",sumxsquare) sumxdoubled = sumx ** 2 print("(Total x)^2 : ",sumxdoubled) meanx = sumx / n print("Average x : ",meanx) for i in range(78): sumy = sumy + y[i] print("Total y : ",sumy) meany = sumy / n print("Average y : ",meany) a1 = ((n*sumxy) - (sumx * sumy)) / ((n*sumxsquare) - sumxdoubled) print("a1 = ",a1) a0 = meany - a1 * meanx print("a0 = ",a0) for i in range (78): sumerror = sumerror + (y[i] - a0 - (a1 * x[i])) print("Total error = ",sumerror) And the output is: Total (x.y) : 42117.0 Total x : 283.0 Total (x^2) : 1093.0 (Total x)^2 : 80089.0 Average x : 3.628205128205128 Total y : 11201.0 Average y : 143.60256410256412 a1 = 22.312294288480153 a0 = 62.64898354307843 Total error = -7.673861546209082e-13 The error value when i try the same data with microsoft excel is…
has title: Python, weird value when trying to calculate error of linear regression
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: excel

http://stackoverflow.com/a/47562037
has comment: http://stackoverflow.com/comment/82093803
has comment: http://stackoverflow.com/comment/82153655
has body: You can verify urllib3 is present in the venv with the pip module: http://docs.ansible.com/ansible/latest/pip_module.html I think you need to pass the host/hostgroup as a var on command line to the playbook: ansible-playbook playbookX.yml -e "myhosts=[host or hostgroup]" --ask-vault-pass I suggest use no_log on the task to hide the parameters in the output. I guess it will still show in with ps though. --- - name: Run on remote host hosts: "{{ myhosts }}" tasks: - &lt;my other tasks on remote host&gt; - name: run python script locally local_action: command python scriptname.py "{{ my_ecrypted_password }}" "{{ myhosts }}" no_log: True You could create a template scriptname.py.j2, add "{{ my_encrypted_password }}" where needed, then create your tmp scriptname.py, execute and remove the tmp file. That was it won't show with ps but it will be in the tmp .py file. Last suggestions would be to just put it in the .py scipt and encrypt it with ansible-vault.
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82134429
score: 3
has comment: http://stackoverflow.com/comment/82118008
accepted answer of: http://stackoverflow.com/q/47551111
type: Answer
answers question: http://stackoverflow.com/q/47551111

http://stackoverflow.com/q/47631328
has title: Is there any way to update zone in specific views using dnspython?
answer count: 1
has answer: http://stackoverflow.com/a/47667697
type: Question
tagged with: view
score: 0
type: UnansweredQuestion
tagged with: dns
tagged with: python
has body: Just like the title. I was struggling to work with that, but I couldn't find any way to make that work. Is there anyone know how to do that. Please help, thanks!
tagged with: bind
tagged with: dnspython

http://stackoverflow.com/comment/82228074
has text: You can explicitly convert a map object to list like `list(map(lambda i: 0 if i%2!=0 else i, bar))`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47634677
type: Comment

http://stackoverflow.com/comment/82185831
type: QuestionComment
comment on: http://stackoverflow.com/q/47613053
type: Comment
has text: i need to use mumps library. inverse of large sparse matrix
score: 0

http://stackoverflow.com/a/47684462
has body: I would suggest using something like AWS Lambda. Lambda is an AWS product that will allow you to host your function online and you can just call it with HTTP requests and GET a response. More at aws.amazon.com/lambda
answers question: http://stackoverflow.com/q/47684408
type: Answer
score: 0

http://stackoverflow.com/a/47593136
score: 3
answers question: http://stackoverflow.com/q/47592463
has body: There are quite a few issues with your code, ie program crashing if the file does not exist: with open(storage_path,'r') as f: opening storage_path for writing but actually not writing anything: print('each time I am creating the new one') with open(storage_path,'w') as f: data_base = {} f.close() And actually if you happened to have f.seek(2) == 2, the json.load(f) would also crash since at this point you moved the file pointer at the 3rd char so subsequent read in json.load() wouldn't get the whole content. Here's a fixed version that should work AFAICT: import argparse import os import tempfile import json storage = argparse.ArgumentParser() storage.add_argument("--key", help="input key's name") storage.add_argument("--val", help="value of key", default=None) args = storage.parse_args() storage_path = os.path.join(tempfile.gettempdir(), 'storage.data') data_base = None if os.path.exists(storage_path): with open(storage_path,'r') as f: try: data_base = json.load(f) print('loaded that: ',data_base) except Exception as e: print("got %s on json.load()" % e) if data_base is None: print('each time I am creating the new one') data_base = {} with open(storage_path,'w') as f: json.dump(data_base, f) # don't prevent the user to set `"Not found" as value, if might # be a legitimate value. # NB : you don't check if `args.key` is actually set... maybe you should ? sentinel = object() if data_base.get(args.key, sentinel) is sentinel: if args.val is not None: data_base[args.key] = args.val with open(storage_path, 'w') as f: json.dump(data_base, f) print('dumped this: ',data_base)
type: Answer
has comment: http://stackoverflow.com/comment/82145040
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82144975
accepted answer of: http://stackoverflow.com/q/47592463

http://stackoverflow.com/comment/109385171
type: AnswerComment
comment on: http://stackoverflow.com/a/61842925
type: Comment
has text: Hey Joel, you should convert all code statements in coding format. For reference, you can take a look https://stackoverflow.com/help/how-to-answer
score: 0

http://stackoverflow.com/comment/82193242
score: 0
comment on: http://stackoverflow.com/q/47617045
type: Comment
type: QuestionComment
has text: thanks. what was unclear for me was that the `l` has regular step.

http://stackoverflow.com/a/47656380
type: Answer
has body: I came with a solution which to me looks awful, so any improvements are welcome sess = tf.InteractiveSession() x = tf.zeros((2,3,2)) indices_1 = tf.constant([0, 1]) indices_2 = tf.constant([1, 1]) updates_tf = tf.ones((2, 2)) x_temp = tf.Variable(tf.reshape(x, [-1, 2])) indices_flat = tf.shape(x)[1]*indices_1 + indices_2 sess.run(tf.initialize_all_variables()) print(sess.run(tf.reshape(tf.scatter_update(x_temp, indices_flat, updates_tf), tf.shape(x)))) Result [[[ 0. 0.] [ 1. 1.] [ 0. 0.]] [[ 0. 0.] [ 1. 1.] [ 0. 0.]]]
answers question: http://stackoverflow.com/q/47655896
score: 0

http://stackoverflow.com/comment/82349532
type: Comment
comment on: http://stackoverflow.com/a/47694956
type: AnswerComment
has text: @CarloAllocca Is it that big data? You put the data and expected output later, I have to go now, let me update the answer and go.
score: 0

http://stackoverflow.com/a/47641204
upvote count: 3
answers question: http://stackoverflow.com/q/47639983
type: Answer
has body: The strip() method will strip all the characters from the end of the string. In your case, strip starts at the end of your string, encounters a '\n' character, and exits. It seems a little unclear what you are trying to do, but I will assume that you are looking to clear out any white space between the last non-whitespace character of your string and the newline. Correct me if I'm wrong. There are many ways to do this, and this may not be the best, but here is what I came up with: m = ['This, is a string. \n', 'another string! \n', 'final example\n '] m = map(lambda(x): x.rstrip() + '\n' if x[-1] == '\n' else x.rstrip(' '), m) print(m) ['This, is a string.\n', 'another string!\n', 'final example\n'] Here I use the built in map function iterate over each list element and remove all white space from the end (rstrip() instead of strip() which does both the start and end) of the string, and add in a new line if there was one present in the original string.
downvote count: 0
score: 3

http://stackoverflow.com/a/47687314
has comment: http://stackoverflow.com/comment/82374397
has comment: http://stackoverflow.com/comment/82334216
has comment: http://stackoverflow.com/comment/82334367
answers question: http://stackoverflow.com/q/47687285
has comment: http://stackoverflow.com/comment/82372376
has body: If both files are in the same folder you can: file_b.py from file_a import var1 print(var1 " is the current path") userinput = input("Type new directory path here: ") var1 = userinput Or import file_a print(file_a.var1 " is the current path") userinput = input("Type new directory path here: ") file_a.var1 = userinput But, Do you know that you can't modify the another file itself? var1 will be changed in the memory, but if you open file_a.py, var1 will be "/path/to/file". P.S: A little suggestion print(var1 " is the current path") --> print(var1, "is the current path"). Edit: I think this will be good by your level (you are doing this like homework, if I make something more efficient or with some modules the teacher would notice it). def re_write(new): with open("file_a.py", 'r') as file: new_file = [] for line in file: if "var1" in line: new_file.append(line.split("var1")[0] + "var1 = '" + new + "'") else: new_file.append(line) with open("file_a.py", 'w') as file: for line in new_file: file.writelines(line) A better code (faster, with less memory usage and maybe better in general) could be find in this question.
accepted answer of: http://stackoverflow.com/q/47687285
has comment: http://stackoverflow.com/comment/82334179
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82375535
downvote count: 0

http://stackoverflow.com/comment/82205138
has text: `sparse.random` produces values in the (0,1) range, so the resulting `log` will all be negative.
type: Comment
comment on: http://stackoverflow.com/q/47615473
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82583055
type: QuestionComment
score: 3
type: Comment
comment on: http://stackoverflow.com/q/47643872
has text: Have you tried that `sudo apt-get install python-pandas`?

http://stackoverflow.com/q/47637288
type: UnansweredQuestion
tagged with: naivebayes
has title: R saving Naive Bayes for training, R equivalent to Pythons pickle.
tagged with: python
score: 4
tagged with: http://stackoverflow.com/tag/r
upvote count: 4
has answer: http://stackoverflow.com/a/47640609
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I have been practicing data analysis on Python and have been looking to do the same with R particularly sentiment analysis. With python to train a NB algorithm I could save it as a pickle and reuse to continue training it however I am unsure how I would do this with R. This is currently what I have followed to train and test a data set using the library e1071. After cleaning the data. convert_count &lt;- function(x) { y &lt;- ifelse(x &gt; 0, 1,0) y &lt;- factor(y, levels=c(0,1), labels=c("No", "Yes")) y } trainNB &lt;- apply(dtm.train.nb, 2, convert_count) testNB &lt;- apply(dtm.test.nb, 2, convert_count) system.time( classifier &lt;- naiveBayes(trainNB, df.train$class, laplace = 1) ) system.time( pred &lt;- predict(classifier, newdata=testNB) ) table("Predictions"= pred, "Actual" = df.test$class ) Can anyone explain to me what the Python pickle equivalent would be when using R? Another question I have is is using tm to clean the corpus and then using the document term matrix achieve bag of words? Thanks

http://stackoverflow.com/comment/106726557
score: 1
comment on: http://stackoverflow.com/a/47562412
type: Comment
has text: A way to create static methods is by calling `plot = staticmethod(plot)` after the import. You could also automate this process by writing a metaclass...
type: AnswerComment

http://stackoverflow.com/q/47557989
has title: Recursively parse all category links and get all products
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82073791
downvote count: 1
favorite count: 0
type: Question
tagged with: xpath
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47559086
has comment: http://stackoverflow.com/comment/82073708
has body: I've been playing around with web-scraping (for this practice exercise using Python 3.6.2) and I feel like I'm loosing it a bit. Given this example link, here's what I want to do: First, as you can see, there are multiple categories on the page. Clicking each of the categories from above will give me other categories, then other ones, an so on, until I reach the products page. So I have to go in depth x number of times. I thought recursion will help me achieve this, but somewhere I did something wrong. Code: Here, I'll explain the way I approached the problem. First, I created a session and a simple generic function which will return a lxml.html.HtmlElement object: from lxml import html from requests import Session HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/62.0.3202.94 Safari/537.36" } TEST_LINK = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128' session_ = Session() def get_page(url): page = session_.get(url, headers=HEADERS).text return html.fromstring(page) Then, I thought I'll need two other functions: one to get the category links and another one to get the product links To distinguish between one and another, I figured out that only on category pages, there's a title which contains CATEGORIES every time, so I used that: def read_categories(page): categs = [] try: if 'CATEGORIES' in page.xpath('//div[@class="boxData"][2]/h2')[0].text.strip(): for a in page.xpath('//*[@id="carouselSegment2b"]//li//a'): categs.append(a.attrib["href"]) return categs else: return None except Exception: return None def read_products(page): return [ a_tag.attrib["href"] for a_tag in page.xpath("//ul[@id='prodResult']/li//div[@class='imgWrapper']/a") ] Now, the only thing left, is the recursion part, where I'm sure I did something wrong: def read_all_categories(page): cat = read_categories(page) if not cat: yield read_products(page) else: yield from read_all_categories(page) def main(…
accepted answer: http://stackoverflow.com/a/47559086
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82074232
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47562688
possible better answer: http://stackoverflow.com/a/47562688
tagged with: lxml

http://stackoverflow.com/comment/82364217
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47673406
has text: Have you tried just listing the first 12 URLs in the test list, to see if they are eventually crawled? Based on https://scrapy.readthedocs.io/en/0.14/faq.html#does-scrapy-crawl-in-breath-first-or-depth-first-order I think that URLs are not crawled linearly, so that may explain why your first items are pushed into a queue until later.

http://stackoverflow.com/comment/82294774
type: QuestionComment
comment on: http://stackoverflow.com/q/47667945
type: Comment
score: 0
has text: Can you please try this `employee_list = Employee.objects.all().values(*val_params).order_by('id') `

http://stackoverflow.com/a/47601270
has comment: http://stackoverflow.com/comment/82166133
has comment: http://stackoverflow.com/comment/82166154
answers question: http://stackoverflow.com/q/47600932
has comment: http://stackoverflow.com/comment/82166137
has comment: http://stackoverflow.com/comment/82166176
has comment: http://stackoverflow.com/comment/82166122
has comment: http://stackoverflow.com/comment/82165888
has body: Two steps df['result']=df.B.map(df.groupby('B').B.apply(lambda x : [x.index.values][0])) df['result']=df.reset_index().apply(lambda x : list(set(x['result'])-set([x['index']])),axis=1) df Out[1569]: B result 0 1 [1, 2] 1 1 [0, 2] 2 1 [0, 1] 3 5 [5] 4 0 [] 5 5 [3]
has comment: http://stackoverflow.com/comment/82165898
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47600932
downvote count: 0
has comment: http://stackoverflow.com/comment/82302107
score: 2
has comment: http://stackoverflow.com/comment/82166207
has comment: http://stackoverflow.com/comment/82166098
has comment: http://stackoverflow.com/comment/82166088
has comment: http://stackoverflow.com/comment/82166091
has comment: http://stackoverflow.com/comment/82302264
type: Answer

http://stackoverflow.com/q/47634530
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: mypy
tagged with: python-3.x
has title: Mypy rejects type objects created with `type(name, (bases,), {})`
has body: I'm having some trouble getting mypy to accept type objects. I am convinced I'm just doing it wrong but my google searches have not led me to any answers so far. class Good(object): a = 1 def works(thing: Good): print(thing.a) o = Good() works(o) Bad = type('Bad', (object, ), dict(a=1)) def fails_mypy(thing: Bad): print(thing.a) s = Bad() fails_mypy(s) Things constructed like 'Good' are ok, while things constructed like 'Bad' fail mypy checks with: error: Invalid type "test.Bad" error: Bad? has no attribute "a"
upvote count: 2
accepted answer: http://stackoverflow.com/a/47635138
tagged with: python
tagged with: python-3.6
has answer: http://stackoverflow.com/a/47635138
score: 2
type: AnsweredQuestion
tagged with: types

http://stackoverflow.com/q/47611139
tagged with: cloud
tagged with: websocket
tagged with: python
has comment: http://stackoverflow.com/comment/82181201
has comment: http://stackoverflow.com/comment/82194450
has title: websocket data collection design
has answer: http://stackoverflow.com/a/47617568
upvote count: 3
score: 3
tagged with: aiohttp
downvote count: 0
has comment: http://stackoverflow.com/comment/82193298
has body: I have a more open-ended design oriented question for you here. I have background in Python but not in web nor async programming. I am writing an app to save data collect from websockets 24/24, 7/7 with the aim to minmise data loss. My initial thoughts is to use Python 3.6 with asyncio, aiohttp and aiofiles. I don't know whether to use one co-routine per websocket connection or one thread per websocket connection. Performance may not an issue as much as good connection error handling.
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82193177
has comment: http://stackoverflow.com/comment/82181137
tagged with: python-aiofiles
type: UnansweredQuestion

http://stackoverflow.com/comment/90549220
type: AnswerComment
comment on: http://stackoverflow.com/a/47589259
score: 0
has text: @trallgorm There was a strange character in the text in the cell - I think it was a bendy quote mark or something, which caused Excel to crash.
type: Comment

http://stackoverflow.com/q/47637477
has comment: http://stackoverflow.com/comment/82257322
has comment: http://stackoverflow.com/comment/82250280
type: AnsweredQuestion
tagged with: nao-robot
accepted answer: http://stackoverflow.com/a/47665202
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47665202
upvote count: 1
score: 1
favorite count: 0
type: Question
has body: If the power batch is lifted, this means Pepper is probably charging and the motions around the room and the rotations around himself are disabled. Is there a way to forbid those motions and rotations while this power batch is closed?
has title: How to disable Pepper moving around the room
tagged with: pepper
tagged with: python

http://stackoverflow.com/q/47659088
tagged with: python
type: UnansweredQuestion
answer count: 1
tagged with: docker
tagged with: rest
type: Question
score: 3
upvote count: 3
tagged with: kubernetes
has body: I am trying to consume Python Rest API call from a container running inside the Kubernetes. I am able to consume the service inside the pod *curl http://localhost:5002/analyst_rating -v * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 5002 (#0) &gt; GET /analyst_rating HTTP/1.1 &gt; Host: localhost:5002 &gt; User-Agent: curl/7.47.0 &gt; Accept: */* &gt; * HTTP 1.0, assume close after body &lt; HTTP/1.0 200 OK &lt; Content-Type: application/json &lt; Content-Length: 37 &lt; Server: Werkzeug/0.12.2 Python/2.7.12 &lt; Date: Tue, 05 Dec 2017 17:02:00 GMT &lt; { "Analyst Rating": "Hello World" * Closing connection 0* When I am running the curl command from outside the cluster, I am getting the below error: curl -I http://184.173.44.62:30484/analyst_rating -v * Trying 184.173.44.62... * TCP_NODELAY set * Connected to 184.173.44.62 (184.173.44.62) port 30484 (#0) &gt; HEAD /analyst_rating HTTP/1.1 &gt; Host: 184.173.44.62:30484 &gt; User-Agent: curl/7.54.0 &gt; Accept: */* &gt; * Closing connection 0 curl: (8) Weird server reply My Cluster IP is 184.173.44.62 and my service node port is 30484. I am able to make connections but not able to receive any response. Also, I have checked inside the pod, I am not getting any GET request. Also, Following is my deployment info: kubectl describe deployment Name: sunlife-analystrating-deployment Namespace: default CreationTimestamp: Tue, 05 Dec 2017 10:53:53 -0500 Labels: app=sunlife-analystrating-deployment Annotations: deployment.kubernetes.io/revision=1 Selector: app=sunlife-analystrating-deployment Replicas: 1 desired | 1 updated | 1 total | 1 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 1 max unavailable, 1 max surge Pod Template: Labels: app=sunlife-analystrating-deployment Containers: sunlife-analystrating-deployment: Image: registry.ng.bluemix.net/dockerservice/tensorflowrunningimage:02 Port: 5002/TCP Environment: &lt;none&gt; Mounts: &lt;none&gt; Volumes: &lt;n…
tagged with: curl
favorite count: 0
has title: "curl: (8) Weird server reply" from kubernetes
downvote count: 0
has answer: http://stackoverflow.com/a/47664299

http://stackoverflow.com/q/47657176
downvote count: 0
favorite count: 0
upvote count: 1
has body: My dataframe looks like this: Person Number BOB 1.23 BOB -1.23 Jeff 18.01 Jack 82.04 Jack 14.02 Jeff -18.01 what I want to do is look at the Persons columns and then say if there are multiple people under the name BOB and we know that BOB is unique so its the same person. I want to then look at the Number column and if their is a negative value present for BOB as well as a Postive I want to change both numbers to Zero. Furthermore, for cases like Jack where there are two positive numbers I dont want to do anything for him. So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0 So the final dataframe would look like such... Person Number BOB 0 BOB 0 Jeff 0 Jack 82.04 Jack 14.02 Jeff 0 Another issue I am having is that Python isn't detecting the negatives appropriately so it changes negatives to look like this ($4.00) instead of keeping it like -1.23. I am just not sure how I can achieve the designated answer so any help would be greatly appreciated, thank you
type: Question
has answer: http://stackoverflow.com/a/47658441
type: UnansweredQuestion
tagged with: python
has title: Finding all Negative numbers
has answer: http://stackoverflow.com/a/47657838
has comment: http://stackoverflow.com/comment/82273518
has comment: http://stackoverflow.com/comment/82272806
has comment: http://stackoverflow.com/comment/82272894
answer count: 2
tagged with: pandas
score: 1

http://stackoverflow.com/comment/82344980
comment on: http://stackoverflow.com/q/47692726
type: QuestionComment
has text: @Stéphane yep. Is it the wrong way?
type: Comment
score: 0

http://stackoverflow.com/a/47688018
answers question: http://stackoverflow.com/q/47685090
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/88469259
downvote count: 0
has body: Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer: return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob })) .map((res:Response) =&gt; { var blob = res.blob(); var arrayBuffer; var fileReader = new FileReader(); fileReader.onload = function() { arrayBuffer = this.result; try { let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"}); let obj = JSON.parse(result); console.log(obj); } catch (err) { console.log("Error " + err); } }; fileReader.readAsArrayBuffer(blob); return "abc"; });
type: AcceptedAnswer
score: 11
accepted answer of: http://stackoverflow.com/q/47685090

http://stackoverflow.com/comment/82078357
type: AnswerComment
comment on: http://stackoverflow.com/a/47560096
type: Comment
score: 0
has text: ahh i see. it took me a minute to understand the "if not input". I was thinking of ENTER as an input, but i guess its really the absence of an input... i had it backwards.

http://stackoverflow.com/q/47602068
has comment: http://stackoverflow.com/comment/82162935
has title: Python, split user input twice. At pair and space
tagged with: python-3.3
has comment: http://stackoverflow.com/comment/82162939
tagged with: python
score: -6
has comment: http://stackoverflow.com/comment/82163024
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47604451
answer count: 1
has comment: http://stackoverflow.com/comment/82163239
has comment: http://stackoverflow.com/comment/82163098
favorite count: 0
type: Question
has body: I'm a Python beginner and would like to know how to split a user input at pair and at space and add it to a list. E.g: user = input('A1 KW') user.split(" " ) # split on space Then I'd like to print the input on index 0 what should be A1 and also print the alphabet and number/alphabet of each index. E.g: input[0] = A1 alphabet = A number = 1 input[1] = KW alphabet1 = K alphabet2 = W Then add it to a list. list = ['A1, KW'] I hope you guys know what I mean.
downvote count: 6

http://stackoverflow.com/comment/82070410
comment on: http://stackoverflow.com/q/47553951
has text: oh, you actually need to make a query to check for uniqueness? then yes, i guess @SajiXavier solution works.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82084479
has text: `for thread in self.threads:` does start threads in `self.threads` every time server does get a connection from a client. It is not what you want.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47562879
type: Comment

http://stackoverflow.com/comment/82143896
comment on: http://stackoverflow.com/q/47593366
type: QuestionComment
has text: See https://docs.python.org/3/library/typing.html
score: 3
type: Comment

http://stackoverflow.com/q/47648106
accepted answer: http://stackoverflow.com/a/47648560
score: -6
has answer: http://stackoverflow.com/a/47648560
favorite count: 0
type: Question
has body: I found the following code in a conway's game of life clone. I don't understand how exactly the following code is run. Can someone give an in depth explanation in how the Code is executed? def iterate(Z): # find number of neighbors that each square has N = np.zeros(Z.shape) N[1:, 1:] += Z[:-1, :-1] N[1:, :-1] += Z[:-1, 1:] N[:-1, 1:] += Z[1:, :-1] N[:-1, :-1] += Z[1:, 1:] N[:-1, :] += Z[1:, :] N[1:, :] += Z[:-1, :] N[:, :-1] += Z[:, 1:] N[:, 1:] += Z[:, :-1] # a live cell is killed if it has fewer than 2 or more than 3 neighbours. part1 = ((Z == 1) &amp; (N &lt; 4) &amp; (N &gt; 1)) # a new cell forms if a square has exactly three members part2 = ((Z == 0) &amp; (N == 3)) return (part1 | part2).astype(int)
has comment: http://stackoverflow.com/comment/82254423
tagged with: python
tagged with: slice
downvote count: 6
tagged with: numpy
type: AnsweredQuestion
has title: Python: Numpy slicing indepth explnation
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/82292004
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47666220
has text: Do you want a pixel perfect circle button or can it be a rect with roughly the size of the circle? Pixel perfect collision detection is more difficult.
score: 0

http://stackoverflow.com/comment/82075245
type: Comment
comment on: http://stackoverflow.com/a/47558697
type: AnswerComment
has text: So let's say, I store dfs[0] into another dataframe (say cl0), that'll work fine too right? Since I need to generate csv files out of it.
score: 0

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

http://stackoverflow.com/comment/82124685
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47583064
type: QuestionComment
has text: does it work with the plot alone? i.e. without dash?

http://stackoverflow.com/a/47661279
accepted answer of: http://stackoverflow.com/q/47659197
type: AcceptedAnswer
downvote count: 0
has body: Obviously for this to be possible, both keys and values must be hashable. This means that none of your keys or values can be a list. We can take advantage of this to know which dictionary elements have been already processed. Since you can't iterate and modify a dictionary at the same time, we must start over every time we swap a key/value. That makes this very slow, an O(n^2) operation. def invert_dict(d): done = False while not done: done = True for key, val in d.items(): if isinstance(val, list): if len(val) &gt; 1: d[key] = [val[1]] val = val[0] else: del d[key] if not isinstance(val, list): if val in d: d[val] = [d[val], key] else: d[val] = [key] done = False break for key, val in d.items(): d[key] = val[0]
has comment: http://stackoverflow.com/comment/82282393
has comment: http://stackoverflow.com/comment/82284486
answers question: http://stackoverflow.com/q/47659197
type: Answer
has comment: http://stackoverflow.com/comment/82281665
score: 2
upvote count: 2

http://stackoverflow.com/comment/82348405
has text: Your question is confusing somehow. I feel you are feeding us much more information than we need to know.
comment on: http://stackoverflow.com/q/47694493
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/a/47556833
has comment: http://stackoverflow.com/comment/82072141
accepted answer of: http://stackoverflow.com/q/47556360
has comment: http://stackoverflow.com/comment/82072091
has comment: http://stackoverflow.com/comment/82071642
has comment: http://stackoverflow.com/comment/82071162
has comment: http://stackoverflow.com/comment/82072135
type: Answer
has body: The very simple answer is that count is implemented in pure C, and so runs faster than a Python loop. However, there are a lot of subtleties to consider. First, you haven't written your loop in the most efficient way. Every time the expression t in (e, e[::-1]) is executed, three things happen: The e tuple is reversed with e[::-1]. Note that this only has to happen once -- you could store the result and reuse it. But right now, it's executed every time through the loop. The two tuples are stored in an outer tuple. This also only has to happen once, but again, it's executed every time through the loop. Finally, each item in the outer tuple is checked for equality with t. This does have to happen every time through the loop because the value of t changes each time. Here's the result of the speed test on my computer: In [6]: %%timeit ...: c = 0 ...: for t in l: ...: if t in (e, e[::-1]): ...: c += 1 ...: 7.39 µs ± 43.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) To streamline this, you could just create the outer tuple once. Call it e_test: e_test = (e, e[::-1]) Then things are way faster: In [8]: %%timeit ...: c = 0 ...: for t in l: ...: if t in e_test: ...: c += 1 ...: 3.05 µs ± 62.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) I think this might be the fastest way to implement this test using a vanilla Python for loop. However, the count-based solution is still faster! In [9]: %timeit l.count(e) + l.count(e[::-1]) 2.19 µs ± 62 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) We can improve on that even more by again pre-calculating the reversed tuple: In [10]: e_rev = e[::-1] In [11]: %timeit l.count(e) + l.count(e_rev) 2.06 µs ± 62.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) It's certainly true that performing two tests inside the same loop is a benefit. But the benefit is actually very small compared to other factors. And it's even smaller in this case because the count loops happen in C, which aggressive…
has comment: http://stackoverflow.com/comment/82071248
has comment: http://stackoverflow.com/comment/82072118
has comment: http://stackoverflow.com/comment/82071080
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82071214
has comment: http://stackoverflow.com/comment/82071119
has comment: http://stackoverflow.com/comment/82071564
answers question: http://stackoverflow.com/q/47556360
downvote count: 0
has comment: http://stackoverflow.com/comment/82072486
type: AcceptedAnswer

http://stackoverflow.com/comment/82270824
score: 0
has text: What line in the code gives you the error? Also, reading the "TypeError", it seems to me that your indices are of type string. Convert the 'list indices' to integers `int(<result here>)`
comment on: http://stackoverflow.com/q/47655797
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82092323
comment on: http://stackoverflow.com/q/47566763
has text: I don't think reading the same file from many processes concurrently would be a big issue—the OS should easily be able to deal with it—however are they all writing to the same "different" output file? The latter could be a significant bottle-neck.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82328696
score: 0
type: Comment
type: QuestionComment
has text: print(request.method) doesn't print anything to the cmd. The only thing I see in cmd is GET/POST, GET/POST
comment on: http://stackoverflow.com/q/47684182

http://stackoverflow.com/comment/82160148
type: Comment
type: QuestionComment
has text: no problem. I hope someone may have better idea
score: 0
comment on: http://stackoverflow.com/q/47583819

http://stackoverflow.com/a/51330451
has body: Try this in pyspark from pyspark.sql.functions import col, explode words(explode(col('words')).alias('word'))\ .groupBy('word').count().orderBy('count',ascending=False).show(100, truncate=False)
answers question: http://stackoverflow.com/q/47597258
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47651708
tagged with: dictionary
has answer: http://stackoverflow.com/a/47651828
accepted answer: http://stackoverflow.com/a/47651828
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47652148
score: 0
has comment: http://stackoverflow.com/comment/82261681
answer count: 3
linked to: http://stackoverflow.com/q/3294889
tagged with: pandas
tagged with: flickr
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82263297
has answer: http://stackoverflow.com/a/47655521
favorite count: 0
has comment: http://stackoverflow.com/comment/82263427
type: Question
has answer: http://stackoverflow.com/a/47652148
has title: Iteration over the dictionary and extracting values
has body: I have a dictionary (result_dict) as follows. {'11333216@N05': {'person': {'can_buy_pro': 0, 'description': {'_content': ''}, 'has_stats': '1', 'iconfarm': 3, 'iconserver': '2214', 'id': '11333216@N05', 'ispro': 0, 'location': {'_content': ''}, 'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'}, 'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'}, 'nsid': '11333216@N05', 'path_alias': 'kishansamarasinghe', 'photos': {'count': {'_content': 442}, 'firstdate': {'_content': '1193073180'}, 'firstdatetaken': {'_content': '2000-01-01 00:49:17'}}, 'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'}, 'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'}, 'realname': {'_content': 'Kishan Samarasinghe'}, 'timezone': {'label': 'Sri Jayawardenepura', 'offset': '+06:00', 'timezone_id': 'Asia/Colombo'}, 'username': {'_content': 'Three Sixty Five Degrees'}}, 'stat': 'ok'}, '117692977@N08': {'person': {'can_buy_pro': 0, 'description': {'_content': ''}, 'has_stats': '0', 'iconfarm': 1, 'iconserver': '404', 'id': '117692977@N08', 'ispro': 0, 'location': {'_content': 'Almere, The Nederlands'}, 'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'}, 'nsid': '117692977@N08', 'path_alias': 'meijsvo', 'photos': {'count': {'_content': 3237}, 'firstdate': {'_content': '1392469161'}, 'firstdatetaken': {'_content': '2013-06-23 14:39:30'}}, 'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'}, 'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'}, 'realname': {'_content': 'Markéta Eijsvogelová'}, 'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna', 'offset': '+01:00', 'timezone_id': 'Europe/Amsterdam'}, 'username': {'_content': 'meijsvo'}}, 'stat': 'ok'}, '21539776@N02': {'person': {'can_buy_pro': 0, 'description': {'_content': ''}, 'has_stats': '1', 'iconfarm': 0, 'iconserver': '0', This contains more than 150 usernames …
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47666124
has comment: http://stackoverflow.com/comment/82291491
has comment: http://stackoverflow.com/comment/82291447
has comment: http://stackoverflow.com/comment/82291598
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/82291888
type: Question
type: UnansweredQuestion
has body: I'm currently writing a relatively basic Socket program in python which is a Ping application using ICMP request and reply messages. I have most of the code finished, yet however I am getting some errors when I run my python file. Can anyone help me out? This is a screenshot of what the output should look like: from socket import * import os import sys import struct import time import select import binascii import socket ICMP_ECHO_REQUEST = 8 timeRTT = [] packageSent =0; packageRev = 0; def checksum(str): csum = 0 countTo = (len(str) / 2) * 2 count = 0 while count &lt; countTo: thisVal = ord(str[count+1]) * 256 + ord(str[count]) csum = csum + thisVal csum = csum &amp; 0xffffffffL count = count + 2 if countTo &lt; len(str): csum = csum + ord(str[len(str) - 1]) csum = csum &amp; 0xffffffffL csum = (csum &gt;&gt; 16) + (csum &amp; 0xffff) csum = csum + (csum &gt;&gt; 16) answer = ~csum answer = answer &amp; 0xffff answer = answer &gt;&gt; 8 | (answer &lt;&lt; 8 &amp; 0xff00) return answer def receiveOnePing(mySocket, ID, timeout, destAddr): global packageRev,timeRTT timeLeft = timeout while 1: startedSelect = time.time() whatReady = select.select([mySocket], [], [], timeLeft) howLongInSelect = (time.time() - startedSelect) if whatReady[0] == []: # Timeout return "0: Destination Network Unreachable," timeReceived = time.time() recPacket, addr = mySocket.recvfrom(1024) #Fill in start #Fetch the ICMP header from the IP packet icmpHeader = recPacket[20:28] requestType, code, revChecksum, revId, revSequence = struct.unpack('bbHHh',icmpHeader) if ID == revId: bytesInDouble = struct.calcsize('d') timeData = struct.unpack('d',recPacket[28:28 + bytesInDouble])[0] timeRTT.append(timeReceived - timeData) packageRev += 1 return timeReceived - timeData else: return "ID is not the same!" #Fill in end timeLeft = timeLeft - howLongInSelect if timeLeft &lt;= 0: return "1: Destination Host Unreachable." def sendOnePing(mySocket, destAddr, ID): global packageSent # Header is type (8), co…
answer count: 1
tagged with: websocket
has answer: http://stackoverflow.com/a/47666217
score: 0
has title: ICMP Pinger Socket Program Application
tagged with: network-programming

http://stackoverflow.com/comment/82199294
type: QuestionComment
has text: You should show your URLs. The request is clearly not being routed to that view, as you would get an error because you are not returning an httpresponse. In any case, you really shouldn't make db changes in a get request.
comment on: http://stackoverflow.com/q/47620621
score: 0
type: Comment

http://stackoverflow.com/comment/82286323
score: 2
comment on: http://stackoverflow.com/q/47663498
type: Comment
has text: don't mix environments native windows and cygwin; please note, that from cygwin you have called native windows python and it not see cygwin variables. Use powershell or cmd.exe instead of cygwin
type: QuestionComment

http://stackoverflow.com/q/47629308
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82220940
has answer: http://stackoverflow.com/a/47649769
has title: Authentication when using Gmail API and Google App-Engine
type: UnansweredQuestion
tagged with: google-app-engine
has body: This might (once again) be a silly/basic question. But here it goes. I am trying to build a web-app that queries and displays some information from the user's Gmail. My current idea is as follows: Have the backend run on Google AppEngine (coded in Python) where it has endpoints that take in queries like "How many such emails in the past one month" and returns the correct answer. The frontend can be a website or an android app that can query the endpoints using REST. The issue currently is with Authentication. I would like to know the right flow of authentication for my app. As far I see, there are two potential options: 1) Use the front-end to check if the user is logged in. If not, authenticate and send the user credentials to the backend (using the javascript version of GMAIL API perhaps?). 2) Let the backend handle the authentication. Once it gets the query on the endpoints, if the user is not authenticated, it redirects the user to a login page. One of the issues I have with this is that I am using the Python on my AppEngine and all the GMAIL API tutorial for Python requires reading the credentials/clientID from a JSON file on the hard disk. This is not possible on AppEngine since we cannot store any file on local disk. Can someone point me in the right direction? Thanks.
score: 1
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/82253144
tagged with: gmail
downvote count: 0
answer count: 1
tagged with: authentication

http://stackoverflow.com/comment/82292693
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47618885
score: 0
has text: I don't understand how blueprint is going to solve the problem. Blueprints are meant to separate the applications.

http://stackoverflow.com/comment/82238649
score: 0
type: Comment
type: QuestionComment
has text: How about starting by adding a space after 'excel.exe' in your `os.system(r"excel.exe" + filename)` call... You need that to give the OS a chance of understanding what you're trying to ask it to do...
comment on: http://stackoverflow.com/q/47637232

http://stackoverflow.com/a/47638883
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82950929
upvote count: 3
answers question: http://stackoverflow.com/q/47638843
downvote count: 0
has body: Make sure your Python version in the virtualenv is Python 3.4+. Django 2.0 only supports Python 3.4+, and functools.lru_cache is only available in 3.2+. To check the Python version in your current virtualenv: python --version To create a new virtualenv with python 3: python3 -m venv venv --prompt=myenv

http://stackoverflow.com/q/47654162
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/47654209
has comment: http://stackoverflow.com/comment/82266889
favorite count: 0
has answer: http://stackoverflow.com/a/47654209
type: Question
has body: I have a nested list like the following: x = [[1, 5, 3, 4], [5, 10, 7, 8], [9, 9, 2, 12]] I need to find to find the min and max values of the nested list transposed such that the result for min is: 1, 5, 2, 4 # 1 is the min of first column (1, 5, 9) a.s.o and the max should be: 9, 10, 7, 12 I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.
has comment: http://stackoverflow.com/comment/82266630
has answer: http://stackoverflow.com/a/47654477
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/47654617
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/47654477
has title: find the min and max values of nested list by index of element in nested list
answer count: 3

http://stackoverflow.com/comment/82283799
has text: Do you just want to switch between two images, the normal and the rotated one?
score: 0
comment on: http://stackoverflow.com/q/47661930
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47616531
has comment: http://stackoverflow.com/comment/82212122
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82222057
tagged with: cross-validation
tagged with: grid-search
has comment: http://stackoverflow.com/comment/82215680
tagged with: python
tagged with: keras
has title: Grid Search with custom metrics in Keras
has comment: http://stackoverflow.com/comment/82217467
score: 0
has comment: http://stackoverflow.com/comment/82215776
has body: I use Keras (Python) for a CNN model and have a custom call back function to calculate metrics such as a precision, recall etc. I have given the function below. This function works fine for a single call of a fit function and returns correct metric values at epoch end. However, I am trying K-Fold cross validation with the GridSearchCV function and would like to have the custom metrics returned for each of the Folds and also when I use grid_result.grid_scores_ to get the mean/std across K-Folds. This doesn’t work. Also, is it possible to get the metrics calculated for a separate validation data. from keras.callbacks import Callback from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score class CustomMetrics(Callback): def on_train_begin(self, logs={}): self.validation_f1 = [] self.validation_recall = [] self.validation_precision = [] def on_epoch_end(self, epoch, logs={}): # Extracting the second column since the activation is softmax predicted_prob = self.model.predict(self.validation_data[0])[:,1] true_y = self.validation_data[1][:,1] threshold = optimal_cutoff_PRC(true_y,predicted_prob) convert_to_01 = lambda x: 1 if x &gt; threshold else 0 vfunc = numpy.vectorize(convert_to_01) test_predicted_01 = vfunc(predicted_prob) _val_f1 = f1_score(true_y, test_predicted_01) _val_recall = recall_score(true_y, test_predicted_01) _val_precision = precision_score(true_y, test_predicted_01) self.validation_f1.append(_val_f1) self.validation_recall.append(_val_recall) self.validation_precision.append(_val_precision) print " — val_f1: %f — val_precision: %f — val_recall %f" %(_val_f1, _val_precision, _val_recall) return custom_metrics = CustomMetrics() The following call works fine on the above function: model.fit(timeseries_train, y_train, batch_size = 512, epochs=2, callbacks = [custom_metrics] , validation_data= val_data) However, this doesn’t work fine with GridSearchCV function defined as follows: seed = 7 numpy.random.seed(seed) model = KerasCla…
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/82222578
has comment: http://stackoverflow.com/comment/82214622
has comment: http://stackoverflow.com/comment/82221958
type: Question
has comment: http://stackoverflow.com/comment/82216646
answer count: 0

http://stackoverflow.com/comment/82074372
has text: Your question is not that much clear. Also you asked too many questions out of one question. Try to explore yourself first before asking and be specific.
comment on: http://stackoverflow.com/q/47558136
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82227846
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47634739
has text: Thanks @JarvisCochrane, this is perfect because I need to use this another time further down the code as well!

http://stackoverflow.com/q/47602922
tagged with: numpy
has comment: http://stackoverflow.com/comment/82164718
score: 0
tagged with: list
tagged with: for-loop
answer count: 0
type: Question
tagged with: tuples
has title: List doesn't build up right
has body: here is my script. I want to list all the "e_p" and "e_f" elements with my for loop but e_f somehow becomes a tuple and my "liste2" is only composed of the last "e_p" value given by my for loop. Thanks for helping import rty as cpt import numpy as np import CoolProp.CoolProp as cp competition=cpt.rty() import enthalpies as ent import meteo as met Ti = [competition.temp_liquide] T_ext = [met.temp_journee,met.temp_max,met.temp_journee] Teb = cp.PropsSI("T","P",met.press_journee,"H",0,ent.substance) - 273.15 def energie_perdue(T_liquide,T_air,P,force_vent): v_vent = (force_vent*2) + 2 e_perdue_conv = ((10.45*v_vent)+(10*np.sqrt(v_vent)))*np.pi*(7.98/2)**2*np.abs(T_liquide-T_air)*8*3600 return e_perdue_conv def energie_fournie(T,P): Teb = cp.PropsSI("T","P",P,"H",0,ent.substance) Cap = cp.PropsSI("C","T",298.15,"P",P,ent.substance) rho = cp.PropsSI("D","T",273.15+T,"P",P, ent.substance) V = 2*np.pi*(7.98/2)**2 m = rho*V e_fournie = m*Cap*(Teb-273.15-T) return e_fournie, m, Cap for i in range (0,3): e_f = energie_fournie(Ti[i],met.press_journee) liste1 = [] liste1.append(e_f) e_p = energie_perdue(Ti[i],T_ext[i],met.press_journee,0) liste2 = [] liste2.append(e_p) dif_e = e_f[0] - e_p dif_T = dif_e/(e_f[1]*e_f[2]) Tf = Ti[i] + dif_T Ti.append(Tf) P.S enthalpies and meteo are scripts that I coded in other scripts Thanks a lot
has comment: http://stackoverflow.com/comment/82165308
type: UnansweredQuestion
tagged with: python

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

http://stackoverflow.com/comment/82369603
comment on: http://stackoverflow.com/a/47695025
score: 0
type: AnswerComment
has text: Thank you for your effort and time! Appreciate it. I haven't been able to get imap working with my code yet. One thing i probably should have mentioned is I am using `Manager().dict()` to update the results from every processes. If i pass my jobs as a generator to imap it works. But does nothing when I pass `iterator_slicer`.
type: Comment

http://stackoverflow.com/a/47657220
has comment: http://stackoverflow.com/comment/82276079
accepted answer of: http://stackoverflow.com/q/47657008
has comment: http://stackoverflow.com/comment/82276229
has body: lista = [] response = et.XML(xml) for i, child in enumerate(response): text = child.find('text').text value = child.find('value').text lista.append({text: value})
answers question: http://stackoverflow.com/q/47657008
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/48198708
has body: I had the same issue, this worked for me: class RetryRequest(Retry): def __init__(self, backoff_max=60, **kwargs): super(RetryRequest, self).__init__(**kwargs) self.BACKOFF_MAX = backoff_max I don't think you need to override get_backoff_time(), simply overriding the constructor and setting self.BACKOFF_MAX should work. Also, using kwargs lets you omit the other params.
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47675138

http://stackoverflow.com/comment/82116177
type: QuestionComment
comment on: http://stackoverflow.com/q/47570903
has text: This is an *unusual* paradigm. Most often, when two populations are compared the hypothesis would be that their probabilities of success are equal. Following from this confidence intervals would be calculated around p=0. This might be the explanation why you aren't getting any answers here.
score: 0
type: Comment

http://stackoverflow.com/comment/82084989
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47563506
type: QuestionComment
has text: You’re goin to have to share more info than this.

http://stackoverflow.com/a/47561552
has comment: http://stackoverflow.com/comment/82081257
type: Answer
accepted answer of: http://stackoverflow.com/q/47561142
has comment: http://stackoverflow.com/comment/82081340
has comment: http://stackoverflow.com/comment/82080967
score: 2
answers question: http://stackoverflow.com/q/47561142
has comment: http://stackoverflow.com/comment/82081520
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82081078
has comment: http://stackoverflow.com/comment/82081452
has body: it seems that you're reusing the same Network object in both routines. The issue is that communicate only works once. It's a convenient method to get separate output &amp; error streams and hide the complexity of deadlock avoidance when consuming those streams. You cannot use communicate more than once on a subprocess.Popen object. If you want to feed input to your program you should do: Network.stdin.write(password.encode('utf-8')) And of course don't close the input stream: Network.stdin.close() don't forget to follow by a linefeed Network.stdin.write(b"\n") I also suggest that you don't use stdout=PIPE but leave the default (or redirect to nothing with stdout=DEVNULL so the output buffer doesn't gets full &amp; blocks.
has comment: http://stackoverflow.com/comment/82081415

http://stackoverflow.com/comment/82071642
comment on: http://stackoverflow.com/a/47556833
score: 0
type: Comment
has text: btw I don't think precalculating `e[::-1]` for the `l.count` call makes any difference at all because, contrary to the loop, `e[::-1]` is only evaluated once.
type: AnswerComment

eclipse
tags question: http://stackoverflow.com/q/47673229
tag name: eclipse
tags question: http://stackoverflow.com/q/47670660
tags question: http://stackoverflow.com/q/47616499
tags question: http://stackoverflow.com/q/47630440
tags question: http://stackoverflow.com/q/47657030
tags question: http://stackoverflow.com/q/47599858
type: Tag
tags question: http://stackoverflow.com/q/47548499

http://stackoverflow.com/q/47602278
has title: correctly override __new__ in python3
upvote count: 12
has comment: http://stackoverflow.com/comment/82164052
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/82163802
has body: So I am trying to override __new__ and let it exist as a factory to create derived instances. After some reading on SO, I am under the impression that I should be calling __new__ on the derived instance as well. BaseThing class BaseThing: def __init(self, name, **kwargs): self.name = name # methods to be derived ThingFactory class Thing(BaseThing): def __new__(cls, name, **kwargs): if name == 'A': return A.__new__(name, **kwargs) if name == 'B': return B.__new__(name, **kwargs) def __init__(self, *args, **kwargs): super().__init__(name, **kwargs) # methods to be implemented by concrete class (same as those in base) A class A(BaseThing): def __init__(self, name, **kwargs): super().__init__(name, **kwargs) B class B(BaseThing): def __init__(self, name, **kwargs): super().__init__(name, **kwargs) what I am expecting was that it'd just work. &gt;&gt;&gt; a = Thing('A') gives me TypeError: object.__new__(X): X is not a type object (str) I am bit confused by this; when I just return a concrete instance of derived classes, it just worked. i.e. def __new__(cls, name, **kwargs): if name == 'A': return A(name) if name == 'B': return B(name) I don't think this is the correct way to return in __new__; it may duplicate the calls to __init__. when I am checking signatures of __new__ in object it seems be this one: @staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ &quot;&quot;&quot; Create and return a new object. See help(type) for accurate signature. &quot;&quot;&quot; pass I didn't expect this was the one; I'd expect it came with args and kwargs as well. I must have done something wrong here. it seems to me that I need to inherit object directly in my base but could anyone explain the correct way of doing it?
has comment: http://stackoverflow.com/comment/82164088
tagged with: python
score: 11
tagged with: inheritance
accepted answer: http://stackoverflow.com/a/47602346
tagged with: factory-pattern
has comment: http://stackoverflow.com/comment/82163337
has comment: http://stackoverflow.com/comment/82164008
has comment: http://stackoverflow.com/comment/82164138
has comment: http://stackoverflow.com/comment/82163325
has comment: http://stackoverflow.com/comment/82164042
has answer: http://stackoverflow.com/a/47602346
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82164309
tagged with: oop
has comment: http://stackoverflow.com/comment/82164119
has comment: http://stackoverflow.com/comment/82163969
has comment: http://stackoverflow.com/comment/82164074
answer count: 1
has comment: http://stackoverflow.com/comment/82164017
downvote count: 1
linked to: http://stackoverflow.com/q/674304
favorite count: 0
type: Question

http://stackoverflow.com/q/47590890
has comment: http://stackoverflow.com/comment/116171566
has comment: http://stackoverflow.com/comment/82174395
answer count: 0
tagged with: pycaffe
has title: Error message: ImportError: No module named _caffe
type: UnansweredQuestion
tagged with: caffe
tagged with: python
has comment: http://stackoverflow.com/comment/82141242
linked to: http://stackoverflow.com/q/28177298
score: 0
has comment: http://stackoverflow.com/comment/82219931
has comment: http://stackoverflow.com/comment/82143421
tagged with: macos
type: Question
tagged with: terminal
has comment: http://stackoverflow.com/comment/82221332
has body: I tried to install that install Caffe Tutorial, but I am block at this line in the tuto: ./tools/demo.py I havre this error message: MacBook-Pro-de-OlostA:fast-rcnn OlostA$ ./tools/demo.py Traceback (most recent call last): File "./tools/demo.py", line 19, in &lt;module&gt; from fast_rcnn.config import cfg File "/Users/OlostA/Technologies/fast-rcnn/tools/../lib/fast_rcnn/__init__.py", line 9, in &lt;module&gt; from . import train File "/Users/OlostA/Technologies/fast-rcnn/tools/../lib/fast_rcnn/train.py", line 10, in &lt;module&gt; import caffe File "/Users/OlostA/Technologies/fast-rcnn/tools/../caffe-fast-rcnn/python/caffe/__init__.py", line 1, in &lt;module&gt; from .pycaffe import Net, SGDSolver File "/Users/OlostA/Technologies/fast-rcnn/tools/../caffe-fast-rcnn/python/caffe/pycaffe.py", line 13, in &lt;module&gt; from ._caffe import Net, SGDSolver ImportError: No module named _caffe Thanks in advance.

http://stackoverflow.com/a/47656661
answers question: http://stackoverflow.com/q/47645081
has body: As mentioned in the comments this is something wrong in your setup.py. Based on the error messages it seems that the setup.py script is trying to access a ll_plot executable. Since it is saying that it doesn't exist it is likely that you have an entry point script (via setuptools) or are trying to access the binary executable relative to the setup.py or other build script. You'll want to check the shebang on any scripts you have to make sure they aren't trying to use a non-existent environment. Of course if this is a public package (or not too) you'll want to make sure to document the build prerequisites and how the environment needs to be configured to build the package properly.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47645081
type: Answer

http://stackoverflow.com/q/47597738
answer count: 3
tagged with: pandas
score: 1
has title: Word count of single column in pandas dataframe
has comment: http://stackoverflow.com/comment/82154346
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/46863602
favorite count: 0
has answer: http://stackoverflow.com/a/47597851
type: Question
linked to: http://stackoverflow.com/q/47487753
has answer: http://stackoverflow.com/a/47597819
possible better answer: http://stackoverflow.com/a/47597819
duplicate of: http://stackoverflow.com/q/47487753
tagged with: python
has body: Here is my attempt at a word count for a single column using group by with pandas : First setup the data : columns = ['col1','col2','col3'] data = np.array([['word1','word2','word3'] , ['word1','word5','word3'], ['word3','word7','word3']]) to_count = pd.DataFrame(data,columns=columns) I'm attempting to count words in col1 in to_count. to_count contains : col1 col2 col3 0 word1 word2 word3 1 word1 word5 word3 2 word3 word7 word3 To count the words I then use : print(to_count.groupby('col1').count()) which displays : col2 col3 col1 word1 2 2 word3 1 1 This seems partly correct in that the word counts are returned but they are spread across multiple columns. How to access word count for a single column ? I could just access a single column in the word count dataframe but this does not seem correct.
has answer: http://stackoverflow.com/a/47597863
accepted answer: http://stackoverflow.com/a/47597851
type: AnsweredQuestion

http://stackoverflow.com/comment/82209883
has text: i used that data that you generated in the post, which seems to be different from the data that you're mentioning here? for this combination im getting ````[(4.8669925765449484, (('ABC', 'X', 'plus'), ('DEF', 'Y', 'minus'), ('DEF', 'Z', 'star')))]````. and according to your data table, total values should be ````[0.64515316530289457, 0.58542398144044849, 0.036449070043609644]````, assuming its simply the ````value```` field that corresponds to the tuple row.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47625493
type: AnswerComment

http://stackoverflow.com/comment/82125223
comment on: http://stackoverflow.com/a/47564499
type: AnswerComment
has text: It's shown right in my answer. The `(?:....)` construction is a non-capturing group.
score: 0
type: Comment

http://stackoverflow.com/comment/82155521
type: QuestionComment
comment on: http://stackoverflow.com/q/47598627
has text: @user2357112 added a picture of the error
score: 0
type: Comment

http://stackoverflow.com/comment/82251282
type: Comment
score: 0
type: AnswerComment
has text: @BehzadJamali That probably means there are missing labels. Your solution is only correct if the sum for label `0` is actually `0`. Is that the case?
comment on: http://stackoverflow.com/a/47645709

http://stackoverflow.com/comment/82278133
score: 0
comment on: http://stackoverflow.com/q/47659506
type: Comment
type: QuestionComment
has text: You need to perform `.replace()` on a *string* object not on the file pointer. Hence, you need to retrieve the content from `file2` before. Hint: `read()`, `readlines()`, etc.

http://stackoverflow.com/comment/82166058
type: Comment
type: AnswerComment
has text: @BrendanAbel: SHA-1's *output* is 160 bits. Every hash function has a fixed-length output, that's why they're useful. They can take any amount of data and produce a fixed-length hash derived from it.
comment on: http://stackoverflow.com/a/47601889
score: 1

http://stackoverflow.com/q/47627900
has answer: http://stackoverflow.com/a/47629032
accepted answer: http://stackoverflow.com/a/47629032
tagged with: tkinter
has title: How to bind async method to a keystroke in Tkinter?
has body: Consider the following example: import asyncio import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.create_widgets() self._configure_bindings() # I believe it is not possible # to do this if the method needs # to be async as well def create_widgets(self): pass def _configure_bindings(self): self.bind('&lt;F5&gt;', self.spam) # what's the proper way? # does this method need to be async as well? async def spam(self, event): await self.do_something() async def do_something(): pass async def run_tk(root): try: while True: root.update() await asyncio.sleep(.01) except tk.TclError as e: if "application has been destroyed" not in e.args[0]: raise if __name__ == '__main__': app = App() asyncio.get_event_loop().run_until_complete(run_tk(app)) What is the proper way to bind async method to a keystroke in tkinter? I've tried something like: self.bind('&lt;F5&gt;', self.spam) self.bind('&lt;F5&gt;', await self.spam) self.bind('&lt;F5&gt;', await self.spam()) self.bind('&lt;F5&gt;', lambda event: await self.spam(event)) ...and a bunch of other combinations, but to no avail.
upvote count: 3
tagged with: python-3.5
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/29158811
type: Question
tagged with: python-asyncio
tagged with: python
tagged with: python-3.6
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/47661728
score: 4
has comment: http://stackoverflow.com/comment/82282701
upvote count: 4
has comment: http://stackoverflow.com/comment/82285141
has body: Pearson Correlation Coefficient Code (modified) def mean(someList): total = 0 for a in someList: total += float(a) mean = total/len(someList) return mean def standDev(someList): listMean = mean(someList) dev = 0.0 for i in range(len(someList)): dev += (someList[i]-listMean)**2 dev = dev**(1/2.0) return dev def correlCo(someList1, someList2): # First establish the means and standard deviations for both lists. xMean = mean(someList1) yMean = mean(someList2) xStandDev = standDev(someList1) yStandDev = standDev(someList2) # r numerator rNum = 0.0 for i in range(len(someList1)): rNum += (someList1[i]-xMean)*(someList2[i]-yMean) # r denominator rDen = xStandDev * yStandDev r = rNum/rDen return r print(correlCo([1,2,3,4,4,8], [3,3,4,5,8,9])) Output 0.884782972876
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47661043
has comment: http://stackoverflow.com/comment/82285100
answers question: http://stackoverflow.com/q/47661043
has comment: http://stackoverflow.com/comment/82284983
has comment: http://stackoverflow.com/comment/82285223
type: Answer

http://stackoverflow.com/a/47586204
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47585184
score: 1
accepted answer of: http://stackoverflow.com/q/47585184
has body: Grouping with collections.defaultdict() is always straightforward: from collections import defaultdict LA = [[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]] # create defaultdict of list values d = defaultdict(list) # loop over each list for sublist in LA: # group by first element of each list key = sublist[0] # add to dictionary, each key will have a list of values d[key].append(sublist) # definitely can be more readable result = [[key, sum(x[1] for x in [y for y in value])] for (key, value) in sorted(d.items())] print(result) Output: [[1, 11], [2, 10], [4, 8], [6, 5]]

http://stackoverflow.com/a/47619958
downvote count: 0
has comment: http://stackoverflow.com/comment/82197853
has comment: http://stackoverflow.com/comment/82207896
has comment: http://stackoverflow.com/comment/82198201
type: Answer
accepted answer of: http://stackoverflow.com/q/47619923
has comment: http://stackoverflow.com/comment/82198334
score: 4
has comment: http://stackoverflow.com/comment/82197836
has body: Use Rational. &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; x = Symbol('x', real=True) &gt;&gt;&gt; eq = x**4 + Rational(4,9)*x**2 - Rational(13,9) &gt;&gt;&gt; sol = solve(eq, x) &gt;&gt;&gt; sol [-1, 1] &gt;&gt;&gt; print (latex(eq)) x^{4} + \frac{4 x^{2}}{9} - \frac{13}{9} &gt;&gt;&gt; print(latex(sol)) \left [ -1, \quad 1\right ]
upvote count: 4
answers question: http://stackoverflow.com/q/47619923
type: AcceptedAnswer

http://stackoverflow.com/comment/82092254
has text: You can use `var.rstrip("/")` to remove any trailing slashes in the string, then concatenate the rest, e.g.: `var.rstrip("/") + "/" + "/".join(list_here)`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47561279

http://stackoverflow.com/a/47540817
accepted answer of: http://stackoverflow.com/q/47540780
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82038913
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47540780
has body: You are trying to run format, a str method, on a list object (like the exception mentions). To fix this, change the position of your format call: print(subprocess.run(["commands", "-arg1 -arg2 {0}1.gz {0}2.gz".format(file)]))
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82038971

http://stackoverflow.com/q/47549244
type: AnsweredQuestion
answer count: 2
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/47549745
has answer: http://stackoverflow.com/a/47549745
has answer: http://stackoverflow.com/a/47549343
downvote count: 1
favorite count: 0
type: Question
has title: fast hash bucket into 1 and n in python
tagged with: hash
has body: I have a list /array of 5000 integer values, and integer are between 10000 and 20000. There are 2060 different values of integer. How to "re-hash" the initial values into [0-2059] ? without using assignement to a dict 13457 --&gt; 0 13260 --&gt; 1 14237 --&gt; 2 initial order values of integer does not matter, it's just a rescaling. Think one solution might to hash into [0-2599] bucket. Thanks
possible better answer: http://stackoverflow.com/a/47549343
tagged with: python

http://stackoverflow.com/comment/82150166
comment on: http://stackoverflow.com/a/47584481
score: 0
has text: Thanks, I did think of trying it that way too. Although, I think the problem will still arise. i.e. isinstance() will always evaluate attributes as string, and not registered_types. I must be doing something wrong.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82372124
comment on: http://stackoverflow.com/a/47685623
has text: Excellent looking forward to it
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/115342814
score: 0
type: Comment
has text: This helped me! Pip was giving 'invalid syntax' no matter what I added after 'pip'. Thanks!
comment on: http://stackoverflow.com/a/51194147
type: AnswerComment

http://stackoverflow.com/a/47598200
upvote count: 4
has comment: http://stackoverflow.com/comment/82154895
has body: We using pct_change df.groupby('security').price.pct_change() Out[1393]: 0 NaN 1 0.020000 2 0.058824 3 NaN 4 -0.020000 5 0.071429 6 0.019048 Name: price, dtype: float64
downvote count: 0
answers question: http://stackoverflow.com/q/47598095
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82157342
has comment: http://stackoverflow.com/comment/82154536
accepted answer of: http://stackoverflow.com/q/47598095
type: Answer
score: 4

http://stackoverflow.com/a/47688771
has comment: http://stackoverflow.com/comment/82340571
has comment: http://stackoverflow.com/comment/82341691
score: 0
has comment: http://stackoverflow.com/comment/82342917
has comment: http://stackoverflow.com/comment/82341781
has comment: http://stackoverflow.com/comment/82340373
has body: Use the csv writer to correctly handle special characters as delimiters. It is defined by the quoting argument of the csv_writer. In your case you can skip this attribute completely, as it will default to QUOTE_MINIMAL when not defined. Still added into the example for completeness. Source: import csv with open('output.csv', 'w') as csvfile: writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) writer.writerow(["te,st:foo", "test:nope, yes", "nodelimiter"]) output.csv: "te,st:foo","test:nope, yes",nodelimiter CSV is automatically controlling when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants and defaults to quote_minimal QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator. NOTE You are passing a string, you need to pass a list of strings def summarise(self): s = [str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))] return s
has comment: http://stackoverflow.com/comment/82342844
answers question: http://stackoverflow.com/q/47688582
has comment: http://stackoverflow.com/comment/82342412
has comment: http://stackoverflow.com/comment/82341896
type: Answer
has comment: http://stackoverflow.com/comment/82341948
has comment: http://stackoverflow.com/comment/82342565
has comment: http://stackoverflow.com/comment/82341463

http://stackoverflow.com/q/47659558
has title: I am getting an error when installing youtube-dl via the pip command on macOS High Sierra
has answer: http://stackoverflow.com/a/47661525
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47659663
score: 0
has answer: http://stackoverflow.com/a/47659663
has comment: http://stackoverflow.com/comment/82277929
tagged with: macos-high-sierra
has body: Long story short, I am creating a discord bot and I need youtube-dl to do so. When I went to install it on terminal, I used the command pip install youtube-dl and I got this Collecting youtube-dl Using cached youtube_dl-2017.12.2-py2.py3-none-any.whl Installing collected packages: youtube-dl Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/youtube_dl' I don't really know what to make of this or weather or not it is a bug with the pip command itself in High Sierra. Any help would be appreciated. Thanks!
possible better answer: http://stackoverflow.com/a/47661525
tagged with: terminal
tagged with: discord.py
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82277932
tagged with: python
tagged with: youtube-dl

http://stackoverflow.com/comment/108984685
type: Comment
comment on: http://stackoverflow.com/a/47562412
type: AnswerComment
has text: @alper I see - that would be a complete anti-pattern to this. `_plotstuff` cannot import `Fitter` by definition. In fact, it should never (the way this design is imagined) be invoked directly. That is like a method in your class trying to import your parsed class into an inner method (pre-parsing), after trying to invoke it without parsing the class - which does not make sense to me. To me it seems the circularity is made by hand here - a bad design which causes this is not related specifically to whether we are splitting a class or just have two modules which have a circular dependence.
score: 0

http://stackoverflow.com/q/47688696
tagged with: plot
has comment: http://stackoverflow.com/comment/82337582
score: 2
has comment: http://stackoverflow.com/comment/82337712
downvote count: 0
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/82337651
has answer: http://stackoverflow.com/a/47689425
has comment: http://stackoverflow.com/comment/82336836
has comment: http://stackoverflow.com/comment/82336611
favorite count: 0
type: Question
upvote count: 2
has body: How can I make a scatter plot colored by density in matplotlib? When I plot a colorbar it shows density scale, I want counts/percentage instead. How to convert density estimation to frequency counts? Expected result is Fig.3 on page 8 of this paper: https://www.atmos-meas-tech.net/9/3293/2016/amt-9-3293-2016.pdf If anyone can guide me to draw a plot similar to one shown in paper, it will be really helpful. Thank you in advance. import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # Generate fake data x = np.random.normal(size=1000) y = x * 3 + np.random.normal(size=1000) # Calculate the point density xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) fig, ax = plt.subplots() cax=ax.scatter(x, y, c=z, s=10, cmap=plt.cm.jet) cbar = fig.colorbar(cax) plt.show() Another Method Tried: #libraries import matplotlib.pyplot as plt import numpy as np from scipy.stats import kde # create data x = np.random.normal(size=500) y = x * 3 + np.random.normal(size=500) # Evaluate a gaussian kde on a regular grid of nbins x nbins over nbins=50 k = kde.gaussian_kde([x,y]) xi, yi = np.mgrid[min(x):max(x):nbins*1j, min(y):max(y):nbins*1j] zi = k(np.vstack([xi.flatten(), yi.flatten()])) # Add color bar plt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.jet) plt.colorbar() plt.show()
type: UnansweredQuestion
has title: 2D Density or Frquency Scatter Plot in python
tagged with: python
has comment: http://stackoverflow.com/comment/82337158

http://stackoverflow.com/comment/82224271
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47633077
score: 0
has text: I have two tables of city names that I need to match - one with 'A Coruña' and the other with 'A Coruna'.

http://stackoverflow.com/q/47633919
has comment: http://stackoverflow.com/comment/82225489
has title: How to slice different verb tenses word ending with -ed,-ing in a list?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/24647400
answer count: 3
has comment: http://stackoverflow.com/comment/82225384
tagged with: nltk
tagged with: python
has comment: http://stackoverflow.com/comment/82225312
has answer: http://stackoverflow.com/a/47634304
has answer: http://stackoverflow.com/a/47634256
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47634117
has body: So here is the sample list: [work,worked,working,play,works,lotus] I want to slice the -ed,-ing,-s form of work,the result should be like this: [work,play,lotus] So,how can i achieve that with pure python code since the NLTK approach seemed to be inaccurate?
type: UnansweredQuestion

http://stackoverflow.com/q/47586587
downvote count: 1
possible better answer: http://stackoverflow.com/a/47586784
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47586784
tagged with: opencv
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47590870
tagged with: python
tagged with: image-processing
answer count: 2
has comment: http://stackoverflow.com/comment/82130830
has title: Vehicle counting based on classification (cars,buses,trucks)
tagged with: bounding-box
upvote count: 1
has answer: http://stackoverflow.com/a/47590870
has body: I am currently working on vehicle platooning for which I need to design a code in python opencv for counting the number of vehicles based on the classification.The input is a real time traffic video. The aim is finding an average size "x" for the bounding box and say that for cars its "x", for buses its "3x" and so on.Based on size of "x" or multiples of "x", determine the classification.Is there any possible way I can approach this problem statement?

http://stackoverflow.com/comment/82215820
has text: Problem is that the output does not contain the "Date_over". Is there anyway I can include "Date_over" column with empty values?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47629075

http://stackoverflow.com/comment/82120397
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47570247
has text: Welcome to Stack Overflow. Please read the following doc about how to ask good questions https://stackoverflow.com/help/how-to-ask
score: 0

http://stackoverflow.com/comment/82220940
has text: What do you mean by cannot store JSON file in the App Engine? you can save JSON file in App Engine then you have to just point the path to the JSON file in the authentication code.
type: QuestionComment
comment on: http://stackoverflow.com/q/47629308
type: Comment
score: 0

http://stackoverflow.com/comment/82353848
comment on: http://stackoverflow.com/q/47697073
has text: what happens if some are true and some are false?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82072141
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160112/discussion-between-senderle-and-dabadaba).
type: Comment
comment on: http://stackoverflow.com/a/47556833
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82210800
type: Comment
type: AnswerComment
has text: I changed my code already. So, I uploaded please one more check.
score: 0
comment on: http://stackoverflow.com/a/47625102

http://stackoverflow.com/q/47655934
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82301295
has title: Rotate Plotly Line Markers
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/82274728
score: 0
has body: I am trying to plot a timeline of events with Plotly, and I have the following example code: res = { "First event": 5, "Second event": 6, "Third event": 30 } names, dates = zip(*res.items()) trace = go.Scatter( x=dates, y=[0] * len(names), text=names, mode='lines+markers+text', marker=dict( symbol="hexagon-dot", size=10, ) ) layout = go.Layout() fig = go.Figure(layout=layout, data=[trace]) iplot(fig) I get the following result: What I would like to do is rotate the marker text so that the markers do not overlap. Can this be done?
tagged with: plotly
tagged with: python
answer count: 0

http://stackoverflow.com/comment/82064371
comment on: http://stackoverflow.com/q/47543754
type: Comment
type: QuestionComment
has text: @Micka, I meant by similarity is the measurement between a pair of matched descriptors (e.g. Euclidean distance) But comparing the SIFT descriptors themselves in an image to those of another is not feasible because you will end up with multiple SIFT descriptors in an image, and their number varies depending on how you extract them as I mention for example image A has 16X128 (=2048) descriptors and the other has 1028.
score: 0

http://stackoverflow.com/q/47659050
has comment: http://stackoverflow.com/comment/82277262
has comment: http://stackoverflow.com/comment/82277487
linked to: http://stackoverflow.com/q/18971928
type: Question
tagged with: django-settings
answer count: 0
has body: There are a few questions on this topic, but none of them solved my challenge. I cannot login to Django Admin with a correct username and password. settings.py: import os from django.core.exceptions import ImproperlyConfigured BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_env_variable(variable_name): try: return os.environ[variable_name] except KeyError: error_msg = 'Set the {} environment variable'.format(variable_name) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_env_variable('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['XXXXXXXX'] INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'alerts.apps.AlertsConfig', 'widget_tweaks', ] SESSION_COOKIE_SECURE = False SESSION_EXPIRE_AT_BROWSER_CLOSE = True 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', ] ROOT_URLCONF = 'myProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'XXXXXXXXXXx', 'HOST': get_env_variable('DATABASE_HOST'), 'NAME': ge…
tagged with: django-admin
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
has title: Django Admin - Cannot Login with Superuser

http://stackoverflow.com/comment/82091490
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47566214
type: AnswerComment
has text: Thanks for your advice. The totally time reduce from 6363 ms to 967 ms. And it's really easy to understand and readable.

http://stackoverflow.com/comment/82053256
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47547483
has text: sorry, I have included the sample csv format in the question. it's a bit tricky aligning the columns.

http://stackoverflow.com/q/47553596
type: Question
has comment: http://stackoverflow.com/comment/82063816
has body: I am comparing fist element of list vs all the elements of list. If False is there I need to return false or if all are true, I need to return True. Currently I am doing this with if-else. is there any pythonic way to return bool value def checker(inp): _compare = [ _==inp[0] for _ in inp] return False if False in _compare else True lst = [5, 5, 5] lst2 = [5, 5, 6] # Case 1 level = checker(inp=lst) print(level) True # Case 2 level2 = checker(inp=lst2) print(level2) False Any pythonic way to achieve this return False if False in _compare else True
has comment: http://stackoverflow.com/comment/82063677
accepted answer: http://stackoverflow.com/a/47553694
tagged with: python
has title: Return bool value in pythonic way comparing within list?
has answer: http://stackoverflow.com/a/47553698
type: AnsweredQuestion
tagged with: boolean
has answer: http://stackoverflow.com/a/47553635
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82063798
linked to: http://stackoverflow.com/q/3787908
duplicate of: http://stackoverflow.com/q/3844801
possible better answer: http://stackoverflow.com/a/47553635
duplicate of: http://stackoverflow.com/q/3787908
has answer: http://stackoverflow.com/a/47553694

http://stackoverflow.com/a/47653296
has body: You can do it in VBA if the files have had the "Trust Access to the VBA project object model" option set on. http://www.cpearson.com/excel/vbe.aspx
has comment: http://stackoverflow.com/comment/82343512
answers question: http://stackoverflow.com/q/47649553
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/47621356
has body: I found this problem reported in the mycli issues: https://github.com/dbcli/mycli/issues/479 https://github.com/dbcli/mycli/issues/493 The developer's reply is: This appears to be an issue only on Python 2 when a row has newlines in it. The upcoming release of mycli fixes this. If you installed mycli via pip, you can fix this now by doing this: $ pip install -U cli_helpers
downvote count: 0
answers question: http://stackoverflow.com/q/47620031
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82209972
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47620031

http://stackoverflow.com/comment/82211686
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47626932
has text: @mshsayem I have used this result = set(chunks_1[0]),for s in chunks_1[1:]:, result.intersection_update(s),print result, but these gives me only "TestRun" as common , when "Then page is successfully launched" these statement is repeated in every list , this is not shown as output?
score: 0

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/47649787
tags question: http://stackoverflow.com/q/47622542
tags question: http://stackoverflow.com/q/47660617
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/47608583
tags question: http://stackoverflow.com/q/47558863
tags question: http://stackoverflow.com/q/47609591
tags question: http://stackoverflow.com/q/47649968

http://stackoverflow.com/comment/82171272
has text: Same python? Same ram? Same processor? Same backgroundactivity?
comment on: http://stackoverflow.com/q/47606295
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82191130
type: QuestionComment
comment on: http://stackoverflow.com/q/47616430
has text: I got two types of list. Integers and list of floats.
score: 0
type: Comment

http://stackoverflow.com/q/47653156
favorite count: 0
has title: How to create editable list view divided into different number of months in Odoo?
score: 3
tagged with: odoo-11
tagged with: odoo-10
tagged with: odoo
tagged with: python
has answer: http://stackoverflow.com/a/49854527
has body: I want to create budgets module divided into months in Odoo. Something like this: Requirements: Editable in place, like in Excel. I've used List View and Editable parameter so it is done. I want to have dynamic number of months. Different budgets have different number of months. Moreover it would be great to add new month to existing budget. What I know? I know that it is impossible to have dynamic fields, because tables in database are created earlier. My solutions: Solution 1: I'm setting maximum number of months. For example 36 months. If I need only 4 months I'm hiding remaining 32 fields. I'm creating a button to unhide next hidden column of month. Solution 2: I'm making each budget value as object with value, budget line and month. For example in my table above I need first object with: Month: January 2018 Budget line: Accommodation Value: 10000 Then I have to build my own view. I'd dont't know if it is good idea. I dont't even know where to start. Solution 3: Use/modify some existing module. Maybe "2D matrix for x2many fields" module? Conclusion: Please help me with some advise. Any hint will be much appreciated. PS. I'm using Odoo 11 Enterprise.
type: Question
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82312108
type: QuestionComment
comment on: http://stackoverflow.com/q/47675434
has text: You use `evec[2]`, but the eigenvectors are in the *columns*, so it should be `evec[:,2]`.
score: 3
type: Comment

http://stackoverflow.com/comment/82086752
has text: You have a long way to go yet but you're on the right track. This is a great example of the kind of beginner question I wish I could see more of: the code is all messed up but you know exactly what you want to do, and are able to articulate it well because you've put a lot of thought into it. The tools will come with practice. Keep it up and happy coding.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47560474
score: 0

http://stackoverflow.com/q/47631914
has answer: http://stackoverflow.com/a/52822293
has answer: http://stackoverflow.com/a/75528670
score: 61
upvote count: 61
favorite count: 0
tagged with: command-line
type: Question
has answer: http://stackoverflow.com/a/61119770
linked to: http://stackoverflow.com/q/1132941
downvote count: 0
has comment: http://stackoverflow.com/comment/82221602
tagged with: python
has answer: http://stackoverflow.com/a/47730333
accepted answer: http://stackoverflow.com/a/47730333
answer count: 6
has body: I want to call a python script through the command line with this kind of parameter (list could be any size, eg with 3): python test.py --option1 ["o11", "o12", "o13"] --option2 ["o21", "o22", "o23"] using click. From the docs, it is not stated anywhere that we can use a list as parameter to @click.option And when I try to do this: #!/usr/bin/env python import click @click.command(context_settings=dict(help_option_names=['-h', '--help'])) @click.option('--option', default=[]) def do_stuff(option): return # do stuff if __name__ == '__main__': do_stuff() in my test.py, by calling it from the command line: python test.py --option ["some option", "some option 2"] I get an error: Error: Got unexpected extra argument (some option 2]) I can't really use variadic arguments as only 1 variadic arguments per command is allowed (http://click.pocoo.org/5/arguments/#variadic-arguments) So if anyone can point me to the right direction (using click preferably) it would be very much appreciated.
has answer: http://stackoverflow.com/a/59422737
possible better answer: http://stackoverflow.com/a/59422737
tagged with: parameters
has answer: http://stackoverflow.com/a/52876175
has title: How to pass several list of arguments to @click.option
type: AnsweredQuestion
tagged with: python-click
has comment: http://stackoverflow.com/comment/82221765

http://stackoverflow.com/a/47910009
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47639304
answers question: http://stackoverflow.com/q/47639304
type: Answer
has body: I'm gonna answer my own question here. It turns out that the scripts name was 'mymodule.py' bin/ bin/mymodule.py lib/ lib/mymodule/ lib/mymodule/__init__.py lib/mymodule/example.py When importing from the repl, the pythonpath resolves to the lib/mymodule module, and the code is loaded correctly (mostly). When running the script mymodule.py, the python interpreter prepends the script's directory bin/ to the pythonpath. The script then sees an import statement(s) for mymodule, and sources itself. When it fails to find a namespace that can be traversed to look for 'example' within the script, it throws the ImportError. The solution is to either rename the module or rename the script, (e.g. bin/my_module.py) so that the namespaces don't collide.
score: 0

http://stackoverflow.com/comment/82208103
comment on: http://stackoverflow.com/a/47624986
type: Comment
score: 0
has text: I expanded the answer, adding an alternative to sorting.
type: AnswerComment

http://stackoverflow.com/q/47597615
has answer: http://stackoverflow.com/a/47599901
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/25386119
answer count: 1
has comment: http://stackoverflow.com/comment/82154307
has title: Django: "<...>" needs to have a value for field "id" before this many-to-many relationship can be used
score: 1
favorite count: 0
type: Question
has body: This is my method save on my form.py file. This is the ErroValue: Exception Type: ValueError Exception Value: "&lt;Nana: E&gt;" needs to have a value for field "id" before this many-to-many relationship can be used. 1.-I understand that I'm saving my Nana not at the correct time. What Am I doing wrong? 2.-'habilidades' and 'especiliades' are select mutiple fields in html. I need to save that data to the "Nana" model. @transaction.atomic() def save(self): valid_data = self.cleaned_data documento_codigo = valid_data.pop('documento') documento_tipo_id = valid_data.pop('tipo_documento') documento = Documento(codigo=documento_codigo, tipo_documento_id=documento_tipo_id) documento.save() #habilidad habilidades_nombre = valid_data.pop('habilidades') habilidades_habilidades = Habilidad(habilidades_nombre) habilidades_habilidades.save() nana = Nana(documento=documento, **valid_data) nana.save() nana.habilidades.add(habilidades_habilidades) return nana My form (without method save): class NanaForm(forms.Form): nombre = forms.CharField(label='Nombre', max_length=200) apellido_paterno = forms.CharField(label='Apellido paterno', max_length=100) apellido_materno = forms.CharField(label='Apellido materno', max_length=100) fecha_de_nacimiento = forms.DateField(label='Fecha de nacimiento') documento = forms.CharField(label='Documento', max_length=60, required=True) tipo_documento = forms.CharField(label='Tipo de documento', max_length=100) direccion = forms.CharField(label='Dirección', max_length=100) telefono_o_celular = forms.CharField(label='Teléfono o celular', max_length=14) latitud = forms.CharField(label='Latitud', max_length=100) longitud = forms.CharField(label='Longitud', max_length=100) genero = forms.CharField(label='Género', max_length=100) habilidades = forms.CharField(label='Habilidades', max_length=100) especialidades = forms.CharField(label='Especialidades', max_length=100) # habilidades = forms.MultipleChoiceField(label="Habilidades", required=False, widget=forms.S…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82153871

http://stackoverflow.com/comment/82179003
comment on: http://stackoverflow.com/q/47608215
type: QuestionComment
has text: these are the imports using from selenium import webdriver import os import shutil import sys import time import selenium from selenium.webdriver.common.keys import Keys import random
score: 0
type: Comment

http://stackoverflow.com/q/47545993
has answer: http://stackoverflow.com/a/47549617
type: UnansweredQuestion
tagged with: python
has title: Extract zip archive in Google Cloud Storage Bucket using Python api client
downvote count: 0
tagged with: google-cloud-platform
score: 1
upvote count: 1
has body: I'm trying to create a cloud function using api, the source code will be provided in a zip archive which includes an index.js &amp; package.json files. I have uploaded this archive to storage bucket and create a cloud function via API request but now I need to extract this zip archive to point out the source for cloud function, how can I achieve that? Here's what I have done: From views.py sclient = storage.Client() bucket = sclient.get_bucket(func_obj.bucket) blob = bucket.blob(func_obj.sourceFile.name) print('Uploading archive...') print(blob.upload_from_filename(file_name)) name = "projects/{}/locations/us-central1/functions/{}".format(func_obj.project, func_obj.fname,) print(name) req_body = { "name": name, "entryPoint": func_obj.entryPoint, "timeout": "3.5s", "availableMemoryMb": func_obj.fmemory, # "sourceUploadUrl": upload_url, "sourceArchiveUrl": "gs://newer_bucket/func.zip", "httpsTrigger": {}, } service = discovery.build('cloudfunctions', 'v1') func_api = service.projects().locations().functions() response = func_api.create(location='projects/' + func_obj.project + '/locations/us-central1', body=req_body).execute() pprint.pprint(response)
answer count: 1
tagged with: google-api-python-client
favorite count: 0
tagged with: google-cloud-storage
type: Question
linked to: http://stackoverflow.com/q/12985181

http://stackoverflow.com/q/47625632
tagged with: pyside
tagged with: maya
type: Question
has comment: http://stackoverflow.com/comment/82210017
has title: PySide QlistWidget selected Item directory(path)
tagged with: qlistwidget
answer count: 0
has body: I have a problem; How can i get the path (directory) from "QListWidget" selected item. When I 'am using os.path, this gives me Autodesk Maya Directory. But i need directory of my selected item from QListWidget item. from PySide.QtGui import * from maya.app.general.mayaMixin import MayaQWidgetDockableMixin import os import maya.cmds as cm Import maya commands from maya as cm. This not include python source files. class projectManagerMainWindow(MayaQWidgetDockableMixin, QWidget): def __init__(self): super(projectManagerMainWindow, self).__init__() self.selectProject = QComboBox() self.selectProject.setFixedHeight(30) items = ["Main Projects","Assets"] self.selectProject.addItems(items) self.createNewProject = QPushButton() self.createNewProject.setFixedSize(100,30) icon = QPixmap('C:/Users/Faithcure/Documents/maya/2016/scripts/projectManager/new.png') self.createNewProject.setText("New Project") self.createNewProject.setIcon(icon) self.dir_label = QLabel() def select_driectory(): select_path = cm.fileDialog2(fileMode=3, okc = "Select") self.sceneList.clear() for path in select_path: folders = os.listdir(path) self.sceneList.addItems(folders) self.dir_label.setText(path) self.choose_directory = QPushButton() self.choose_directory.setText("Directory") self.choose_directory.setIcon(icon) self.choose_directory.setFixedSize(100,30) self.choose_directory.clicked.connect(select_driectory) def new_project_window(): import newProject reload(newProject) ui = newProject.start() ui.exec_() def selected_item_path(): pass self.createNewProject.clicked.connect(new_project_window) This is Qlistwidget from selected directory items. self.sceneLabel = QLabel() self.sceneLabel.setText("Episodes: ") self.sceneList = QListWidget() self.sceneList.itemClicked.connect(selected_item_path) And this is my second list widget (i want to list under the selected directories folder from scneneList Widget... self.shotLabel = QLabel("Shots: ") self.shotList = QListWidget() self.topLayout = QHBoxLayout(…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82210540
has comment: http://stackoverflow.com/comment/82251945
tagged with: python
has comment: http://stackoverflow.com/comment/82210720
has comment: http://stackoverflow.com/comment/82210558
score: 0

http://stackoverflow.com/q/47666620
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has title: Set vertical Index for dataframe
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I want to bring the index 'Stkcd' into vertical index so that it will show a row of 1,2,3 .... for each row. I have try many transpose with different index but I seem that the index always shifting to the horizontal row, which is not what I want. I want my result to be like this.Stkcd on the vertical index on the left side This is what I am getting I don't want the Stkcd to be on the horizontal line And the original data is this enter image description here
has answer: http://stackoverflow.com/a/47667004
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82292402
accepted answer: http://stackoverflow.com/a/47667004

sql-server
tags question: http://stackoverflow.com/q/47573523
tags question: http://stackoverflow.com/q/47683981
tags question: http://stackoverflow.com/q/47664579
tags question: http://stackoverflow.com/q/47590982
tags question: http://stackoverflow.com/q/47553527
tags question: http://stackoverflow.com/q/47637374
tags question: http://stackoverflow.com/q/47625525
tags question: http://stackoverflow.com/q/47655600
tags question: http://stackoverflow.com/q/47696221
type: Tag
tags question: http://stackoverflow.com/q/47607971
tags question: http://stackoverflow.com/q/47673271
tags question: http://stackoverflow.com/q/47560405
tags question: http://stackoverflow.com/q/47670856
tags question: http://stackoverflow.com/q/47628477
tags question: http://stackoverflow.com/q/47677361
tags question: http://stackoverflow.com/q/47617346
tags question: http://stackoverflow.com/q/47652662
tags question: http://stackoverflow.com/q/47657850
tags question: http://stackoverflow.com/q/47682991
tags question: http://stackoverflow.com/q/47690983
tag name: sql-server
tags question: http://stackoverflow.com/q/47571713
tags question: http://stackoverflow.com/q/47555711

http://stackoverflow.com/comment/82207295
has text: @BIckknght Can you please elaborate what you mean by "masked by its own return value"? What are your suggestions for fixing the code?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47623834
score: 0

http://stackoverflow.com/a/47593988
has comment: http://stackoverflow.com/comment/82147228
downvote count: 0
has comment: http://stackoverflow.com/comment/82147132
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47589461
upvote count: 3
has body: Check this it will do the trick: from bokeh.plotting import figure, ColumnDataSource, output_notebook, show from bokeh.models import HoverTool, WheelZoomTool, PanTool, BoxZoomTool, ResetTool, TapTool, SaveTool from bokeh.palettes import brewer output_notebook() #preprocessing the data with column album_name category = 'album_name' category_items = df[category].unique() #selecting the colors for each unique category in album_name palette = brewer['Set2'][len(category_items) + 1] #mapping each category with a color of Set2 colormap = dict(zip(category_items, palette)) #making a color column based on album_name df['color'] = df[category].map(colormap) title = "Album_names" #feeding data into ColumnDataSource source = ColumnDataSource(df) #Editing the hover that need to displayed while hovering hover = HoverTool(tooltips=[('Album_name', '@album_name')]) #tools that are need to explote data tools = [hover, WheelZoomTool(), PanTool(), BoxZoomTool(), ResetTool(), SaveTool()] #finally making figure with scatter plot p = figure(tools=tools,title=title,plot_width=700,plot_height=400,toolbar_location='right',toolbar_sticky=False, ) p.scatter(x='valence',y='energy',source=source,size=10,color='color',legend=category) #displaying the graph show(p) The output will be displayed as shown for album_name Ctrl The output will be displayed as shown for album_name Z
score: 3
accepted answer of: http://stackoverflow.com/q/47589461
type: Answer

http://stackoverflow.com/comment/82227040
has text: I think in Python the most used term is "nested functions". Closures are not as pervasive in Python as they are in languages like Javascript (thanks God). Other than closures, having a function that depends on the enclosing namespace is often a code smell in any language so most python programmers would keep the signature as `bar(a)` even if it is a nested function.
score: 0
comment on: http://stackoverflow.com/q/47633807
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47544088
has answer: http://stackoverflow.com/a/47544285
linked to: http://stackoverflow.com/q/29815129
downvote count: 0
tagged with: python
score: 4
type: AnsweredQuestion
has body: This question is similar to Pandas DataFrame to List of Dictionaries, except that the DataFrame is not 'full': there are some nan values in it. Suppose I generate a DataFrame from a list of dictionaries like so: import pandas as pd data = [{'foo': 1, 'bar': 2}, {'foo': 3}] df = pd.DataFrame(data) so that the resulting df looks like bar foo 0 2.0 1 1 NaN 3 I would like a function which turns df back into the original data list of dictionaries. Unfortunately, assert df.to_dict('records') == data fails because the former is [{'bar': 2.0, 'foo': 1.0}, {'bar': nan, 'foo': 3.0}] with the additional 'bar': nan key-value pair in the second item. How can I get back the original data?
has answer: http://stackoverflow.com/a/47544280
accepted answer: http://stackoverflow.com/a/47544280
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47544134
possible better answer: http://stackoverflow.com/a/47544134
has title: How to convert a pandas DataFrame to a list of dictionaries where NaN values are omitted?
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/a/47613446
score: 0
has comment: http://stackoverflow.com/comment/82203497
answers question: http://stackoverflow.com/q/47611584
has body: %k return the name of the desktop file with path. Assume main.py is the name of your script You can try : Exec=python2 $(dirname %k)/main.py Hope this help.
type: Answer
has comment: http://stackoverflow.com/comment/82200534

http://stackoverflow.com/comment/82162228
comment on: http://stackoverflow.com/q/47601029
score: 0
type: QuestionComment
has text: "is is_prime a function or a variable?" Functions are just like any other object, and are assigned to *variables*, so I'm not sure what you mean, but it *is* a variable, one that doesn't happen to reference a function.
type: Comment

http://stackoverflow.com/comment/82237757
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47639656
has text: One thing right off the bat, you never need to do `if found==True:`. `if found:` will evaluate to the same expression and make your code look cleaner.

http://stackoverflow.com/a/47622923
has comment: http://stackoverflow.com/comment/84766454
has body: you can do like this.. f = open('yourTxtFile.txt','w') with open('your_csv_file.csv', 'r+') as file_obj: for line in file_obj.readlines(): f.write(line) if "death" in line.lower(): print line f.close() if you open a file as your way you have to close file. so you can use with open statement to open a file where in you need not have to worry to close the file.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47622691

curl
tags question: http://stackoverflow.com/q/47687888
tag name: curl
tags question: http://stackoverflow.com/q/47624975
tags question: http://stackoverflow.com/q/47652879
tags question: http://stackoverflow.com/q/47690344
tags question: http://stackoverflow.com/q/47654886
tags question: http://stackoverflow.com/q/47686045
tags question: http://stackoverflow.com/q/47659088
tags question: http://stackoverflow.com/q/47570338
tags question: http://stackoverflow.com/q/47673996
type: Tag
tags question: http://stackoverflow.com/q/47550043
tags question: http://stackoverflow.com/q/47588402

http://stackoverflow.com/q/47594122
downvote count: 1
has comment: http://stackoverflow.com/comment/82146463
favorite count: 0
has comment: http://stackoverflow.com/comment/82145478
has title: Find tuple of strings in string in python
duplicate of: http://stackoverflow.com/q/3389574
type: AnsweredQuestion
has body: With the startswith() and endswith() functions it is possible to pass a tuple of strings, where if there is a match on any element the result is returned True e.g.,: text_to_find = ("string_1", "string2") test = "string_to_look_in" if test.startswith(text_to_find ) == True: print ("starts with one of the strings") Is there a similar command, that will work with tuples, for finding a string in a string - i.e., one of the strings in the tuples appearing anywhere in the text. (instead of e.g., using a for loop, where individually look each item in the string).
has comment: http://stackoverflow.com/comment/82145437
score: 1
has comment: http://stackoverflow.com/comment/82145514
accepted answer: http://stackoverflow.com/a/47594252
has answer: http://stackoverflow.com/a/47594252
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82145537
upvote count: 2
linked to: http://stackoverflow.com/q/3389574
answer count: 1
tagged with: python

http://stackoverflow.com/q/47592399
tagged with: python
has body: I am new to python and trying to perform stop word removal in a csv file and write the results to another csv. Below is the code I have written : import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import csv import codecs f = codecs.open("F:/mtech/Project/answer_sample.csv","r","utf-8") answers = f.read() f.close() file_out = open('answer_swr','w') unicode(answers) #for x in answers: # print("type of x is") # print type(x) #for y in stopwords.words('english'): # print("type of y is") for line in answers: stop_words=set(stopwords.words("english")) words=word_tokenize(line) filtered_sentence=[""] for n in words: if n not in stop_words: filtered_sentence.append(""+n) file_out.writelines(filtered_sentence+["\n"]) print("Stop words removed..") and I am receiving an error: file_out.writelines(filtered_sentence+["\n"]) TypeError: writelines() argument must be a sequence of strings
has comment: http://stackoverflow.com/comment/82142280
has comment: http://stackoverflow.com/comment/82144067
has comment: http://stackoverflow.com/comment/82142219
has comment: http://stackoverflow.com/comment/82143828
answer count: 0
has comment: http://stackoverflow.com/comment/82142445
score: 1
has comment: http://stackoverflow.com/comment/82143952
has comment: http://stackoverflow.com/comment/82141878
downvote count: 0
has comment: http://stackoverflow.com/comment/82142320
has comment: http://stackoverflow.com/comment/82142089
upvote count: 1
favorite count: 0
has title: Read data from CSV file, perform stop word removal and write to another CSV file
type: Question
has comment: http://stackoverflow.com/comment/82143879
has comment: http://stackoverflow.com/comment/82141906
has comment: http://stackoverflow.com/comment/82142036
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82142556
has comment: http://stackoverflow.com/comment/82143935

http://stackoverflow.com/q/47546552
linked to: http://stackoverflow.com/q/19744391
favorite count: 0
has title: Checksum for HEX string Python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82052409
score: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/100716715
tagged with: checksum
type: Question
has body: Here is HEX string: 57 F1 0F 9A A8 B7 00 08 0B 19 10 00 00 00 00 00 11 0B 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 A8 and B7 is a checksum that i need to calculate In C it calculated like that (100% worked): void ByteStream_ComputeCS(void) { int i; DWORD cs = 0; for (i = 0; i &lt; ByteStream[2] + 3; i++) { if (i != 2) cs += *((WORD*)ByteStream + i); } cs = (cs &amp; 0xFFFF) + (cs &gt;&gt; 16); ByteStream[4] = (BYTE)cs; ByteStream[5] = (BYTE)(cs &gt;&gt; 8); } Im trying to do it like that: data = bytearray.fromhex('57 F1 0F 9A 00 00 00 08 0B 19 10 00 00 00 00 00 11 0B 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00') c_sum = sum(data) I just replace checksum with 0 - in C its just dont sum if (i != 2) cs += *((WORD*)ByteStream + i); But i get 0x25e. And cant get it to A8 and B7. What I'm doing wrong?
has comment: http://stackoverflow.com/comment/82051899
tagged with: python
has answer: http://stackoverflow.com/a/47548080

http://stackoverflow.com/a/47602346
upvote count: 15
answers question: http://stackoverflow.com/q/47602278
type: AcceptedAnswer
type: Answer
has body: You're calling __new__ wrong. If you want your __new__ to create an instance of a subclass, you don't call the subclass's __new__; you call the superclass's __new__ as usual, but pass it the subclass as the first argument: instance = super().__new__(A) I can't guarantee that this will be enough to fix your problems, since the code you've posted wouldn't reproduce the error you claim; it has other problems that would have caused a different error first (infinite recursion). Particularly, if A and B don't really descend from Thing, that needs different handling.
has comment: http://stackoverflow.com/comment/82163973
score: 15
has comment: http://stackoverflow.com/comment/82179449
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47602278

http://stackoverflow.com/a/47597606
accepted answer of: http://stackoverflow.com/q/47597545
answers question: http://stackoverflow.com/q/47597545
has comment: http://stackoverflow.com/comment/82153600
has comment: http://stackoverflow.com/comment/82154177
has comment: http://stackoverflow.com/comment/82154116
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82154208
has body: You can use a single dictionary comprehension: terms=['the', 'fox', 'the', 'quick', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] new_terms = {term:terms.count(term) for term in terms} Output: {'lazy': 1, 'over': 1, 'fox': 2, 'dog': 1, 'quick': 1, 'the': 3, 'jumps': 1} using the multiset: import itertools import multiset final_data = [multiset.Multiset(list(b)) for a, b in itertools.groupby(sorted(terms))] Output: [Multiset({'dog': 1}), Multiset({'fox': 2}), Multiset({'jumps': 1}), Multiset({'lazy': 1}), Multiset({'over': 1}), Multiset({'quick': 1}), Multiset({'the': 3})]
type: AcceptedAnswer

http://stackoverflow.com/q/47583295
type: Question
tagged with: python-3.x
has body: print(index) split = index.split(',') split = split[0].split(' ') print(split) print(split[1]) if split[1] == '': ####It's working c.execute("SELECT * FROM registros WHERE ID = ?", split[2]) for row in c.fetchall(): c.execute("UPDATE registros SET datasaida = ?,valor = ? WHERE ID = ?", (dateout, valor, split[2])) else: ####It's not working a = split[1] c.execute("SELECT * FROM registros WHERE ID = ?", str(split[1])) for row in c.fetchall(): c.execute("UPDATE registros SET datasaida = ?,valor = ? WHERE ID = ?", (dateout, valor, split[1])) 10, qwerwe 30/11/2017 13:45 ['', '10'] 10 Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\ThomasCaio\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/PycharmProjects/Project/Program.py", line 399, in &lt;lambda&gt; but1 = ttk.Button(pop,text='Encerrar serviço',command=lambda:self.Saida()) File "C:/PycharmProjects/Project/Program.py", line 422, in Saida c.execute("SELECT * FROM registros WHERE ID = ?", str(split[1])) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied. The if is working well but the else, that has the same code, doesn't working What happenned?
type: UnansweredQuestion
has title: Python3 Sqlite3 Error
tagged with: python
duplicate of: http://stackoverflow.com/q/16856647
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82124278
has comment: http://stackoverflow.com/comment/82124528
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82124457
tagged with: sqlite
favorite count: 0

http://stackoverflow.com/a/47603514
has body: incr_num(x+1, y) keeps getting called until x == y, and then the recursion ends, then you return to the previous execution where x=9, so x still has the value it's passed, and x &lt;= y is not False. Therefore the recursion happens again and prints 10 You'll at least want a x+=1 after that recursive call. I wouldn't call a while loop inside recursion straightforward ;) If that's your base case for ending the recursion, you want if x&lt;=y
downvote count: 0
answers question: http://stackoverflow.com/q/47603498
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/82192803
type: Comment
has text: Moreover this approach is more slow than the others
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47617160

http://stackoverflow.com/comment/82287407
type: AnswerComment
has text: you mean the dataset ?
score: 0
comment on: http://stackoverflow.com/a/47664007
type: Comment

http://stackoverflow.com/comment/82221169
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47631594
has text: @Morb {}'.format('yourtext') has no effect. It is still printing the string in the form of unicode codes

http://stackoverflow.com/q/47542549
type: AnsweredQuestion
score: 0
has body: I am writing a script that creates multiple plotly interactive charts that are saved in HTML format. I want to write code that sends these HTML files out in an email as an attachment. I can't seem to find any documentation on this, only instructions on how to embed the HTML in an email which is not what I want. I just want to attach the file, just like I was attaching a JPG picture or PDF file. Code I have so far, which just embeds the HTML: import lxml.html import smtplib import sys import os page = 'report.html' root = lxml.html.parse(page).getroot() root.make_links_absolute() content = lxml.html.tostring(root) message = """From: &lt;me@gmail.com&gt; To: &lt;you@gmail.com&gt; MIME-Version: 1.0 Content-type: text/html Subject: %s %s""" %(page, content) s = smtplib.SMTP('localhost') s.sendmail('me@gmail.com', ['you@gmail.com'], message) s.quit() Appreciate the help. I'd hopefully like to find a dynamic way to send files that are in multiple formats, so that I don't have to worry about different functions to send different types of files.
tagged with: mime
answer count: 1
tagged with: smtp
accepted answer: http://stackoverflow.com/a/47542639
type: Question
has title: MIME- sending an email with an HTML file as an attachment?
tagged with: email
tagged with: python
has answer: http://stackoverflow.com/a/47542639

http://stackoverflow.com/comment/82081231
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47561723
type: AnswerComment
has text: thank you so much! that worked. i will try to format my questions more appropriately next time as well.

http://stackoverflow.com/a/47638997
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47638896
upvote count: 2
downvote count: 0
has body: You are trying to create a dict from a str: newDictionaryItem = """{'author': {'nickname': '%s'}, 'body': '%s'}""" % (userName, userMessage) posts.append(dict(newDictionaryItem)) ^^^^^ Python will not do this parsing for you. To fix this, create the dictionary manually: newDictionaryItem = {'author': {'nickname': userName }, 'body': userMessage } posts.append(newDictionaryItem)

http://stackoverflow.com/comment/82118649
comment on: http://stackoverflow.com/a/47580381
score: 0
type: AnswerComment
type: Comment
has text: If you have multiindex columns, you may need to pass `level=...` too. Check the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html).

http://stackoverflow.com/q/47614844
has comment: http://stackoverflow.com/comment/82188557
has comment: http://stackoverflow.com/comment/82188856
has comment: http://stackoverflow.com/comment/82188826
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82188866
has answer: http://stackoverflow.com/a/47615394
has comment: http://stackoverflow.com/comment/82188484
has comment: http://stackoverflow.com/comment/82188446
has comment: http://stackoverflow.com/comment/82188421
tagged with: python
has title: python *list syntax error on server only, code working fine on local client
tagged with: flask
tagged with: python-3.6
type: AnsweredQuestion
has body: When I execute my code on my external flask server, I get the following server-side error: 2017-12-03 02:40:53 ", line 2017-12-03 02:40:53 430 2017-12-03 02:40:53 2017-12-03 02:40:53 2017-12-03 02:40:53 combinedheader = ["Protein", "MW", *listheadersSpC, *listheadersNSAF, *listheadersloge] 2017-12-03 02:40:53 2017-12-03 02:40:53 2017-12-03 02:40:53 ^ 2017-12-03 02:40:53 SyntaxError 2017-12-03 02:40:53 : 2017-12-03 02:40:53 invalid syntax 2017-12-03 02:40:53 This is the line of code that's causing grief: combinedheader = ["Protein", "MW", *listheadersSpC, *listheadersNSAF, *listheadersloge] Locally, the code runs just fine. Also note that the following code returns no errors when executed separately on the server: list1 = ['a'] list2 = ['d' , 'e' , 'f'] list3 = ["Hi", "there", *list1, *list2] print(list3) Retuns: ['Hi', 'there', 'a', 'd', 'e', 'f'] EDIT: Code is running on a web app that's using a virtual environment for Python. Both the webapp and virtualenv python = 3.6. Local client running same version of python, same installed modules.
has comment: http://stackoverflow.com/comment/82188971
accepted answer: http://stackoverflow.com/a/47615394
has comment: http://stackoverflow.com/comment/82188850
downvote count: 0
has comment: http://stackoverflow.com/comment/82188795
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82188411
answer count: 1

http://stackoverflow.com/comment/82413365
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47697667
has text: @SamHecquet yes it is working. but unfortunately I m having another problem :(
type: Comment

http://stackoverflow.com/comment/82075175
type: Comment
type: QuestionComment
has text: Yeah it's odd that it wants a float coz I didn't tell it to use a float! I get this in the errorlog - Internal File "...miniconda3/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1781, in get_prep_value return float(value) ValueError: could not convert string to float: "'1910" [29/Nov/2017 17:45:27] "GET /weatherstats/wales HTTP/1.1" 500 175801
score: 0
comment on: http://stackoverflow.com/q/47558374

http://stackoverflow.com/a/47602290
downvote count: 0
has body: replace doesn't check inside the list element, you'll have to use loops/apply in this case: df['a'] = df.a.apply(lambda x: [s for s in x if s != '$A']) df # a b #0 [1] 4 #1 [3] 5 #2 [] 6
answers question: http://stackoverflow.com/q/47602234
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/82185782
type: QuestionComment
comment on: http://stackoverflow.com/q/47613643
score: 0
type: Comment
has text: *in a dictionary* - but your `countdict` is a list

http://stackoverflow.com/q/47662378
tagged with: python-2.7
tagged with: wxwidgets
score: 0
has title: wxPython problems with StaticText RightAlign
has comment: http://stackoverflow.com/comment/82318553
has body: I'm using a wx statictext class to display readings that will be updated every second. I want the readings to be right aligned in the grid bag sizer. When I begin my program to start displaying values, the values are left aligned, but if I go from maximize window -> minimize window -OR- minimize window -> maximize window, the readings align and continue to stay re-aligned. I've set the wx.ALIGN_RIGHT for the static text style, and flag wx.ALIGN_RIGHT when adding it to the grid bag sizer. I'm not sure why I need to do a window size change before the values have the correct alignment. When I adjust the size of the windows via the edges the values stay wrongly aligned, it is only when it is maximized/minimized. static_text_reading[i] = wx.StaticText(self, wx.ID_ANY, DEFAULT_START_TEXT, style = wx.ALIGN_RIGHT) main_gbs = wx.GridBagSizer( 0, 0 ) main_gbs.Add(static_text_reading[i], pos=(1,i+1), flag=wx.ALIGN_RIGHT, border=self.border) topSizer.Add(main_gbs, 0, wx.ALL|wx.EXPAND, self.border)
has comment: http://stackoverflow.com/comment/82285135
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: wxpython
tagged with: python
has comment: http://stackoverflow.com/comment/82284446

http://stackoverflow.com/q/47671676
type: UnansweredQuestion
has body: Action Reading multiple LAZ point cloud files to a Dask DataFrame. Problem Unzipping LAZ (compressed) to LAS (uncompressed) requires a lot of memory. Varying filesizes and multiple processes created by Dask result in MemoryError's. Attempts I tried limiting the number of workers following the guide, but it does not seem to work. from distributed import Client, LocalCluster cluster = LocalCluster(n_workers=3) client = Client(cluster) dfs = [load(file) for file in lasfiles] df = dd.from_delayed(dfs, meta=meta) df = df.repartition(npartitions=len(df) // part_size) df.to_parquet('/raw', compression='GZIP') Question How to go about loading such large amount of data in a non-standard format? Example Following example is my current implementation. It groups all input files per 5 to limit max 5 parallel uncompressing processes. Then repartitions and write to Parquet to enable further processing. To me this implementation seems to totally miss the point of Dask. from laspy.file import File import numpy as np import pandas as pd import dask.dataframe as dd from dask.delayed import delayed @delayed def load(file): with File(file.as_posix(), mode='r') as las_data: las_df = pd.DataFrame(las_data.points['point'], dtype=float) return las_df meta = pd.DataFrame(np.empty(0, dtype=[('X',float),('Y',float),('Z',float),('intensity',float),('raw_classification',int)])) lasfile_dir = Path('/data/las/') lasfiles = sorted(list(lasfile_dir.glob('*.laz'))) part_size = 5000000 for idx, sublasfiles in enumerate([lasfiles[i:i+5] for i in range(0,len(lasfiles),5)]): try: dfs = [load(file) for file in sublasfiles] df = dd.from_delayed(dfs, meta=meta) df = df.repartition(npartitions=len(df) // part_size) df.to_parquet('/data/las/parquet/'+str(idx), compression='GZIP')
tagged with: laspy
answer count: 1
tagged with: dask-delayed
favorite count: 0
type: Question
tagged with: dask
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/47674679
tagged with: python
has comment: http://stackoverflow.com/comment/85781470
has title: Reading LAZ to Dask dataframe using delayed loading
has comment: http://stackoverflow.com/comment/85848308
downvote count: 0

http://stackoverflow.com/comment/82335305
comment on: http://stackoverflow.com/a/47686192
has text: There are only duplicate values in the `value` column of `df`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82064092
score: 0
comment on: http://stackoverflow.com/a/47549412
has text: This looks like a better approach. However, I want to output the same date formatting from the input file to the output file. i.e. the output file should contain: 12/2/12 Jan-12
type: Comment
type: AnswerComment

http://stackoverflow.com/a/74203963
has body: The TypeError: NoneType object is not iterable error is raised when you try to iterate over an object whose value is equal to None. To solve this error, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list. Thus, if you forgot to add a return statement to a function it will return None. However, this is not always possible. In my case, I obtained a generator from another library that contained a None at some point. So when iterating over the generator or transforming it to a list, it generated the error. Alternatively, we can use the error inside a try and except. We can iterate through it saving the iterated elements in try until the element that gives error, at which point it will be handled by except allowing the code to continue running. save_elements = [] try: for i, c in enumerate(response): # print(i, c) save_elements.append(i) except: pass print(all) # values saves before the TypeError NoneType response is a variable returned by the package to mine a social network that is full until the next paging index is empty.
type: Answer
answers question: http://stackoverflow.com/q/47581334
score: 0

http://stackoverflow.com/comment/82346695
score: 0
type: Comment
type: AnswerComment
has text: Thanks. I was thinking it is returning Datetime instance.
comment on: http://stackoverflow.com/a/47686826

http://stackoverflow.com/a/47695091
accepted answer of: http://stackoverflow.com/q/47684885
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/47684885
downvote count: 0
has comment: http://stackoverflow.com/comment/82371625
type: AcceptedAnswer
has body: Circles and intercepting points MDN gives "A rx,ry xAxisRotate LargeArcFlag,SweepFlag x,y" as an arc in the path element. What are rx and ry? I would guess radius for x,y. I am guessing you would use it as // x,y start position // rx,ry radius x and y // x1,y1 end position <path d="M x,y A rx, ry, 0 1 1 x1, y1"/> Below is the problem solved as javascript. I have Commented the part you need for the SVG. The two end points (intercepts) There is a lot of redundancy but its not clear what you want so the code provides how to find other parts of two intersecting circles. Law of Cosines The math to solve the problem is called the law of cosines that is used to solve triangles. In this case the triangle is created from 3 lengths. One each of the circle radius and one is the distance between circle centers. The image gives more details With the angle c you can find the lengths GE, DE, and EF. If you want the angle for the other side at point f just swap B and C. Example Move mouse to check intercept. const ctx = canvas.getContext("2d"); const m = { x: 0, y: 0 }; document.addEventListener("mousemove", e => { var b = canvas.getBoundingClientRect(); m.x = e.pageX - b.left - scrollX; m.y = e.pageY - b.top - scrollY; }); const PI = Math.PI; const PI2 = Math.PI * 2; const circles = []; function circle(x, y, r, col, f = 0, t = PI2, w = 2) { var c; circles.push(c = { x, y,r, col, f, t, w}); return c; }; function drawCircle(A) { ctx.strokeStyle = A.col; ctx.lineWidth = A.w; ctx.beginPath(); ctx.arc(A.x, A.y, A.r, A.f, A.t); ctx.stroke(); } function mark(x, y, r, c) { ctx.strokeStyle = c; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(x, y, r, 0, PI2); ctx.stroke(); } function line(A, B, c) { ctx.strokeStyle = c; ctx.lineWidth = 2; ctx.beginPath(); ctx.lineTo(A.x, A.y); ctx.lineTo(B.x, B.y); ctx.stroke(); } // note I am sharing calc results between function function circleIntercept(A, B) { var vx, vy, dist, c, d, x, y, x1, y1, x2, y2, dir, a1, a2; // Vec from A to B vx = B.x - A.x; vy =…
has comment: http://stackoverflow.com/comment/82361350
type: Answer

http://stackoverflow.com/q/47545327
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Append missing values to CSV file
score: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/47545580
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82047879
has body: I have a sorted CSV file in following format- X,Y 0,0 0,1 0,2 1,0 1,1 2,0 2,1 2,1 Here, a value 1,2 is absent. This is just a sample, my file contains a 1 million records with a few thousand absent. How can I write a script to detect and append these values to the file? I have tried generating all possible pairs and check if they are present in the file or not, but is way too slow- import csv with open('myfile.csv') as csvfile: r = csv.reader(csvfile, delimiter=',') for row in r: for i in range(1000): for j in range(1000): if (int(row[0]) == i and int(row[1]) == j): # Can perform operations here Is there some way I can use Numpy or Pandas (I'm very new to those) to solve this problem?
has comment: http://stackoverflow.com/comment/82047790

http://stackoverflow.com/comment/82190796
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47613566
type: Comment
has text: You’re right, this was it. Combination of not reading the docs correctly and I don’t usually read/write Python. Thanks!

http://stackoverflow.com/comment/82197481
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47619709
type: AnswerComment
has text: you didn't read fully then: drop `.keys()`, but mostly add a `not` to your condition. The condition is ok for `setitem` since you want to avoid overwrite of existing, but get & del need negation.

http://stackoverflow.com/q/47559845
type: Question
has answer: http://stackoverflow.com/a/47559965
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
has answer: http://stackoverflow.com/a/47559994
answer count: 4
has comment: http://stackoverflow.com/comment/82078136
has answer: http://stackoverflow.com/a/47559972
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47559901
favorite count: 0
has body: I want to create a dictionary of the capitals and governors and then later choose a random state to ask the user what the capital of _ is or who the governor of _ is. I have import random def state_dict(): states={"Alabama":["montgomery","kay ivey"],"Alaska":["Juneau","Bill Wallker"]} def main(): question_list=["What is the capital of","Who is the governor of"] choose_question=random.choice(question_list) if choose_question=="What is the capital of": choose_state= random.choice(states_dict) print("What is the capital of",choose_state) elif choose_question=="Who is the governor of": choose_state_2= random.choice(states_dict) print("Who is the governor of", choose_state_2) main() I get an error that states is undefined and I am unable to figure out why.
has title: How to create a dictionary of capitals and governors of states
has comment: http://stackoverflow.com/comment/82078331
has comment: http://stackoverflow.com/comment/82078215

http://stackoverflow.com/comment/82287756
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47663908
has text: can you share the csv file

http://stackoverflow.com/q/47680410
tagged with: python
has comment: http://stackoverflow.com/comment/82322216
favorite count: 0
type: Question
tagged with: task
answer count: 0
type: UnansweredQuestion
has body: I'm trying to run a chain inside a chord in celery. My workflow looks like this: task1.s(arg1) | task2.s() | chord([task3.s(), (task4a.s()| task4b.s())], task5.s()) | task 6.s() where : task3 and task4a are taking same arguments (=return value of task2) task5 should wait for both task3 and task4b to finish (and take their output as input). When running such a pipe, it seems that only task3 received the output of task2as argument. Indeed I'm having an error of kind TypeError: task4a() missing 1 required positional argument. If I replace the chain (task4a.s()| task4b.s()) by a single task, there is no error and argument are well passed. It seems that celery does not handle chain in chords (or I don't know how to use it). I do not want to "fuse" my 2 tasks into 1 (because I need to see intermediate results). Has anyone encounter a similar issue and find a solution/workaround? Cheers Edit: I use celery 4.1.0 with redis backend and RabbitMQ broker.
tagged with: celery
has title: Celery chain inside a chord argument error
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47637955
answer count: 1
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
tagged with: error-handling
has body: What is the recommended way of separately handling exceptions of the same type based on differences in what caused the exception? Let's say one desire to handle the following two instances of AttributeError differently: 'str' object has no attribute 'append' 'float' object has no attribute 'append' At the same time, we don't want to handle other attribute errors. Are there any generalizable answers that work for all exception types? Can I interrogate the exception object for details using some method or function on the exception object? Try: blah Except AttributeError as exc: if exc.baz('foo') is bar: handle 'str' object has no attribute 'append' elif plugh(exc): handle 'float' object has no attribute 'append' else: raise exc I assume that the obvious answer is to refactor. My question specifically regards the cases where that would be inefficient or simply not possible (if there are any such cases at all).
favorite count: 0
tagged with: python-3.x
has title: Exception handling: Differentiating between instances of the same error in Python
type: Question
accepted answer: http://stackoverflow.com/a/47638448
tagged with: exception
has answer: http://stackoverflow.com/a/47638448
tagged with: python

http://stackoverflow.com/q/47546585
tagged with: node.js
duplicate of: http://stackoverflow.com/q/25696323
has comment: http://stackoverflow.com/comment/82049788
has comment: http://stackoverflow.com/comment/82052725
tagged with: mongodb
answer count: 0
linked to: http://stackoverflow.com/q/25696323
type: UnansweredQuestion
tagged with: pymongo
tagged with: mongoose
has title: How to connect to an already existing database in python
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82053826
tagged with: python
has body: I made a database using mongoose on express js. Then when I try to access that database in python using pymongo it creates a new database with same name on same connection and new collections. Below is my connection code in python import pymongo connection = pymongo.MongoClient('mongodb://localhost:27017/fileUpoadStats') file1 = connection.fileStats cursor = file1.find() for doc in cursor: print doc I want to access the same database in python. Can anyone help?
has comment: http://stackoverflow.com/comment/82050258
has comment: http://stackoverflow.com/comment/82052177

http://stackoverflow.com/comment/131700110
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/64630179
has text: The link is not working

http://stackoverflow.com/comment/82200990
type: Comment
type: QuestionComment
has text: "List comprehensions run a bit faster than equivalent for-loops (unless you're just going to throw away the result)." from: https://wiki.python.org/moin/PythonSpeed
comment on: http://stackoverflow.com/q/47621511
score: 1

http://stackoverflow.com/comment/82622788
type: Comment
score: 0
has text: Where is the actual memory error happening? What stage of your training?
type: QuestionComment
comment on: http://stackoverflow.com/q/47696236

http://stackoverflow.com/q/47627030
has title: Spoonacular API integration with Python
tagged with: spoonacular
type: Question
has comment: http://stackoverflow.com/comment/82212227
tagged with: python
type: UnansweredQuestion
has body: def getRecipeByIngredients(): payload = { 'fillIngredients': False, 'ingredients': ingredients, 'limitLicense': False, 'number': 5, 'ranking': 1 } api_key = os.environ['api_key'] endpoint = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients" headers={ "X-Mashape-Key": "mashape key", "X-Mashape-Host": "mashape host" } r = requests.get(endpoint, params=payload, headers=headers) results = r.json() title = results[0]['title'] print(title) I am having trouble accessing the title of the recipe when searching for recipes by ingredients using the Spoonacular API. I've followed all the instructions on the page and made sure I'm getting to the title correctly, however when I search for the recipe nothing is outputted besides the GET request. Any ideas?
tagged with: api
downvote count: 0
has answer: http://stackoverflow.com/a/51778526
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/82326181
comment on: http://stackoverflow.com/q/47683265
has text: yes, i'm sorry :(
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82189355
type: Comment
has text: I read this question as "how can I conditionally execute code without using conditionals". What...?
score: 2
comment on: http://stackoverflow.com/q/47615528
type: QuestionComment

http://stackoverflow.com/comment/82242450
comment on: http://stackoverflow.com/q/47641949
score: 1
type: Comment
type: QuestionComment
has text: `sys.getsizeof()` **only gives you the size of the dictionary itself, not the size of the objects contained in the dictionary, nor any objects on those objects**

http://stackoverflow.com/a/47666829
type: Answer
score: 4
type: AcceptedAnswer
has body: The memcache key used can be found in google.appengine.ext.context.py: Context.get(): if use_memcache: mkey = self._memcache_prefix + key.urlsafe() The prefix (in my version at least) is 'NDB9:'. So to get the memcache key you can use something similar to: from google.appengine.ext import ndb key = ndb.Key('User', 5229916580741120) mkey = 'NDB9:' + key.urlsafe() print mkey This results in something like: NDB9:ahpzfmR5bmFtaWMtdHJhdmVsbGVyLTItdGVzdHIRCxIEVXNlchiAgIDAzZKlCQw To delete: from google.appengine.api import memcache value = memcache.get(mkey) result = memcache.delete(mkey) print "Memcache delete result={}".format(result) if result == 2: print "{} memcache value has been deleted".format(key) elif result == 1: print "{} memcache value not found".format(key) else: print "Failed to delete {} memcache value".format(key) Caveat: without the memcache.get() call before memcache.delete() the delete result was always '1' (not found) using the interactive console. Not sure why that's the case.
answers question: http://stackoverflow.com/q/47628075
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47628075
downvote count: 0

http://stackoverflow.com/q/47603959
has answer: http://stackoverflow.com/a/47604102
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: sqlite
has body: I currently develop a web application in python 2.7 that is build on a couple of module that I import in my main python application and call function from them. Almost all of these module are opening a connection to the same SQLite3 database and some of them are doing update or insert into table from time to time. Sometime, I get database locked error when two or more module try to update the db at the same time. That lead me to questionning myself... Am I doing the wrong thing opening and closing the connection to the database all the time or should I better to open it at the beginning of the program and close it at the end? In this case, what would be the better way of sharing this connection between all my module? Thanks for your help!
linked to: http://stackoverflow.com/q/47632288
favorite count: 0
type: Question
has title: What is the best approach when using SQLite3 from multiple module in the same global python application?
answer count: 1
accepted answer: http://stackoverflow.com/a/47604102
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/a/47622268
accepted answer of: http://stackoverflow.com/q/47621525
score: 3
type: Answer
has body: After looking around some more I came across this thread PySide threading and http downloading I wish I had found it sooner because I did a lot of searching before my post. The person who answered that thread reclosedev also posted this in the comments: https://pastebin.com/b4MD5jKh Which helped me immensely to understand some things better. I used his code and slightly altered it to fit mine and it will work great for what I would like to do. Here is my full working code using my original example for anyone out there that may find it useful. import urllib2 from PyQt4 import QtGui, QtCore from PyQt4.QtCore import QThread, pyqtSignal from PyQt4.QtGui import QApplication import sys class MainWindow(QtGui.QWidget): def __init__(self): super(self.__class__, self).__init__() layout = QtGui.QVBoxLayout(self) self._Button = QtGui.QPushButton() self._Button.setObjectName("_Button") self.line_edit = QtGui.QLineEdit() self.line_edit.setObjectName("line_edit") self.txt_box = QtGui.QTextEdit() self.txt_box.setObjectName("txt_Box") self.img_label = QtGui.QLabel() self.img_label.setObjectName("img_label") self.imagepreview = ImagePreview() layout.addWidget(self._Button) layout.addWidget(self.line_edit) layout.addWidget(self.img_label) layout.addWidget(self.txt_box) layout.addWidget(self.imagepreview) self._thread = test_thread() self._Button.clicked.connect(self.start_thread) self._Button.clicked.connect(self.imagepreview.startDownload) self.get_Text = self._thread.test_Signal.connect(self.line_edit.setText) def start_thread(self): self._thread.start() self._thread.test_Signal.connect(self.txt_box.setText) class test_thread(QThread): test_Signal = pyqtSignal(str) def __init__(self): super(test_thread, self).__init__() def run(self): string = 'This is a test string.' self.test_Signal.emit(string) class DownloadThread(QtCore.QThread): data_downloaded = pyqtSignal() def __init__(self, url): QtCore.QThread.__init__(self) self.url = url self._data = None def run(self): self._data = ur…
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47621525
type: AcceptedAnswer

http://stackoverflow.com/comment/82248336
has text: So I tried doing getattr() and maybe I'm doing something wrong. It doesn't allow a string in the first argument and I can't include all of L100ENABLE.GetValue in the second argument. getattr(string, GetValue) doesn't work because it looks for the attribute in str. I also tried getattr(frame, "L100ENABLE.GetValue") but that did not work either.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47643618
score: 0

http://stackoverflow.com/q/47653090
type: Question
has title: find total data in N*N matrix
accepted answer: http://stackoverflow.com/a/47655193
tagged with: algorithm
has answer: http://stackoverflow.com/a/47655193
tagged with: python
has body: a matrix consists of N × N blocks .the block number is equal to the sum of the row number and the column number. each block consists of data, and data is equal to difference of sum of even and odd digits of the block number . calculate total data of n*n blocks i/o format lets n = 4 so matrix will be 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 so total data = 2+3+4+5+3+4+5+6+4+5+6+7+5+6+7+8=80 if number of block is 4256 in any case then data in it will be abs(diff(sum(even digits)- sum(odd digits))) which is abs((4+2+6)-(5))= 7 my naive attempt n = int(raw_input()) sum1=0 sum2=0 for i in range(1,n+1): for j in range(1,n+1): sum1 = i+j diffsum = diff(sum1) sum2 = sum2+diffsum print sum2 again optimized attempt def diff(sum1): sum1 = str(sum1) m = sum([int(i) for i in sum1 if int(i) % 2 == 0]) f = sum([int(i) for i in sum1 if int(i) % 2 != 0]) return abs(m - f) n = int(raw_input()) sum1 = 0 k = 1 # t1 = time.time() p = 2 * n for i in range(2, n + 2): diffsum = diff(i) diffsum1 = diff(p) sum1 = sum1 + (diffsum * k) sum1 = sum1 + (diffsum1 * k) p = p - 1 k = k + 1 sum1 = sum1 - (diff(n + 1) * n) print sum1 diff is common function in both case. i need more optmization with the following algorithm
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47583501
has body: I have a matrix (of vectors) X with shape [3,4], and I want to calculate the dot product between each pair of vectors (X[1].X[1]) and (X[1].X[2])...etc. I saw a cosine similarity code were they use tf.reduce_sum(tf.multyply(X, X),axis=1) to calculate the dot product between the vectors in a matrix of vectors.However, this result in only calculates the dot product between (X[i], X[i]). I used tf.matmul(X, X, transpose_b=True) which calculate the dot product between every two vectors but I am still confused why tf.multiply didn't do this I think the problem with my code. the code is: data=[[1.0,2.0,4.0,5.0],[0.0,6.0,7.0,8.0],[8.0,1.0,1.0,1.0]] X=tf.constant(data) matResult=tf.matmul(X, X, transpose_b=True) multiplyResult=tf.reduce_sum(tf.multiply(X,X),axis=1) with tf.Session() as sess: print('matResult') print(sess.run([matResult])) print() print('multiplyResult') print(sess.run([multiplyResult])) The output is: matResult [array([[ 46., 80., 19.], [ 80., 149., 21.], [ 19., 21., 67.]], dtype=float32)] multiplyResult [array([ 46., 149., 67.], dtype=float32)] I would appreciate any advise
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/47583685
has answer: http://stackoverflow.com/a/71741223
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48171529
possible better answer: http://stackoverflow.com/a/47583685
has comment: http://stackoverflow.com/comment/98595680
accepted answer: http://stackoverflow.com/a/48172033
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48172033
has title: tf.multiply vs tf.matmul to calculate the dot product
tagged with: tensorflow
score: 24
upvote count: 24
favorite count: 0

http://stackoverflow.com/q/47612640
has comment: http://stackoverflow.com/comment/82183683
has title: Changing the default pip
has comment: http://stackoverflow.com/comment/82183594
score: 0
linked to: http://stackoverflow.com/q/42871090
tagged with: development-environment
answer count: 0
tagged with: installation
has body: I have two locations of pip. which -a pip returns /opt/moose/miniconda/bin/pip /Users/sterlingbutters/anaconda3/bin/pip I would like to use the pip located in anaconda by default so that packages install in the anaconda environment. The configuration must leave the default python as that installed under the miniconda environment. In addition, the pip under the miniconda environment is associated with Python2 and the pip under the anaconda environment is associated with Python3. How can I change the default pip so that running pip install &lt;package&gt; installs to the anaconda environment? Also, what is the difference between regular pip, pip2, and pip3? If I am using python 3, do I need pip3 (I have regular pip)? All help is appreciated, thanks!
has comment: http://stackoverflow.com/comment/82183651
has comment: http://stackoverflow.com/comment/82183621
has comment: http://stackoverflow.com/comment/89101641
type: Question
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82183609

http://stackoverflow.com/comment/82218906
has text: Sidenote: Compare agains `None` with `if weekend_ans is not None` instead of the `!=` operator
comment on: http://stackoverflow.com/q/47630127
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47545540
has comment: http://stackoverflow.com/comment/82048370
tagged with: python
tagged with: lstm
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47545838
has body: I am using keras to run bi-LSTM to do sentiment analysis in python, however, python gives me the error message: 'NoneType' object has no attribute 'update'. I searched on website however this problem still can't be solved. here is my code: import numpy as np import pickle as pk from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score import os os.environ['KERAS_BACKEND'] = 'theano' from keras.layers import Dense, Input from keras.layers import Embedding, LSTM, Bidirectional from keras.models import Model from keras import regularizers def get_idx_from_sent(sent, word_idx_map, max_l=1187, filter_h=3): """ Transforms sentence into a list of indices. Pad with zeroes. """ x = [] pad = filter_h - 1 for i in range(pad): x.append(0) words = sent.split() for word in words: if word in word_idx_map: x.append(word_idx_map[word]) while len(x) &lt; max_l + 2 * pad: x.append(0) return x def make_idx_data_cv(revs, word_idx_map, max_l=1187, k=300, filter_h=3): """ Transforms sentences into a 2-d matrix. """ data = [] for rev in revs: sent = get_idx_from_sent(rev["text"], word_idx_map, max_l, filter_h) sent.append(rev["y"]) data.append(sent) x = np.array(data, dtype="int")[:,:-1] data_y= np.array(data, dtype="int")[:,-1] return x, data_y #load data x = pk.load(open("mr.p", "rb")) revs, W, W2, word_idx_map, vocab = x[0], x[1], x[2], x[3], x[4] X,Y = make_idx_data_cv(revs, word_idx_map, max_l=1187, k=300,filter_h=3) #Keras layers embedding_layer = Embedding(len(vocab) + 1, 300, weights=[W], input_length=1191, trainable=True) sequence_input = Input(shape=(1191,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) l_lstm1 = Bidirectional(LSTM(100,return_sequences=True,kernel_regularizer=regularizers.l2(0.001),recurrent_regularizer=regularizers.l2(0.001), dropout=0.4,recurrent_dropout=0.4))(embedded_s…
accepted answer: http://stackoverflow.com/a/47545838
has title: AttributeError: 'NoneType' object has no attribute 'update'
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/47586275
possible better answer: http://stackoverflow.com/a/47586330
score: -3
accepted answer: http://stackoverflow.com/a/47586457
has title: Save 10,000 digits of string to text document
downvote count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/82130191
type: AnsweredQuestion
has body: I am relatively new to python3 and I just got the code for a string that adds one number to the previous number, and adds that number onto the previous number as a string For example if the first number was 1, it would 1+1 to equal 2 and attach that to the string to make 12. The first few digits of the number would be 123456789101112131415161718... I have the code from itertools import count for c in count(): print(c, end="") And I am wondering if there is a way to stop it at a certain amount of digits lets say 10,000 and then save it to a document called number.txt
has answer: http://stackoverflow.com/a/47586457
tagged with: python
has answer: http://stackoverflow.com/a/47586330
has comment: http://stackoverflow.com/comment/82130362
has comment: http://stackoverflow.com/comment/82130188
has comment: http://stackoverflow.com/comment/82130472
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/82309377
comment on: http://stackoverflow.com/q/47654716
score: 0
type: Comment
has text: @V.Asher see answer for a `def` that accomplishes a "us"-first else "en" approach
type: QuestionComment

http://stackoverflow.com/comment/82292031
has text: Thanks, that worked! Just curious, why didn't my code work? I did register my class-based view as you told, and it seems like the class has a `send_email` function. Why didn't Python recognize that?
comment on: http://stackoverflow.com/a/47664280
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47566035
answers question: http://stackoverflow.com/q/47566009
type: Answer
accepted answer of: http://stackoverflow.com/q/47566009
score: 0
has body: You may use tick_params function like plt.tick_params(axis='y', which='major', labelsize=10)
type: AcceptedAnswer

http://stackoverflow.com/a/73039941
has body: There is a difference. pd.DataFrames And pd.Series have an index, which might not be consecutive, e.g. [0 ... n), but is when you don't specify it during creation. Therefore people often confuse them. Consider this parabola import pandas as pd import numpy as np data = pd.Series(16 - np.arange(-4,5) ** 2) 0 0 1 7 2 12 3 15 4 16 5 15 6 12 7 7 8 0 dtype: int64 The labels are set to [0 ... 9), because we didn't specify them. In this case, both data.argmax() and data.idxmax() result in 4, because that's the integer position and label for 16. However, if we filter out the odd values, that the index isn't consecutive anymore: filtered = data[data % 2 == 0] 0 0 2 12 4 16 6 12 8 0 dtype: int64 Here, filtered.argmax() returns 2 whereas filtered.idxmax() returns 4. This is particularly relevant when you want to reference data, using entries extracted from filtered. That is data.loc[4] will return the found value via the unfiltered version.
type: Answer
upvote count: 11
score: 11
accepted answer of: http://stackoverflow.com/q/47596390
answers question: http://stackoverflow.com/q/47596390
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82247783
score: 0
comment on: http://stackoverflow.com/q/47644517
type: Comment
has text: When asking a question for code that throws an exception, you should include the complete Traceback (formatted as code). Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the links it contains. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.
type: QuestionComment

http://stackoverflow.com/q/47644660
has answer: http://stackoverflow.com/a/47644829
tagged with: numpy
has body: I happened onto this when trying to find the means/sums of non-nan elements in rows of a pandas dataframe. It seems that df.apply(np.mean, axis=1) works fine. However, applying np.mean to a numpy array containing nans returns a nan. Is this all speced out somewhere? I would not want to get burned down the road...
type: AnsweredQuestion
score: 0
answer count: 2
has title: numpy/pandas NaN difference confusion
has comment: http://stackoverflow.com/comment/82248064
accepted answer: http://stackoverflow.com/a/47644743
possible better answer: http://stackoverflow.com/a/47644829
has comment: http://stackoverflow.com/comment/82248106
has comment: http://stackoverflow.com/comment/82248004
has answer: http://stackoverflow.com/a/47644743
type: Question
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/43865602
has comment: http://stackoverflow.com/comment/82252859

http://stackoverflow.com/a/47676139
type: AcceptedAnswer
has body: You may have to read the content as string, manipulate it and load as JSON. Something like this, import json with open('Example.json','r') as f: data = f.read() data = "[" + data.replace("}", "},", data.count("}")-1) + "]" json_data = json.loads(data) It seems your data has numbers begins with 0, so you may ended up with an exception "ValueError". You may refer how to deal the issue from Why is JSON invalid if an integer begins with 0 Note: I manually removed 0 from "Example.json"
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82311343
accepted answer of: http://stackoverflow.com/q/47675367
type: Answer
answers question: http://stackoverflow.com/q/47675367
score: 1

http://stackoverflow.com/comment/82324741
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47682695
type: QuestionComment
has text: OK, I will look into it.

http://stackoverflow.com/comment/82172974
score: 0
has text: Please try yourself first! I am familiar with python and you can do that in 10 lines of code. I believe in you! :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47607278
type: Comment

http://stackoverflow.com/a/47696700
score: 0
has comment: http://stackoverflow.com/comment/82353542
has comment: http://stackoverflow.com/comment/82353311
answers question: http://stackoverflow.com/q/47696409
has comment: http://stackoverflow.com/comment/82353220
has body: I guess you have to wait to end of script execution. try { Process process = Runtime.getRuntime().exec("/usr/bin/python print.py"); process.waitFor(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } You can try to read exitCode from process ;-)
type: Answer

http://stackoverflow.com/a/47623301
has body: NumPy forward filling based on np.maximum.accumulate - def numpy_ffill(s): arr = s.values mask = np.isnan(arr) idx = np.where(~mask,np.arange(len(mask)),0) out = arr[np.maximum.accumulate(idx)] return pd.Series(out) Sample run - In [41]: s Out[41]: 0 1.0 1 NaN 2 NaN 3 3.0 4 NaN 5 5.0 6 NaN 7 NaN 8 NaN dtype: float64 In [42]: numpy_ffill(s) Out[42]: 0 1.0 1 1.0 2 1.0 3 3.0 4 3.0 5 5.0 6 5.0 7 5.0 8 5.0 dtype: float64
has comment: http://stackoverflow.com/comment/82204902
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82204645
answers question: http://stackoverflow.com/q/47623233

http://stackoverflow.com/comment/82080511
score: 0
comment on: http://stackoverflow.com/q/47560842
type: Comment
has text: not really, the REPL is just as present as Idle. Ptpython just replaces the REPL. Since your question is about the shell -- you will find that it will address your indent issue. Aside from that, the only thing that comes to mind is that you are mixing tabs and spaces. Try again, use only spaces (4) on both the print statements. It works.
type: QuestionComment

http://stackoverflow.com/q/47611446
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47611482
tagged with: pandas
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47611482
has title: How to merge two exclusive columns in Pandas?
downvote count: 0
tagged with: python
has body: I have two columns and these columns are exclusive. If the entry in row i in column1 is NaN, I want to replace the NaN with whatever in column2. How to do it quickly without iterating all the rows?

http://stackoverflow.com/a/47830174
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47554397
downvote count: 0
upvote count: 1
has body: I ended up using a slightly different solution than Scott's answer, but his approach was key, as the number of observations (records) was relatively low, while on the other hand, the number of time elements (e.g. seconds, depending on the required resolution) was far greater given the elapsed time between the first and the last observation. However, I first collected all generated date ranges (Series) into a list, and concatenated all of them in a second, separate step, which was faster than continuously modifying the original Dataframe using apply(). # Expand the datetime range, creating records according to the given resolution (e.g. minutes). # This creates a Series object for each session. All of those Series objects are then added to a list # in order to concatenate them in 1 go, which is more efficient. sessions=[] for key, cols in df_sessions.iterrows(): sess = pd.Series(data=pd.date_range(start=cols['logon'].floor('T'), end=cols['logoff'].ceil('T'), freq='T'), name='sess_dt') sessions.append(sess) # Concatenate all Series objects and convert to a DataFrame df_sessions_2 = pd.DataFrame(pd.Series().append(sessions, ignore_index=True), columns=['ref_dt']) # Add a counter which we can use to aggregate df_sessions_2['sess_cnt'] = 1 # Aggregate according to the datetime df_sessions_2 = df_sessions_2.groupby('ref_dt').sum() Plotting then only requires one extra statement: df_sessions_2.plot()

http://stackoverflow.com/comment/93460942
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47594898
has text: Did you ever figure this out? I'm having a very similar situation. Everything works fine on my local computer but then when I push it up to EC2 I get the decode error.
score: 0

http://stackoverflow.com/q/47659197
has comment: http://stackoverflow.com/comment/82278010
has title: In-place Python dictionary inverse
has comment: http://stackoverflow.com/comment/82277431
has comment: http://stackoverflow.com/comment/82277321
upvote count: 3
score: 0
answer count: 1
downvote count: 3
tagged with: in-place
has comment: http://stackoverflow.com/comment/82277623
has comment: http://stackoverflow.com/comment/82277348
has comment: http://stackoverflow.com/comment/82277855
has comment: http://stackoverflow.com/comment/82277708
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82277603
has comment: http://stackoverflow.com/comment/82277702
has comment: http://stackoverflow.com/comment/82277333
has comment: http://stackoverflow.com/comment/82277474
has comment: http://stackoverflow.com/comment/82277216
has comment: http://stackoverflow.com/comment/82277651
has comment: http://stackoverflow.com/comment/82277979
tagged with: swap
has comment: http://stackoverflow.com/comment/82277176
tagged with: python
has comment: http://stackoverflow.com/comment/82277955
tagged with: dictionary
has body: The task that I wanted to see if possible to solve is, swapping key,value pairs of a dictionary (in Python), with an in-place calculation, without additional data-structures (Only a constant number of extra variables). It seems rather impossible (in a finite world), but I'm open to hear suggestions on solving it. I've seen a few posts about in-place dictionary inverse in python, and I've found one common thing between all of the solutions. The following dictionary won't be properly inversed: dict = {'b':'a','a':'c','c':123} The reason for that is, when swapping the first argument, we overwrite 'a''s actual value (The values are unique, the keys are unique, but that doesn't mean there isn't a value that is the same as an already existing key) NOTES: 1) The dictionary given as an example has hashable values. 2) The key/values can be of any data-type. Not necessarily strings. I'd love to hear ways to solve it, I've thought of one but it only works if we have infinite memory, which obviously is not true. EDIT: 1) My Idea was, changing the dictionary such that I add a constant number of underscores ("_") to the beginning of each key entry. The number of underscores is determined based on the keys, if some key has X underscores, I'll add X+1 underscores (max_underscores_of_key_in_prefix+1). To work around objects in the keys, I'll make a wrapper class for that. I have tried my best explaining my intuition, but I am not sure this is practical. 2) @Mark Ransom's solution works perfectly, but if anyone has an other algorithmic solution to the problem, I'd still love to hear it out! I mark this question as solved because it is solved, but again, other solutions are more than welcome :-)
has comment: http://stackoverflow.com/comment/82277281
has comment: http://stackoverflow.com/comment/82277976
accepted answer: http://stackoverflow.com/a/47661279
has comment: http://stackoverflow.com/comment/82277146
has comment: http://stackoverflow.com/comment/82277618
has answer: http://stackoverflow.com/a/47661279
type: AnsweredQuestion

http://stackoverflow.com/q/47556302
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82069898
has answer: http://stackoverflow.com/a/47571836
has comment: http://stackoverflow.com/comment/82093599
type: Question
tagged with: encode
linked to: http://stackoverflow.com/q/147741
has comment: http://stackoverflow.com/comment/82069816
tagged with: python
type: UnansweredQuestion
tagged with: utf-8
score: -3
has comment: http://stackoverflow.com/comment/82093577
has comment: http://stackoverflow.com/comment/82088859
upvote count: 0
has comment: http://stackoverflow.com/comment/82069775
downvote count: 3
has title: How reading file in 'utf-8'
has comment: http://stackoverflow.com/comment/82088826
has comment: http://stackoverflow.com/comment/82099513
has body: I have a txt file, that for each line contains a last name, some last names have a special letter 'Ñ' Apellidos200.txt Ramos Rios Arias Muñoz To parse and read this file I use this code. apellidos_list = list() with io.open('Apellidos200.txt',encoding='utf-8') as fp: for line in fp: x = line.replace('\t','') x = x.replace('\'', '')# I try this x = x.replace('\n','') x = x.replace('\r','') x = x.replace('\\','') x = x.replace('"','') # And try this apellidos_list.append(repr(x)) Output: 'Ramos' 'Rios' 'Arias' 'Muñoz' The problem is that the strings are passed with simple quotes that I cannot remove, I guess that is for the encoding in 'utf-8' I use this string to concatenate and make an url e.g example.com/Ramos, but with this simple quotes it remains, this way -> example.com/'Ramos' and this cause an error when I use 'request.get' Edit: Add a image with debug of code. Image of debug

http://stackoverflow.com/a/47692463
has body: I'd advise to use csv.DictReader and csv.DictWriter: filename = os.path.join(datapath, "input.csv") with open(filename, 'rb') as infile: reader = csv.DictReader(infile) data_in = [row for row in reader] fieldnames = reader.fieldnames filename = os.path.join(datapath, "temp.csv") with open(filename, 'wb') as outfile: writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(data_in[5:])
type: Answer
answers question: http://stackoverflow.com/q/47691425
score: 0

http://stackoverflow.com/q/47592759
has comment: http://stackoverflow.com/comment/82142831
favorite count: 0
has title: Scope in functions defined in code executed with exec()
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82143219
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I have a simple test bench implemented in python. The test runner exposes a set of functions to the test. This may be considered as a domain specific language for writing tests. Most test cases form simple sequences of calls to these functions, sometimes involving control flow statements, but nothing more complicated than that. Now a few test cases have become too complex and would benefit from being refactored using functions. This is where I run into problems. From within the functions I cannot access local symbols defined inside the test case. I can also not access the functions exposed by the runner (log and verify). ''' Testing variable scopes in exec()''' PRG_1 = ''' a = 42 log('Testing a = ' + str(a)) verify(a, 42) ''' PRG_2 = ''' a = 42 def f(): c = a # Error 'a' not defined log(c) # Error 'log' not defined f() ''' class TestRunner(): def __init__(self, prg): self.prg = prg def log(self, msg): print(msg) def verify(self, a, b): print('PASSED' if a == b else 'FAILED') def run(self): # Bring methods into local scope to avoid having 'self.' in DSL log = self.log verify = self.verify # Execute test exec(self.prg) r = TestRunner(PRG_1) r.run() r = TestRunner(PRG_2) r.run() Any idea on how I can get this to work? Maybe there is a different (and better way) to accomplish this, that I as a C++ developer do not see. $ python3 test.py Testing a = 42 PASSED Traceback (most recent call last): File "test.py", line 42, in &lt;module&gt; r.run() File "test.py", line 35, in run exec(self.prg) File "&lt;string&gt;", line 7, in &lt;module&gt; File "&lt;string&gt;", line 4, in f NameError: name 'a' is not defined
has answer: http://stackoverflow.com/a/47593117
score: 1
upvote count: 1

http://stackoverflow.com/comment/82289788
comment on: http://stackoverflow.com/a/47665185
type: AnswerComment
score: 1
has text: Sure, you can just assign the result of this to a new column in the usual way.
type: Comment

http://stackoverflow.com/a/47674576
has comment: http://stackoverflow.com/comment/82307887
answers question: http://stackoverflow.com/q/47672155
type: Answer
score: 0
has body: CloudApper™ is a label, you have to click logo, use this xpath //a[@href='http://www.m2sys.com/cloudapper-modularized-framework-enterprise-cloud-application/']

http://stackoverflow.com/comment/82263807
score: 1
type: QuestionComment
has text: Adding to @ncfirth 's comment, please see here to know how scikit handles multi-class and multi-label problems implicitly :- http://scikit-learn.org/stable/modules/multiclass.html
comment on: http://stackoverflow.com/q/47650917
type: Comment

http://stackoverflow.com/q/47632684
upvote count: 1
downvote count: 0
tagged with: linear-programming
has comment: http://stackoverflow.com/comment/82225100
has comment: http://stackoverflow.com/comment/82224453
has comment: http://stackoverflow.com/comment/82229296
has body: I'm trying to implement regularized sinkhorn algorithm (Wilson 62) that computes optimal transport between two uniform distribution (lat,lon). The basic idea is fixed point iteration. If you don't know this you may look at http://www.numerical-tours.com/matlab/optimaltransp_5_entropic/ mine is exactly the same. import pandas as pd from sklearn.cluster.hierarchical import AgglomerativeClustering from sklearn.neighbors import KNeighborsClassifier import numpy as np from shapely.geometry import shape, Point import shapefile from sklearn.metrics.pairwise import pairwise_distances if __name__ == '__main__': inst = pd.read_csv('inst.csv', encoding='utf-8')'lat', 'lng' ht = pd.read_csv('ht.csv', encoding='utf-8')'lat', 'lng' for k in range(0,4): print('k = {}'.format(k)) gamma = 0.5 M = pairwise_distances(inst'lat','lng',ht'lat','lng') K = np.exp(-M/0.5) N1 = len(inst) N2 = len(ht) v = np.ones((N1,1)) i = 0 M = 99999 a = np.divide(np.ones((N2,1)),N2) b = np.divide(np.ones((N1,1)),N1) while i&lt;M: print('i = {}'.format(i)) u = np.divide(a,np.dot(K.T,v)) v = np.divide(b,np.dot(K,u)) i = i+1 print('cluster {} has wassersetein distance {}'.format(k,np.sum(np.multiply(np.dot(np.dot(np.diagflat(u),K.T),np.diagflat(v)),M).reshape(-1,1)))) The final distance blows up and always equals the number of iteration. What's wrong with my algorithm? cluster 2 has wassersetein distance 99999.0 I tried the library. Doesn't work, too. for k in range(0,4): N1 = len(inst) N2 = len(ht) b = np.divide(np.ones((N2,1)),N2) a = np.divide(np.ones((N1,1)),N1) M = ot.dist(inst[inst.lb==k]'lat','lng',ht[ht.lb==k]'lat','lng') print(ot.sinkhorn2(a,b,M,1e-3)) gives broadcast gin error ValueError: operands could not be broadcast together with shapes (132,1) (2011,93)
has title: Sinkhorn algorithm doesn't converge
favorite count: 0
type: Question
answer count: 0
tagged with: algorithm
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/82224493
tagged with: optimization
has comment: http://stackoverflow.com/comment/115143207
score: 1

http://stackoverflow.com/a/47761097
answers question: http://stackoverflow.com/q/47673193
downvote count: 0
upvote count: 1
score: 1
has body: The client library you are using uses a new Pub/Sub API for subscribing called StreamingPull. One effect of this is that the subscription deadline you have set is no longer used, and instead one calculated by the client library is. The client library also automatically extends the deadlines of messages for you. When you get these duplicate messages - have you already ack'd the message when it is redelivered, or is this while you are still processing it? If you have already ack'd, are there some messages you have avoided acking? Some messages may be duplicated if they were ack'd but messages in the same batch needed to be sent again. Also keep in mind that some duplicates are expected currently if you take over a half hour to process a message.
type: Answer
has comment: http://stackoverflow.com/comment/82506383

http://stackoverflow.com/a/47715366
has comment: http://stackoverflow.com/comment/88778140
has comment: http://stackoverflow.com/comment/117128794
has body: You can try this also. It worked for me. pip install --upgrade pyasn1-modules
type: Answer
answers question: http://stackoverflow.com/q/47600597
downvote count: 0
score: 19
upvote count: 19

http://stackoverflow.com/q/47656361
upvote count: 0
downvote count: 2
type: UnansweredQuestion
score: -2
has body: I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you print ("Welcome to UTOPIA") river= "" while not river: river = input ("\n\n\n\nYou come across a raging river, what do you do? ") if river == "swim" or "swim through it": print ("Correct, seems you're smarter than I thought...") elif river == "walk through it" or "walk through": print ("You cant walk through such a big river... silly!") else: print ("Well, sensible suggestions now...")
has comment: http://stackoverflow.com/comment/82271115
has comment: http://stackoverflow.com/comment/82271026
has title: Very simple code, not working
linked to: http://stackoverflow.com/q/6838238
answer count: 3
has answer: http://stackoverflow.com/a/47656562
tagged with: python
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/82271106
has comment: http://stackoverflow.com/comment/82271004
favorite count: 0
has answer: http://stackoverflow.com/a/47656438
type: Question
has comment: http://stackoverflow.com/comment/82271084
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47656457

http://stackoverflow.com/a/47620406
type: Answer
has body: I upvoted schwobaseggl but had something similar going on. We could also check if mod equals 0: x = 3 if len(onetonine) % x == 0: result = [sum(onetonine[i:i+x]) for i in range(0, len(onetonine), x)] else: result = 'Error!'
answers question: http://stackoverflow.com/q/47620259
score: 0

split
tags question: http://stackoverflow.com/q/47669536
tags question: http://stackoverflow.com/q/47684623
tags question: http://stackoverflow.com/q/47647413
tags question: http://stackoverflow.com/q/47565573
tags question: http://stackoverflow.com/q/47604449
tag name: split
tags question: http://stackoverflow.com/q/47662156
tags question: http://stackoverflow.com/q/47603564
type: Tag
tags question: http://stackoverflow.com/q/47686897
tags question: http://stackoverflow.com/q/47620972
tags question: http://stackoverflow.com/q/47663704
tags question: http://stackoverflow.com/q/47572037
tags question: http://stackoverflow.com/q/47577301
tags question: http://stackoverflow.com/q/47624974

http://stackoverflow.com/a/47619589
has comment: http://stackoverflow.com/comment/82197212
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47619568
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82197174
has body: You'll have to double the backslash characters: var morgen = '{"a": [{"title": "Fotoausstellung \\"Berlin, Berlin\\""]}'; That is necessary because JavaScript will remove the single backslashes when it parses the overall string constant. (The \" pair in a string constant is interpreted as meaning a single " character.) If all you want is that structure as a JavaScript object, you'd just do this: var morgen = {"a": [{"title": "Fotoausstellung \"Berlin, Berlin\""]};
has comment: http://stackoverflow.com/comment/82197294

http://stackoverflow.com/comment/82140834
has text: you can use `try/except` to catch this error and do something
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47591408

http://stackoverflow.com/comment/82348105
has text: @JohnS. i didn't get this line and then reprint the names with the new days - 1 , how steve have 14 there ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47693581
score: 0

http://stackoverflow.com/comment/82089506
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47563354
type: Comment
has text: Do you notice a difference with `Image.load()` instead of `Image.open()`? `Image.open()` is a lazy/deferred operation whereas `Image.load()` is an explicit call to load pixel data. If that doesn't work, try `numpy.array(a.getdata())`. Also does `show()` work?

django-nose
tags question: http://stackoverflow.com/q/47655737
tag name: django-nose
type: Tag

http://stackoverflow.com/comment/82594414
type: Comment
type: QuestionComment
has text: If you remove the dependencies, the exe is not going to be able to run your script, or am I missing something?
score: 1
comment on: http://stackoverflow.com/q/47692213

http://stackoverflow.com/comment/82109682
comment on: http://stackoverflow.com/a/47576329
has text: using that instead of having 'a = float(input("Enter length of side A: ") ' or would I keep that?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82259069
comment on: http://stackoverflow.com/q/47650158
type: Comment
type: QuestionComment
has text: @schwobaseggl Then you have two different dictionarry keys for the same value. It's not a problem. Thanks for the link !
score: 0

http://stackoverflow.com/q/47547688
tagged with: python
accepted answer: http://stackoverflow.com/a/47547934
type: AnsweredQuestion
downvote count: 4
has answer: http://stackoverflow.com/a/47547934
has comment: http://stackoverflow.com/comment/82052436
tagged with: pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/82052028
has comment: http://stackoverflow.com/comment/82051880
has comment: http://stackoverflow.com/comment/82052043
answer count: 1
has body: I have 13 files with the extension .Las. Each has 80 columns and 180 thousand lines. I need to read my files sequentially one after the other: the first, then the second, and so on. Next is my script, in which I process data from files. At the end, the program must output the data to the file with the same extension. Thank you in advance for your response!!! And i programming in pandas, Jupyter notedook cols = ['IK05', 'IK20', 'DA20', 'LLS', 'LLD', 'STP'] data = pd.read_table("data/1.las", delim_whitespace = True,na_values = '-999.25', index_col=False) ndata = data.STP_AX.as_matrix(columns=None) nstop = 1 stop = 1 for i in range(len(ndata)): if(ndata[i]&gt;0.1): stop = 0 ndata[i] = nstop else: if(stop == 0): stop = 1 nstop = nstop + 1 nstop data.STP = ndata data.STP = ndata df = data[cols] df1 = df.groupby('STP') df1.head() dfp = pd.DataFrame() for name, group in df1: df1 = df.groupby('STP') df1.head() ​ dfp = pd.DataFrame() ​ ​ for name, group in df1: #print(name) #print(group) k,p=stats.mstats.normaltest(group[5:-5]) #print(p) dfp[name] = p
favorite count: 0
type: Question
has title: Consecutive reading of files in Python
score: -2

http://stackoverflow.com/comment/82308182
comment on: http://stackoverflow.com/a/47674434
score: 0
type: Comment
has text: Could you expand on your answer, explaining how it solves the issue? If this is just a comment or a guess than it might not belong into an answer. See also https://meta.stackexchange.com/a/214174/266197 specifically the section `Can I put my comment in an answer?`
type: AnswerComment

http://stackoverflow.com/a/47679123
has body: Thanks for the tips and feedback. I resolved it by capturing the information in a list and then printing out results, and using a try statement to handle the error and apply the right unicode. Your suggestions pointed me in the right direction.
answers question: http://stackoverflow.com/q/47645224
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/47651413
has comment: http://stackoverflow.com/comment/82276060
has title: Move replace files with in HDFS
has comment: http://stackoverflow.com/comment/82556663
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82279248
tagged with: hdfs
has comment: http://stackoverflow.com/comment/82319735
type: Question
tagged with: hadoop
has comment: http://stackoverflow.com/comment/82494348
type: UnansweredQuestion
has body: With in HDFS, trying to move directory once all sub-directories/files have been processed. Using hadoop -mv command through python's subprocess module for this. My problem is, directories with same name can come again for processing with different set of files. hadoop -mv is failing with File exists error. Looping through complete directory and move files that does not exist will make the process slow as there can be lot of sub-directories in a given directory Is there a standard way to move files to achieve move/replace functionality? Or can follow if there is any other standard way of handling processed files/directories My directory structure: New unprocessed files - /new/YEAR/MONTH/DAY/ID/files Processed files - /processed/YEAR/MONTH/DAY/ID/files Files will be moved to processed once all files in DAY gets processed
tagged with: python

http://stackoverflow.com/a/47647477
answers question: http://stackoverflow.com/q/47647464
score: 1
downvote count: 0
upvote count: 1
has body: You need (): species_plots_types.groupby("plot_type").size().to_frame() Or: species_plots_types.groupby("plot_type").count() Explanation: groupby["plot_type"] means you call __getitem__ on groupby, but since this method isn't defined, you get a TypeError: 'type' object is not subscriptable. Check python documentation for getitem for more details.
type: Answer

http://stackoverflow.com/comment/82276499
score: 2
comment on: http://stackoverflow.com/q/47658462
type: Comment
has text: Do you really need to import both scripts? Why not just execute them with `subprocess` (or use a shell script to execute both scripts)?
type: QuestionComment

http://stackoverflow.com/q/47575407
type: Question
has answer: http://stackoverflow.com/a/47576498
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82107765
has title: Unable to leave the loop
has comment: http://stackoverflow.com/comment/82111932
has body: I've checked the program all over again and again, but I still can't understand why I can't leave the loop after I've entered 'n'. The boolean value of 'end' should be determined by the 'y' or 'n' the user has chosen. However, every time I hit 'n' or 'y', the loop just keep going on. This is not the whole program, I only pick the part which might be related to the problem here. def k(response): while response !='y' and response!='n': response=input("Would you like to do again (y/n)") if response=='y': end= False elif response=='n': end= True return end end=False while not end: year=int(input("Year of birth:")) y(year) month=int(input("Month of birth:")) m(month) day=int(input("Day of birth:")) d(day) j(month) response=input("Would you like to do again (y/n)") k(response) end
has comment: http://stackoverflow.com/comment/82107611
tagged with: python
has comment: http://stackoverflow.com/comment/82109890
has comment: http://stackoverflow.com/comment/82111123
has comment: http://stackoverflow.com/comment/82111741
score: -1
has comment: http://stackoverflow.com/comment/82108293
has comment: http://stackoverflow.com/comment/82107731
has comment: http://stackoverflow.com/comment/82110699
upvote count: 2
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/82109976
has comment: http://stackoverflow.com/comment/82108508
tagged with: loops
has comment: http://stackoverflow.com/comment/82110385
favorite count: 0

http://stackoverflow.com/comment/82164142
has text: but when you call `flatten` within `flatten` the you are also doing *recursion*!
score: 1
comment on: http://stackoverflow.com/a/47602245
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47694919
has body: I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here. newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30} I created this dict and I want to use a while loop to output it this way: Jan 31 Feb 29 Mar 31 Apr 30 May 31 Jun 30 Jul 31 Aug 30 I am able to do it with a for loop, just curious how it can be done with a while loop.
has comment: http://stackoverflow.com/comment/82349557
upvote count: 1
downvote count: 1
has title: Printing dictionary in a While Loop
has comment: http://stackoverflow.com/comment/82350302
possible better answer: http://stackoverflow.com/a/47695407
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/79128147
has answer: http://stackoverflow.com/a/47695407
has answer: http://stackoverflow.com/a/47695058
type: Question
has answer: http://stackoverflow.com/a/47695148
tagged with: python
has comment: http://stackoverflow.com/comment/82349443
has answer: http://stackoverflow.com/a/47695023
accepted answer: http://stackoverflow.com/a/47695070
has answer: http://stackoverflow.com/a/47695089
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47695070
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47641847
score: 0
has answer: http://stackoverflow.com/a/47653260
has comment: http://stackoverflow.com/comment/82264085
answer count: 2
has comment: http://stackoverflow.com/comment/82243611
has body: When Delphi introduced actions some years ago now, one of the great advantages was that the status (enabled/disabled) of the action was handled in the event loop, rather than that the programmer had to think about updating these states concommittant to all status changes of the application. For example: procedure TMyForm.SaveActionUpdate(Sender: TObject) begin (sender as TAction).enabled := self.contentHasChanged(); end; instead of procedure TMyForm.onContentChanging(sender: TObject) begin SaveAction.enabled := True; SaveAsAction.enabled := True; RevertAction ... etc. end; Now I am trying to rebuild some of these old Delphi programs in Python using Qt, but so far I have failed to figure out how to enable QActions without resorting to explicitly setting it enabled whenever my content changes. What would be a fruitful approach to do this?
has title: updating enabled-status of QAction
type: Question
tagged with: qt
has answer: http://stackoverflow.com/a/47653142
has comment: http://stackoverflow.com/comment/82254502
tagged with: python
tagged with: action
accepted answer: http://stackoverflow.com/a/47653260
type: AnsweredQuestion
tagged with: delphi
possible better answer: http://stackoverflow.com/a/47653142

http://stackoverflow.com/comment/82355653
score: 0
type: Comment
has text: @TheWind-UpBird And in regards to your pseudorandom-question: it's unclear what you want. I never saw some distribution-model. The basic concept is: with access to uniform numbers in [0,1) (which a good hash provides; in best-case a crypto-hash which is slow), you can always generate any distribution, at the cost of using more than one uniform number (e.g. wiki's article of sampling gaussians for a specialized variant; inverse-transform sampling for a general slower approach given a cdf).
type: AnswerComment
comment on: http://stackoverflow.com/a/47681859

http://stackoverflow.com/comment/82179511
score: 0
comment on: http://stackoverflow.com/q/47592367
type: Comment
type: QuestionComment
has text: Your question doesn't provide actionable information. You need to put more work into the question. Reduce the problem down to a minimal, complete example. A minimal example is as small and self-contained as possible.

http://stackoverflow.com/comment/82118643
type: QuestionComment
comment on: http://stackoverflow.com/q/47580575
score: 0
has text: gunrarity isn't initialised to any value. If none of the conditions match, then gunrarity isn't defined. Hence, the error 'gunrarity' is not defined in the last line.
type: Comment

http://stackoverflow.com/comment/120027500
score: 1
type: Comment
has text: When I tried, I have to put "!" first. Like: !jupyter --version
type: AnswerComment
comment on: http://stackoverflow.com/a/51641071

http://stackoverflow.com/q/47575101
linked to: http://stackoverflow.com/q/45621412
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/47575377
duplicate of: http://stackoverflow.com/q/43086584
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/33355608
tagged with: python-2.7
tagged with: typeerror
linked to: http://stackoverflow.com/q/43086584
answer count: 1
has body: I just fork clone a repo inconvergent/hyphae on github to reuse hyphae.py with an update from python2.6 to python2.7 (and then 3.5) I fixed some error due to update but i still have TypeError for now. Done Update from python2.6 to pyton2.7.13 by adding () after all print Fix File "/home/user/hyphae/hyphae.py", line 378 main() ^ IndentationError: expected an indented block By adding 2 whitespace When do python2.7 /home/user/hyphae/hyphae.py with terminal () ('filename', 'generations_a') ('SIZE', 15000) ('ZONEWIDTH', 80.0) ('RAD', 0.002666666666666667) ('ZONES', 187) ('one', 6.666666666666667e-05) Traceback (most recent call last): File "/home/user/hyphae/hyphae.py", line 378, in &lt;module&gt; main() File "/home/user/hyphae/hyphae.py", line 203, in main R = np.zeros(NMAX,'float') TypeError: 'float' object cannot be interpreted as an index I not that few questions were asked about TypeError: 'float' object cannot be interpreted as an index in stackoverflow, e.g Here ot there, but as the noob as i'm, i don't find how to solve the matter.
upvote count: 1
has title: Python2.7 TypeError: 'float' object cannot be interpreted as an index

http://stackoverflow.com/comment/82130635
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160249/discussion-between-adeel-ahmad-and-tmaker).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47586200

http://stackoverflow.com/comment/82142966
comment on: http://stackoverflow.com/q/47587547
type: Comment
has text: A [mcve], including the values of m, p, c, self._chord, would help.
score: 0
type: QuestionComment

http://stackoverflow.com/a/47606745
answers question: http://stackoverflow.com/q/47606732
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47606732
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82171903
has body: If you're using Python 3.6.0 or above you can use statistics.harmonic_mean: &gt;&gt;&gt; import statistics &gt;&gt;&gt; hose_flows = [6.6, 14, 12.6, 8.8, 11.8] &gt;&gt;&gt; statistics.harmonic_mean(hose_flows) 9.986200495805194

http://stackoverflow.com/comment/82127092
score: 1
comment on: http://stackoverflow.com/q/47584427
type: Comment
type: QuestionComment
has text: @JDN something like `i = my_func.func_code.co_freevars.index('my_var')` and `my_object = my_func.func_closure[i].cell_contents`. Note, I'm not sure if the `i` is guaranteed to line up for `func_code.co_freevars` and `func_closure`, it seems to, but as I said, hackey

http://stackoverflow.com/comment/82320131
comment on: http://stackoverflow.com/a/47633326
type: AnswerComment
has text: I have a Boolean variable that holds the state of "clicked", and it updates the bckground colour fine, but the previous text and buttons still appear on the screen, even after using `blit()`. I'll try the `screen.fill( (0,0,0) )` when I get back in tomorrow and come back if I discover that not working, Thank you!
score: 0
type: Comment

http://stackoverflow.com/q/47653149
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47653297
tagged with: python
score: -1
has title: Convolutional Neural Network using TensorFlow
tagged with: conv-neural-network
tagged with: deep-learning
upvote count: 0
answer count: 1
has body: I'm building a CNN model using Tensorflow, without the use of any frontend APIs such as Keras. I'm creating a VGG-16 model and using the pre-trained weights, and want to fine tune the last layers to serve my purpose. Following the tutorial here, http://cv-tricks.com/tensorflow-tutorial/training-convolutional-neural-network-for-image-classification/ I re-created the training script and modified as per my requirements. However, my training does not happen and the training accuracy is stuck at 50.00% and validation accuracy is forming a pattern repeating the numbers. Attached is the screenshot of the same. I have been stuck on this for days now and can't seem to find the error. Any help is appreciated. The code is pretty long and hence here is the gist file for the same
downvote count: 1

http://stackoverflow.com/comment/82272378
comment on: http://stackoverflow.com/q/47657030
score: 1
type: Comment
type: QuestionComment
has text: I've used relative imports before of form: "from .module_1 import ...". I can't speak for best practice though.

http://stackoverflow.com/comment/82238353
comment on: http://stackoverflow.com/a/47621118
score: 0
has text: "Not visible in the instances" Is a desirable feature.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82146199
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47594473
type: Comment
has text: `UserPassword == UserPassword.islower()` Those checks do not make sense. You are comparing a string to a boolean.

http://stackoverflow.com/comment/82185314
score: 0
has text: it's about converting a string to an array, and how can I read data from file to a variable?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47613376

http://stackoverflow.com/comment/82284383
score: 1
has text: No, I would write an actual `@property` instead that uses the `data_source_type`. If you'd really like to use a custom descriptor, have `ValidDataSourcePath` assume `obj` has a `data_source_type` and use that instead of storing it on itself. It's hacky, but I can't think of anything else.
type: QuestionComment
comment on: http://stackoverflow.com/q/47624767
type: Comment

http://stackoverflow.com/q/47571647
tagged with: django-rest-framework
has body: we are getting the weirdest error ever. Our whole dev team was on this for the past two days and we cannot get over it. We have our DRF serializer with a following function: def get_custom_fields(self, obj): custom_fields = obj.company.ticketcustomfieldtype_set.all() return [{ 'id': field.id, 'name': str(field.name), 'type': field.type, 'value': obj.custom_fields[str(field.id)] if str(field.id) in obj.custom_fields else None } for field in custom_fields] custom_fields there is a regular Django QuerySet Now the weird thing: On localhost, this works just fine. On remote, it works fine only when the QuerySet is empty. If there is something in it, we get the following error: TypeError: string indices must be integers It appears that the custom_fields is now a string. We have no idea why, because on local it works just fine... Django 1.11.5 DRF 3.6.4 Python 3.4.3 Postgres 9.6.5 Any help much appreciated, getting desperate :( EDIT: TicketCustomFieldType model: class TicketCustomFieldType(models.Model): TICKET_CUSTOM_FIELD_TYPES = ( ('CHAR', _('Text field')), ('DATE', _('Date field')) ) TICKET_DEFAULT_CUSTOM_FIELD_TYPE = 'CHAR' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) company = models.ForeignKey( to=Company, verbose_name=_('Company') ) name = I18nCharField( verbose_name=_('Name'), max_length=80, ) type = models.CharField( verbose_name=_('Field type'), max_length=20, choices=TICKET_CUSTOM_FIELD_TYPES, default=TICKET_DEFAULT_CUSTOM_FIELD_TYPE, help_text=_('In this field, you can store either text, or date value.'), ) priority = models.IntegerField(default=0) Ticket model (abbreviated): from django.contrib.postgres.fields import JSONField from django.core.serializers.json import DjangoJSONEncoder (...) class Ticket(models.Model): (...) custom_fields = JSONField(encoder=DjangoJSONEncoder, default=dict, verbose_name=_('Custom fields')) def get_custom_field(self, field_type): qs = self.customfields.filter(type=field_type) if qs.exi…
type: Question
has answer: http://stackoverflow.com/a/47571851
tagged with: postgresql
has comment: http://stackoverflow.com/comment/82105076
has comment: http://stackoverflow.com/comment/82111869
type: UnansweredQuestion
tagged with: python
has title: Django QuerySet TypeError
score: 0
has comment: http://stackoverflow.com/comment/82103922
answer count: 1
tagged with: django

http://stackoverflow.com/q/47544476
has comment: http://stackoverflow.com/comment/82045864
has body: How come my counter is only returning 1? I would like it to return the value of all the numbers, what am I doing wrong? def custom_len(input): counter = 0 for i in a: counter += 1 return counter arr_input = input("enter arr :") length = custom_len(arr_input) print("length is ", length)
has answer: http://stackoverflow.com/a/47544526
has comment: http://stackoverflow.com/comment/82046096
has comment: http://stackoverflow.com/comment/82045970
has title: How come my counter is only returning 1?
tagged with: python
has comment: http://stackoverflow.com/comment/82045963
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47544490
upvote count: 2
has answer: http://stackoverflow.com/a/47544490
downvote count: 2
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47544526

http://stackoverflow.com/q/47692049
possible better answer: http://stackoverflow.com/a/47692734
downvote count: 1
has body: I have simple Python code whitch starts from command line on Raspberry PI like: import ... def def_1(....) def def_2(....) if __name__ == ‘__main__’: while: def_1(....) def_2(....) So,I want to add 3 buttons(GUI): Which starts only def_1(infinite loop) Which starts only def_2(infinite loop) Whitch end def_1 or def_2 How I can do it?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47692734
tagged with: raspberry-pi
tagged with: python
score: -1
has title: Using Button(GUI) and WhileLoop in Python
type: AnsweredQuestion
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/47693313
has answer: http://stackoverflow.com/a/47693313

http://stackoverflow.com/a/47667086
downvote count: 0
score: 1
upvote count: 1
has body: You may use findChildren() function. e.g. for ctl in self.findChildren(QtGui.QLineEdit): ctl.setFixedHeight() Please note this will call setFixedHeight() on all Line Edits.
answers question: http://stackoverflow.com/q/47666922
type: Answer
has comment: http://stackoverflow.com/comment/82293363

http://stackoverflow.com/a/47545709
type: Answer
has comment: http://stackoverflow.com/comment/82048177
downvote count: 1
has body: scikits.talkbox seems to have lpc and mfcc. For audio processing, I usually use librosa, but this module does not have lpc. https://github.com/cournape/talkbox/tree/master/scikits/talkbox/linpred
accepted answer of: http://stackoverflow.com/q/47543712
score: 1
answers question: http://stackoverflow.com/q/47543712
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/82042416
score: 0
type: AnswerComment
has text: Yes. Thank you for your help.
type: Comment
comment on: http://stackoverflow.com/a/47541390

http://stackoverflow.com/a/47682601
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47682380
has body: You are probably referencing the file incorrectly. Take a look at this tutorial https://chrishavlin.wordpress.com/2016/11/16/shapefiles-tutorial/ for an example on using shapefiles with MatPlotLib. Also you might want to search https://gis.stackexchange.com for more help and pointers.

http://stackoverflow.com/q/47691228
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82342059
linked to: http://stackoverflow.com/q/38361526
has title: How to fill missing date in timeSeries
has answer: http://stackoverflow.com/a/48940624
favorite count: 0
has body: Here's what my data looks like: There are daily records, except for a gap from 2017-06-12 to 2017-06-16. df2['timestamp'] = pd.to_datetime(df['timestamp']) df2['timestamp'] = df2['timestamp'].map(lambda x: datetime.datetime.strftime(x,'%Y-%m-%d')) df2 = df2.convert_objects(convert_numeric = True) df2 = df2.groupby('timestamp', as_index = False).sum() I need to fill this missing gap and others with values for all fields (e.g. timestamp, temperature, humidity, light, pressure, speed, battery_voltage, etc...). How can I accomplish this with Pandas? This is what I have done before weektime = pd.date_range(start = '06/04/2017', end = '12/05/2017', freq = 'W-SUN') df['week'] = 'nan' df['weektemp'] = 'nan' df['weekhumidity'] = 'nan' df['weeklight'] = 'nan' df['weekpressure'] = 'nan' df['weekspeed'] = 'nan' df['weekbattery_voltage'] = 'nan' for i in range(0,len(weektime)): df['week'][i+1] = weektime[i] df['weektemp'][i+1] = df['temperature'].iloc[7*i+1:7*i+7].sum() df['weekhumidity'][i+1] = df['humidity'].iloc[7*i+1:7*i+7].sum() df['weeklight'][i+1] = df['light'].iloc[7*i+1:7*i+7].sum() df['weekpressure'][i+1] = df['pressure'].iloc[7*i+1:7*i+7].sum() df['weekspeed'][i+1] = df['speed'].iloc[7*i+1:7*i+7].sum() df['weekbattery_voltage'][i+1] = df['battery_voltage'].iloc[7*i+1:7*i+7].sum() i = i + 1 The value of sum is not correct. Cause the value of 2017-06-17 is a sum of 2017-06-12 to 2017-06-16. I do not want to add them again. This gap is not only one gap in the period. I want to fill all of them.
tagged with: pandas
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82343329
has comment: http://stackoverflow.com/comment/82342945
has comment: http://stackoverflow.com/comment/82344439
has answer: http://stackoverflow.com/a/60004769
type: Question
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47599425
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82192013
tagged with: spacy
has body: I am working with spaCy and python trying to clean some text for sklearn. I run the loop: for text in df.text_all: text = str(text) text = nlp(text) cleaned = [token.lemma_ for token in text if token.is_punct==False and token.is_stop==False] cleaned_text.append(' '.join(cleaned)) And it works pretty well but it leaves in &lt;br /&gt;&lt;br /&gt; inside of some text. I thought that would be taken out by the token.is_punct==False filter but no. I looked for something like html tags but couldn't find anything. Does anyone know what I can do?
answer count: 1
has title: spaCy and text cleaning, getting rid of ' '
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47601719
type: Question
has answer: http://stackoverflow.com/a/47601719
tagged with: python
tagged with: nlp

http://stackoverflow.com/q/47696515
tagged with: python
has title: Django url.py regex not working
has comment: http://stackoverflow.com/comment/82352763
has comment: http://stackoverflow.com/comment/82352658
type: AnsweredQuestion
has body: I am trying to catch all URLs from the safer app and send them to a catch all view; for example: http://127.0.0.1:8000/saferdb/123 http://127.0.0.1:8000/saferdb/12 I think I have an issue with my reg ex in url.py: from django.conf.urls import url from . import views app_name = 'saferdb' urlpatterns = [ url(r'^/$', views.index, name='index'), url(r'^(?P&lt;pk&gt;[0-9]+)/$', views.detail, name='detail'), ] Views.py is the sample code from the django tutorial: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.all()[:5] output = ', '.join([q.DOT_Number for q in latest_question_list]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) I noticed that /saferdb/ will not work unless the reg ex contains a slash: r'^/$' instead of r'^$' as shown in the django tutorial.
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47696646
tagged with: python-3.x
type: Question
tagged with: regex
tagged with: django
accepted answer: http://stackoverflow.com/a/47696646

http://stackoverflow.com/comment/82402412
comment on: http://stackoverflow.com/a/47670113
has text: thanks you, I tested your method it is much faster than mine, I also found below method to be the fastest, by using dict instead of list for seen names new_dct = {} for i,x in enumerate(lst): if not new_dct.get(x['name']): new_dct[x['name']] = x
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82167883
comment on: http://stackoverflow.com/q/47604564
type: Comment
type: QuestionComment
score: 0
has text: You're already doing a binary search on the items from `list` (which is a bad variable name, by the way), so you only do `log(len(list))` tests using the `simulation` function. Without knowing something more about the structure of the data, or how `simulation` works, I don't think we can improve that by more than a constant factor. You could get some small improvement in the search code (avoiding slicing for instance), but that won't help much if the calls to `simulation` are the slow part.

http://stackoverflow.com/a/47680120
has comment: http://stackoverflow.com/comment/82351155
has body: You will require to mount that path in your docker deployment. For that you need to do two things: 1. Add a volume in your Dockerfile WORKDIR /path/in/container VOLUME ["/path/in/container"] 2. run your container with -v option docker run -i -t -v /path/on/host:/path/in/container:rw "container name"
score: 0
has comment: http://stackoverflow.com/comment/82359153
has comment: http://stackoverflow.com/comment/82359567
answers question: http://stackoverflow.com/q/47679962
type: Answer

http://stackoverflow.com/a/47582815
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47582680
score: 2
type: Answer
has body: Use unstack: In [18]: df['sum'].unstack('Month') Out[18]: Month 1 2 3 4 5 6 7 8 9 10 11 12 Year 2005.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN -159681.70 -252105.4 598190.0 2006.0 868641.3 1673673.0 1218341.00 413197.0 109049.9 1495985.0 1736795.0 115507.1 784736.9 -55641.39 -743568.2 107336.1 2017.0 342765.2 357443.2 50260.18 NaN NaN NaN NaN NaN NaN NaN NaN NaN
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47582680

http://stackoverflow.com/a/47616559
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Unless you have autocommit on the connection set to True you will need to call the commit() function of the session. Documentation: http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it The reason your person_id incremented even without the commit is because it is using a sequence - either your created that explicitly or it was created for you when you defined the column type as SERIAL (or similar). That sequence will increment with or without a commit and does not depend on the successful insertion of a record in the table. Note that calling a commit is not required for statements only involving SELECT.
accepted answer of: http://stackoverflow.com/q/47615152
answers question: http://stackoverflow.com/q/47615152
type: Answer

http://stackoverflow.com/q/47615211
upvote count: 1
has title: Using Tweepy API Search to search for any element in a list
has answer: http://stackoverflow.com/a/47615272
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
score: 1
answer count: 1
downvote count: 0
tagged with: twitter
has body: I want to use Tweepy's search API to return tweets that feature any of the terms in a list, not only tweets that contain all terms. twts = api.search(q=["Hello World!", "I love Python!"]) This returns tweets that contain both "Hello World!" and "I love Python!", but I want tweets that contain either.

http://stackoverflow.com/a/47626028
accepted answer of: http://stackoverflow.com/q/47625793
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47625793
has body: You can use Series.between(): df.loc[~df.Vader_Sentiment.between(-0.1, 0.1)] Text Vader_Sentiment 1 B 0.206 Three things: The tilde (~) operator denotes an inverse/complement. Make sure you have numeric data. df.dtypes should show float for Vader_Sentiment, not "object" You can specify an inclusive parameter to note if you want intervals to be closed or open
type: Answer
upvote count: 4

http://stackoverflow.com/q/47541000
has comment: http://stackoverflow.com/comment/82120027
has body: I'm using Linux Mint. Using Anaconda, I've just created virtual env with python 3.5 that's called AI. When I'm running (AI) karol ~ $ conda list I can see e.g.: spyder 3.2.4 py35h27cea69_0 python 3.5.4 h417fded_24 I can also run python --version to get Python 3.5.4 :: Anaconda, Inc. But, when I want to run (AI) karol ~ $ spyder My system starts spyder version 3.2.3 with python 2.7. When I'm running spyder3 it starts spyder with python 3.5.2 instead 3.5.4. On this tread it worked to just run spyder when environment was active: How can I start the version that I've installed on this environment? Why is it starting spyder that is not installed here? Thanks
tagged with: conda
favorite count: 0
type: Question
has title: Starting spyder installed in virtual env
has comment: http://stackoverflow.com/comment/82067262
has comment: http://stackoverflow.com/comment/82112350
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/82092820
has comment: http://stackoverflow.com/comment/82093207
linked to: http://stackoverflow.com/q/30170468
tagged with: anaconda
score: 1
tagged with: spyder
tagged with: python

http://stackoverflow.com/comment/82287160
has text: Please make your question title informant of the actual problem at hand in the first place, as opposed to a ridiculously broad statement such as "Need urgent suggestion".
comment on: http://stackoverflow.com/q/47663860
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47644581
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82247842
has answer: http://stackoverflow.com/a/47644672
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82247859
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82247959
has comment: http://stackoverflow.com/comment/82247922
has title: Extracting the variables names from a list of variables
has body: Consider two series which are attributes of a class instance xyz, and a list containing them: For the sake of reproducing the problem, imagine s1 and s2 are: s1 = pd.Series(np.random.rand(10)) s2 = pd.Series(np.random.rand(10)) list= [xyz.s1, xyz.s2] Given the list, how can I extract the series' names 's1' and 's2'? I tried something like: series_names = [str(x) for x in list] But it did not work; it tried to convert the series' values into string, instead of the series' names. Also, series_names = [x.name for x in list] led to: series_names = ['xyz', 'xyz'] Desired output: series_names = ['s1', 's2']
has answer: http://stackoverflow.com/a/47644651
downvote count: 0

http://stackoverflow.com/a/47675155
accepted answer of: http://stackoverflow.com/q/47670677
answers question: http://stackoverflow.com/q/47670677
score: 5
upvote count: 5
type: AcceptedAnswer
has body: Let's sum what was said in comments: To get information from function, which executed in another process, you should communicate with function's process with either a Queue or a Pipe. While you have a channel to communicate with - keep checking continiously for messages via self-scheduling after. Keep in mind that idea to pass a Label or anything tk-related to that process isn't an option, since it isn't a thread/process-safe practice. After all of this you should come with something similar to this approach: try: import Tkinter as tk # Python 2 import ttk import Queue as queue except ImportError: import tkinter as tk # Python 3 import tkinter.ttk as ttk import queue import multiprocessing as mp import time class App(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.minsize(width=400, height=25) self.label = tk.Label(self, text='Waiting for "work"') self.label.pack(expand=True, fill='both') self.progressbar = ttk.Progressbar(self, orient='horizontal', value=0, maximum=3, mode='determinate') self.progressbar.pack(fill='x') self.button = tk.Button(self, text='Start', command=self.start_work) self.button.pack(fill='x') self.queue = mp.Queue() self.process = None def start_work(self): self.process = mp.Process(target=work, args=(self.queue,)) self.button.configure(state='disabled') self.process.start() self.periodic_call() def periodic_call(self): # check a queue once self.check_queue() # if exit code is None - process is on the run and we should re-schedule check if self.process.exitcode is None: self.after(100, self.periodic_call) # things are executed else: self.process.join() self.button.configure(state='normal') self.label.configure(text='Waiting for "work"') self.progressbar.configure(value=0) def check_queue(self): # common check of the queue while self.queue.qsize(): try: self.label.configure(text=self.queue.get(0)) self.progressbar.configure(value=self.progressbar['value'] + 1) except queue.Empty: pass def work(working_queue): …
downvote count: 0
type: Answer

http://stackoverflow.com/q/47582192
has title: python - iterate list and get list index for use in array
type: Question
tagged with: numpy
score: 0
answer count: 0
type: UnansweredQuestion
has body: Sorry, I know this is probably simple and covered in another post but I couldn't find it so: I want to iterate through two lists and then store a result in an array based on the position of the inputs. So, for example: z = np.array(len(xlist), len(ylist)) for x in xlist: for y in ylist: z[index of x, index of y] = f(x,y) Thanks!
linked to: http://stackoverflow.com/q/522563
has comment: http://stackoverflow.com/comment/82124413
tagged with: python
has comment: http://stackoverflow.com/comment/82122023
duplicate of: http://stackoverflow.com/q/522563

http://stackoverflow.com/comment/91235740
score: 0
type: AnswerComment
has text: Hey, you can follow this instructions https://gist.github.com/carlochess/658a98589709f46dbb3d20502e48556b
comment on: http://stackoverflow.com/a/49295045
type: Comment

http://stackoverflow.com/comment/82138161
type: QuestionComment
has text: @electrogas yes, my user is already in dialout
comment on: http://stackoverflow.com/q/47551983
score: 0
type: Comment

http://stackoverflow.com/q/47659998
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I'm learning ML and doing the task for Boston house price predictions. I have following code: from sklearn.metrics import fbeta_score, make_scorer from sklearn.model_selection import GridSearchCV def fit_model(X, y): """ Tunes a decision tree regressor model using GridSearchCV on the input data X and target labels y and returns this optimal model. """ # Create a decision tree regressor object regressor = DecisionTreeRegressor() # Set up the parameters we wish to tune parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)} # Make an appropriate scoring function scoring_function = make_scorer(fbeta_score, beta=2) # Make the GridSearchCV object reg = GridSearchCV(regressor, param_grid=parameters, scoring=scoring_function) print reg # Fit the learner to the data to obtain the optimal model with tuned parameters reg.fit(X, y) # Return the optimal model return reg.best_estimator_ reg = fit_model(housing_features, housing_prices) This gives me ValueError: continuous is not supported for the reg.fit(X, y) line and I don't understand why. What is the reason for this, what am I missing here?
tagged with: grid-search
tagged with: python
accepted answer: http://stackoverflow.com/a/47660705
has title: GridSearchCV gives ValueError: continuous is not supported for DecisionTreeRegressor
has answer: http://stackoverflow.com/a/47660705
upvote count: 4
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: decision-tree
score: 4

http://stackoverflow.com/a/47661337
downvote count: 0
has body: Use the not operator: In [1]: b = True In [2]: not b Out[2]: False In [3]: b = not b In [4]: b Out[4]: False In [5]: not b Out[5]: True
answers question: http://stackoverflow.com/q/47661242
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/82318471
type: Comment
comment on: http://stackoverflow.com/a/47678905
score: 0
type: AnswerComment
has text: @Alexbrini In the meantime, if my answer helped, don't forget to accept it by ticking it :)

http://stackoverflow.com/comment/82118737
type: AnswerComment
comment on: http://stackoverflow.com/a/47565399
has text: @CameronHamilton You will need to use `v.get()` when you want that variable to manipulate other stuff. So there can be a need.
type: Comment
score: 0

http://stackoverflow.com/a/47817345
has comment: http://stackoverflow.com/comment/82699676
accepted answer of: http://stackoverflow.com/q/47574798
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47574798
has body: Disclaimer: Due to a lack of reputation points, I am not allowed to comment Normally, append is not used in place. Hence, I would suggest to say df_destination = df_destination.append(df_newlines, ignore_index=True) Hope that's it. Apart from that, I suggest to use os.walk and fnmatch to browse the files.
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47685882
type: Answer
has body: You can use list comprehension to iterate over the keys and values of the original dictionary and search for similar keys in the dictionary. Lasting, simple filtering will create "nan" if no result is found for any key: d = {(1, 1): 0, (2, 1): 1, (3, 1): 2, (10, 41):3} new_d = {a:[c for c, b in d.items() if any(abs(i-a[0]) == 1 or abs(i-a[-1])==1 for i in c) and c != a] for a, h in d.items()} final_d = {a:"nan" if not b else b for a, b in new_d.items()} Alternative solution with math.hypot(): import math new_d = {a:[c for c, b in d.items() if math.hypot(a[0]-c[0], a[1]-c[1])&lt;= 1 and c != a] for a, h in d.items()} final_d = {a:"nan" if not b else b for a, b in new_d.items()} Output: {(3, 1): [(2, 1)], (10, 41): 'nan', (1, 1): [(2, 1)], (2, 1): [(3, 1), (1, 1)]}
has comment: http://stackoverflow.com/comment/82331908
has comment: http://stackoverflow.com/comment/82331736
has comment: http://stackoverflow.com/comment/82331592
answers question: http://stackoverflow.com/q/47685820
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82332140
has comment: http://stackoverflow.com/comment/82765707
has comment: http://stackoverflow.com/comment/82331702
has comment: http://stackoverflow.com/comment/82331587

http://stackoverflow.com/a/47677061
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47675444
has comment: http://stackoverflow.com/comment/82316327
answers question: http://stackoverflow.com/q/47675444
type: Answer
has body: You have a list of empty lists. So while matrix[0] is fine, matrix[0][0] is out of bounds. You have to either preallocate the lengths of the sublists beforehand if you wish to access them by index, or you append the averages as shown in Gary02127's answer. If you choose the former, you must also increment m after matrix[k][m]=sum/9. However, your code has another out-of-bounds bug waiting to be triggered. Suppose you have a 3x4 image, i.e., one of the dimensions isn't divisible by 3. You average the first 3x3 block just fine, and then you try to access the pixels at column indices 3-5. If your dimensions aren't divisible by the downsample factor, you have 3 choices: raise an error at the beginning of the function call, add extra rows/columns to make your matrix divisible by your factor (you can use the value of the last element of the row/column to extend it further), or use only as many elements are you have left. Here's an implementation with approach #3 and preallocating your matrix. def downsample(image, factor): height = len(image) # this assumes that all sublists have the same length! width = len(image[0]) matrix = [[None] * ((width + factor - 1) // factor) for _ in range((height + factor - 1) // factor)] k = 0 m = 0 for i in range(0, height, factor): for j in range(0, width, factor): # don't overshadow the `sum` builtin total = 0 count = 0 for r in range(i, min(i+factor, height)): for c in range(j, min(j+factor, width)): total += image[r][c] count += 1 matrix[k][m] = total / count m += 1 m = 0 k += 1 return matrix
score: 0

http://stackoverflow.com/a/47583005
type: Answer
answers question: http://stackoverflow.com/q/47573735
downvote count: 0
score: 1
upvote count: 1
has body: The development version of gmpy2 supports the 96-bit IEEE numeric type. &gt;&gt;&gt; import gmpy2 &gt;&gt;&gt; gmpy2.version() '2.1.0a1' &gt;&gt;&gt; gmpy2.set_context(gmpy2.ieee(96)) &gt;&gt;&gt; gmpy2.get_context() context(precision=83, real_prec=Default, imag_prec=Default, round=RoundToNearest, real_round=Default, imag_round=Default, emax=4096, emin=-4175, subnormalize=True, trap_underflow=False, underflow=False, trap_overflow=False, overflow=False, trap_inexact=False, inexact=False, trap_invalid=False, invalid=False, trap_erange=False, erange=False, trap_divzero=False, divzero=False, allow_complex=False, rational_division=False) &gt;&gt;&gt; gmpy2.mpfr(1)/7 mpfr('0.14285714285714285714285714',83) &gt;&gt;&gt; It is also possible in older versions of gmpy2 but requires a bit more effort. &gt;&gt;&gt; import gmpy2 &gt;&gt;&gt; gmpy2.version() '2.0.8' &gt;&gt;&gt; ieee96 = gmpy2.context(precision=83, emax=4096, emin=-4175, subnormalize=True) &gt;&gt;&gt; gmpy2.set_context(ieee96) &gt;&gt;&gt; gmpy2.mpfr(1)/7 mpfr('0.14285714285714285714285714',83) &gt;&gt;&gt; You may need to down to download the source directly from https://github.com/aleaxit/gmpy . Some very early wheels are available at https://pypi.python.org/pypi/gmpy2/2.1.0a1 . Disclaimer: I maintain gmpy2.

http://stackoverflow.com/q/47628924
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/47629075
favorite count: 0
type: Question
has body: {'endDate': '2017-12-31', 'results': [{'data': [{'period': '2017-01-01', 'ratio': 26.91301}, {'period': '2017-02-01', 'ratio': 19.77063}, {'period': '2017-03-01', 'ratio': 20.40775}, {'period': '2017-04-01', 'ratio': 16.02843}, {'period': '2017-05-01', 'ratio': 10.38159}, {'period': '2017-06-01', 'ratio': 8.2087}, {'period': '2017-07-01', 'ratio': 8.67815}, {'period': '2017-08-01', 'ratio': 19.58956}, {'period': '2017-09-01', 'ratio': 36.94587}, {'period': '2017-10-01', 'ratio': 36.28194}, {'period': '2017-11-01', 'ratio': 16.64543}, {'period': '2017-12-01', 'ratio': 1.67661}], 'keywords': ['Data_spec'], 'title': 'Data_spec'}, {'data': [{'period': '2017-01-01', 'ratio': 17.65139}, {'period': '2017-02-01', 'ratio': 14.52618}, {'period': '2017-03-01', 'ratio': 15.00234}, {'period': '2017-04-01', 'ratio': 12.1521}, {'period': '2017-05-01', 'ratio': 10.63644}, {'period': '2017-06-01', 'ratio': 8.59767}, {'period': '2017-07-01', 'ratio': 8.95312}, {'period': '2017-08-01', 'ratio': 13.05747}, {'period': '2017-09-01', 'ratio': 48.00482}, {'period': '2017-10-01', 'ratio': 23.7811}, {'period': '2017-11-01', 'ratio': 16.90027}, {'period': '2017-12-01', 'ratio': 0.89866}], 'keywords': ['Data_rate'], 'title': 'Date_rate'}, {'data': [], 'keywords': ['Data_over'], 'title': 'Data_over'}, {'data': [{'period': '2017-01-01', 'ratio': 79.17644}, {'period': '2017-02-01', 'ratio': 84.01851}, {'period': '2017-03-01', 'ratio': 100.0}, {'period': '2017-04-01', 'ratio': 91.19442}, {'period': '2017-05-01', 'ratio': 93.21976}, {'period': '2017-06-01', 'ratio': 93.42096}, {'period': '2017-07-01', 'ratio': 89.14895}, {'period': '2017-08-01', 'ratio': 91.85165}, {'period': '2017-09-01', 'ratio': 91.24136}, {'period': '2017-10-01', 'ratio': 90.35611}, {'period': '2017-11-01', 'ratio': 81.88585}, {'period': '2017-12-01', 'ratio': 7.49111}], 'keywords': ['Data_under'], 'title': 'Data_under'}, {'data': [{'period': '2017-01-01', 'ratio': 0.70417}, {'period': '2017-02-01', 'ratio': 1.11997}, {'period'…
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47629075
type: AnsweredQuestion
has title: json to DataFrame conversion issues

http://stackoverflow.com/a/47624351
has body: Forces and torques cause changes in momentum and angular momentum of a body. For these calculations physics is unavoidable and there is no general solution because unless we know details about the system (what kind of force or torque is acting, what is the shape and mass of the system etc.) under consideration we cannot calculate the changes in momentum. So if we know how force F varies with time we can calculate the x, y and z components of changes in angular momentum by integrating the corresponding components of force with time. SymPy can help us to do the integration. Although, SymPy has a dedicated Physics Vector module, we don't even need it if we have a simple enough force equation for which just Sympy's integrate function is sufficient. For example, let's say that the only non-zero component of the force acting on the system is the x-component given as cos(t). import sympy as sp t,t0,t1 = sp.symbols('t,t0,t1') Fx = sp.cos(t) # x-component of Force MomX = sp.integrate( Fx, (t,t0,t1) ) # x-component of change in momentum # MomX = sin(t1) - sin(t0) Similar discussion holds for change in angular momentum except that force will be replaced by a torque or if one has enough details about the geometry of the system one may be able to calculate the torque from the force itself and then integrate it with respect to time to get the change in angular momentum.
answers question: http://stackoverflow.com/q/47608132
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82266889
comment on: http://stackoverflow.com/q/47654162
score: 0
type: Comment
type: QuestionComment
has text: `z = [min(i) for i in x]` gives the list with all the minimums , and `z = [max(i) fro i in x]` would give otherwise!

http://stackoverflow.com/a/47683268
has body: Here's the solution I came up with though I think you could probably improve this by using an apply with scipy.interpolate for the interpolation step. First create floor, ceiling and delta columns for df1. enter df1['C_floor'] = df1.C.apply(np.floor) df1['C_ceil'] = df1.C.apply(np.ceil) df1['C_delta'] = df1.C - df1.C_floor Do a double left join to obtain the V corresponding to the floor and ceiling of C from df2. df1 = df1.merge(df2, how ='left', left_on = ['B', 'C_floor'], right_on = ['B', 'C']) df1 = df1.merge(df2, how ='left', left_on = ['B', 'C_ceil'], right_on = ['B', 'C']) Here's where I think you could make the code faster, but I wrote a brief function to find the weighted mean and account for cases where C falls outside the range available in df2. def weighted_mean(x): if np.isnan(x.V_x): return x.V_y elif np.isnan(x.V_y): return x.V_x else: return x.V_y + (x.V_x - x.V_y) * x.C_delta df1['V'] = df1'V_x', 'V_y', 'C_delta'.apply(weighted_mean, axis = 1) Finally some cleanup. df1 = df1'A', 'B', 'C_x', 'V' df1.columns = ['A', 'B', 'C', 'V'] Which gives. A B C V 0 ABC USD 2.31 1.283 1 DEF MXN 4.72 0.880 2 XYZ EUR 5.83 0.120
type: Answer
answers question: http://stackoverflow.com/q/47681517
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82364793
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47681517
has comment: http://stackoverflow.com/comment/82355556

http://stackoverflow.com/q/47579635
tagged with: neural-network
tagged with: loss-function
tagged with: python
has body: I would like to capture the loss value for every step that is output in the log when I train a tensorflow.estimator.DNNRegressor model. Given the trivial nonsense example: In [1]: import pandas as pd In [2]: import numpy as np In [3]: import tensorflow as tf In [4]: X = pd.DataFrame({'X1':np.arange(1,10), 'X2':np.arange(11,20)}) In [5]: X Out[5]: X1 X2 0 1 11 1 2 12 2 3 13 3 4 14 4 5 15 5 6 16 6 7 17 7 8 18 8 9 19 In [6]: y = pd.Series(np.arange(1,10)/2) In [7]: feature_cols = [tf.feature_column.numeric_column(col) for col in X.columns] In [8]: regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols, hidden_units=[3,3], model_dir='mymodel') INFO:tensorflow:Using default config. INFO:tensorflow:Using config: {'_tf_random_seed': 1, '_save_checkpoints_secs': 600, '_log_step_count_steps': 100, '_keep_checkpoint_max': 5, '_save_checkpoints_steps': None, '_session_config': None, '_model_dir': 'mymodel', '_keep_checkpoint_every_n_hours': 10000, '_save_summary_steps': 100} In [9]: regressor.train( input_fn=tf.estimator.inputs.pandas_input_fn( x=X, y=y, num_epochs=None, shuffle=True), steps=1000) INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Saving checkpoints for 1 into mymodel/model.ckpt. INFO:tensorflow:step = 1, loss = 1090.0 INFO:tensorflow:global_step/sec: 685.57 INFO:tensorflow:step = 101, loss = 580.524 (0.146 sec) INFO:tensorflow:global_step/sec: 807.454 INFO:tensorflow:step = 201, loss = 423.964 (0.124 sec) INFO:tensorflow:global_step/sec: 875.857 INFO:tensorflow:step = 301, loss = 353.421 (0.114 sec) INFO:tensorflow:global_step/sec: 788.649 INFO:tensorflow:step = 401, loss = 297.249 (0.127 sec) INFO:tensorflow:global_step/sec: 649.258 INFO:tensorflow:step = 501, loss = 254.237 (0.154 sec) INFO:tensorflow:global_step/sec: 803.059 INFO:tensorflow:step = 601, loss = 303.544 (0.125 sec) INFO:tensorflow:global_step/sec: 674.359 INFO:tensorflow:step = 701, loss = 234.27 (0.148 sec) INFO:tensorflow:global_step/sec: 818.35 INFO:tensorflow:step = 8…
score: 2
has answer: http://stackoverflow.com/a/47676362
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has title: TensorFlow DNNRegressor Retrieve Loss Values from Training Regressor

http://stackoverflow.com/comment/82078768
type: QuestionComment
comment on: http://stackoverflow.com/q/47560087
has text: Do the strings contain newline characters, or do they contain a literal "\" followed by "n"? Your regex seems to suggest the latter, but a lot of the answers you've got are assuming the former.
score: 0
type: Comment

http://stackoverflow.com/comment/82297197
score: 0
comment on: http://stackoverflow.com/q/47668802
type: Comment
type: QuestionComment
has text: In this case you only get five different sizes of circles, how do you want to handle 10 or 20 or 100 or 1000 different sizes?

http://stackoverflow.com/comment/82314702
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47677439
type: Comment
has text: @MadPhysicist, thank you for the example, I think it illustrates well how this could be used, & I added it to the answer.

http://stackoverflow.com/q/47636747
has comment: http://stackoverflow.com/comment/92445103
downvote count: 0
has body: I have configured logging in logging.config file. I have created a class where I access this configuration file, enable/disable the logger, and log some Info messages. I am importing this class in all the modules where I need to do some logging. When I try to log to a file, I get this error message. I am not able to understand what this error means. File "/usr/local/lib/python3.6/configparser.py", line 959, in getitem raise KeyError(key) KeyError: 'formatters' logging.config [loggers] keys=root [handlers] keys=fileHandler [formatters] keys=simpleFormatter [logger_root] level=INFO handlers=fileHandler [handler_fileHandler] class=FileHandler level=INFO formatter=simpleFormatter args=('example.log','a') [formatter_simpleFormatter] class=logging.Formatter format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= #Log.py import logging.config class Monitor(object): fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") print (fileName) #prints /usr/local/lib/python3.6/site-packages/myproject-0.0.1-py3.6.egg/MyPackageName/logging.config logging.config.fileConfig(fileName) logger = logging.getLogger('root') logger.disabled = False @staticmethod def Log(logMessage): Monitor.logger.info(logMessage) #sub.py import Monitor class Example def simplelog(self,message): Monitor.Log("Logging some message here") #call some function here Monitor.Log("Logging some other messages here for example")
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82232031
linked to: http://stackoverflow.com/q/23161745
has title: python3.6 : KeyError: 'formatters'
favorite count: 0
tagged with: logging
tagged with: keyerror
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82232549
has comment: http://stackoverflow.com/comment/82243369
score: 2
upvote count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/59278515

http://stackoverflow.com/comment/82062277
has text: Perfect! Thanks a lot!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47552894
score: 0

http://stackoverflow.com/comment/82184698
comment on: http://stackoverflow.com/q/47613121
type: QuestionComment
has text: Please isolate the issue you are having instead of dumping a code block and saying How to do this?
type: Comment
score: 0

http://stackoverflow.com/comment/82116176
type: AnswerComment
has text: I made those migrations, and now the data is being saved...however, the comment text and the form remains in the table after the redirect. when the submit button is clicked a second time (after the initial save), comment text remains and entity and logic become blank. `formset.errors` shows `[{}, {}, {} ..... {}]`
type: Comment
comment on: http://stackoverflow.com/a/47579024
score: 0

http://stackoverflow.com/comment/82164518
has text: The less hacky, although less pretty way is `[(lambda i: lambda x: x**i)(i) for i in range(n)]`. Note, this essentially reproduces your nested function approach using `lambda`. Also note, don't wrap your `range` in `list`, that completely defeats the purpose of `range`, and is completely useless and just makes your function needlessly inefficient.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47602645
score: 0

http://stackoverflow.com/comment/82173836
comment on: http://stackoverflow.com/q/47607653
score: 0
type: QuestionComment
type: Comment
has text: In any way, you should not use double underscore for private attributes, please use only one

http://stackoverflow.com/a/47616150
has body: def main(i): if i &lt; 2: print(i) if i &gt; 2: print(i) else: print("Hello") Based on this simple program, if you try a few cases: &gt;&gt;&gt; main(1) &gt;&gt;&gt; 1 Hello &gt;&gt;&gt; main(3) 3 &gt;&gt;&gt; main(2) Hello Did you see the difference? When the first IF is TRUE, then the 2nd IF will be FALSE and hence the ELSE part will be executed.
score: 0
answers question: http://stackoverflow.com/q/47616073
type: Answer

http://stackoverflow.com/comment/82348039
comment on: http://stackoverflow.com/a/47694397
type: Comment
has text: This is not the right way to do it since a html page may contain more than one ` ` tag.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82098440
type: AnswerComment
comment on: http://stackoverflow.com/a/47569858
has text: Sure are you working on same database? Please, double check connection string.
score: 0
type: Comment

http://stackoverflow.com/a/47598078
has comment: http://stackoverflow.com/comment/82182571
answers question: http://stackoverflow.com/q/47597483
has body: Instead of creating 9000 collections with one triangle in each, it is for sure more efficient to create one single collection with 9000 triangles in it. import numpy as np import mpl_toolkits.mplot3d as a3d import matplotlib.colors as colors import matplotlib.pyplot as plt Vertex1 = np.random.rand(9000,3) Vertex2 = np.random.rand(9000,3) Vertex3 = np.random.rand(9000,3) ax = a3d.Axes3D(plt.figure()) v = np.stack((Vertex1,Vertex2,Vertex3),axis=2) tri = a3d.art3d.Poly3DCollection(v) tri.set_color(colors.rgb2hex([0.9,0.6,0.])) tri.set_edgecolor('k') ax.add_collection3d(tri) plt.show()
has comment: http://stackoverflow.com/comment/82182351
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47633649
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: files is a list, then you can use len() function. So, files.index(files[-1]) is equal to len(files) - 1. Actually your question is about finding the last index. Take a look at this link.
answers question: http://stackoverflow.com/q/47630416

http://stackoverflow.com/q/47663656
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47674057
has body: I'm trying to get a direct text response from dialogflow. I do get an answer from the example code on github, but thats not user-friendly at all. How can I get the "Speech-Only" response? import os.path import sys try: import apiai except ImportError: sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) ) import apiai CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN' def main(): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.lang = 'de' # optional, default value equal 'en' request.session_id = "&lt;SESSION ID, UNIQUE FOR EACH USER&gt;" request.query = "Hello" response = request.getresponse() print (response.read()) if __name__ == '__main__': main() I just expect a a simple result. A plain hello text. What I get instead = b'{\n "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n "timestamp": "2017-12-05T22:18:15.563Z",\n "lang": "en",\n "result": {\n "source": "agent",\n "resolvedQuery": "hi",\n "action": "input.welcome",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {\n "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n "webhookUsed": "false",\n "webhookForSlotFillingUsed": "false",\n "intentName": "Default Welcome Intent"\n },\n "fulfillment": {\n "speech": "Hi there!",\n "messages": [\n {\n "type": 0,\n "speech": "Hi there!"\n }\n ]\n },\n "score": 1.0\n },\n "alternateResult": {\n "source": "domains",\n "resolvedQuery": "hi",\n "action": "smalltalk.greetings.hello",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {},\n "fulfillment": {\n "speech": "Hey!",\n "source": "agent"\n },\n "score": 1.0\n },\n "status": {\n "code": 200,\n "errorType": "success",\n "webhookTimedOut": false\n },\n "sessionId": "mr.9000"\n}'
has title: How to get text response directly on Dialogflow?
has answer: http://stackoverflow.com/a/47680930
tagged with: chatbot
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/47674057
downvote count: 0
tagged with: dialogflow-es
upvote count: 1
possible better answer: http://stackoverflow.com/a/47680930

http://stackoverflow.com/q/47568470
tagged with: dictionary
has body: I am currently struggling with an issue. I have a file that contains one 5 letter word per line. Lets say for example the words are Hello Hella Pales Piles I am trying to create a nested dictionary with each key corresponding to the letter in the word. For example with these words the output would be. {'H':{'e':{'l':{'l':{'o':'Hello','a':'Hella'}}}}, 'P':{'a':{'l':{'e': {'s':'Pales'}}}, 'i':{'l':{'e':{'s':'Piles}}}}} I have tried some code that almost works, but does not produce the right results. T={} for w in wordsFile: T[list(w)[0]]={list(w)[1]:{list(w)[2]:{list(w)[3]:{list(w)[4]:w}}}} return(T) Does anyone know of a better way to do this. I just am not quite sure as to go about solving this problem. Thanks in advance!
type: AnsweredQuestion
score: 1
has title: Creating a deeply nested dictionary from a text file
accepted answer: http://stackoverflow.com/a/47568593
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47568593
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47576025
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47576043
favorite count: 0
has title: Pandas, how to reindex a dataframe that is generated from appending multiple dataframe.
has answer: http://stackoverflow.com/a/47576043
type: Question
possible better answer: http://stackoverflow.com/a/47576083
has answer: http://stackoverflow.com/a/47576083
tagged with: dataframe
tagged with: python
has body: I have a dataframe that is generated from appending multiple dataframe together into a long list. As shown in figure, the default index is a loop between 0 ~ 7 because each original df has this index. The total row number is 240. So how can reindex the new df into 0~239 instead of 30 x 0~7. I tried df.reset_index(drop=True), but it doesn't seem to work. I also tried:df.reindex(np.arange(240)) but it returned error ValueError: cannot reindex from a duplicate axis
tagged with: pandas
upvote count: 2

http://stackoverflow.com/comment/82258635
has text: Ok. NP, but any idea to fetch email without UI?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47639870
type: QuestionComment

network-programming
tags question: http://stackoverflow.com/q/47583880
tag name: network-programming
tags question: http://stackoverflow.com/q/47680840
tags question: http://stackoverflow.com/q/47586545
tags question: http://stackoverflow.com/q/47641318
tags question: http://stackoverflow.com/q/47618385
tags question: http://stackoverflow.com/q/47666124
type: Tag
tags question: http://stackoverflow.com/q/47581334
tags question: http://stackoverflow.com/q/47618710

http://stackoverflow.com/q/47603957
tagged with: latex
answer count: 0
type: UnansweredQuestion
has body: I've installed LaTex through pip install latex And also run the Mactex installer from here: https://tug.org/mactex/mactex-download.html But when I try to build with Tex through Python, I get this error message: Traceback (most recent call last): File "write_case_insert_from_json.py", line 341, in &lt;module&gt; output_pdf_filename) File "trace_case_insert.py", line 245, in compile_tex_into_pdf pdf = latex.build_pdf(open(tex_filename)) File "/Library/Python/2.7/site-packages/latex/build.py", line 234, in build_pdf raise RuntimeError('No available builder could be instantiated. ' RuntimeError: No available builder could be instantiated. Please make sure LaTeX is installed. Why can't Python find tex? What am I doing incorrectly? Thanks in advance!
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82167233
favorite count: 0
has title: Building with Tex not working from Python
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82166853
type: Question

http://stackoverflow.com/q/47673455
tagged with: pandas
has title: fail astype method to grouped dataframe in pandas
score: 1
has answer: http://stackoverflow.com/a/47673484
answer count: 1
downvote count: 0
upvote count: 1
has body: I get following error when I try to apply astype(float) method to grouped dataframe in pandas. ValueError: could not convert string to float: Do you know what is the reason why I cannot convert string to float by astype method? and how I can solve this? Below is the code I get error and example data. def group(self,agg_method): df=self.df grouped=df.groupby(['Tilt [deg]', 'Azimuth [deg]'],as_index=False) groupdf=grouped.agg(agg_method) print(groupdf['Azimuth [deg]'][0],len(groupdf['Azimuth [deg]'][0])) groupdf['Azimuth [deg]']=groupdf['Azimuth [deg]'].astype(float) &lt;- I get error here Example data Tilt [deg] Azimuth [deg] Glass SHGC Area of Multiplied Openings [m2] \ 0 90.0 124.48 0.57 1450.24 1 90.0 207.3 0.57 115.66 2 90.0 207.47 0.57 115.62 3 90.0 208.25 0.57 23.18 4 90.0 208.26 0.57 113.12 5 90.0 214.48 0.57 451.94 6 90.0 218.57 0.57 230.08 7 90.0 304.46 0.57 72.66 8 90.0 304.48 0.57 1827.53 9 90.0 34.48 0.57 917.29
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47673484

http://stackoverflow.com/q/47675691
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47682643
has title: Python Flask Uploading FIles
score: 3
tagged with: python
tagged with: flask
has body: I'm trying to upload user selected image into my firebase. When I browse for the file file = request.files['inputFile'] and I try this storage.child("images/examples.jpg").put(file) I get an error io.UnsupportedOperation: fileno How do I go about fixing this? I just want user to select the file and I be able to make use of the .jpg file and upload it
tagged with: firebase
tagged with: firebase-storage
type: UnansweredQuestion
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48634339
accepted answer of: http://stackoverflow.com/q/47567146
has body: The issue ended up being, as @dirkgroten correctly pointed out, that the structure of my Heroku directory was incorrect. I organized the directory using the structure described in this repo https://github.com/heroku/heroku-django-template and that resolved the problems.
answers question: http://stackoverflow.com/q/47567146
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82284536
score: 0
comment on: http://stackoverflow.com/q/47662078
type: Comment
type: QuestionComment
has text: Note: If you weren't opposed to Python 3, as of Python 3.2, `configparser` [would support the exact approach you're trying to use](https://docs.python.org/3/library/configparser.html#mapping-protocol-access).

http://stackoverflow.com/comment/82049637
type: Comment
has text: I added `listen 8080;` and `listen [::]:8888 ipv6only=off default_server;` Still does not work. I also tried the different combinations of those modes.
type: QuestionComment
comment on: http://stackoverflow.com/q/47546274
score: 0

http://stackoverflow.com/a/47674908
answers question: http://stackoverflow.com/q/47674670
type: Answer
has body: The feature_importance_ method keeps the order of features the tree was trained upon. So you can use a zip function between the original feature list and the feature_importance_ return value to get per each features its importance.
score: 0

http://stackoverflow.com/q/47607685
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47607855
tagged with: exponential
type: AnsweredQuestion
score: 0
tagged with: scipy
answer count: 1
tagged with: networkx
has body: n=sc.shape(A)[0] sim=sc.eye(n) I=sc.eye(n) P= normalize(A, norm='l1', axis=0) Q=P*(1-np.exp(-A)) A is an adjacency matrix created by the code: df=pd.read_csv('training.csv') G=nx.from_pandas_dataframe(df,'node1','node2','weight') A = nx.adjacency_matrix(G) The error I am getting : File "ROC_final.py", line 36, in ASCOSplus Q=P*(1-np.exp(-A)) File "C:\Python27\lib\site-packages\scipy\sparse\base.py", line 647, in __getattr__ raise AttributeError(attr + " not found") AttributeError: exp not found note :I have tried the solution A= A.astype(float) as suggested by SO answer too.
type: Question
has answer: http://stackoverflow.com/a/47607855
has title: AttributeError: exp not found
tagged with: python

http://stackoverflow.com/a/47696839
answers question: http://stackoverflow.com/q/47696719
type: Answer
has body: class ecom_common_functions_class(sendmailobject): This line implies that your class ecom_common_functions_class wants to extends another class called sendmailobject. with sendmailobject name this does not seem to be class. Class names should normally use the CapWords convention. Either you have not imported sendmailobject or it is not a class
score: 0

http://stackoverflow.com/a/47689354
type: Answer
has body: Try replacing this: path('application/register',oauth2_views.ApplicationRegistration.as_view(), name='register'), with path('application/register/', oauth2_views.ApplicationRegistration.as_view(), name='register'),
has comment: http://stackoverflow.com/comment/82493578
answers question: http://stackoverflow.com/q/47666257
score: 0

http://stackoverflow.com/q/47684885
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/svg
answer count: 2
has body: I've been trying to understand arc svg since it seems I need them in plotly -- my goal is to plot circle intersections. My original idea was something like this: for every intersection, to find the start and end coordinates as well as the height - but I am not very sure of where to go from here. It seems I am lacking the rotation and Large Arc Flag / Sweep parameters, and I am not sure how I would go about retrieving them. If anyone could point me into the right direction here, that would be great!
upvote count: 2
has answer: http://stackoverflow.com/a/47699426
downvote count: 0
tagged with: javascript
tagged with: python
has title: Arc SVG Parameters
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47699426
tagged with: plotly
tagged with: trigonometry
accepted answer: http://stackoverflow.com/a/47695091
has answer: http://stackoverflow.com/a/47695091

nwb
type: Tag
tag name: nwb
tags question: http://stackoverflow.com/q/47645674

http://stackoverflow.com/a/47646253
has comment: http://stackoverflow.com/comment/82251171
upvote count: 0
has body: This script worked ps -aux | grep -i 'healthcheck' | awk {'print $2'} | xargs kill -9 nohup python &lt;path_to_file/healthcheck.py&gt; &amp; cat nohup.out with the crontab entry 0 1 * * * cron.sh
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/47626931

http://stackoverflow.com/q/47561835
has title: Best practice for keeping a config file in python
upvote count: 4
answer count: 1
downvote count: 0
tagged with: config
has answer: http://stackoverflow.com/a/47562243
favorite count: 0
type: Question
has body: I have a python script in which I have a config file which looks like this: PROD = 'production' DEV = 'dev' ENVIRONMENT = None and I have a function which gets the wanted environment from a command argument and sets it like: if sys.argv[1] in [config.PROD, config.DEV]: config.ENVIRONMENT = sys.argv[1] I understood it's not good practice when I started importing the config file in multiple files and ENV kept resetting back to None. So, my question is: what is the best practice is this case
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47562243
tagged with: python
score: 4

http://stackoverflow.com/comment/82288867
comment on: http://stackoverflow.com/q/47661965
type: Comment
has text: @Prune Thank you, I've marked the question as completed.
type: QuestionComment
score: 0

gtk3
tags question: http://stackoverflow.com/q/47622043
type: Tag
tags question: http://stackoverflow.com/q/47614702
tags question: http://stackoverflow.com/q/47583495
tag name: gtk3
tags question: http://stackoverflow.com/q/47569017
tags question: http://stackoverflow.com/q/47657995

http://stackoverflow.com/a/54693364
answers question: http://stackoverflow.com/q/47616680
score: 3
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/122412453
downvote count: 2
has body: The best example I have found is here: https://djangowaves.com/tips-tricks/gitignore-for-a-django-project/ This is not my work!!! I don't want to take credit for someone else's good collection! Not everything in there is relevant. The author documents it well, though, so you can boil it down to what you need. I would also add: **/migrations *.DS_Store **/__pycache__ **/.DS_Store

http://stackoverflow.com/comment/82077296
score: 0
has text: have you tried `nx.circular_layout`?
type: Comment
comment on: http://stackoverflow.com/q/47555594
type: QuestionComment

http://stackoverflow.com/comment/82302349
score: 0
type: Comment
has text: lol its printing from 15 mins :D
comment on: http://stackoverflow.com/q/47671606
type: QuestionComment

http://stackoverflow.com/a/47666505
has comment: http://stackoverflow.com/comment/82530739
has comment: http://stackoverflow.com/comment/82292250
type: Answer
has body: You can calculate the distance to the center of the circle with the math.hypot function. If the distance is below the radius, the circle was clicked. import math import pygame as pg def main(): screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() circle_pos = (300, 200) circle_radius = 40 done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.MOUSEBUTTONDOWN: # x and y distance to the mouse position (event.pos). x_offset = event.pos[0] - circle_pos[0] y_offset = event.pos[1] - circle_pos[1] distance = math.hypot(x_offset, y_offset) if distance &lt; circle_radius: print('Circle clicked.', distance) screen.fill((30, 30, 30)) pg.draw.circle(screen, (240, 120, 0), circle_pos, circle_radius) pg.display.flip() clock.tick(30) if __name__ == '__main__': pg.init() main() pg.quit() You could also use pygame.mask.Masks for the collision detection, but the hypot solution is simpler.
has comment: http://stackoverflow.com/comment/82534059
has comment: http://stackoverflow.com/comment/82330529
has comment: http://stackoverflow.com/comment/82330223
score: 0
answers question: http://stackoverflow.com/q/47666220
has comment: http://stackoverflow.com/comment/82330281

http://stackoverflow.com/a/47722881
type: Answer
has comment: http://stackoverflow.com/comment/82410355
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47682103
has body: To set the alpha/transparency of images with per-pixel alpha, you need to use a little trick. You can create an intermediate surface, fill it with white and the desired alpha value and then blit it onto the other surface with the pygame.BLEND_RGBA_MULT flag. That will leave fully transparent pixels untouched and just change the transparency of the visible parts. So if you want to fade one surface in and the other out, you just have to store their alpha values, change them every frame and then call the change_alpha function to get new surfaces with the right transparency. (I'm using text surfaces in this example, but it works with other surfaces/loaded images as well). import pygame as pg def change_alpha(orig_surf, alpha): """Create a copy of orig_surf with the desired alpha value. This function creates another surface with the desired alpha value and then blits it onto the copy of the original surface with the `BLEND_RGBA_MULT` flag to change the transparency.""" surf = orig_surf.copy() # This surface is used to adjust the alpha of the txt_surf. alpha_surf = pg.Surface(surf.get_size(), pg.SRCALPHA) alpha_surf.fill((255, 255, 255, alpha)) # Set the alpha value. surf.blit(alpha_surf, (0, 0), special_flags=pg.BLEND_RGBA_MULT) return surf def main(): clock = pg.time.Clock() screen = pg.display.set_mode((640, 480)) font = pg.font.Font(None, 64) # The original surface which will never be modified. orig_surf = font.render('Enter your text', True, pg.Color('dodgerblue')) alpha = 255 # The current alpha value of the surface. # Surface 2 orig_surf2 = font.render('Another text surface', True, pg.Color('sienna1')) alpha2 = 0 done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True if alpha &gt; 0: # Reduce alpha each frame. alpha -= 4 alpha = max(0, alpha) # Make sure it doesn't go below 0. surf = change_alpha(orig_surf, alpha) if alpha2 &lt; 255: alpha2 += 4 alpha2 = min(255, alpha2) surf2 = change_alpha(orig_surf2, alpha2) screen.fill((…
score: 1
has comment: http://stackoverflow.com/comment/82410165

http://stackoverflow.com/a/47630973
has comment: http://stackoverflow.com/comment/82252354
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/82255325
answers question: http://stackoverflow.com/q/47630892
score: 7
type: Answer
has body: Taking "average" as "the average number of items in the lists", you can achieve it as: average_length = sum( len(v) for v in data.values() ) / len(data) The first part adds together the length of all the lists you have as dictionary values, while len(data) is the number of key:value pair you have in the dictionary.

http://stackoverflow.com/q/47644612
has title: Split one column to two columns depending one the content in pandas dataframe
has answer: http://stackoverflow.com/a/47645355
type: Question
accepted answer: http://stackoverflow.com/a/47648726
has answer: http://stackoverflow.com/a/47648726
has body: I have a pandas DataFrame like this: df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9]) 0 0 A 1 1 2 2 3 3 4 B 5 4 6 5 7 C 8 6 9 7 10 8 11 9 It's mix of strings and numbers. I want to split this DF into tow columns like this: name value 0 A 1 1 A 2 2 A 3 3 B 4 4 B 5 5 C 6 6 C 7 7 C 8 8 C 9 what's an efficient way to do this?
tagged with: python
possible better answer: http://stackoverflow.com/a/47644744
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47644744
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/82045184
type: AnswerComment
comment on: http://stackoverflow.com/a/47544079
has text: Thanks for the suggestion. It's working perfectly now.
score: 0
type: Comment

http://stackoverflow.com/q/47581672
linked to: http://stackoverflow.com/q/45327767
tagged with: python
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/82122516
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82122283
answer count: 2
downvote count: 0
tagged with: seaborn
has title: Replacement for deprecated tsplot
has comment: http://stackoverflow.com/comment/83187724
linked to: http://stackoverflow.com/q/45831596
favorite count: 0
has body: I have a time-series with uniform samples save to a numpy array and I'd like to plot their mean value with a bootstrapped confidence interval. Typically, I've used tsplot from Seaborn to accomplish this. However, this is now being deprecated. What am I supposed to use a replacement? Here is an example usage below adapted from the Seaborn documentation: x = np.linspace(0, 15, 31) data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1) sns.tsplot(data) Note: this is similar to questions "Seaborn tsplot error" and "Multi-line chart with seaborn tsplot". However, in my case, I actually need the confidence interval functionality of Seaborn and thus cannot simply use Matplotlib without some awkward coding.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47582329
accepted answer: http://stackoverflow.com/a/47582329
has answer: http://stackoverflow.com/a/50356077
possible better answer: http://stackoverflow.com/a/50356077
tagged with: matplotlib

http://stackoverflow.com/q/47566060
upvote count: 1
score: 1
tagged with: mysql-python
favorite count: 0
type: Question
has title: How to properly stay connected to MySQL database using pymysql with Tweepy Streaming API?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19440055
tagged with: pymysql
tagged with: python
has body: I'm using Tweepy's Streaming API to listen to tweets for an upcoming event. There are keywords specified to listen to and write to my database hosted on a server(gearhost). However, when there are no tweets coming in for a set period of time, it will display this error for the next tweet coming in and won't be able to write to my database. pymysql.err.OperationalError: (2006, MySQL server has gone away(BrokenPipeError(32, 'Broken Pipe'))") I've searched up a few solutions such as: Correct way of keeping mysql connection but it doesn't seem to work for me. It displayed this error: AttributeError: 'NoneType' object has no attribute 'cursor' I searched up another solution but its saying I should use a connection pool instead but I'm new to python and don't really know how connection pools work. Can anyone help me? Here's my code: import tweepy from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import re import sys import json import pytz from pytz import timezone #connect to pymysql import pymysql conn = pymysql.connect(host='hosting', user='username', password='password', db='database', autocommit=True, charset='utf8mb4',) consumer_key = '******' consumer_secret = '********' access_token = '****-****' access_token_secret = '*****' KEYWORDS = ['singaporepoly','singapore poly', 'sp courses', 'sp open house', 'sp mcdonald', 'sp singapore', 'sp map', 'spoh18', 'sp cca', 'sp career', 'sp library', 'sp part time', 'sp starbucks', '#speye', '#singaporepoly','sp facilities', 'sp polite', 'sp memories','spgusto', 'sp engineering', 'sp campus','sp bowling', 'sp dmit','sp wifi', 'sp bowling','sp FC1', 'sp FC2', 'sp FC3', 'sp FC4', 'sp FC5', 'sp FC6', 'sp mae', 'sp eee', 'sp aircon', 'sp internet','sp mac', 'spdb', 'sp goodies','sp goodie','sp kfc', 'sp bridge', 'sp mrt', 'sp cls','sp sb','#spbizsch', 'sp jae','sp results','sp result','sp jpsae','sp dsa', 'sp interview', 'sp eat','sp student','sp camp','sp freshies','sp foc','sp …
tagged with: tweepy
tagged with: twitter-streaming-api
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/82103430
comment on: http://stackoverflow.com/q/47573190
type: Comment
has text: You are making the parent the frame, not the canvas
score: 0
type: QuestionComment

http://stackoverflow.com/q/47590724
has comment: http://stackoverflow.com/comment/82140160
tagged with: django-database
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82140246
answer count: 1
tagged with: chatroom
has answer: http://stackoverflow.com/a/47590920
type: Question
has title: Check whether user is in django_db or no
has body: I have the django model called "create-chat" and there I write names of people I want to see in a group chat. So. I created the model, but I don't know how to make a condition whether user is in django_db or no, if so then I want to show them the button "join chat" And after clicking the button he will be transferred to the url sitename.com/lobby/1 Now I have the view that shows the page /lobby/any_number First of all I'd to block these pages from users and only if the user is in django_db He is able to visit the page Lobby/1 ONLY THE lobby/1 not lobby/2 I don't ask you to do it, I just want you to explain me how to do it, or maybe advice me some articles about my problem. https://i.sstatic.net/FQw4Y.jpg ..1). How to block all users for visiting this url sitename.com/1234 &lt;- here goes any number u d liked. ( 4 characters ) So now I blocked all the users for visiting this page, and how now make it visible for a certain users/user?
tagged with: django-models
tagged with: django-urls
tagged with: python

http://stackoverflow.com/q/47601460
has answer: http://stackoverflow.com/a/47601589
upvote count: 1
score: 1
answer count: 1
tagged with: keyboard
favorite count: 0
type: Question
tagged with: python
tagged with: pygame
tagged with: image
has comment: http://stackoverflow.com/comment/82161624
has body: Im trying to make a simple image gallery which loads images with keystrokes using pygame in python, and this is how far i got import pygame pygame.init() width=1366; height=768 screen = pygame.display.set_mode((width, height ), pygame.NOFRAME) pygame.display.set_caption('Katso') penguin = pygame.image.load("download.png").convert() mickey = pygame.image.load("mickey.jpg").convert() x = 0; # x coordnate of image y = 0; # y coordinate of image *keys = pygame.event.get() for event in keys: if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT: screen.blit(mickey,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT: screen.blit(penguin,(x,y)); pygame.display.update()* running = True while (running): # loop listening for end of game for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #loop over, quit pygame pygame.quit() i expect to press the arrow keys to load certain images the screen opens but no image gets loaded
type: AnsweredQuestion
has title: Image Loading by keystrokes in Python with pygame
accepted answer: http://stackoverflow.com/a/47601589
downvote count: 0

http://stackoverflow.com/a/47562477
upvote count: 1
answers question: http://stackoverflow.com/q/47562198
has body: You are using the zipfile library incorrectly. Try this: from zipfile import ZipFile from tkinter import filedialog zip_file = ZipFile(filedialog.askopenfilename()) zip_file.extractall()
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82318129
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47679406
has text: I guess this is not possible with the OS-GUI drawn menus. Maybe you could take a look at https://wxpython.org/Phoenix/docs/html/wx.lib.agw.flatmenu.html and modify it accordingly.
score: 1

http://stackoverflow.com/q/47617512
accepted answer: http://stackoverflow.com/a/47617967
has comment: http://stackoverflow.com/comment/82193312
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82193455
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47617967
has title: Predicting availability on a bike station
answer count: 1
tagged with: machine-learning
tagged with: keras
has body: I finally decided to start learning ML, to do so I am trying to predict the availability of bikes of my city's public bike sharing system. Dataset (1MB) for one bike station. Columns: date, weekday, id, station, free_bikes, free_docks I've been following Machine Learning Mistery's tutorials with Keras, in this case one for multivariate time series forecasting LSTM, which I think is adequate for my problem. Currently, I am training the NN feeding it with: weekday(t-1), free_bikes(t-1) and free_bikes(t). The loss and val_loss graph I think looks good(ish). If I am not mistaken a RMSE of 0.9 is that I'll probably have an error or 1 bike when making predictions. If all that is correct I'll also like to give the NN the date the sample was taken but I run into some problems I don't know I can solve. Adding an extra column I get this kind of error: ValueError: operands could not be broadcast together with shapes (5949,2) (3,) (5949,2) To add the date into the problem I'll just delete the part on line 63 that says index_col = 0 when reading the file. Is it correct to add the date to improve the prediction and how should it be done? script

http://stackoverflow.com/comment/82321436
has text: Possible duplicate of [pandas: Extracting specific selected columns from a DataFrame to new DataFrame](https://stackoverflow.com/questions/34682828/pandas-extracting-specific-selected-columns-from-a-dataframe-to-new-dataframe)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47680732
type: Comment

http://stackoverflow.com/a/47609856
downvote count: 1
has comment: http://stackoverflow.com/comment/82188507
has body: Maybe this? from subprocess import check_output, CalledProcessError import sys def is_conda_managed(): try: out = check_output(['conda', 'env', 'list']).decode('utf-8') lines = (line for line in out.splitlines() if line[:1] != '#') roots = set(line.split()[-1] for line in lines if line.strip()) except CalledProcessError: roots = set() return sys.prefix in roots
type: Answer
has comment: http://stackoverflow.com/comment/82189687
score: 0
answers question: http://stackoverflow.com/q/47608532
upvote count: 1
has comment: http://stackoverflow.com/comment/82195030

http://stackoverflow.com/a/47596522
accepted answer of: http://stackoverflow.com/q/47596479
has comment: http://stackoverflow.com/comment/82150941
type: Answer
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82151024
has body: Use read_csv with StringIO: from pandas.compat import StringIO #if this doesn't work try: from io import StringIO df = pd.read_csv(StringIO(dfstr), sep='\s+') print (df) A B 0 one Aa 1 one Bb 2 two Cc 3 three Aa 4 one Bb 5 one Cc 6 two Aa 7 three Bb 8 one Cc 9 one Aa 10 two Bb 11 three Cc
score: 9
answers question: http://stackoverflow.com/q/47596479
upvote count: 9

http://stackoverflow.com/comment/82180901
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47610423
has text: @Sh1elds please see my answer below.
score: 0

http://stackoverflow.com/comment/82185308
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47613460
has text: Putting everything into one queue like that is very inefficient. Give each consumer its own queue!
score: 0

http://stackoverflow.com/q/47613897
favorite count: 0
type: AnsweredQuestion
has body: I came across the following statement: train_set_x.reshape(train_set_x.shape[0], -1).T The shape of train_set_x is: (209, 64, 64, 3) I thus believe that shape[0] is 209, and T is the transpose? I couldn't however understand the reshape statement above? What is -1? Any clarifications on that is very much appreciated. Thanks.
tagged with: python
has title: What does the parameter (..., -1) mean when reshaping an array?
type: Question
tagged with: numpy
score: 2
upvote count: 2
tagged with: arrays
tagged with: shapes
answer count: 1
downvote count: 0
tagged with: reshape
has answer: http://stackoverflow.com/a/47613905
accepted answer: http://stackoverflow.com/a/47613905

http://stackoverflow.com/q/47612058
has comment: http://stackoverflow.com/comment/82182759
accepted answer: http://stackoverflow.com/a/47613629
downvote count: 0
tagged with: equation
upvote count: 1
has comment: http://stackoverflow.com/comment/82182659
has answer: http://stackoverflow.com/a/47613629
possible better answer: http://stackoverflow.com/a/47612322
type: AnsweredQuestion
has body: Here's the problem: I am trying to solve a second order matricial equation of the form : Where X(to find) and C (known) are of sizes [nxn]. (n is on the order of 1000). C is a symmetric covariance matrix known. (and X should be symmetric too) Here is my code: from sympy import solve from sympy import Indexed, IndexedBase, Tuple import numpy as np X = IndexedBase('X',shape=(n,n)) eqs = Tuple(np.dot(X,X)-np.dot(C,X)-np.eye(n)) solve(eqs, X) Is it the right way to do it? My code is taking ages. I am looking for any type of algorithm that could help me solve this kind of equation efficiently.
has comment: http://stackoverflow.com/comment/82182583
tagged with: matrix
score: 1
tagged with: python
favorite count: 0
has title: Matrix Equation solver Python
type: Question
has answer: http://stackoverflow.com/a/47612322
has comment: http://stackoverflow.com/comment/82182544
answer count: 2
tagged with: sympy

http://stackoverflow.com/a/47639981
has comment: http://stackoverflow.com/comment/82251955
has comment: http://stackoverflow.com/comment/82241054
type: Answer
has body: The problem is that you are trying to run run_conversion without an object. run_conversion is a method of the class PyPDFOCR. So you will need an object of that class to run the method. Once you have made an PyPDFOCR object (for instance my_ocr), you should be able to write: newfile = my_ocr.run_conversion(filepath)
answers question: http://stackoverflow.com/q/47639233
has comment: http://stackoverflow.com/comment/82240703
score: 0

http://stackoverflow.com/comment/82208615
score: 0
type: AnswerComment
has text: your last approach was the fastest solution. It tooks about 15% of time less than the first one. Thanks.
type: Comment
comment on: http://stackoverflow.com/a/47595811

http://stackoverflow.com/comment/82290018
has text: this is exactly what he asked for, and even tho I shared a link to the documentation when it points out all it's side effects and if the module designer made an __all__ it won't make a mess, so why this down-vote? :T @jwodder
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47665367

pygobject
type: Tag
tags question: http://stackoverflow.com/q/47569017
tag name: pygobject

http://stackoverflow.com/q/47650465
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82259325
has comment: http://stackoverflow.com/comment/82259880
type: AnsweredQuestion
has body: I tried to do filtering for the extension field, which is actually not a field at all as the following example suggests. For the sake of this example, let's imagine we have a running Django with django-filer installed and some file already uploaded. &gt;&gt;&gt; from filer.models import File &gt;&gt;&gt; File.objects.all()[0].extension 'some_ext' # just as example But when trying to filter: &gt;&gt;&gt; File.objects.filter(extension='pdf') django.core.exceptions.FieldError: Cannot resolve keyword 'extension' into field. Choices are: _file_size, clipboarditem, description, downloadfilemodel, file, filer_image_file, folder, folder_id, has_all_mandatory_data, id, in_clipboards, is_public, modified_at, name, news_attachment, original_filename, owner, owner_id, polymorphic_ctype, polymorphic_ctype_id, sha1, uploaded_at This is because extension are not stored with the model but in fact are computed properties. My question: What's the rationale of not storing this meta data in the File Model. Update: I do not complain about the implementation. I ask for the possible motivation of the implementation.
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47651538
accepted answer: http://stackoverflow.com/a/47651538
tagged with: django-filer
has title: What's the rationale of using properties instead of fields within the File model of django-filer

http://stackoverflow.com/comment/82198310
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47618890
has text: please can you check it
type: Comment

http://stackoverflow.com/q/47549421
has comment: http://stackoverflow.com/comment/82058326
possible better answer: http://stackoverflow.com/a/47549482
downvote count: 1
has answer: http://stackoverflow.com/a/47550881
favorite count: 0
has body: I have a df, A B 0 a 1.0 1 b,c 2.0 2 3 c,d NaN I am trying to slice df["A"] when df["B"] is NaN or empty space " " , I failed in slicing it by (,) Please help me to achieve it, my desired output is, out_df, A B 0 a 1.0 1 b,c 2.0 2 3 c NaN
has comment: http://stackoverflow.com/comment/82055385
has comment: http://stackoverflow.com/comment/82055949
tagged with: data-analysis
type: Question
answer count: 2
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47549482
score: -1
has comment: http://stackoverflow.com/comment/82058198
has title: slicing a datacolumn based on a condition in pandas
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47550881

http://stackoverflow.com/comment/82277281
type: Comment
type: QuestionComment
has text: Could you explain why something like `{v: k for k, v in dict.iteritems()}` doesn't meet the requirements?
comment on: http://stackoverflow.com/q/47659197
score: 0

http://stackoverflow.com/q/47619007
type: Question
accepted answer: http://stackoverflow.com/a/47619776
has comment: http://stackoverflow.com/comment/82196788
type: AnsweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82197389
has comment: http://stackoverflow.com/comment/82196960
has title: Set pygame surface DPI
has comment: http://stackoverflow.com/comment/82197253
has answer: http://stackoverflow.com/a/47619776
has body: I am rendering Mandelbrot fractal on a pygame surface from a numpy array. When I generate a 10k px * 10k px image and save it using pylab in a 10 * 10 inch image with a 1000dpi I get a 10k pixels image which render pretty well when windows build in photo app display it with zoom ajustment. In pygame, the image looks pretty ugly although it is displayed with the same size : I'm using this code : pygame.init() display = pygame.display.set_mode((1000, 1000)) surf = pygame.surfarray.make_surface(gimage) surf = pygame.transform.rotate(surf, 90) surf = pygame.transform.scale(surf, (1000, 1000)) How would one set pygame image size and ajust DPI ?
answer count: 1
has comment: http://stackoverflow.com/comment/82197378
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/47614396
favorite count: 0

http://stackoverflow.com/comment/82085206
has text: `import imageio; im = imageio.imread('actin2.tif')`
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47563354

http://stackoverflow.com/q/47545513
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: qspinbox
type: UnansweredQuestion
has body: This is my sample code for QDoubleSpinBox of PyQt4. I got this code from the site and modified it. class PowerSpinBox(QtGui.QDoubleSpinBox): def __init__(self, min, max, step, decimals, dec_format, parent=None): super(PowerSpinBox, self).__init__(parent) self.setRange(min,max) self.step = step self.dec = decimals self.dec_fmt = '%.6E' self.setDecimals(decimals) def textFromValue(self, value): if value &gt;= 0: return ' %.6E'%value else: return '%.6E'%value def fixup(self, input): value = input.toDouble()[0] print '&gt;&gt;&gt; PowerSpinBox:fixup:', value, input, step, value%step if (value % self.step) &gt; 0: #self.step*0.1: # old: '&gt; 0:' if value &lt; 0: value=value*(-1) minus=True else: minus=False newValue = value # old: float((int(value*1000)/1)*1)/1000 if minus: newValue = newValue*(-1) newInput = '%.6E'%newValue # newInput: string if not minus: newInput = '+'+newInput print "Invalid value [%s] replaced with [%s]"%(input, newInput) QtGui.QApplication.beep() input.replace(0, input.length(), newInput) def validate(self, input, pos): valid = QtGui.QValidator.Invalid newChar = input.at(pos-1) # print '+++ PowerSpinBox.validate:', input, newChar, pos if pos &lt; 1: valid = QtGui.QValidator.Acceptable else: if not newChar.isDigit(): if ((newChar.cell() == '.') and (input.count('.') == 1)) or \ ((newChar.cell() == '-') and (pos == 1)) or \ ((newChar.cell() == '+') and (pos == 1)): valid = QtGui.QValidator.Acceptable else: valid = QtGui.QValidator.Invalid else: value = input.toDouble()[0] if (not (value &gt;= self.minimum() and value &lt;= self.maximum())) or \ (input.length() &gt; input.indexOf('.')+self.decimals()+6): valid = QtGui.QValidator.Invalid else: valid = QtGui.QValidator.Acceptable return (valid, pos) # class_PowerSpinBox In this example code, I want to control the value by stepsize of 1.0e-14. But I couldn't do that. How can I set the minimum value step to 1.0e-14 in QDoubleSpinBox of PyQt4. Thank you in advance.
tagged with: pyqt4
has title: How do I set the minimum value step to 1.0E-14 for QDoubleSpinBox in PyQt4?
tagged with: python
answer count: 0
downvote count: 0
tagged with: pyqt

http://stackoverflow.com/comment/82231776
comment on: http://stackoverflow.com/q/47636816
has text: In what was does it not work? Also, please fix your indentation .. if this is actually how your code is indented you have an empty`for` loop
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47638907
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47636810
has body: Using numpy, we have access to the poly1d object. With that, j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d is equivalent to: In [ ]: j, q, w, e, k, w, l, d = range(1, 9) ...: poly1 = j*np.poly1d([-q, -w, -e], r=1) ...: poly2 = k*np.poly1d([-w, -e], r=0) ...: poly3 = l*np.poly1d([-e]) ...: poly = poly1 + poly2 + poly3 + d ...: print(poly) 3 2 1 x + 12 x + 14 x + 8

http://stackoverflow.com/q/47579641
score: 4
upvote count: 4
has title: How to get "Client name:" of a perforce workspace using "p4 info" from python script?
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: I have a scenario where i need to have perforce workspace Client name information. Trying out with script as follows: import sys import subprocess cmd = "p4 info | grep" + """ "Client name" """ +"" print ("p4 command is: ",cmd) p4 = subprocess.call(cmd) print( p4) Where i get out put as : p4 command is: p4 info | grep "Client name" Usage: info [-s] Unexpected arguments. 1 I tried doing as follows too but did not worked: import sys import subprocess p4_info = subprocess.call([sys.executable, "p4 info | grep "Client name""]) I actually want to fetch only Client name information. So, suggest me how i may have that. If there is another way of doing it please suggest. The script will be executed within the workspace and shall return the only Client name:
favorite count: 0
type: Question
tagged with: perforce
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/47580676

http://stackoverflow.com/comment/82155626
type: AnswerComment
has text: can i define it in this way its write or wrong # Fitting K-Means to the dataset x = np.array([[15,39],[60,40],[87,27],[60,50],[72,34]]) kmeans = KMeans(n_clusters = 5, init =x, random_state = 42)
comment on: http://stackoverflow.com/a/47598626
type: Comment
score: 0

http://stackoverflow.com/comment/82144413
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47591650
has text: I would recommend not to use `tsplot` for a normal timeseries. See e.g. yesterday's [question](https://stackoverflow.com/questions/47578622/simple-tsplot-for-timeseries).
score: 3

http://stackoverflow.com/comment/82185491
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47613561
has text: Yea I have dimensions and variables listed elsewhere in my existing code. I wanted to know how to set up the rectangle with arrays so that I could create multiple at a time,

http://stackoverflow.com/q/47561443
tagged with: arrays
tagged with: python
has body: Need to compare each value inside a numpy array and return 1 to the largest value and 0 to the others. I am having problem with different numbers of []. Input Example: [[[0.6673975 0.33333233]] . . . [[0.33260247 0.6673975]]] Expected Output: [[[1 0]] . . . [[0 1]]]
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: n-dimensional
possible better answer: http://stackoverflow.com/a/47561769
has answer: http://stackoverflow.com/a/47561811
upvote count: 2
has title: comparing values in numpy array of n-dimension
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47561811
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82081140
has answer: http://stackoverflow.com/a/47561769

node.js
tags question: http://stackoverflow.com/q/47612518
tags question: http://stackoverflow.com/q/47572018
type: Tag
tags question: http://stackoverflow.com/q/47622102
tag name: node.js
tags question: http://stackoverflow.com/q/47546585
tags question: http://stackoverflow.com/q/47652769
tags question: http://stackoverflow.com/q/47616490

http://stackoverflow.com/a/47629722
answers question: http://stackoverflow.com/q/47629640
score: 1
downvote count: 0
upvote count: 1
has body: Do you want to iterate over the list elements in every value? If you don't use the key, you can use dict.values() directly: &gt;&gt;&gt; [option for v in info.values() for option in v] ['option1', 'option2', 'option3', 'option4', 'option5', 'option6', 'option7', 'option8', 'option9', 'option10', 'option11']
type: Answer

http://stackoverflow.com/comment/82346995
comment on: http://stackoverflow.com/a/47692552
score: 0
type: Comment
type: AnswerComment
has text: If you are using only two columns as mentioned, you can sum it straightaway, df.withColumn('sum1',df['`A.p1`']+df['`B.p1`']). But if there are many columns, can use UDF.

http://stackoverflow.com/q/47604132
has answer: http://stackoverflow.com/a/47604179
type: AnsweredQuestion
score: 3
tagged with: key-value
tagged with: list
has answer: http://stackoverflow.com/a/47604201
upvote count: 3
has comment: http://stackoverflow.com/comment/82167168
has answer: http://stackoverflow.com/a/47604366
has body: I have two python lists: keys=[1,2,2,3,2,3] values=['apple','book','pen','soccer','paper','tennis'] The "keys" are cluster ID list for the corresponding words in "values" list. I wish to print key-value pairs using keys=[1,2,2,3,2,3] values=['apple','book','pen','soccer','paper','tennis'] dictionary = dict(zip(keys, values)) for key, value in dictionary.items() : print (key, value) But it only prints 1 apple 2 paper 3 tennis What I actually want is to get all values for all keys like this 1 [apple] 2 [book,pen,paper] 3 [soccer,tennis] I know that my current code should logically print the first output as keys are unique. But how can I change it so that it will print all values for all keys? Thank you in advance!
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47604201
possible better answer: http://stackoverflow.com/a/47604181
has answer: http://stackoverflow.com/a/47604484
answer count: 5
has answer: http://stackoverflow.com/a/47604181
linked to: http://stackoverflow.com/q/33091911
downvote count: 0
has title: Python dictionary print all values for all keys
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47652027
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I would like the title in the legend of my matplotlib figure to be more distant from the content of the legend. Currently, I have the following: I see the set_title function of the Legend class accepts a prop dictionary, which should be the one described in the text properties page. This one contains the field bbox, where a pad property could be added. But when I try something like the following legend.set_title('Legend', prop={'bbox':{'pad':somepad}}) python complains that bbox is not an accepted parameter. I'm using matplotlib 2.1.0 under Python 3.6.3 on Arch Linux. An obvious workaround would be add a linebreak, like this: legend.set_title('Legend\n ') Although one might like the result, matplotlib has the great advantage that everything can be configured to the slightest detail, so I'm looking for a solution which gives me more fine-grained control over this spacing.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47653536
tagged with: legend
tagged with: python
has comment: http://stackoverflow.com/comment/82262661
tagged with: legend-properties
has title: Legend title pad in matplotlib
upvote count: 1
score: 1

http://stackoverflow.com/comment/82179826
type: AnswerComment
has text: That's an even better use case for exceptions. Have your callable accept an argument and return a value. Pass the output value from the previous iteration as the argument. If you need more details, I'd recommend asking another question for that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47606035

http://stackoverflow.com/comment/82089717
comment on: http://stackoverflow.com/q/47559323
type: Comment
type: QuestionComment
has text: are the labels in your plot the indices of of `u`
score: 0

http://stackoverflow.com/comment/82285389
comment on: http://stackoverflow.com/q/47663090
score: 3
has text: `UserGenerator.generateUser` => `UserGenerator().generateUser`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47642369
has comment: http://stackoverflow.com/comment/82246756
tagged with: android
tagged with: content-length
tagged with: python
has comment: http://stackoverflow.com/comment/82281296
has comment: http://stackoverflow.com/comment/82246788
possible better answer: http://stackoverflow.com/a/47642637
type: AnsweredQuestion
answer count: 2
score: 0
accepted answer: http://stackoverflow.com/a/47661264
has title: Received length differs from sent length
tagged with: httpurlconnection
has answer: http://stackoverflow.com/a/47661264
has body: I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this: URL url = new URL("http://foo.bar/blabla"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setDoOutput(true); conn.setFixedLengthStreamingMode(base64s.length()); OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(base64s.getBytes()); So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this: cl = cherrypy.request.headers['Content-Length'] rawbody = cherrypy.request.body.read() print "{} bytes, {}".format(len(rawbody), cl) The numbers cl and len(rawbody) are different. How can that be?
tagged with: cherrypy
type: Question
has answer: http://stackoverflow.com/a/47642637

http://stackoverflow.com/q/47590429
accepted answer: http://stackoverflow.com/a/47590985
tagged with: events
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47590985
has comment: http://stackoverflow.com/comment/82138626
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82138759
has body: As the question stated, I was wondering if there is any actual way to view the whole event queue at the end of runtime. I'm very new to pygame and the only 2 methods I'm familiar relating to events so far are: pygame.event.get() and pygame.event.poll(). Thing is, both of these method removes it's corresponding event in the queue - most likely to save space I assume. So that means I need to be able to print out the whole event at the very end of runtime, my code are as follows: import pygame pygame.init() screen = pygame.display.set_mode((500,300)) thing = 0 while thing &lt; 100000000: thing += 1 event = pygame.event.get() print (event) pygame.quit() The problem with this code is that whenever I try to move the pygame window, it became unresponsive and I wasn't able to interact with it, this happens every time I try to create a new pygame window, I'm able to click and move it around - but the moment I click the close button, the window unresponsive and I had to shut it down via the console. Is there a more effective alternative to do this?
has comment: http://stackoverflow.com/comment/82138815
has title: Pygame, are there any ways to view the entire event queue from a display?
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: 1

http://stackoverflow.com/a/47654331
has comment: http://stackoverflow.com/comment/82267068
accepted answer of: http://stackoverflow.com/q/47653808
type: AcceptedAnswer
has body: I happen to have the source for ctext (which is part of tklib) so I can let my Tcl library know about the additional package location using TCLLIBPATH environment variable. Then it can just be loaded. However, you will need to do some interfacing to python pat@uknml7167 ~ $ TCLLIBPATH=/opt/src/tklib/modules 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 tkinter as tk &gt;&gt;&gt; root = tk.Tk() &gt;&gt;&gt; root.tk.call('package','require','ctext') '3.3' So the short answer is 'yes'. There is a bit of an example for tkribbon on this site. I'm sure there are better examples of using a native Tk package around. A quick demo based on the above: class Ctext(tk.Widget): def __init__(self, master): tk.Widget.__init__(self, master, 'ctext') ctext = Ctext(root) ctext.pack(expand=True, fill='both') A tkinter wrapper class has been uploaded to github along with a small demo script.
answers question: http://stackoverflow.com/q/47653808
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82267230
type: Answer
has comment: http://stackoverflow.com/comment/82266859

http://stackoverflow.com/comment/82273434
type: Comment
comment on: http://stackoverflow.com/q/47609591
type: QuestionComment
has text: I mean more what is it actually? Have a read on how to create a [good example](https://stackoverflow.com/help/mcve). Basically need at least some bits of your actual data.
score: 0

http://stackoverflow.com/comment/82246287
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga Oh, I thought that were tabs to separate the fields but they are spaces. Thanks.
score: 0
comment on: http://stackoverflow.com/q/47643685

http://stackoverflow.com/q/47661633
tagged with: python
possible better answer: http://stackoverflow.com/a/47661794
type: Question
score: 0
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/47661794
tagged with: function
linked to: http://stackoverflow.com/q/43691803
upvote count: 1
has comment: http://stackoverflow.com/comment/82282353
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47662003
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47662003
has title: Check if letters from word are all in string Hangman
has body: I'm trying to create a simple hangman game in Python. I've come quite far for a beginner I guess :) The only thing I can't accomplish is checking wether the word is actually guessed. I need to check if all the letters are actually in a list I've created, yet I'm not sure how. I do realise there was a topic regarding this, this didn't help me tho. import random with open('randomlist.txt') as bestand: woordenlijst = bestand.read().splitlines() print("Welcome to Hangman.") naam = input("What is your name? ") print("Hello", naam, ", the computer selecter a secret word.") woord = random.choice(woordenlijst) lengte_woord = len(woord) ingevoerde_letters = [] galg = [] i = 0 print("The length of the word is: \n") while i &lt; lengte_woord: print("_", end=" ") i = i + 1 levens = 0 invoer = " " print(woord) while levens &lt;= 10: letter = input("Letter: ") if letter in ingevoerde_letters: print("You already tried this letter.") elif letter in woord: print("This letter is in the word. We'll fill it in for you.") i = 0 while i &lt; lengte_woord: if woord[i] == letter: print(letter, end=" ") ingevoerde_letters.append(letter) i = i + 1 elif woord[i] in ingevoerde_letters: print(woord[i], end=" ") i = i + 1 else: print("_", end=" ") i = i + 1 else: ingevoerde_letters.append(letter) print("This letter is not in the word", galg[levens]) levens = levens + 1 print(galg[10], "\nGame over!")
tagged with: words
has comment: http://stackoverflow.com/comment/82282419

http://stackoverflow.com/q/47567982
tagged with: package
has comment: http://stackoverflow.com/comment/82093984
tagged with: python
has body: I need to publish a development version of python package without affect current cases where latest version is used. after testing(for some reason can't test locally), will need to publish the development version as latest version. for example: current latest version is : 1.0 how should the dev version of package can be named. 1.0.dev or 1.1.dev or something else. (pip install) I want my dev version can only be install by "pip install packagename==version", not "pip install packagename"
type: Question
score: 0
has answer: http://stackoverflow.com/a/47568291
type: UnansweredQuestion
answer count: 1
tagged with: pip
has title: Publish python dev version of package

http://stackoverflow.com/a/47604244
downvote count: 0
upvote count: 1
has body: If the run() methods could return a boolean success value and each task should only be run if previous succeeded, then it could be done like: class Workflow(): def run(self, ): task_list = (Task1(), Task2(), Task3(), ...) success = all(t.run() for t in task_list)
type: Answer
has comment: http://stackoverflow.com/comment/82170408
has comment: http://stackoverflow.com/comment/82167270
answers question: http://stackoverflow.com/q/47604214
score: 1

http://stackoverflow.com/comment/82100822
comment on: http://stackoverflow.com/q/47571727
has text: you just need to write lines instead of _sum... and remember to joint the lines with newlines before wirting, something like `out.write('\n'.join(lines))`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47614867
type: Answer
has body: You have the basic idea down, just use one of the dataframes and the . method syntax to get the correct form: join = df.merge(df2, on="year")
answers question: http://stackoverflow.com/q/47614815
score: 0

http://stackoverflow.com/comment/82203564
has text: you can't pass keyword args to `input`, you can't pass multiple args to `input`. Just use `value = int(input("Please enter integer #" + str(n) + ": "))`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47622831
score: 0

http://stackoverflow.com/comment/82255876
comment on: http://stackoverflow.com/q/47648453
score: 0
has text: While you draw your shape, you can use facecolor="" and give the color value to it.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47572922
has body: It should be fine to use protocol buffers that are much larger than 1MB. We do it all the time at Google, and I wasn't even aware of the recommendation you're quoting. The main problem is that you'll need to deserialize the whole protocol buffer into memory at once, so it's worth thinking about whether your data is better off broken up into smaller items so that you only have to have part of the data in memory at once. If you can't break it up, then no worries. Go ahead and use a massive protocol buffer.
upvote count: 25
downvote count: 1
answers question: http://stackoverflow.com/q/47564437
type: Answer
score: 24

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

http://stackoverflow.com/comment/82290045
type: QuestionComment
comment on: http://stackoverflow.com/q/47665176
type: Comment
score: 0
has text: I mean ll_raw.dtypes

http://stackoverflow.com/comment/82143094
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47593000
type: Comment
has text: the speed cost is likely so nominal that you needn't ever worry about it in this case. With Python, you should usually go with the most readable option. Do "import this" in your Shell

http://stackoverflow.com/comment/82074594
type: AnswerComment
comment on: http://stackoverflow.com/a/47558267
has text: nice solution :)
type: Comment
score: 0

http://stackoverflow.com/comment/82084214
score: 0
type: AnswerComment
has text: you didn't say why it doesn't work - so I assumed you have it but you don't know have to use it. Install `Pillow` using `pip install pillow`
type: Comment
comment on: http://stackoverflow.com/a/47562405

http://stackoverflow.com/a/47719224
type: Answer
answers question: http://stackoverflow.com/q/47577505
score: 0
has body: The script does import pbr before running setup() so setup() was not given a chance to install pbr. The fix is to not import pbr before running setup(). See https://docs.openstack.org/pbr/latest/user/using.html: #!/usr/bin/env python from setuptools import setup setup( setup_requires=['pbr'], pbr=True, )

http://stackoverflow.com/comment/123865099
has text: REFER @Saji ANSWER, it'll help you solve the issue without destroying the database.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49525132

http://stackoverflow.com/comment/93757533
has text: I think it's important to add that passing `*args` and `**kwargs` to `__new__` instead of `__init__` isn't recommended. as Python 3.3+ will most likely throw an error if you do so.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47559606

http://stackoverflow.com/comment/82053138
type: Comment
has text: Also, the OP (probably) doesn't want to compare every pair of elements, so that double for loop is incorrect.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47548246

http://stackoverflow.com/q/47693934
possible better answer: http://stackoverflow.com/a/47693978
type: Question
has answer: http://stackoverflow.com/a/47693978
accepted answer: http://stackoverflow.com/a/47694001
has body: I am very new to python. I am trying to rename the columns of a data frame based on another dataframe. Essentially My data looks like DataFrame1 A B C D 1 2 3 4 I have another table that looks like this' DataFrame2 Col1 Col2 A E B Q C R D Z I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same. E Q R Z 1 2 3 4
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47694001
tagged with: pandas
type: AnsweredQuestion
answer count: 2
downvote count: 0
has title: Updating dataframe column names based on values given in another dataframe
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/47573824
answers question: http://stackoverflow.com/q/47573416
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: To me, it seems like the second example is also one where a generator object is created first. Is this correct? Yes, you're correct, checkout the CPython bytecode: &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis("*(thing for thing in thing),") 1 0 LOAD_CONST 0 (&lt;code object &lt;genexpr&gt; at 0x7f56e9347ed0, file "&lt;dis&gt;", line 1&gt;) 2 LOAD_CONST 1 ('&lt;genexpr&gt;') 4 MAKE_FUNCTION 0 6 LOAD_NAME 0 (thing) 8 GET_ITER 10 CALL_FUNCTION 1 12 BUILD_TUPLE_UNPACK 1 14 POP_TOP 16 LOAD_CONST 2 (None) 18 RETURN_VALUE Is there any difference between these expressions in terms of what goes on behind the scenes? In terms of performance? I assume the first and third could have latency issues while the second could have memory issues (as is discussed in the linked comments). My timings suggest the first 1 is slightly faster, presumably because the unpacking is more expensive via BUILD_TUPLE_UNPACK than the tuple() call: &gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; def f1(): tuple(thing for thing in range(100000)) ... &gt;&gt;&gt; def f2(): *(thing for thing in range(100000)), ... &gt;&gt;&gt; timeit(lambda: f1(), number=100) 0.5535585517063737 &gt;&gt;&gt; timeit(lambda: f2(), number=100) 0.6043887557461858 Comparing the first one and the last, which one is more pythonic? The first one seems far more readable to me, and also will work across different Python versions.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47573416

http://stackoverflow.com/a/47633568
has comment: http://stackoverflow.com/comment/82255063
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47632209
has body: Vimscript You're looking for the shellescape() function. If you use the :! Vim command, the {special} argument needs to be 1. silent execute '!tmux send-keys -t 0 -l ' . shellescape(cmd, 1) But as you're not interested in (displaying) the shell output, and do not need to interact with the launched script, I would switch from :! to the lower-level system() command. call system('tmux send-keys -t 0 -l ' . shellescape(cmd)) Python The use of Python (instead of pure Vimscript) doesn't have any benefits (at least in the small snippet in your question). Instead, if you embed the Python cmd variable in a Vimscript expression, now you also need a Python function to escape the value as a Vimscript string (something like '%s'" % str(cmd).replace("'", "''"))). Alternatively, you could maintain the value in a Vim variable, and access it from Python via vim.vars.
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47632209
has comment: http://stackoverflow.com/comment/82254236
has comment: http://stackoverflow.com/comment/82253972
type: Answer
score: 4

http://stackoverflow.com/comment/82224430
comment on: http://stackoverflow.com/q/47630640
type: Comment
type: QuestionComment
score: 0
has text: problem is you use `while` inside `for`. Inside `for` every object has to do only small step - it will only need `if` to check object position. And `for` should be inside some `while` loop which have to somehow check if it still need to execute `for` to move objects with small step.

http://stackoverflow.com/a/78514045
score: 0
answers question: http://stackoverflow.com/q/47632855
has body: It is generally a good practice to close the file after you're done reading or writing to it using the json.load function in Python. However, Python has a built-in mechanism called the "context manager protocol" that automatically takes care of closing the file for you, so it's not strictly necessary to close the file manually in this case. When you use the with statement along with the open() function, it automatically closes the file for you when you're done with it, even if an exception occurs during the execution of the code block inside the with statement. This is known as the "try-finally" behavior of context managers. Here's an example of how you can use json.load with the with statement: import json with open('data.json', 'r') as file: data = json.load(file) # Do something with the data print(data) In this example, the with statement automatically takes care of closing the file after the json.load function has finished reading the contents of the file. If you don't use the with statement, then it's your responsibility to close the file manually using the close() method after you're done with it, like this: import json file = open('data.json', 'r') data = json.load(file) file.close() # Do something with the data print(data) In this case, it's necessary to call file.close() to close the file and release the system resources associated with it. It's still a good practice to use the with statement to ensure that the file is properly closed, even in the presence of exceptions.
type: Answer

http://stackoverflow.com/comment/82332991
has text: @J.New glad to help!
type: Comment
comment on: http://stackoverflow.com/a/47686498
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82129057
type: Comment
type: QuestionComment
has text: Placing a few `print`s to check if the variables contain the expected results (or using a debugger instead) is generally helpful
score: 0
comment on: http://stackoverflow.com/q/47585688

http://stackoverflow.com/comment/136958006
comment on: http://stackoverflow.com/a/47657006
score: 1
type: Comment
type: AnswerComment
has text: @Alice - thank you, code was changed.

http://stackoverflow.com/comment/82332635
has text: Thank you, I could not have figured that out.
comment on: http://stackoverflow.com/a/47636062
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47564412
answers question: http://stackoverflow.com/q/47559295
has body: Got it! You can't use just a key for Directory API queries, you need a Service account. I'm using google-auth (see here) since oauth2client is deprecated. You also need to: Delegate the necessary permissions for your service account (mine has the role of Viewer and has scope access to https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly) Delegate API access to it separately in the Admin Console (Security -&gt; Advanced Settings -&gt; Authentication) Get your json client secret key and place it with your app (don't include it in your VCS) Obtain your credentials like this: credentials = service_account.Credentials.from_service_account_file( settings.CLIENT_KEY, scopes=settings.SCOPES, subject=settings.ADMIN_USER) where ADMIN_USER is the email address of an authorized Domain admin. Then you send a GET request like so: authed_session = AuthorizedSession(credentials) response = authed_session.get(request_id_url) This returns a Requests object you can read via response.content. Hope it helps someone else!
score: 0
type: Answer

http://stackoverflow.com/q/47579387
upvote count: 0
has body: Suppose that I have a table like this: CustomerID | Customer Name | Category | Price A1 Name1 Cat1 10 A2 Name2 Cat2 20 B1 Name3 Cat1 40 A1 Name1 Cat2 50 A2 Name2 Cat2 5 I want to group and sort this dataframe according to CustomerID and Sum of Price for each Customer as the each group will be grouped and sorted by Category, like this: CustomerID | Customer Name | Category | Price | A1 Name1 Cat2 50 Cat1 10 B1 Name2 Cat1 40 A2 Name2 Cat2 25 df.groupby(["Customer ID", "Customer Name", "Category"]).apply(lambda x: x['PRICE'].sum()).reset_index(name="Sum").sort_values(by="Customer ID",ascending=False) this code that i wrote doesn't work.
answer count: 1
has comment: http://stackoverflow.com/comment/82116037
downvote count: 1
favorite count: 0
has title: Trying to group and order with pandas
type: Question
has comment: http://stackoverflow.com/comment/82116121
has answer: http://stackoverflow.com/a/47579563
has comment: http://stackoverflow.com/comment/82116081
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: pandas

http://stackoverflow.com/comment/82337651
comment on: http://stackoverflow.com/q/47688696
type: Comment
has text: where's that code?
type: QuestionComment
score: 0

http://stackoverflow.com/q/47646312
score: 3
answer count: 2
tagged with: many-to-many
tagged with: pandas
upvote count: 3
tagged with: relationship
downvote count: 0
accepted answer: http://stackoverflow.com/a/47646579
has comment: http://stackoverflow.com/comment/82251542
favorite count: 0
has answer: http://stackoverflow.com/a/47646579
type: Question
has answer: http://stackoverflow.com/a/47656184
has title: group all directly and indirectly related records using python pandas
has body: thanks in advance: I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities: Example dataframe below: (parent (p), and child (c)) df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]])) df.columns= ['p', 'c'] Table looks like below: p c 1 7 1 3 1 4 3 2 5 1 6 0 I am trying to get all directly and indirectly linked records in a group. For example: Parent Record 1 is parent of [7,3,4], and Parent Record 5 is the parent of 1 Parent Record 3 has is parent of 2 and 2 is grand-child of 1 So I want to generate an ID for all related record. where parent record 6 is not related to any record, I will move it to another group, a sample result like below: p c grp 1 7 A 1 3 A 1 4 A 3 2 A 5 1 A 6 0 B My current way of thinking : For each record, if it doesn't have a group yet: Getting all directly related record IDs Then for each directly related record IDs Recursively perform the same function to find all related record for the child until they have no child record Then assign a group to the group of record IDs (list) I am not sure if it is the right way to do it, and it seemed to be unnecessarily slow, and I have to pass down all the parent records in the chain to the child record in order for it not to perform the same search for already searched results. Would really appreciate if someone can give me a better solution. :)
tagged with: python
possible better answer: http://stackoverflow.com/a/47656184
type: AnsweredQuestion

http://stackoverflow.com/q/47579701
tagged with: python
has title: sqlalchemy filter table valued function
type: AnsweredQuestion
downvote count: 0
tagged with: sql
score: 1
upvote count: 1
answer count: 1
tagged with: orm
tagged with: sqlalchemy
has body: If I have a table valued function, so that the SQL looks like: SELECT a, b FROM tvf(c, d) where e = 3 Is it possible to express this in sqlalchemy without using raw strings? select([column['name']]).select_from(func.func_name(*vars)) Gives me the above minus the were clause, but I can't find a way to put the where clause in anywhere. func.funcname(*args).filter(column["colname"]=="val"] gives a filterfunc instance, which I don't think is what I want filtering the outer expression gives ("select object has no attribute filter")
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47579855
accepted answer: http://stackoverflow.com/a/47579855

http://stackoverflow.com/comment/82043606
comment on: http://stackoverflow.com/q/47543262
type: Comment
type: QuestionComment
has text: Are you aware that the only line that's actually inside the loop is `doc = open(arg, "r")`? Everything after that is outside the loop.
score: 5

http://stackoverflow.com/comment/82382622
has text: You are welcome. May you mark this question answered?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47690404

http://stackoverflow.com/a/47560341
type: Answer
score: -7
upvote count: 1
has comment: http://stackoverflow.com/comment/82100597
has comment: http://stackoverflow.com/comment/101869980
has body: Production-grade Machine Learning pipelines have CPU utilisations more like this, almost 24 / 7 / 365: Check both the CPU% and also other resources' state figures across this node. What is my mistake? The problem is deeply determined by a respect to elementary Computer Science + algorithm rules. The problem is not demanding a strong scientific background, but a common sense. The problem is not any especially Big Data but requires to sense how the things actually work. Facts or emotions? ... that's the question! ( The tragedy of Hamlet, Prince of Denmark ) Next, the toys, the architecture, Resources and Process-scheduling facts that matter: The imperative form of a syntax-constructor ignites an immense amount of activities to start: joblib.Parallel( n_jobs = <N> )( joblib.delayed( <aFunction> ) ( <anOrderedSetOfFunParameters> ) for ( <anOrderedSetOfIteratorParams> ) in <anIterator> ) To at least guess what happens, a scientifically fair approach would be to test several representative cases, benchmarking their actual execution, collect quantitatively supported facts and draw a hypothesis on a model of behaviour and its principal dependencies on CPU_core-count, on RAM-size, on <aFunction>-complexity and resources-allocation envelopes etc. Test case A: def a_NOP_FUN( aNeverConsumedPAR ): """ __doc__ The intent of this FUN() is indeed to do nothing at all, so as to be able to benchmark all the process-instantiation add-on overhead costs. """ pass ############################################################## ### A NAIVE TEST BENCH ############################################################## from zmq import Stopwatch; aClk = Stopwatch() JOBS_TO_SPAWN = 4 # TUNE: 1, 2, 4, 5, 10, .. RUNS_TO_RUN = 10 # TUNE: 10, 20, 50, 100, 200, 500, 1000, .. try: aClk.start() joblib.Parallel( n_jobs = JOBS_TO_SPAWN )( joblib.delayed( a_NOP_FUN ) ( aSoFunPAR ) for ( aSoFunPAR ) in range( RUNS_TO_RUN ) ) except: pass finally: try: _ = aClk.stop() except: _ = -1 pass print( "CLK:: {0:_>24d…
downvote count: 8
answers question: http://stackoverflow.com/q/47551850

http://stackoverflow.com/q/47689007
has answer: http://stackoverflow.com/a/47689258
upvote count: 4
tagged with: python-2.7
has title: face_recognition.load_image_file("{}"), what does it mean?
tagged with: face-detection
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/82337259
score: 1
favorite count: 0
tagged with: python-3.x
has body: I'm newbie in python. Now I'm working with python related project. I saw following code while I am searching in google related to project. image = face_recognition.load_image_file("{}") What does "{}" do inside load_image_file() function? Also, When and where should I use it?
accepted answer: http://stackoverflow.com/a/47689173
type: Question
has comment: http://stackoverflow.com/comment/82337159
answer count: 2
has answer: http://stackoverflow.com/a/47689173
possible better answer: http://stackoverflow.com/a/47689258
tagged with: python

pixel
tags question: http://stackoverflow.com/q/47582033
type: Tag
tag name: pixel
tags question: http://stackoverflow.com/q/47549699

http://stackoverflow.com/q/47651628
has comment: http://stackoverflow.com/comment/82304544
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64301391
has answer: http://stackoverflow.com/a/74027762
has comment: http://stackoverflow.com/comment/82261560
score: 1
accepted answer: http://stackoverflow.com/a/47651869
has title: Tkinter quit freezes
answer count: 4
type: Question
possible better answer: http://stackoverflow.com/a/64301391
has answer: http://stackoverflow.com/a/68336457
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82261448
has comment: http://stackoverflow.com/comment/82274447
upvote count: 2
has body: I have written a very simple snippet of code just to try tkinter: import tkinter as tk root=tk.Tk() frame = tk.Frame(root).pack() button = tk.Button(frame, text="next", command=root.quit).pack() root.mainloop() The above code causes the window to freeze. Could someone explain to me what is the reason behind this behaviour?
tagged with: python
linked to: http://stackoverflow.com/q/47619074
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47651869

http://stackoverflow.com/q/47662692
has title: How can I display the version of my Jupyter notebook and run cells in Jupyter notebooks? I get an error: bad interpreter
has comment: http://stackoverflow.com/comment/82284778
tagged with: python
score: 42
tagged with: kernel
has comment: http://stackoverflow.com/comment/82284791
tagged with: jupyter-notebook
upvote count: 42
type: AnsweredQuestion
answer count: 3
has body: I have installed Anaconda and I use the conda environments and the conda command to install software. When I type: jupyter notebook --version I get the following error: zsh: /Users/cr517/.local/bin/jupyter: bad interpreter: /Users/cr517/anaconda/envs/snakes/bin/python: no such file or directory 5.2.1 I can open a jupyter notebook by typing: jupyter notebook xyz.ipynb but I cannot run any cells. The cell is marked with * after I run it. Soon, this message appears in a pop-up box: The kernel has died, and the automatic restart has failed. It is possible the kernel cannot be restarted. If you are not able to restart the kernel, you will still be able to save the notebook, but running code will no longer work until the notebook is reopened. I get this in the terminal after opening a jupyter notebok: zsh: /Users/cr517/.local/bin/jupyter: bad interpreter: /Users/cr517/anaconda/envs/snakes/bin/python: no such file or directory [I 21:01:55.558 NotebookApp] JupyterLab alpha preview extension loaded from /Users/cr517/anaconda/lib/python3.6/site-packages/jupyterlab [I 21:01:55.558 NotebookApp] JupyterLab application directory is /Users/cr517/anaconda/share/jupyter/lab [I 21:01:55.564 NotebookApp] Serving notebooks from local directory: /Users/cr517/Documents/teach/demonstrations/python/python-functions-and-modules-master [I 21:01:55.564 NotebookApp] 0 active kernels [I 21:01:55.564 NotebookApp] The Jupyter Notebook is running at: [I 21:01:55.564 NotebookApp] http://localhost:8888/?token=0a0b3368be051aceea02ddfdb677ba5b48724f050e78fa59 [I 21:01:55.564 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 21:01:55.584 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=0a0b3368be051aceea02ddfdb677ba5b48724f050e78fa59 [I 21:01:55.852 NotebookApp] Accepting one-time-token-authenticated connection from ::1 [I 21:01:57.808 NotebookApp] Kernel st…
possible better answer: http://stackoverflow.com/a/51641071
downvote count: 0
has answer: http://stackoverflow.com/a/48002648
has answer: http://stackoverflow.com/a/51641071
accepted answer: http://stackoverflow.com/a/49755839
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49755839
tagged with: anaconda

http://stackoverflow.com/a/47584953
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82146529
answers question: http://stackoverflow.com/q/47581326
type: Answer
has comment: http://stackoverflow.com/comment/82146673
upvote count: 2
has body: Here's my answer: from timeit import timeit from collections import Counter import types import random def setup_data(n): digits = "0123456789" return dict(text = ''.join(random.choice(digits) for i in range(n))) def f_counter(text): c = Counter() for i in range(len(text)-2): ss = text[i:i+3] c.update([ss]) return (i for i in c.items() if i[1] &gt; 1) def f_dict(text): d = {} for i in range(len(text)-2): ss = text[i:i+3] if ss not in d: d[ss] = 0 d[ss] += 1 return ((i, d[i]) for i in d if d[i] &gt; 1) def f_array(text): a = [[[0 for _ in range(10)] for _ in range(10)] for _ in range(10)] for n in range(len(text)-2): i, j, k = (int(ss) for ss in text[n:n+3]) a[i][j][k] += 1 for i, b in enumerate(a): for j, c in enumerate(b): for k, d in enumerate(c): if d &gt; 1: yield (f'{i}{j}{k}', d) for n in (1E1, 1E3, 1E6): n = int(n) data = setup_data(n) print(f'n = {n}') results = {} for name, func in list(globals().items()): if not name.startswith('f_') or not isinstance(func, types.FunctionType): continue print("{:16s}{:16.8f} ms".format(name[2:], timeit( 'results[name] = f(**data)', globals={'f':func, 'data':data, 'results':results, 'name':name}, number=10)*100)) for r in results: print('{:10}: {}'.format(r, sorted(list(results[r]))[:5])) The array lookup method is very fast (even faster than @paul-panzer's numpy method!). Of course, it cheats since it isn't technicailly finished after it completes, because it's returning a generator. It also doesn't have to check every iteration if the value already exists, which is likely to help a lot. n = 10 counter 0.10595780 ms dict 0.01070654 ms array 0.00135370 ms f_counter : [] f_dict : [] f_array : [] n = 1000 counter 2.89462101 ms dict 0.40434612 ms array 0.00073838 ms f_counter : [('008', 2), ('009', 3), ('010', 2), ('016', 2), ('017', 2)] f_dict : [('008', 2), ('009', 3), ('010', 2), ('016', 2), ('017', 2)] f_array : [('008', 2), ('009', 3), ('010', 2), ('016', 2), ('017', 2)] n = 1000000 counter 2849.00500992 ms dict 438.44007…
has comment: http://stackoverflow.com/comment/82145811

http://stackoverflow.com/a/47704546
has body: You might want to check out the MultiSplitterWindow widget: https://wxpython.org/Phoenix/docs/html/wx.lib.splitter.MultiSplitterWindow.html It allows you to have more than two windows in a splitter window widget. I actually wrote a bit about the various splitter windows that wxPython supports over on my blog, so you might want to check that out too. Anyway, here is a simple example that uses that widget: import wx from wx.lib.splitter import MultiSplitterWindow class SplitterPanel(wx.Panel): def __init__(self, parent, color): """Constructor""" wx.Panel.__init__(self, parent) main_sizer = wx.BoxSizer(wx.VERTICAL) splitter = MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE) for col in range(3): panel = wx.Panel(splitter, size=(200, 200)) panel.SetBackgroundColour(color) splitter.AppendWindow(panel) main_sizer.Add(splitter, 1, wx.ALL|wx.EXPAND) self.SetSizer(main_sizer) class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title='Splitters') panel = wx.Panel(self) main_sizer = wx.BoxSizer(wx.VERTICAL) splitter_panel = SplitterPanel(panel, color='blue') main_sizer.Add(splitter_panel, 1, wx.ALL|wx.EXPAND) splitter_panel_two = SplitterPanel(panel, color='red') main_sizer.Add(splitter_panel_two, 1, wx.ALL|wx.EXPAND) panel.SetSizer(main_sizer) self.Show() if __name__ == '__main__': app = wx.App(False) frame = MainFrame() app.MainLoop()
type: Answer
answers question: http://stackoverflow.com/q/47636985
score: 0

http://stackoverflow.com/comment/82323985
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47682356
has text: Please count the number of spaces at the start of `x = input(...)` and the number of spaces at the start of `while invalid:`. What are those counts?
score: 0

http://stackoverflow.com/comment/82200270
comment on: http://stackoverflow.com/q/47620895
type: Comment
type: QuestionComment
has text: @ahed87 can you enlighten me with some sample code?
score: 0

http://stackoverflow.com/comment/82121456
type: Comment
has text: @hawkia that should not be happening, it works fine on mine. [os.walk](https://docs.python.org/2/library/os.html#os.walk) returns 3 tuples. Can you paste the code you tried?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47562022

http://stackoverflow.com/q/47570307
upvote count: 23
has answer: http://stackoverflow.com/a/47570754
tagged with: scikit-learn
tagged with: python
accepted answer: http://stackoverflow.com/a/47570754
type: AnsweredQuestion
has title: Tuning parameters of the classifier used by BaggingClassifier
downvote count: 0
score: 23
has body: Say that I want to train BaggingClassifier that uses DecisionTreeClassifier: dt = DecisionTreeClassifier(max_depth = 1) bc = BaggingClassifier(dt, n_estimators = 500, max_samples = 0.5, max_features = 0.5) bc = bc.fit(X_train, y_train) I would like to use GridSearchCV to find the best parameters for both BaggingClassifier and DecisionTreeClassifier (e.g. max_depth from DecisionTreeClassifier and max_samples from BaggingClassifier), what is the syntax for this?
favorite count: 0
has answer: http://stackoverflow.com/a/54478502
type: Question
possible better answer: http://stackoverflow.com/a/54478502
answer count: 2

http://stackoverflow.com/comment/82333608
comment on: http://stackoverflow.com/q/47659318
has text: the command window shows "'import' is not recognized as an internal or external command,operable program or batch file. " Is there any other way?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82082732
score: 2
has text: Welcome to Stackoverflow, please read [How To Ask](https://stackoverflow.com/help/how-to-ask). Pay special attention to [How To Create MCVE](https://stackoverflow.com/help/mcve). The more effort you'll put into posting a good question: one which is easy to read, understand and which is [on topic](https://stackoverflow.com/help/on-topic) - the chances are higher that it will attract the relevant people and you'll get help even faster. Good luck!
comment on: http://stackoverflow.com/q/47562455
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47606422
type: AnsweredQuestion
score: 0
tagged with: django-allauth
has body: Django-allauth package creates a model SocialAccount, with a ForeignKey to User. I can't manage to prefetch this information in my queryset. My model: class Placerating(models.Model): author = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL) Django-allauth model: class SocialAccount(models.Model): user = models.ForeignKey(allauth.app_settings.USER_MODEL, on_delete=models.CASCADE) When I try to prefetch this data: rating = Placerating.objects.all().prefetch_related('author__socialaccount') I get the following error message: AttributeError: Cannot find 'socialaccount' on User object, 'author__socialaccount' is an invalid parameter to prefetch_related() Any clue ? Thanks!
has title: How to prefetch SocialAccount with django-allauth?
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/53042734
accepted answer: http://stackoverflow.com/a/53042734
tagged with: django
tagged with: python
tagged with: prefetch

http://stackoverflow.com/comment/82120296
comment on: http://stackoverflow.com/q/47581167
score: 0
type: Comment
type: QuestionComment
has text: Of course, but it was not escaped before Django 1.10.

solver
tags question: http://stackoverflow.com/q/47556668
tag name: solver
type: Tag

http://stackoverflow.com/q/47584535
tagged with: python
has title: Returning count of more persons
has body: I am new in python and I have problem in my code. My function count_transitive_sellers_with_degree is returning count only from person sellers. I need to get it return count of person sellers and seller sellers and so on. I do not know how to write it.. Could you help me and say where it is a problem? Thank you :) class Person: def __init__(self, name, year_of_birth, degree): self.name = name self.year_of_birth = year_of_birth self.degree = degree self.leader = None self.sellers = [] def create_leadership(leader, seller): seller.leader = leader leader.sellers.append(seller) def count_transitive_sellers_with_degree(person, degree): count = 0 for seller in person.sellers: if seller.degree == degree: count += 1 + count_transitive_sellers_with_degree(seller,degree) return count &gt;&gt;&gt; martin = Person('Martin', 1991, 'phd') &gt;&gt;&gt; tom = Person('Tom', 1993, 'mgr') &gt;&gt;&gt; josh = Person('Josh', 1995, 'bc') &gt;&gt;&gt; create_leadership(martin, tom) &gt;&gt;&gt; create_leadership(tom, josh) &gt;&gt;&gt; count_transitive_sellers_with_degree(martin, 'bc') what it should write... -> 1 what it is writing now... -> 0
has answer: http://stackoverflow.com/a/47584563
answer count: 3
has answer: http://stackoverflow.com/a/47584597
has answer: http://stackoverflow.com/a/47584561
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82126677
has comment: http://stackoverflow.com/comment/82126720
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47622356
has answer: http://stackoverflow.com/a/47623287
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has body: I am getting the following error when I tried to install pyglet: $ conda install -c conda-forge pyglet Fetching package metadata ............. Solving package specifications: . UnsatisfiableError: The following specifications were found to be in conflict: - pyglet -&gt; python 3.5* -&gt; xz 5.0.5 - python 3.6* Use "conda info &lt;package&gt;" to see the dependencies for each package.
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: pyglet installation error in anaconda (python 3.6)
tagged with: anaconda
tagged with: pyglet
accepted answer: http://stackoverflow.com/a/47623287
tagged with: python

http://stackoverflow.com/comment/82213997
type: AnswerComment
comment on: http://stackoverflow.com/a/47628168
type: Comment
has text: getting error saying - Invalid field name(s) given in select_related: 'productimages_set', 'productcolor_set'. Choices are: category, sub_category
score: 0

http://stackoverflow.com/q/47545219
has comment: http://stackoverflow.com/comment/82047314
has body: When I code: x = 4 y = 10 print("X is", x, "and Y is", y) I get as a result: ('X is', 4, 'and Y is', 10) Instead of: X is 4 and Y is 10 Why is this happening? Please help.
has title: print statement comma acting weird in python
has comment: http://stackoverflow.com/comment/82047305
tagged with: python
linked to: http://stackoverflow.com/q/6182964
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82047331
has answer: http://stackoverflow.com/a/47545242
answer count: 2
tagged with: printing
has comment: http://stackoverflow.com/comment/82047487
accepted answer: http://stackoverflow.com/a/47545256
possible better answer: http://stackoverflow.com/a/47545242
has answer: http://stackoverflow.com/a/47545256
type: AnsweredQuestion

http://stackoverflow.com/q/47596837
has body: I need to have ten counters that I update in a loop if certain conditions are met. My normal approach would be to create a list of 10 elements and update the elements of this list. Dummy example: my_counters = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(100000): if condition1: my_counters[0] += 1 my_counters[4] += 1 elif condition2: my_counters[2] += 1 my_counters[8] += 1 ... However this appears to be bad and inefficient code, which I don't really know why. So I'd like to know what would be the best approach for this simple issue. Of course I have some suggestions: 1) Using one variable for each counter CONS: Too many variables, what if I need 100 counters? 2) Using a numpy array instead of a list (would then it be considered good and efficient code?) 3) Use a dictionary: This way each variable can have a representative name, but wouldn't the hash make the access slower than an index? What is the correct way of solving this problem? And also, why is updating elements of a list inneficient? Shouldn't the address be immediate to calculate? Base address + offset Thanks
has comment: http://stackoverflow.com/comment/82151945
tagged with: list
tagged with: performance
has title: Updating list elements is slow
has comment: http://stackoverflow.com/comment/82151656
has comment: http://stackoverflow.com/comment/82152672
answer count: 0
has comment: http://stackoverflow.com/comment/82151639
has comment: http://stackoverflow.com/comment/82151816
has comment: http://stackoverflow.com/comment/82151747
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82151579
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82152482
has comment: http://stackoverflow.com/comment/82151618
type: UnansweredQuestion
tagged with: counter
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82195012
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47618096
has text: I revieve the following terminal error "skipping ObsID {} as it was not found on archive site"
type: Comment

http://stackoverflow.com/a/47670658
has comment: http://stackoverflow.com/comment/82300801
has comment: http://stackoverflow.com/comment/82301069
answers question: http://stackoverflow.com/q/47669683
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: I think what you are looking for is NumPy broadcasting. import numpy as np x = np.array([[0, 1], [1, 1], [2, 2]]) rowsum = x.sum(axis=1) x[rowsum &lt;= 2] Gives: array([[0, 1], [1, 1]]) The problem is that you used keepdims=True, which means the sum creates a column vector, rather than a rank one array which can be broadcasted.

http://stackoverflow.com/comment/82202151
type: QuestionComment
comment on: http://stackoverflow.com/q/47622065
has text: do you have numpy or pandas installed?
score: 0
type: Comment

http://stackoverflow.com/comment/82221382
type: AnswerComment
has text: Yeah, I have a laptop (windows), a mac (macos) and a raspberry pi(linux) so almost every os to test. Thx again!
comment on: http://stackoverflow.com/a/47631694
type: Comment
score: 0

http://stackoverflow.com/comment/82117810
comment on: http://stackoverflow.com/q/47575979
has text: Any other thoughts on this, its driving me insane
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82299141
has text: It's possible because of the "continue" statement
comment on: http://stackoverflow.com/q/47670089
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47586200
has comment: http://stackoverflow.com/comment/82130619
has comment: http://stackoverflow.com/comment/82130707
has comment: http://stackoverflow.com/comment/82130520
has comment: http://stackoverflow.com/comment/82130287
accepted answer of: http://stackoverflow.com/q/47586162
has comment: http://stackoverflow.com/comment/82130315
type: AcceptedAnswer
has body: Possible duplicate of this question. You have to flush the file after each write function call: f.flush() To avoid this, you can open the file using with, this ensures the file is closed: with open('file.txt', 'w') as f: f.write('some text')
answers question: http://stackoverflow.com/q/47586162
has comment: http://stackoverflow.com/comment/82130048
has comment: http://stackoverflow.com/comment/82130175
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82130545
has comment: http://stackoverflow.com/comment/82130379
has comment: http://stackoverflow.com/comment/82130200
has comment: http://stackoverflow.com/comment/82130493
has comment: http://stackoverflow.com/comment/82130635

http://stackoverflow.com/a/47679364
downvote count: 0
has comment: http://stackoverflow.com/comment/82317954
has body: A simple solution would be agg pd.unique i.e df = pd.DataFrame({'x' : 'v','w','x','v','x'}) df['x'].agg(pd.unique) # Also np.unique 0 [v, w, x] Name: x, dtype: object or df['x'].agg(set).agg(list) 0 [v, w, x] Name: x, dtype: object
answers question: http://stackoverflow.com/q/47678961
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82318079
upvote count: 2

http://stackoverflow.com/q/47622542
answer count: 1
tagged with: python
tagged with: matplotlib-basemap
type: Question
tagged with: python-3.x
has title: Set Basemap meridians or parallels labels within plot or change color of text
type: UnansweredQuestion
has body: I am making a map with Basemap in python and I'd like for the meridians/parallels to be either inside the plot or for the text (i.e. 0˚N) to be white. I want to do this so that I can set the figure against a black background but still read the axes. This is what I have: # plot lines of longitudes m.drawparallels(np.arange(-90.,120.,1),labels=[1,1,1,1]) # plot latitudes m.drawmeridians(np.arange(-180.,180,1),labels=[1,0,0,1]) and in case it helps here's the basemap instance and packages used: m = Basemap(resolution=None, # c, l, i, h, f or None projection='merc', llcrnrlon=33.795774, llcrnrlat=-6.182035, urcrnrlon=34.6000037, urcrnrlat=6.236179,epsg=5520) import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap But it sets the labels outside the map and they're black.
has answer: http://stackoverflow.com/a/47655435
tagged with: plot
score: 0
tagged with: matplotlib

http://stackoverflow.com/a/65293679
answers question: http://stackoverflow.com/q/47646154
has comment: http://stackoverflow.com/comment/115435629
has body: You can try: turtle.pensize.width() It worked for me.
type: Answer
score: 0

http://stackoverflow.com/comment/82116934
type: AnswerComment
has text: @MarcelKlockman my answer also covers all values of n in the second part. Since you edited your question, I also removed the first part of my answer.
comment on: http://stackoverflow.com/a/47578583
type: Comment
score: 0

http://stackoverflow.com/comment/82190700
has text: You want to append `{44:'paes'}` as {1: [{45:'ades'}, {44:'paes'}]} ?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47616191

http://stackoverflow.com/comment/82060132
comment on: http://stackoverflow.com/a/47551485
type: AnswerComment
has text: It gives the following output: '3d\n', '.com\n', '3d\n', 'SQL\n', 'A\n', 'AR\n', 'Application\n', 'CA\n', 'College\n', 'EB\n', 'IE\n', 'India\n', 'LAR\n', 'Management System\n', 'R\n', 'SQL\n', 'System\n', 'VM\n', 'X\n', '\n'
score: 0
type: Comment

http://stackoverflow.com/comment/82321160
type: AnswerComment
type: Comment
has text: So weird, I guess my program wasn't using a proxy when I set up the proxyDict, which leads to the question, "Why do so many other questions related to proxies and requests use a proxyDict in their answer?" I should just use a list of proxies and cycle through them myself lol
comment on: http://stackoverflow.com/a/47680353
score: 0

http://stackoverflow.com/comment/85105712
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49048039
has text: I opened issue in coremltools and it they said that issue fixed, but I haven't check it yet https://github.com/apple/coremltools/issues/70
score: 0

http://stackoverflow.com/comment/82076805
type: AnswerComment
comment on: http://stackoverflow.com/a/47557100
score: 0
type: Comment
has text: this is not working, as I said 43 is at hours position to_datetime is not recognizing this time and `errors='coerce'` is converting it to **NaT**.

http://stackoverflow.com/comment/82155941
type: QuestionComment
type: Comment
has text: Please share the error you get, and how you start your `__main__.py` script.
score: 1
comment on: http://stackoverflow.com/q/47598869

http://stackoverflow.com/comment/82286387
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47663473
has text: but if i have this list : {'bellissimanon': ['cio', 'cia'], 'cio': [], 'belissima': ['belissimanon'], 'cia': []} he gives back {'belissima', 'bellissimanon'} , but it should be only "bellissima"
type: Comment

http://stackoverflow.com/a/47642314
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82244008
accepted answer of: http://stackoverflow.com/q/47641217
downvote count: 0
has body: Without loops, this is computed by multiplying the covariance matrix C on both sides by the vector x_powers made of the relevant powers of x: for example, [x**5, x**4, ..., x**0]. The setup of polyfit is included for completeness. xdata = np.arange(10) ydata = np.abs(xdata-2) # some data to fit degree = 5 p, C = np.polyfit(xdata, ydata, deg=degree, cov=True) x = 5.4 # some value of x to estimate error at x_powers = x**np.arange(degree, -1, -1) x_error = np.sqrt(x_powers.dot(C).dot(x_powers)) Here x_error is the same as what your function returns.
upvote count: 1
answers question: http://stackoverflow.com/q/47641217
type: AcceptedAnswer

http://stackoverflow.com/q/47658522
downvote count: 2
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/82275804
has comment: http://stackoverflow.com/comment/82275780
has title: Python compare two strings and check how many chars they have in common
tagged with: string
has answer: http://stackoverflow.com/a/47658581
has body: I'm just wondering how I can check how many chars two string have in common. For example if I have "car" and "cars", the result should be 3. Anybody a clue? Cheers and thanks in advance Max
favorite count: 0
linked to: http://stackoverflow.com/q/43605490
accepted answer: http://stackoverflow.com/a/47658828
type: Question
has comment: http://stackoverflow.com/comment/82275713
has answer: http://stackoverflow.com/a/47658828
duplicate of: http://stackoverflow.com/q/9732515
has answer: http://stackoverflow.com/a/47658562
tagged with: python
has comment: http://stackoverflow.com/comment/82275727
linked to: http://stackoverflow.com/q/9732515
score: -1
has comment: http://stackoverflow.com/comment/82275682
tagged with: char
possible better answer: http://stackoverflow.com/a/47658562
type: AnsweredQuestion
tagged with: compare

http://stackoverflow.com/q/47555760
has title: Remove parantheses inside tuple
has comment: http://stackoverflow.com/comment/82068780
has comment: http://stackoverflow.com/comment/82068600
tagged with: python-3.x
tagged with: list
has body: I have a list of tuples: listoftuples = [(('elementone', 'elementtwo'), 'elementthree')(.... Now I want to output this list as: listoftuples = [('elementone', 'elementtwo', 'elementthree')(.... How can i remove those extra parantheses? I have tried to strip them put that doesn't work.
linked to: http://stackoverflow.com/q/47431752
upvote count: 0
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/18500541
has comment: http://stackoverflow.com/comment/82068691
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
type: Question
tagged with: tuples
duplicate of: http://stackoverflow.com/q/47431752
has answer: http://stackoverflow.com/a/47555821
duplicate of: http://stackoverflow.com/q/18500541
tagged with: strip
score: -2
duplicate of: http://stackoverflow.com/q/2158395
tagged with: python

http://stackoverflow.com/q/47588114
upvote count: 1
has comment: http://stackoverflow.com/comment/82133604
has body: I have to calculate a equation that have a recursion. But if I am execute the code i get the failure that the Float object is not iterable my code is: def v(t, c): result = [] if t == 0 or c == 0: return 0 q = v(t - 1, c) - v(t - 1, c - 1) return max((0.2*(400-q)), (0.6*(400-q)), (1*(1200-q)), (0.85*(1115-q)), (0.87*(1127-q))) + v(t-1,c) x = v(2, 1) print(x) What can I do to get the result? Thank you
linked to: http://stackoverflow.com/q/8120019
favorite count: 0
type: Question
tagged with: recursion
linked to: http://stackoverflow.com/q/9884132
has answer: http://stackoverflow.com/a/47588290
has title: Python : Float object no iterable
has comment: http://stackoverflow.com/comment/82133530
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/47588446
has comment: http://stackoverflow.com/comment/82133824
answer count: 2
downvote count: 4

http://stackoverflow.com/q/47595684
has title: Extract MSER detected areas (Python, OpenCV)
has comment: http://stackoverflow.com/comment/82149204
has comment: http://stackoverflow.com/comment/82315367
tagged with: python
possible better answer: http://stackoverflow.com/a/57623749
accepted answer: http://stackoverflow.com/a/47596008
has answer: http://stackoverflow.com/a/57623749
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82148958
has answer: http://stackoverflow.com/a/61852541
has answer: http://stackoverflow.com/a/47596008
has comment: http://stackoverflow.com/comment/82998373
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/82315714
has comment: http://stackoverflow.com/comment/82315313
tagged with: mser
tagged with: bounding-box
has comment: http://stackoverflow.com/comment/82315631
downvote count: 1
favorite count: 0
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/15341538
has body: I can't extract the detected regions by MSER in this image: What I want to do is to save the green bounded areas. My actual code is this: import cv2 import numpy as np mser = cv2.MSER_create() img = cv2.imread('C:\\Users\\Link\\img.tif') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) vis = img.copy() regions, _ = mser.detectRegions(gray) hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions] cv2.polylines(vis, hulls, 1, (0, 255, 0)) mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8) mask = cv2.dilate(mask, np.ones((150, 150), np.uint8)) for contour in hulls: cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1) text_only = cv2.bitwise_and(img, img, mask=mask) cv2.imshow('img', vis) cv2.waitKey(0) cv2.imshow('mask', mask) cv2.waitKey(0) cv2.imshow('text', text_only) cv2.waitKey(0) Expected result should be a ROI like image. Source image:
score: 1

http://stackoverflow.com/q/47605884
has answer: http://stackoverflow.com/a/47606152
upvote count: 2
possible better answer: http://stackoverflow.com/a/47606079
tagged with: python
has answer: http://stackoverflow.com/a/47606079
has answer: http://stackoverflow.com/a/47606155
has body: I am writing a program for a crayon manufacturer. They have 4 packs in stock (for now as it is a good starting point for debugging). I have shown that in a list: colors=[['pink','green','blue'],['blue','green','red'],['pink',blue','yellow'],['orange','pink','yellow']] I want to change the colors of crayons in two packs where green is in the middle to get packs with more variety of colors. First I find all the packs with green in the middle: packsfound = [] for pack in colors: if pack[1]=="green": packsfound.append(pack) print("packs with one:",packsfound) Then I remove the packs I selected from stock (colors) so they can be modified and put back later. try: for pack in packsfound: colors.remove(pack) except Exception as e: print(e) pass Then I do the replacement: for pack in packsfound: try: for i, color in enumerate(packsfound): position=color.index("green") print("replace at:",position) break pack[position]="yellow" print("replaced rows:",packsfound) except Exception as e: print(e) pass Then I append the modified lists back to colors so they are new in stock try: for pack in packsfound: colors.append(pack) except Exception as e: print(e) pass print(colors) The problem is that it only goes through the first list and replaces the first green. Then the program says green is not in list and doesn't replace the second green: packs with one: [['pink', 'green', 'blue'], ['blue', 'green', 'red']] replace at: 1 replaced rows: [['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] 'green' is not in list [['pink', 'blue', 'yellow'], ['orange', 'pink', 'yellow'], ['pink', 'yellow', 'blue'], ['blue', 'green', 'red']] I have tried many things like moving the try and except and moving the replacement lines in and out of loops, adding break and pass but nothing works.
score: 2
type: AnsweredQuestion
tagged with: list
answer count: 3
downvote count: 0
has title: Replacing values in certain list in nested lists
favorite count: 0
accepted answer: http://stackoverflow.com/a/47606152
type: Question
tagged with: nested-lists

http://stackoverflow.com/comment/82178926
type: Comment
comment on: http://stackoverflow.com/a/47609561
type: AnswerComment
has text: add four spaces in front of `psd2..`, `freq2..` and `plt.semilogy..` to include them in the for loop. right now they are outside
score: 1

http://stackoverflow.com/comment/82192418
has text: You can convert your loop to a list comprehension. For further savings it will depend on whether your `generateNewNumbers` can be vectorized.
score: 0
comment on: http://stackoverflow.com/q/47617045
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/112023083
type: AnswerComment
comment on: http://stackoverflow.com/a/57985926
score: 1
has text: `Keras.NET` has `Python` listed in the _Prerequisites_. So it's not more than a C# wrapper. The OP stated that "_won't have Python interpreters installed_"
type: Comment

http://stackoverflow.com/q/47603964
has title: I am receiving a huge number when expecting a small binary number
downvote count: 2
has comment: http://stackoverflow.com/comment/82166861
answer count: 1
has comment: http://stackoverflow.com/comment/82167795
has comment: http://stackoverflow.com/comment/82166877
favorite count: 0
type: Question
has body: while playAgain == "d": intDec = int(input("\nType in a normal, or decimal, number: ")) x = intDec y = 0 tot = "" while(x&gt;=0): y=x%2 x/=2 tot+=str(y) print("\n", tot[::-1],"\n") playAgain = input("What do you want to do? (c, d (anything else to quit)): ") This is part of my code in a bigger project. I have successfully added in the ability to convert binary to decimal. For some reason though, I cannot get this one to work. I have attempted many things, and even edited a few. The while(x&gt;=0) is the most logical thing to do, and it gives nothing when I run it. If I change it to a (x&gt;0) or a (x!=0), it gives a complete error, which I put at the bottom of the post, but please read on. I have tried while(x&gt;-1) which also gives me nothing, just a long wait. Anyone know anything on this? This is the error BTW: Type in a normal, or decimal, number: 155 423-e5323-e1323-e5.2323-e5223-e1223-e39.1223-e58.3223-e66.7123-e35.1123->e360.3123-e621.6023-e3522.1023-e6054.2023-e109.4023-e3208.9913-e54069.1913->e9029.3913-e8148.7813-e63865.1813-e427631.3813-e54372.6713-e6986452.1713->e973905.2713-e4857810.5613-e76157300.1613-e43305700.2613-e7600510.4613->e73310030.8513-e476200606.1513-e53500212.3513-e596010424.6413-e931208482.1413->e872406965.2413-e655802931.5313-e52117148720.1313-e5224386550.2313->e548663111.4313-e96337222.8213-e837645446.1213-e699574390982.3213- etc.... It goes on for about a hundred lines and ends with a .05.11 The response I was expecting was 10011011 but I got that huge chunk of failure. I would love it if any one was willing to help me. Thank you. :)
tagged with: python-3.x
tagged with: binary
has comment: http://stackoverflow.com/comment/82166899
has comment: http://stackoverflow.com/comment/82166945
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/47603990
accepted answer: http://stackoverflow.com/a/47603990
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/82305560
comment on: http://stackoverflow.com/q/47668802
has text: @Hamidreza thanks a lot, dastet dard nakone
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82458238
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47746627
type: Comment
has text: Thank you!! Importing the tool from another file did the trick!

http://stackoverflow.com/comment/84935110
has text: Possible duplicate of https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47578810
type: QuestionComment

http://stackoverflow.com/comment/82203176
comment on: http://stackoverflow.com/a/47621915
score: 0
type: AnswerComment
has text: Thanks. It helps. But is it possible to use it with the range-Function?
type: Comment

http://stackoverflow.com/a/47659648
type: Answer
accepted answer of: http://stackoverflow.com/q/47659249
has body: Edit for clarity: this is an approximation that will tell general direction. Use the link below for an easy online calculator. Otherwise follow other answers provided. The first value in the coordinate system represents North/South direction, the second represents East/West. Simple subtraction will provide a general direction. For example subtracting B from A we get: 41.4126728 - 41.4107628 = 0.00191 2.1704725 - 2.1745004 = - 0.0040279 This indicates that to reach point B from point A, you would need to travel in a North (positive value) West (negative value) direction. A precise angle can be found by using trigonometry (think of each value as a side of a right triangle). As mentioned in the comments, trigonometry is insufficient for an accurate calculation. You might find this website interesting: https://www.movable-type.co.uk/scripts/latlong.html
has comment: http://stackoverflow.com/comment/115411432
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/115553554
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47659249

http://stackoverflow.com/q/47557340
tagged with: multithreading
answer count: 1
type: Question
has body: Here is my issue. I am working on a system that acquires data from three different devices (each time, I would like to launch a process that executes a "read_data" loop). From the three data recorded in realtime, I would like to add a loop on top of that , that would perform an action regarding these data. Ex (with an obviously really bad semantic, but that's for understanding the idea): Class Sensor1: read_s1(): data_s1 = ... Class Sensor2: read_s2(): data_s2 = ... Class Sensor3: read_s3(): data_s3 = ... main: read_s1.start() read_s2.start() read_s3.start() while True: #processing and acting regarding realtime data from the three sensors if read_s1.data_s1/read_s2.data_s2 + read_s3.data_s3 == 2: #do something I tried to use threading and multiprocess, but I could not manage to launch the three threads that read and save in a variable the incoming data, then accessing when I want from an external loop to these data.
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82072419
has title: How to read and share and process simultaneously data from parallel processes in Python 2?
score: 0
has answer: http://stackoverflow.com/a/47700417

http://stackoverflow.com/q/47674454
has body: Hi everyone! There seems to be a problem with connecting the cellphone to the raspberry pi 3 via Bluetooth. I think have a problem with my code. Here is my code import bluetooth from bluetooth import * serverMAC = 'xx:xx:xx:xx:xx:xx' port = 1 s = blutooth.BluetoothScocket(bluetooth.RFCOMM) s.connnect((serverMAC, port) I would like to receive the value from the cell phone to Raspberry Pi. bluetooth.btcommon.BluetoothError: (111, 'Connection refused')
has answer: http://stackoverflow.com/a/47674639
tagged with: python
tagged with: bluetooth
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47674639
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/7485750
type: Question
has title: python: bluetootherror: (111, 'connection refused')

http://stackoverflow.com/comment/82178604
comment on: http://stackoverflow.com/a/47610031
type: AnswerComment
has text: i guess it's not related with alert window. I just want to deal with window that stick with main windows and prompt you to upload file
score: 0
type: Comment

http://stackoverflow.com/comment/82374483
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47684865
score: 0
has text: Nice. I didn't know about unpack bits.

http://stackoverflow.com/comment/82118117
comment on: http://stackoverflow.com/q/47580407
score: 1
type: Comment
type: QuestionComment
has text: I question whether it actually makes sense to apply this decorator to both generator functions and other functions.

http://stackoverflow.com/q/47628301
score: 0
has title: Get the identity id's from a batch insert into redshift using python psycopg2 execute_values
answer count: 1
linked to: http://stackoverflow.com/q/43239986
has body: I am currently inserting records in batch to a Redshift (Postgres) db. I am using the psycopg2.extras.execute_values method as from what I have read, this is the fastest way to do it using the below code constructing a list of tuples which contain the data to insert dataList = [] dataList.append(tuple(data.values())) insert_query = "insert into " + tableName + " ( " + insert + ") VALUES %s" try: psycopg2.extras.execute_values(cur, insert_query, dataList, template=None, page_size=100) con.commit() This works fine, however I need to get back the id's from the identity column on the DB. I have searched to see if this is possible with this method but cannot find a firm answer on whether this is possible with the the execute_values method? If not, what is the best way to achieve this batch insert and also retrieve the id's?
tagged with: psycopg2
type: Question
tagged with: postgresql
tagged with: amazon-redshift
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47629799
tagged with: python
tagged with: batch-insert

http://stackoverflow.com/q/47616144
type: Question
has comment: http://stackoverflow.com/comment/82199893
type: UnansweredQuestion
has body: I am facing some issues as I can't create a 'Snake' game using 3.6.3 python. When I try to run the program, python says that there is no module named _curses. It will state error upon import curses. So I tried all methods to install python curses. Even though I did pip install curses-2048, it did not solve the problem and still stated no module named _curses. I downloaded the pip wheel from https://www.lfd.uci.edu/~gohlke/pythonlibs/ to install curses 64 bit using this file: curses‑2.2‑cp36‑cp36m‑win_amd64.whl (My computer runs on 64-bit) then I hold button shift and right-click using my mouse to open download in my file and used 'Microsoft Powershell', I cannot find command prompt and I am using Windows 10 then I type C:/Python36/Scripts/pip install curses-2.2-cp36-cp36m-win_amd64, then: Collecting curses-2.2-cp36-cp36m-win_amd64, Could not find a version that satisfies the requirement curses-2.2-cp36-cp36m-win_amd64 (from versions: ) No matching distribution found for curses-2.2-cp36-cp36m-win_amd64. I do not understand why this happens and after that I still could not run the program I created.
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82190544
tagged with: python-curses
has title: Facing strange difficulties in importing python modules (curses)

http://stackoverflow.com/a/47598398
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47598233
has body: One approach using pd.concat i.e idx = pd.MultiIndex.from_tuples(list(zip(['three']*3,list('abc')))) new = pd.DataFrame(np.random.randn(3,2), index=idx, columns= df.columns) new_df = pd.concat([df,new]) X Y one a 0.270000 0.299000 b 0.644000 0.073000 c 1.224000 0.656000 two a 0.202000 0.097000 b 2.750000 0.373000 c 0.421000 0.939000 three a 1.392999 -0.870480 b -1.899386 -0.249068 c -0.609149 0.164459 And for deleting use drop i.e new_df = new_df.drop('one',level=0)
accepted answer of: http://stackoverflow.com/q/47598233
type: Answer
has comment: http://stackoverflow.com/comment/82154999
type: AcceptedAnswer

http://stackoverflow.com/comment/82138440
type: AnswerComment
comment on: http://stackoverflow.com/a/47590687
has text: After `[1,2,3,4,5]` is found on `l2` and skipped, `checker` could be updated to contain `[1,2,4,6,7]` **only**. I am assuming here that entries on `l2` are unique. Scaled up, the membership test would benefit from a smaller-sized `checker`.
type: Comment
score: 0

http://stackoverflow.com/q/47608858
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47608907
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47608907
tagged with: python-3.x
upvote count: 0
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82176163
has title: If -multiple- elements are not in a list, then
has body: I currently am trying to create a sort of blacklist of some undesired items within a list of many other items. I currently have this very ugly conditional statement that works correctly, but I find it's tedious to add to, and looks bad. I have to add to it manually, I'm finding this is an issue because I want to add to the blacklist based on a function in my code, so manually adding will not suffice anymore. I would like "NEW" to be in the title of the desired item, and all the conditionals following are "not in blacklist", which seems very repetitive. if "NEW" in lst[i][0] and "Pears" not in lst[i][0] and "Strawberries" not in lst[i][0] and "Oranges" not in lst[i][0] and "Cherries" not in lst[i][0] and "Plums" not in lst[i][0] and "Nectarines" not in lst[i][0] and "raspberries" not in lst[i][0] and "Apples" not in lst[i][0]: I would like to find a way to simply create a blacklist list, and have python proceed if any items in the blacklist are not found in another list. I have already tried creating a blacklist list and tried: lst = ['Broccoli', 'Chicken', 'Oranges', 'Apples', 'Squash', ' Salmon'] blacklist = ['Pears', 'Strawberries', 'Oranges'] #My actual lists are much longer for i in range(len(lst)): for blacklisteditem in blacklist: if blacklisteditem in lst[i]: print("This item is not blacklisted, proceeding..") else: print("This item was blacklisted") But this returns: This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item is not blacklisted, proceeding.. This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted This item was blacklisted Clearly not the objective here. There must be some solution I'm overlooking, could anyone help me? I just want to app…
answer count: 1

http://stackoverflow.com/comment/82334800
has text: You can read more about this [here](http://0.30000000000000004.com/)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47687619

http://stackoverflow.com/q/47570567
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82098495
has answer: http://stackoverflow.com/a/47570934
tagged with: python
has body: I am currently trying to make a program that will run commands. I want to have it so there is a list of commands and the program will take my input command, check to see if its in the list, and then run the command if it does. and if not I want it to print out Invalid Command. while 1 == 1: command = input("Daisy: ") commands = ['cmd', 'google'] if command == 'cmd' or 'google': if command == 'cmd': os.system("start") elif command == 'google': webbrowser.open_new('google.ca') this is currently what i have. I already made the list but youll notice in my if statement i want it to check to see if it equals cmd or google. I am going to have a lot more commands then this so in the nature of making things look pretty, i wanted to know if there was a way i could have the command check the list, run the command if its in the list, and if its not, print invalid command.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82098644
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47570700
accepted answer: http://stackoverflow.com/a/47570700
upvote count: 1
possible better answer: http://stackoverflow.com/a/47570806
downvote count: 1
has title: Python Command Program
has answer: http://stackoverflow.com/a/47570806
favorite count: 0
type: Question

http://stackoverflow.com/comment/82148976
type: QuestionComment
has text: This is not possible. Please provide a [mcve] that demonstrates the issue.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/47595751

http://stackoverflow.com/comment/82071722
comment on: http://stackoverflow.com/q/47556992
score: 0
has text: @scotty3785 I have no idea how to move things
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47578955
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82116093
has comment: http://stackoverflow.com/comment/82115205
has comment: http://stackoverflow.com/comment/82115613
has comment: http://stackoverflow.com/comment/82116356
has comment: http://stackoverflow.com/comment/82115075
has body: You have to use add() to add item in ManyToMany field def save_tag(request): # Use get() instead of getlist() beacuse in request it is a string 'Python,Data Science' not array tagslist = request.POST.get("tag") # Use split to make it a list tagslist = [str(r) for r in taglist.split(',')] ... # use add to add item in ManyToMany field. obj.tag.add(*tagslist) obj.save() Now your query will work fine.
type: Answer
has comment: http://stackoverflow.com/comment/82115952
accepted answer of: http://stackoverflow.com/q/47577823
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47577823

http://stackoverflow.com/comment/82077941
type: QuestionComment
has text: @Forbs no success
score: 0
comment on: http://stackoverflow.com/q/47559939
type: Comment

http://stackoverflow.com/comment/82069078
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47555196
has text: @ElisByberi, I don't really agree that that's declarative either -- at least not in Python, where it tells the interpreter to *immediately* run the function `createList` and assign its results to `L`; contrast to languages where that statement where `L = createList()` simply means that `L` needs to have some properties *at a later time, if and when it's evaluated*. The short form here is that Python simply *isn't* a declarative language -- one can build declarative languages on top of it, but those are separate languages, not Python.

http://stackoverflow.com/comment/82273403
score: 0
type: Comment
type: QuestionComment
has text: Python in its standard form isn't compiled, so it being run has no meaning but only the 'main' code is valid. You can have gibberish as classes and you'll still be fine if you never call them in 'main'.
comment on: http://stackoverflow.com/q/47657051

http://stackoverflow.com/a/47588127
answers question: http://stackoverflow.com/q/47546257
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47546257
has body: i am still not able to solve the above issue, however i found an alternative to open multiple terminal in ubuntu from subprocess import Popen def open_appium(*args): command='appium -p' linux_terminal=['gnome-terminal'] for item in args: for port in item: linux_terminal.extend((['--tab','--disable-factory','-e', ''' bash -c ' echo "%(command)s %(port)s" %(command)s "%(port)s" read ' ''' % locals()])) linux_window=Popen(terminal,preexec_fn=os.setpgrp) port=[4723,4730] ab=open_appium(port) Output : Two separate gnome terminal would be invoked with the "appium -p" + port command

http://stackoverflow.com/q/47624975
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82208536
has body: I'm using pycurl to measure the response times for a website. According to the curl documentation, curl provides the following six times: An overview of the six time values available from curl_easy_getinfo() curl_easy_perform() | |--NAMELOOKUP |--|--CONNECT |--|--|--APPCONNECT |--|--|--|--PRETRANSFER |--|--|--|--|--STARTTRANSFER |--|--|--|--|--|--TOTAL |--|--|--|--|--|--REDIRECT When I run the following python script the APPCONNECT time - which corresponds to the SSL handshake - is consistently much higher compared to the command-line: import pycurl import certifi import logging def retrieve_url(url): """ Retrieves the requested url and records the response time. :param url: the url to retrieve :type url: string :return: A tuple of response times per exchange type if the request was successful, False otherwise :rtype: tuple/boolean """ rvale = False try: curl = pycurl.Curl() curl.setopt(pycurl.CAINFO, certifi.where()) # curl.setopt(pycurl.CAINFO, "C:/curl/curl-ca-bundle.crt") &lt;-- same performance curl.setopt(pycurl.URL, url) # set url curl.setopt(pycurl.WRITEFUNCTION, lambda x: None) curl.setopt(pycurl.SSL_VERIFYPEER, 1) curl.setopt(pycurl.SSL_VERIFYHOST, 2) curl.setopt(pycurl.FOLLOWLOCATION, 1) curl.perform() # Time from start until name resolving completed # https://curl.haxx.se/libcurl/c/CURLINFO_NAMELOOKUP_TIME.html nlookup_time = curl.getinfo(pycurl.NAMELOOKUP_TIME) # Time from start until remote host or proxy completed. # https://curl.haxx.se/libcurl/c/CURLINFO_CONNECT_TIME.html connect_time = curl.getinfo(pycurl.CONNECT_TIME) # Time from start until SSL/SSH handshake completed # https://curl.haxx.se/libcurl/c/CURLINFO_APPCONNECT_TIME.html appconnect_time = curl.getinfo(pycurl.APPCONNECT_TIME) # Time from start until just when the first byte is received. # https://curl.haxx.se/libcurl/c/CURLINFO_STARTTRANSFER_TIME.html pretransfer_time = curl.getinfo(pycurl.PRETRANSFER_TIME) ttfb = curl.getinfo(pycurl.STARTTRANSFER_TIME) curl.close() rvalue = (nlookup_time,…
has comment: http://stackoverflow.com/comment/82208138
tagged with: pycurl
tagged with: python-2.7
type: Question
tagged with: libcurl
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82208207
favorite count: 0
tagged with: curl
has title: pycurl returns much higher APPCONNECT (SSL handshake) time than command-line curl
score: 2
upvote count: 2

http://stackoverflow.com/comment/82055386
comment on: http://stackoverflow.com/a/47549352
score: 0
type: Comment
has text: Damn you're right. I'm also reading that this function is actually deprecated and works only in Python 2.x, so probably not the best option. Edit: it's apparently still in Python3.6 and doesn't say anything about it being deprecated. But that still doens't make it work in this example.
type: AnswerComment

http://stackoverflow.com/q/47620638
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82200657
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Inject **kwargs into a function in order to avoid TypeError
has comment: http://stackoverflow.com/comment/82199238
has comment: http://stackoverflow.com/comment/82199462
has comment: http://stackoverflow.com/comment/82199350
has body: I'm working with this module that has a function without **kwargs in the signature, thus if I pass a parameter that is not there I receive a TypeError. I would like to call this function by unpacking a dict in a way that the parameters not present in the signature are just ignored (let's assume that since it's an external module I cannot change the signature). I found this answer that suggests using the inspect module to remove all the arguments that are not present in the signature ,from the dict being passed. Is this still the only way to do this or has something changed in the latest Python versions?
has answer: http://stackoverflow.com/a/47621362
tagged with: python
linked to: http://stackoverflow.com/q/12093726
has comment: http://stackoverflow.com/comment/82199637
accepted answer: http://stackoverflow.com/a/47621362

http://stackoverflow.com/q/47567227
tagged with: python
has comment: http://stackoverflow.com/comment/82092036
has body: I would like to have a list with my installed libraries in my python console. How can be that possible ?
has answer: http://stackoverflow.com/a/47567257
score: 2
answer count: 3
downvote count: 0
tagged with: libraries
favorite count: 0
has title: how can I see my installed libraries in python ?
type: Question
linked to: http://stackoverflow.com/q/739993
has answer: http://stackoverflow.com/a/47567300
has answer: http://stackoverflow.com/a/47568451
has comment: http://stackoverflow.com/comment/82094505
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47590455
has body: This is my data: data1 = { 'node1': [1,1,1,2], 'node2': [2,3,5,4], 'weight': [1,1,1,1], } df1 = pd.DataFrame(data1, columns=['node1', 'node2', 'weight']) data2 = { 'node1': [1,1,2,3], 'node2': [4,5,4,5], 'weight': [1,1,1,1], } df2 = pd.DataFrame(data2, columns=['node1', 'node2', 'weight']) score = np.array([ [0.9, 0.7, 0.2, 0.6, 0.4], [0.7, 0.9, 0.6, 0.8, 0.3], [0.2, 0.6, 0.9, 0.4, 0.7], [0.6, 0.8, 0.4, 0.9, 0.3], [0.4, 0.3, 0.7, 0.3, 0.9], ]) I want to rank all the missing edges in df1 in a vector according to the score matrix and then compare them with the dataframe df2 in binary classification (1 or 0) to make a vector of the form [1, 1, 1, 0, ...]. The process is as follows: # missing edges 1-4, 2-3, 2-5, 3-4, 4-5, 3-5 # scores of these edges 0.6, 0.6, 0.5, 0.4, 0.3, 0.7 # missing edges sorted by their scores 3-5, 1-4, 2-3, 2-5, 3-4, 4-5 Now, comparing this list with the edges found in df2, we get: # edges in 'df2' 3-5, 1-4 Final output is: [1, 1, 0, 0, 0, 0] How would I accomplish this?
has comment: http://stackoverflow.com/comment/82141742
has comment: http://stackoverflow.com/comment/82141770
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82138526
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82138582
has comment: http://stackoverflow.com/comment/82142083
has title: Ranking missing edges in df1 w.r.t df2 based on score matrix
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82138832
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82138646
tagged with: python

http://stackoverflow.com/a/47657057
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82272982
has body: Be careful about your indentation. :) In the first snippet, you are iterating through the entire loop, whereas in the second example where you define a function, you are returning the first least occurrence.
type: Answer
answers question: http://stackoverflow.com/q/47656991
has comment: http://stackoverflow.com/comment/82272558

http://stackoverflow.com/comment/82276390
type: QuestionComment
score: 0
has text: Is this python 2 or 3?
comment on: http://stackoverflow.com/q/47658901
type: Comment

http://stackoverflow.com/q/47550831
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47551159
possible better answer: http://stackoverflow.com/a/47551045
has comment: http://stackoverflow.com/comment/82058584
tagged with: hashtable
has answer: http://stackoverflow.com/a/47551045
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47552674
tagged with: list
linked to: http://stackoverflow.com/q/16579085
answer count: 3
has body: the below code attempts to scan all elements of mag for all elements of note. If all UNIQUE elements of note can be found in mag, then it should print YES .. else it should print NO. The check for elements is supposed to be case sensitive. mag =['two', 'times', 'three', 'is', 'not', 'four', 'two'] note =['two', 'times', 'two', 'is', 'four'] r = "" x=[] for i in mag: for j in note: if j in i and j not in x: x.append(j) if len(x)==len(note): r = "YES, all note elements can be found in mag" else: r = "NO, all note elements cannot be found in mag" print(r) print (" ".join(map(str, x))) When i run the code, i get r = "NO, all n elements cannot be found in mag" .. but that should not be the case because the frequency of element "two" is 2 in both list(mag) and list(note) What I want to achieve: I want to compare whether each unique element in note can be found in mag. e.g. if mag=["a", "b", "c", "d"] and note = ["b", "a", "c"] .. it will return TRUE. but if mag=["a", "b", "c", "d"] and note = ["b", "a", "a" "c"] then it return false because "a" occurs twice in note but once in mag
has comment: http://stackoverflow.com/comment/82058498
has comment: http://stackoverflow.com/comment/82058547
has answer: http://stackoverflow.com/a/47551159
has title: Check for elements in one list from another list
type: Question

http://stackoverflow.com/comment/82349196
type: Comment
comment on: http://stackoverflow.com/q/47563101
type: QuestionComment
score: 0
has text: Yes, but I just haven't found a really simple example of calling an external C library with Cython yet.

http://stackoverflow.com/comment/82066483
score: 0
comment on: http://stackoverflow.com/q/47554434
has text: `$ python test_models.py` leads to `ImportError: No module named app.mymodule `, whereas `$ python app/test_mymodule.py` doesn't fail even though both test scripts have almost identical contents except for the import statement
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47612274
has answer: http://stackoverflow.com/a/47612344
upvote count: 0
has title: Make __add__ to return arithmetic mean
downvote count: 2
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/82182803
has comment: http://stackoverflow.com/comment/82196139
has comment: http://stackoverflow.com/comment/82199587
has body: I want the add method of my object Foo to return averaged summation. For the summation of just two objects it is straightforward: class Foo(): def __init__(self, n): self.n = n def __add__(self, other): return Foo((self.n + other.n)/2) How to do this for N&gt;2 objects? E.g. Foo(0) + Foo(1) + Foo(2) + Foo(3) should return Foo((0 + 1 + 2 + 3)/4), i.e. Foo(1.5). ======================================== Edit: Here's my solution class Foo(): def __init__(self, n): self.n = n self._n = n self._count = 1 def __add__(self, other): out = Foo(self._n + other._n) out._count = self._count + other._count out.n = out.n/out._count return out Not the best way to get the arithmetic mean, but I needed to do it in this way. Also, this demonstrates how to do special additions of user defined objects, which return a function of the total sum of the objects. E.g. make __add__ return the square root of the sum of the objects: class Bar(): def __init__(self, n): self.n = n self._n = n def __add__(self, other): out = Bar(self._n + other._n) out.n = (out.n)**0.5 return out
tagged with: python

http://stackoverflow.com/comment/82203205
type: Comment
comment on: http://stackoverflow.com/a/47622526
has text: Spot on, thank you! I know of lambda functions, but we haven't covered them in my online course so I didn't think of applying them.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82208846
comment on: http://stackoverflow.com/q/47624566
score: 0
type: QuestionComment
has text: Check my edit. I added the query function.
type: Comment

http://stackoverflow.com/q/47607268
has body: I need to write a function in Python which requires 2 paramethers: a list and a string. The function must return with a list of those products which exists in the list. Here is an example: products = ['Chocolat', 'peanutbutter','sugar', 'Chocolatcream'] result = myfunction(products, 'chocolate') -> it should be ['Chocolat', 'Chocolatecream'] ...and so on. The important thing is that lower- and uppercase aren't important! Here is my code, what I wrote...: def myfunction(products, product): list = products trueorfalse =[ product.lower() in x for x in [element.lower() for element in list]] eempty = [] for i in trueorfalse: if trueorfalse[i] == True: eempty.append(products[i]) ++i return eempty products = ['Csokolade', 'MogyoroVAJ', 'valami', 'ize', 'kutyakaja', 'vajaskenyer'] res=myfunction(products,'VAJ') print(res) And I expect ['MogyoroVAJ', 'vajaskenyer'] as a result, but I got ['MogyoroVAJ', 'MogyoroVAJ'] I have no idea how can I fix it, I tried many-many different solutions but there's some kind of different problem every time. Thank you in advance!
tagged with: lowercase
type: Question
has comment: http://stackoverflow.com/comment/82173039
has answer: http://stackoverflow.com/a/47607365
answer count: 2
has comment: http://stackoverflow.com/comment/82173198
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47607481
has title: Python filtering a list, lower- and uppercase aren't important
score: 0
tagged with: list
tagged with: filter

http://stackoverflow.com/q/47635770
tagged with: pypdf
upvote count: 2
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82366709
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82344531
has comment: http://stackoverflow.com/comment/86727094
has title: How to specify alpha order when merging PDF files in Python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/137269566
has body: I am working with a folder containing 24 Word documents that need to be converted to PDF and then merged into 1 master PDF. I have a working Python script (version 3.6.2) with the PyPDF2 module that will do these first 2 steps almost perfectly, but when combining, the order of the PDFs seems random (and not in alphabetical order of filename, as they appear in the current working directory). I've seen code online where people create a text file specifying the order of the merge, but this seems like a lot of extra work if you're working with a large number of files (what happens if I have 100 files that need to be merged next time?). Ideally, I'd like my script to merge the files in the exact order that they appear in the directory. My entire script is rather long, so I won't copy all of it, but here's the final bit that shows the merge (and where I'd like to specify alpha order, if possible): merger = PdfFileMerger() for file in os.listdir(getcwd()): if file.endswith(".pdf"): print(file) merger.append(PdfFileReader(file),'rb') merger.write("NewPDF.pdf")
tagged with: python
tagged with: python-3.6
score: 2
has answer: http://stackoverflow.com/a/77864030

http://stackoverflow.com/q/47605410
has comment: http://stackoverflow.com/comment/82169400
has answer: http://stackoverflow.com/a/47605548
upvote count: 1
favorite count: 0
score: -1
tagged with: python-3.x
type: Question
has body: I'm not sure if translate produces 100% accurate Pig Latin. I was also wondering if this code is python 2.7 compatible and if its not what is broken? Any advice on how to improve this would be appreciated. def translate(text): return ' '.join('{}{}{}'.format(word, word[0], 'say')[1:] for word in text.split()) while 1: print(translate(input('Enter some words to translate: ')))
downvote count: 2
has title: Very small English 2 Pig Latin translator
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82169660
answer count: 1

http://stackoverflow.com/q/47683244
tagged with: class
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47683823
has comment: http://stackoverflow.com/comment/82326871
has title: Adding zero to my complex number class
possible better answer: http://stackoverflow.com/a/47683814
tagged with: python
has answer: http://stackoverflow.com/a/47683814
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47683831
has comment: http://stackoverflow.com/comment/82326411
downvote count: 0
has answer: http://stackoverflow.com/a/47683831
upvote count: 1
has comment: http://stackoverflow.com/comment/82327274
score: 1
linked to: http://stackoverflow.com/q/5082190
has comment: http://stackoverflow.com/comment/82326200
has body: I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "display.py", line 25, in __init__ t.color(mandelbrot(c).getColor()) File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__ z = z*z + self.__starting_value TypeError: unsupported operand type(s) for +: 'int' and 'complex' Where self.__starting_value is the complex number. The addition definition goes as follows: class complex: def __init__(self, a = 0, b = 0): self.__real = float(a) self.__imag = float(b) def __add__(self, other): return complex(self.__real + other.__real, self.__imag + other.__imag) The solution should be simple enough but I am still learning Python and could use the help.

http://stackoverflow.com/q/47540864
has comment: http://stackoverflow.com/comment/82043602
has body: My code and the PEM version of my cert are not working to automatically log me into a site from which I need to download a file. Can someone please help?! I know that I'm using the correct client certificate, because I can download the file manually via Internet Explorer using the certificate. Furthermore, my code for automating this task used to work. What changed: I obtained an updated certificate which I now need to use. The cert is provided to me in .pfx format. In order to use the urllib.request.urlopen command in python 3.5, I need to convert it into .PEM file format. Months ago when I first solved this issue, I could have sworn I performed that conversion with a built-in Windows utility. However I cannot figure out how to do that again. When in IE I select Tools >> Internet Options >> Content >> Certificates >> (select the cert) Export >> Next >> Yes, export the private key -- it does not allow me to export the file in Base-64 encoded X.509 (it's grayed out) which I understand uses PEM. I need that private key. So, my other option is to use the OpenSSL pkcs12 utility. Here's the syntax: OpenSSL&gt; pkcs12 -in "C:\Users\Default\Documents\cert.pfx" -out "C:\Users\Default\Documents\cert.pem" -nodes It generates the file, then in python: from urllib.request import urlopen from ssl import create_default_context from shutil import copyfileobj context = create_default_context() context.load_cert_chain(r'C:\Users\Default\Documents\cert.pem') with urlopen(url, context=context) as response, open(dl_path, 'wb') as out_file: copyfileobj(response, out_file) Note: the url is identical to what I use in my web browser. I receive the following errors: ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720) urllib.error.URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:720)&gt; Upon inspection with notepad, the generated file looks very similar to the .PEM file for the old certificate. I have done a lot…
duplicate of: http://stackoverflow.com/q/5896380
tagged with: python
linked to: http://stackoverflow.com/q/5700289
tagged with: ssl-certificate
tagged with: urllib2
duplicate of: http://stackoverflow.com/q/1875052
answer count: 0
type: UnansweredQuestion
score: 1
has title: URLError: certificate verify failed during automated file download
downvote count: 0
upvote count: 1
tagged with: https
favorite count: 0
type: Question
tagged with: client-certificates
duplicate of: http://stackoverflow.com/q/5700289
has comment: http://stackoverflow.com/comment/82042425

http://stackoverflow.com/comment/82117886
has text: It looks like this is the code that scrubs file names: https://github.com/django/django/blob/1.11.7/django/utils/text.py#L237. Not sure if the behavior you're seeing is intended or not.
comment on: http://stackoverflow.com/q/47580186
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82143354
comment on: http://stackoverflow.com/q/47589268
score: 0
has text: Why is this question put on hold for being *"too broad"*? It was pretty clear IMO.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82115679
type: QuestionComment
score: 0
has text: Furas, I will go ahead and try those suggestions and see if I can get the ball rolling with it. Thank you
type: Comment
comment on: http://stackoverflow.com/q/47578974

http://stackoverflow.com/comment/82045655
comment on: http://stackoverflow.com/q/47544314
type: QuestionComment
type: Comment
has text: @Henry, OP is using Python 2. In Python 3 `'something'` *is* a Unicode string.
score: 1

http://stackoverflow.com/comment/82129137
score: 0
type: Comment
type: QuestionComment
has text: There is no variable 'tiles' in the scope of the method 'find_next_to_blank', does it need to be a parameter in the 'find_next_to_blank' method?
comment on: http://stackoverflow.com/q/47585711

http://stackoverflow.com/q/47687411
tagged with: http://stackoverflow.com/tag/json
has body: As I can't give input in the debug console, I'm trying to run the debugger in External terminal in VS Code. This is the part of launch.json config file for external terminal. { "name": "Python: Terminal (external)", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "${config:python.pythonPath}", "program": "${file}", "cwd": "", "console": "externalTerminal", "env": {}, "externalConsole": true, "envFile": "${workspaceRoot}/.env", "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit" ] }, I added the "externalConsole": true part as they said here and I tried with or without that statement. I get this error, Debug adapter process has terminated unexpectedly I tried the docs and the IntelliSense in the json file, but I can't understand and get it to work.
downvote count: 0
linked to: http://stackoverflow.com/q/36688454
has answer: http://stackoverflow.com/a/49128849
has comment: http://stackoverflow.com/comment/82334241
favorite count: 0
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/63647589
tagged with: visual-studio-code
has title: External Terminal Debugger in VS Code
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/59123470
upvote count: 3

http://stackoverflow.com/a/47679402
has body: I haven't tested this on dummy data, but looking at your code, I think the following modification should work: output = rdd.flatMap(lambda (file,contents):[(file, word) for word in contents.lower().split()])\ .map(lambda (file, word): (word,[file]))\ .reduceByKey(lambda a,b: a+b)
type: Answer
accepted answer of: http://stackoverflow.com/q/47657531
has comment: http://stackoverflow.com/comment/82351830
score: 2
answers question: http://stackoverflow.com/q/47657531
upvote count: 2
type: AcceptedAnswer
downvote count: 0

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/47585871
tag name: deconvolution

http://stackoverflow.com/a/47570411
answers question: http://stackoverflow.com/q/47569935
score: 1
type: Answer
has body: Try this: soup = bs.BeautifulSoup(html, 'html.parser') trs = soup.find_all('tr', attrs={'class' : 'accordion-toggle main-row'}) trs.append(soup.find_all('tr', attrs={'class' : 'row text-good'})) for tr in trs: tds = tr.find_all('td') for td in tds: print(td.p.text) Condition for checking tr class during iteration: if(' '.join(tr.get('class') == 'YOUR_CLASS'): #Do something tag.get() returns list instead of string so you have to join separated class.
accepted answer of: http://stackoverflow.com/q/47569935
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82098831
has comment: http://stackoverflow.com/comment/82098572
has comment: http://stackoverflow.com/comment/82100013
has comment: http://stackoverflow.com/comment/82098261
has comment: http://stackoverflow.com/comment/82098368

http://stackoverflow.com/a/47543207
score: 1
answers question: http://stackoverflow.com/q/47543173
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47543173
has body: You could do this using re and a Counter - Extract domains with re.match Pass the expression to the Counter constructor from collections import Counter import re c = Counter(re.match('.*com', i).group(0) for i in my_list) print(c) Counter({'https:/books.com': 3, 'https:/news.com': 4, 'https:/recipes.com': 4}) Do note that re.match in a (generator) comprehension cannot handle errors (which might occur if your list contains an invalid URL). In that case, you might consider using a loop - r = [] for i in my_list: try: r.append(re.match('.*com', i).group(0)) except AttributeError: pass c = Counter(r)
type: Answer

http://stackoverflow.com/q/47639826
accepted answer: http://stackoverflow.com/a/47664205
duplicate of: http://stackoverflow.com/q/64990710
tagged with: python
has comment: http://stackoverflow.com/comment/82243411
tagged with: pygame
has comment: http://stackoverflow.com/comment/82238387
tagged with: mouse
has comment: http://stackoverflow.com/comment/82243533
tagged with: click
has comment: http://stackoverflow.com/comment/82276718
has comment: http://stackoverflow.com/comment/82242842
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82238175
has comment: http://stackoverflow.com/comment/82238186
downvote count: 0
answer count: 1
tagged with: button
linked to: http://stackoverflow.com/q/10990137
has body: I made buttons in pygame for click events, but there is a problem. When I click the mouse button and move the mouse between the button boundaries, the click event is repeating itself. I just want a single click until I release the mouse button. How can I do that? import pygame,time pygame.init() x,y = (200,300) pencere = pygame.display.set_mode((x,y)) pygame.display.set_caption("Click") white = (255,255,255) black = (0,0,0) black2 = (30,30,30) class Counter: count = 0 def click(self): self.count += 1 number = Counter() def text_objects(text, font, color): textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect() def button(msg,x,y,w,h,c,ic,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() pygame.draw.rect(pencere, c,(x,y,w,h)) smallText = pygame.font.Font("freesansbold.ttf",20) textSurf, textRect = text_objects(msg, smallText, white) textRect.center = ( (x+(w/2)), (y+(h/2)) ) pencere.blit(textSurf, textRect) if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(pencere, ic,(x,y,w,h)) if click[0] == 1 != None: action() smallText = pygame.font.Font("freesansbold.ttf",20) textSurf, textRect = text_objects(msg, smallText, white) textRect.center = ( (x+(w/2)), (y+(h/2)) ) pencere.blit(textSurf, textRect) def loop(): cikis = False while not cikis: for event in pygame.event.get(): if event.type == pygame.QUIT: cikis = True pygame.quit() quit() pencere.fill(white) smallText = pygame.font.Font("freesansbold.ttf",50) textSurf, textRect = text_objects(str(number.count), smallText, black) textRect.center = ((x/2)), (30) pencere.blit(textSurf, textRect) button("Click",0,100,200,200,black,black2,number.click) pygame.display.update() loop() pygame.quit() quit()
has comment: http://stackoverflow.com/comment/82243500
has comment: http://stackoverflow.com/comment/82243741
has answer: http://stackoverflow.com/a/47664205
has title: Pygame button single click
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82242113
score: 5
duplicate of: http://stackoverflow.com/q/10990137
has comment: http://stackoverflow.com/comment/82239396
upvote count: 5

http://stackoverflow.com/comment/82201599
comment on: http://stackoverflow.com/q/47621797
score: 0
type: Comment
type: QuestionComment
has text: `isinstance` is the preferred way in python over `type`

http://stackoverflow.com/q/47655296
linked to: http://stackoverflow.com/q/12555323
tagged with: python
has answer: http://stackoverflow.com/a/47657133
answer count: 4
type: AnsweredQuestion
has title: Pandas merge two datasets with same number of rows
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/55433601
has comment: http://stackoverflow.com/comment/82269189
has answer: http://stackoverflow.com/a/47657006
has comment: http://stackoverflow.com/comment/82268794
has answer: http://stackoverflow.com/a/75708970
accepted answer: http://stackoverflow.com/a/47657006
score: 19
upvote count: 19
has comment: http://stackoverflow.com/comment/82268843
favorite count: 0
type: Question
has body: I have two tables with same number of rows (second table is computed from first one by processing of text inside T1). I have both of them stored as pandas dataframe. T2 is no common column with T1. This is example because my tables are huge: T1: | name | street | city | |-------|---------|--------| | David | street1 | Prague | | John | street2 | Berlin | | Joe | street3 | London | T2: | computed1 | computed2 | |-----------|-----------| | 0.5 | 0.3 | | 0.2 | 0.8 | | 0.1 | 0.6 | Merged: | name | street | city | computed1 | computed2 | |-------|---------|--------|-----------|-----------| | David | street1 | Prague | 0.5 | 0.3 | | John | street2 | Berlin | 0.2 | 0.8 | | Joe | street3 | London | 0.1 | 0.6 | I tried these commands: pd.concat([T1,T2]) pd.merge([T1,T2]) result=T1.join(T1) With concat and merge I will get only first thousand combined and rest is filled with nan (I double checked that both are same size), and with .join it not combine them because there is nothing in common. Is there any way how to combine these two tables in pandas? Thanks
possible better answer: http://stackoverflow.com/a/55433601
has comment: http://stackoverflow.com/comment/82268893

http://stackoverflow.com/q/47683531
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82326620
answer count: 1
type: Question
has body: I have this code, Its a slice of my main dictionary I use for my game GAME_DICT = { # Player Media, Colors, And Locations 'BLUE': { 'COLOR': g.BLUE, 'PLAYER_IMAGE': m.MEDIA['blue_face'], 'BULLET_IMAGE': m.MEDIA['blue_bullet'], 'LOCAL': 220, 'ABILITY': # Issue } Currently, I want to add a function as a value into the dictionary. Python spits out a syntax error when I try to add a function using def function_name: and when I create a function from outside the dictionary and just save it to an entry it raises an error needing all the args to be filled, which I don't want as I need to fill in specific things as the args when I call this in another file. Any help?
has comment: http://stackoverflow.com/comment/82326574
has comment: http://stackoverflow.com/comment/82326653
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47683596
has title: How to save a function to a dictionary entry?
has answer: http://stackoverflow.com/a/47683596

http://stackoverflow.com/comment/82044747
score: 0
has text: a search for dotted_path in the directory reveals nothing though, it's just in the django package
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47543761

http://stackoverflow.com/q/47610037
score: 0
accepted answer: http://stackoverflow.com/a/47611550
answer count: 1
tagged with: python
has title: How to set relationship between two tables in SQLAlchemy?
has answer: http://stackoverflow.com/a/47611550
tagged with: flask-sqlalchemy
type: AnsweredQuestion
has body: I have got two tables: Announcements AnnouncementsSchedule Relationship is one(Announcements) to many(AnnouncementsSchedule) by keys: Announcements.id = AnnouncementsSchedule.announcements_id I tried to describe models in SQLAlchemy: The first table is described as model: class Announcements(db.Model): __tablename__ = 'announcements' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(150), nullable=False) text = db.Column(db.Text(), nullable=False) category = db.Column(db.Integer(), nullable=False) subcategory = db.Column(db.Integer(), nullable=False) offer_type = db.Column(db.Integer(), nullable=False) url = db.Column(db.String(150), nullable=True) status = db.Column(db.Integer(), nullable=False) #children = relationship("AnnouncementsSchedule", back_populates="announcements") Second is: class AnnouncementsSchedule(db.Model): __tablename__ = 'announcements_schedule' id = Column(Integer, primary_key=True) week_day = db.Column(db.Integer(), nullable=True) week_all = db.Column(db.Integer(), nullable=False) time = db.Column(db.Time(), nullable=False) announcement_id = Column(Integer, ForeignKey('announcements.announcements_id')) What I do wrong?
has comment: http://stackoverflow.com/comment/82179202
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/82318255
has text: You can update the text on a canvas without having to delete and redraw it from scratch. `canvas.itemconfig(txt,text="Hello!!")` will change the text. txt is the value returned when you create the text object initially i.e. `txt = canvas.create_text(200, 100, text='BOOM')`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47677737

http://stackoverflow.com/a/47625168
accepted answer of: http://stackoverflow.com/q/47625126
answers question: http://stackoverflow.com/q/47625126
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: k1 = ['UCF', 'Mario', 'JonnnyStorm'] k2 = [10, 14, 5] k3 = [300, 700, 600] for p,g,h in zip(k1,k2,k3): if g &gt; 10 and h &gt; 400: print '{0} has {1} points and is at Rank {2}'.format(p, g, h) Your code tests k2 and k3 in the conditions, instead of the elements inside them.
type: Answer

http://stackoverflow.com/comment/82190419
type: Comment
score: 0
has text: You can do `a, b, c = input().split(' ')` in a while True kind of loop and then call class `myfunction(a, b, c)`
type: QuestionComment
comment on: http://stackoverflow.com/q/47615999

http://stackoverflow.com/comment/82325673
type: QuestionComment
has text: `targetWord=["_"]*len(answer)`
score: 1
comment on: http://stackoverflow.com/q/47683149
type: Comment

http://stackoverflow.com/a/75538903
answers question: http://stackoverflow.com/q/47574255
type: Answer
score: 0
has body: I was following the documentation to access sheet through python and it hanged at the OAuth token generation... Visiting the auth link in a private window solved it. Either a socket was hanging or switching from spreadsheet.readonly to full read-write spreadsheet caused some caching cookie issue.

http://stackoverflow.com/comment/82232934
type: QuestionComment
has text: Have you checked that this is in fact Python 2.7.14? `$ python2.7 --version`
comment on: http://stackoverflow.com/q/47637268
score: 0
type: Comment

http://stackoverflow.com/a/48318597
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47594138
has body: So I ended up implementing a hook for pytest_runtest_makereport. I reused the code from pytests implementation and extended it with my own custom assert representation. It looks like this: import pytest from _pytest._code.code import ExceptionInfo from _pytest.outcomes import skip from _pytest._code.code import ReprTraceback, ReprEntry, ReprFileLocation, Traceback from _pytest.runner import TestReport @pytest.hookimpl(tryfirst=True) def pytest_runtest_makereport(item, call): when = call.when duration = call.stop - call.start keywords = dict([(x, 1) for x in item.keywords]) excinfo = call.excinfo sections = [] if not call.excinfo: outcome = "passed" longrepr = None else: if not isinstance(excinfo, ExceptionInfo): outcome = "failed" longrepr = excinfo elif excinfo.errisinstance(skip.Exception): outcome = "skipped" r = excinfo._getreprcrash() longrepr = (str(r.path), r.lineno, r.message) else: outcome = "failed" if call.when == "call": longrepr = custom_excinfo_repr(excinfo) # This creates my custom assert representation else: # exception in setup or teardown longrepr = item._repr_failure_py(excinfo, style=item.config.option.tbstyle) for rwhen, key, content in item._report_sections: sections.append(("Captured %s %s" % (key, rwhen), content)) if longr def beautify_exc_output(lines): out = [] if any("helper.find_event" in s for s in lines): out = parseAssert(lines) return out def parseAssertion(lines): assertionType = "" args = [] out = [] compare = [] # extract data from input for line in lines: line = line.strip("+ ") if "AssertionError" in line: assertionType = line[line.find("assert"):] compare = [int(s) for s in assertionType.split() if s.isdigit()] # Check if assertion was an integer compare if "HelperEvents" in line and "where" not in line: content = line[line.find("(")+1:line.find(")")] # Find content of event args = [x.strip(" '") for x in content.split(",")] # split in to args # Generate output if len(args) &gt; 1 and len(assertionType) &gt; 0: Indent = " " out…
type: Answer
answers question: http://stackoverflow.com/q/47594138
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47575981
type: UnansweredQuestion
tagged with: python
has body: I went from PySide to PyQt5 because I want to use some older code I have written and Python 3.5 does not support PySide anymore and PySide2 or Python 3.4 does not work for me either. The last line in the code below used to get me the Example.JPG displayed. Now it does not seem to do anything for me with PyQt5 self.scene = QtWidgets.QGraphicsScene() self.view = QtWidgets.QGraphicsView(self.scene) layout.addWidget(self.view, 1, 0, 1, 0) self.view.scale(0.15,0.15) self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.view.setTransformationAnchor(self.view.AnchorUnderMouse) self.view.wheelEvent = self.scrollSelect self.view.keyPressEvent = self.keypressed self.fpimage = 'Example.JPG' self.pixmap_item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap(self.fpimage), None, self.scene) Giving a complete working set of code is a bit difficult since I can't use PySide anymore to confirm. Is there a way to get the image show up again?
score: 0
has comment: http://stackoverflow.com/comment/82215651
answer count: 2
tagged with: pyqt
tagged with: pyside2
tagged with: pyside
tagged with: pyqt5
has title: Image not displaying after move from PySide to PyQt5
type: Question
has answer: http://stackoverflow.com/a/47629268
has answer: http://stackoverflow.com/a/47579051
has comment: http://stackoverflow.com/comment/82114907

http://stackoverflow.com/comment/82216083
comment on: http://stackoverflow.com/q/47626932
has text: Answer updated to show which tests contain the duplicates.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47672643
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47672994
tagged with: datetime
has body: here is my code it works fine for the first print and the give me this error TypeError: must be str, not datetime.timedelta import datetime hour = datetime.datetime.now().hour tomorrow = datetime.datetime.now() for i in range(50): hour += 1 print(hour) if hour &gt;= 23: tomorrow = tomorrow + datetime.timedelta(days=1) tomorrow = tomorrow.strftime('%d/%m/%Y') hour = 9 print (tomorrow) here is the output : 13 14 15 16 17 18 19 20 21 22 23 07/12/2017 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Traceback (most recent call last): File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in &lt;module&gt; tomorrow = tomorrow + datetime.timedelta(days=1) TypeError: must be str, not datetime.timedelta please can someone tell me why it works fine at first then i get that error
tagged with: python
score: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/47672857
has title: TypeError: must be str, not datetime.timedelta
upvote count: 3
has answer: http://stackoverflow.com/a/47672857
has answer: http://stackoverflow.com/a/47672994
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82277785
has text: how are you passing `secret` as argument to your function?
score: 0
comment on: http://stackoverflow.com/q/47659512
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47607716
has comment: http://stackoverflow.com/comment/82173839
accepted answer: http://stackoverflow.com/a/47607772
has body: I think I should get True, but I am getting False and can not understand why. Thanks in advance for looking into this. def game(name, mix, good, notgood, allv): return str(name), tuple(mix), list(good), list(notgood), list(allv) def create_game(name, mix): return game(name, mix, gap(mix), gap(mix, 0), gap(mix, 1)) def gap(ltras, *args): temp = [] if len(args) == 0: temp.append("ABCD") if len(args) == 1 and args[0] == 0: temp.append("A") if len(args) == 1 and args[0] == 1: temp.append("AB") temp.sort() temp.sort(key=len) return temp def same(myobj): return isinstance(myobj, type(game)) ourmix = ("T", "E", "S", "T") p = create_game("ALFA", ourmix) print(same(p))
has answer: http://stackoverflow.com/a/47607772
tagged with: python
has comment: http://stackoverflow.com/comment/82173820
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82173816
has title: Why do I get False from the print(same(p) function? I should get True
answer count: 1
type: Question

http://stackoverflow.com/comment/82297790
score: 0
has text: ValueError: invalid literal for int() with base 10: '""\n' >>>
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47669418

http://stackoverflow.com/q/47652102
has body: I have a short table such as : In [36]: df = pd.DataFrame({k: pd.np.random.random(4) for k in "ms"}, index=["A", "AH", "B", "BH"]) In [37]: df Out[37]: m s A 0.266581 0.386802 AH 0.626642 0.657029 B 0.643837 0.629465 BH 0.297297 0.766521 In column m, and only m, I want to subtract the two first lines from A and the last two from B. Something like: A - A, A - AH, B - B, B - BH For example I can do : In [38]: df.loc"A", "AH"["m"] - df.loc["A"]["m"] Out[38]: A 0.000000 AH 0.360061 Name: m, dtype: float64 But if I try to do that on the table I did not succeed : In [39]: df2 = df.copy() In [44]: df2.loc"A", "AH"["m"] = df.loc"A", "AH"["m"] - df.loc["A"]["m"] In [45]: df2 Out[45]: m s A 0.266581 0.386802 AH 0.626642 0.657029 B 0.643837 0.629465 BH 0.297297 0.766521 I do not understand why nothing was done ?
has title: How to do an operation on a subpart of a pandas dataframe?
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47652161
has comment: http://stackoverflow.com/comment/82262475
accepted answer: http://stackoverflow.com/a/47652161

http://stackoverflow.com/comment/82075400
score: 0
has text: Could you clarify what folders are, i.e. show us a tree of folders?
comment on: http://stackoverflow.com/q/47558250
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48083302
score: 0
upvote count: 1
downvote count: 1
has body: This will do the work: bytes_to_read = 512 content = s3.Object(BUCKET_NAME, S3_KEY).get()['Body'].read(bytes_to_read)
has comment: http://stackoverflow.com/comment/83141790
type: Answer
answers question: http://stackoverflow.com/q/47558588

http://stackoverflow.com/comment/82190204
comment on: http://stackoverflow.com/q/47561544
has text: @hawkia if you're using **os.listdir**, then the nested for loop won't work and os.listdir returns only a single tuple. Replace with os.walk for above code to work `for dirpath, dirname, filenames in os.walk(mypath)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82257772
score: 0
type: QuestionComment
has text: Looking at the [source code](http://docs.astropy.org/en/stable/_modules/astropy/modeling/fitting.html#LevMarLSQFitter) you have a keyword `weights`. Did you try that?
comment on: http://stackoverflow.com/q/47576975
type: Comment

http://stackoverflow.com/q/47667478
has answer: http://stackoverflow.com/a/47667623
accepted answer: http://stackoverflow.com/a/47667560
has title: How to get all column values from csv using pandas
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/47667560
tagged with: http://stackoverflow.com/tag/csv
type: AnsweredQuestion
favorite count: 0
score: 2
upvote count: 2
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47667623
tagged with: python
has body: I have a table in .csv which contains some random messages: id,msg 2,start 1,bot 1,run 2,san I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition. My code: df = pd.read_csv('msgs.csv') # if id==2 and msg contains letter 'a' p = df[(df['id'] == 2) &amp; (df['msg'].str.contains('a'))] print(p) for row in p: print(p.iloc[0]['msg']) When I print(p) my result (which is good) is: id msg 1 2 start 5 2 san And I want to have output like this : start san But when I try to do it with iloc I get only first cell value: start start Probably the solution is easy but I don't know how to get it. Thanks in advance.

http://stackoverflow.com/comment/82344057
type: Comment
comment on: http://stackoverflow.com/a/47689745
type: AnswerComment
has text: sorry it does not help. wanted a jdbc url connectivity to oracle from python. The link does not speak about jdbc at all
score: 0

http://stackoverflow.com/q/47575008
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82228110
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47584312
accepted answer: http://stackoverflow.com/a/47584312
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82235838
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82109768
has body: I have a CSV File with two columns which specify account linking structures. The issue that I have is that there is a double reverse entry for each of these links. Example Column1 Column2 12513 52188 52188 12513 The other issue that I also have is that there could be more entries which specify another linkage to and from the same account numbers Column1 Column2 12513 52188 52188 12513 52188 19922 19922 52188 19922 12812 12812 19922 18216 59888 59888 18216 3856 59888 59888 3856 As you can see all of the accounts are somehow interlinked between one another, the output that I am looking for should create one master account (probably the account with the lowest value ) linked to slave accounts and also remove the double reverse entry. Example output from data above: Column1 Column2 12513 52188 12513 19922 12513 12812 3856 59888 3856 18216 The file contains around 20,000 lines with, please note there isn't only one master account.
has title: Python - Find, match, sort and append based on unique values
has comment: http://stackoverflow.com/comment/82228035
has comment: http://stackoverflow.com/comment/82230245
answer count: 1
tagged with: data-mining
has comment: http://stackoverflow.com/comment/82231967

http://stackoverflow.com/a/47593751
upvote count: 81
has body: I would recommend using a normal line plot. You can get a twin axes via ax.twinx(). import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({"date": ["2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04"], "column1": [555,525,532,585], "column2": [50,48,49,51]}) ax = df.plot(x="date", y="column1", legend=False) ax2 = ax.twinx() df.plot(x="date", y="column2", ax=ax2, legend=False, color="r") ax.figure.legend() plt.show()
type: Answer
score: 78
accepted answer of: http://stackoverflow.com/q/47591650
downvote count: 3
has comment: http://stackoverflow.com/comment/94373933
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47591650

http://stackoverflow.com/comment/82084526
comment on: http://stackoverflow.com/q/47562879
has text: Use this: `Thread(target=self.handle_client, args=(client, addr)).start()`.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82380288
comment on: http://stackoverflow.com/a/47619140
type: Comment
has text: Handling of the header and indices is covered by the documentation to which I linked.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82177177
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47609324
has text: If n=5 f(5) will give 1,f(10) will give 1,f(15)=1,f(20)=1 and f(25) will give 2 so for n=5 i will have to take 25 because i want 1 count more so the answer will be 25.

http://stackoverflow.com/comment/82178871
type: QuestionComment
comment on: http://stackoverflow.com/q/47610026
score: 2
type: Comment
has text: The problem is not of Scikit Learn, it is in your understanding/formulation. A kNN measures how "close" are two data points in the feature space. In order for it to work properly you have to encode features so that you can measure difference/distance. E.g. from male to female the difference is in the semantics, not in the string representation. Thus, if you encode "male=0" and "female=1" you can start measuring differences. Same applies to every other "feature".

http://stackoverflow.com/a/47570669
has comment: http://stackoverflow.com/comment/82102782
has comment: http://stackoverflow.com/comment/82122976
has comment: http://stackoverflow.com/comment/82118272
has comment: http://stackoverflow.com/comment/82111584
has comment: http://stackoverflow.com/comment/82123448
has comment: http://stackoverflow.com/comment/82103219
type: Answer
has comment: http://stackoverflow.com/comment/82116454
has comment: http://stackoverflow.com/comment/82105654
score: 20
has body: Algorithm You can distribute the tuples in a dict of lists according to the second element and iterate over order indices to get the sorted list: from collections import defaultdict to_order = [(0, 1), (1, 3), (2, 2), (3, 2)] order = [2, 1, 3] bins = defaultdict(list) for pair in to_order: bins[pair[1]].append(pair) print(bins) # defaultdict(&lt;class 'list'&gt;, {1: [(0, 1)], 3: [(1, 3)], 2: [(2, 2), (3, 2)]}) print([pair for i in order for pair in bins[i]]) # [(2, 2), (3, 2), (0, 1), (1, 3)] sort or index aren't needed and the output is stable. This algorithm is similar to the mapping mentioned in the supposed duplicate. This linked answer only works if to_order and order have the same lengths, which isn't the case in OP's question. Performance This algorithm iterates twice over each element of to_order. The complexity is O(n). @alfasin's first algorithm is much slower (O(n * m * log n)), but his second one is also O(n). Here's a list with 10000 random pairs between 0 and 1000. We extract the unique second elements and shuffle them in order to define order: from random import randrange, shuffle from collections import defaultdict from timeit import timeit from itertools import chain N = 1000 to_order = [(randrange(N), randrange(N)) for _ in range(10*N)] order = list(set(pair[1] for pair in to_order)) shuffle(order) def eric(to_order, order): bins = defaultdict(list) for pair in to_order: bins[pair[1]].append(pair) return list(chain.from_iterable(bins[i] for i in order)) def alfasin1(to_order, order): arr = [[] for i in range(len(order))] d = {k:v for v, k in enumerate(order)} for item in to_order: arr[d[item[1]]].append(item) return [item for sublist in arr for item in sublist] def alfasin2(to_order, order): return sorted(to_order, key=lambda item: order.index(item[1])) print(eric(to_order, order) == alfasin1(to_order, order)) # True print(eric(to_order, order) == alfasin2(to_order, order)) # True print("eric", timeit("eric(to_order, order)", globals=globals(), nu…
accepted answer of: http://stackoverflow.com/q/47569108
type: AcceptedAnswer
upvote count: 21
has comment: http://stackoverflow.com/comment/82111812
has comment: http://stackoverflow.com/comment/82124147
answers question: http://stackoverflow.com/q/47569108
downvote count: 1

http://stackoverflow.com/comment/82206791
type: QuestionComment
comment on: http://stackoverflow.com/q/47623834
score: 0
has text: There are a bunch of issues with the code at your link. Your `Node.gScore` function (which gets masked by its own return value after it's called by `__init__`, which seems like a bad idea) computes the same value for every node, so the lines in the `astar` function that reject (for the purposes of updating `cameFrom` only) nodes that move farther away from the goal always reject everything. That check is wrong anyway, as the optimal path may need to move away from the goal before moving towards it.
type: Comment

http://stackoverflow.com/comment/82247289
has text: How have you defined ItemStackedWidget?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47644274

http://stackoverflow.com/q/47663683
has body: I was wondering if anyone could help me out a bit with this problem I cannot solve. I am using Pafy to search Youtube from a text file that has a song name written in it and that gets a new song every few minutes. I am using Watchdog to watch for file modification and when i first run the script, watchdog catches the file modification and runs the pafy and opencv script, but it won't do the same when the following modification occurs. #watchdog file change monitoring class MyHandler(FileSystemEventHandler): def on_modified(self, event): print ("Received modified event - %s." % event.src_path) cv2.destroyAllWindows() if __name__ == "__main__": event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path='//PLAYING', recursive=False) observer.start() try: while True: #read PLAYING.txt PLAYING = open('//PLAYING.txt').readline() PLAYING = PLAYING[7:] print (PLAYING) #search youtube based on NowOnAir.txt query_string = urllib.parse.urlencode({"search_query" : PLAYING}) html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string) search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode()) link = ('http://www.youtube.com/watch?v=' + search_results[0]) videoPafy = pafy.new(link) best = videoPafy.getbestvideo() videompv = best.url #opencv youtube video output video = cv2.VideoCapture(videompv) while(video.isOpened()): ret, frame = video.read() resize = cv2.resize(frame, (1680, 1050)) gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY) result = cv2.addWeighted(image, 0.2, resize, 0.8, 0) cv2.namedWindow('frame', 0) cv2.resizeWindow('frame', 1680, 1050) cv2.imshow('frame', result) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() So, I what I want to happen is, when file gets modified, I want openCV to close the window and open a new one with the new youtube query result. Any suggestions would be quite welcome, thank You in advance…
tagged with: python
has comment: http://stackoverflow.com/comment/82311233
tagged with: pafy
has comment: http://stackoverflow.com/comment/82299235
tagged with: watchdog
has comment: http://stackoverflow.com/comment/82311345
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47677094
answer count: 1
has title: close current and open a new openCV window if file modified Python
type: Question
tagged with: opencv
score: 0

http://stackoverflow.com/a/47677863
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/82314780
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/82314905
answers question: http://stackoverflow.com/q/47677800
has body: IIUC: In [362]: df['diff_in_dates '] = df.groupby('student_id')['subject_date'].diff().dt.days In [363]: df Out[363]: student_id subject_id subject_date diff_in_dates 0 100 2000 2010-01-01 NaN 1 100 2001 2010-03-05 63.0 2 100 2002 2012-05-25 812.0 3 101 2000 2009-01-10 NaN 4 101 2001 2016-08-16 2775.0 5 102 2000 2008-05-05 NaN 6 102 2003 2008-05-20 15.0 7 102 2004 2009-01-03 228.0 8 102 2005 2010-02-13 406.0
has comment: http://stackoverflow.com/comment/82314964
accepted answer of: http://stackoverflow.com/q/47677800

http://stackoverflow.com/comment/138880082
has text: how to remove `0 1 2 3 4`, and how to align title of customer ID with another column title? I'm asking this because I want copy to excel without another post processing (pasting)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47684812
type: Comment

http://stackoverflow.com/a/47621693
answers question: http://stackoverflow.com/q/47621670
score: 0
has body: The number of grains on a tile = 2^nrTile. So ask input and return 2^input.
type: Answer

http://stackoverflow.com/q/47547403
has comment: http://stackoverflow.com/comment/82051371
favorite count: 0
accepted answer: http://stackoverflow.com/a/47549412
has answer: http://stackoverflow.com/a/47549412
has title: Regular expression for "mm-dd-yy" date format not finding any match in python
type: Question
has comment: http://stackoverflow.com/comment/82053436
has comment: http://stackoverflow.com/comment/82051514
has comment: http://stackoverflow.com/comment/82051336
tagged with: datetime
answer count: 5
tagged with: python
tagged with: regex
has body: I am reading a .csv file with 5 columns - C1, C2, C3, C4, C5. C4 contains dates, phone numbers, text, etc. Now, I am trying to write a regular expression to find dates with mm-dd-yy format in C4 and output the results to a text file. However, my code is not outputting anything to the file. I know there are dates with that date format in my input file, but something seems wrong. Any suggestions ? My Code: import re inputfile = open("train.csv", 'r') outputfile = open("sample.txt",'w') for line in inputfile: x = re.findall('.*?^([0-9][0-9]-[0-9][0-9]-[0-9][0-9])$.*', line) if len(x) != 0: print &gt;&gt; outputfile, x Sample train.csv file format: sen_id word_id type before after 1 0 text On On 1 1 date 12/2/12 december twelve two thousand twelve 1 2 text there there 2 0 text he he 2 1 text was was 2 2 text born born 2 3 date Jan-12 january two thousand twelve
has comment: http://stackoverflow.com/comment/82052307
possible better answer: http://stackoverflow.com/a/47548355
has answer: http://stackoverflow.com/a/47547483
has comment: http://stackoverflow.com/comment/82052253
upvote count: 2
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47548355
has answer: http://stackoverflow.com/a/47547500
downvote count: 2
has answer: http://stackoverflow.com/a/57337817

http://stackoverflow.com/q/47687797
answer count: 1
downvote count: 0
upvote count: 4
has title: When to remove stop words when using bigram_measures like PMI?
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/19145332
tagged with: nltk
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48491681
tagged with: nlp
has comment: http://stackoverflow.com/comment/82346422
type: Question
accepted answer: http://stackoverflow.com/a/48491681
has body: I need to verify an overall approach to dealing with bigram stop words that are returned from bigram_measures such as PMI. Why deal with these stop words? Well, they're noise and don’t add any additional value past a certain point. I've seen several specific examples of how to use bigram_measures. However, I'm wondering WHEN it's best to remove stop word in the overall process of cleaning data, expansion, lemmatizing/stemming, etc. And yes, I am using a corpus that is sufficiently large. I remember the size of your corpus will also affect the quality of the bigram_measures result. Based on the accepted answer in this post (NLTK - Counting Frequency of Bigram) it seems that stop words could be removed after PMI or other bigram_measures are used on the corpus. "Imagine that if filtering collocations was simply deleting them, then there were many probability measures such as liklihood ratio or the PMI itself (that compute probability of a word relative to other words in a corpus) which would not function properly after deleting words from random positions in the given corpus. By deleting some collocations from the given list of words, many potential functionalities and computations would be disabled..." Therefore, I believe the best process is: Clean the text and remove garbage chars like HTML tags, etc. Expand contractions (e.g.: they're -> they are) Lemmatize or stem to normalize the words Calculate bigrams using bigram_measures like PMI. You can calculate bigrams using other methods, but this is what I'm using. Apply a frequency filter like "apply_freq_filter(N)" to get the bigrams that occur above your threshold. Note this will still return some bigrams with stop words mixed in with valuable bigrams. Check to see if BOTH words are stop words. If yes, then don't include that bigram in the final results but leave them in the corpus for the reasons quoted above. Is this a correct overall approach to dealing with bigram stop words mixed in with valuable bigrams?

http://stackoverflow.com/comment/82107437
type: AnswerComment
comment on: http://stackoverflow.com/a/47575130
score: 0
type: Comment
has text: In the case when I don't have time in UTC, how do I make use of tzinfo? For eg, the doc says in an example tzinfos = {"BRST": -10800}. What does 10800 represent here?

http://stackoverflow.com/comment/82153524
comment on: http://stackoverflow.com/a/47597088
score: 0
type: Comment
has text: @Badatprogramming I don't really understand your comment. When do commas disappear? Note that I `join` by `','`, whereas you probably joined with `''` before, as the `,` were still in the list.
type: AnswerComment

http://stackoverflow.com/q/47625526
has answer: http://stackoverflow.com/a/51754181
upvote count: 19
score: 19
favorite count: 0
has comment: http://stackoverflow.com/comment/82208974
tagged with: debugging
has comment: http://stackoverflow.com/comment/110544118
has answer: http://stackoverflow.com/a/75610463
linked to: http://stackoverflow.com/q/772124
answer count: 5
has comment: http://stackoverflow.com/comment/82208918
tagged with: python
has comment: http://stackoverflow.com/comment/86766924
has answer: http://stackoverflow.com/a/47626134
type: Question
tagged with: pycharm
downvote count: 0
has comment: http://stackoverflow.com/comment/86766568
has answer: http://stackoverflow.com/a/53064059
type: UnansweredQuestion
has title: How to break on `pass` in pycharm
has answer: http://stackoverflow.com/a/68474255
has body: In pycharm, I would like to break on a breakpoint that does nothing, during debugging. How can I do this? For example, I would like to break on the pass statement: for i in range(999999): if i == 6232: pass If I set a breakpoint on pass, the debugger doesn't break there. The closest I've been able to do so far is to make up some unused variable name, and assign it a pointless value, so I can set a breakpoint on that line: for i in range(999999): if i == 6232: foobar_unused_variable = "At least I can set a breakpoint on this line."

http://stackoverflow.com/a/47573525
has comment: http://stackoverflow.com/comment/82104521
has comment: http://stackoverflow.com/comment/82104808
accepted answer of: http://stackoverflow.com/q/47573159
has comment: http://stackoverflow.com/comment/82104385
has body: There's nothing special here with Selenium. That is your tool for interacting with the browser. It is your program that needs to decide how to do that interaction, and what you do with the information from it. It sounds like you want to build a database of users, so why not use a database? something like SQLite or PostgreSQL might work nicely for you. Among the user details, store the name as it appears in the link (assuming it will be unique for each user), and index that name. when scraping your page, pull that link text, then use SQL statements to search if the record exists by that name, if not, then click the link and add a new record.
type: Answer
has comment: http://stackoverflow.com/comment/82104061
has comment: http://stackoverflow.com/comment/82104626
has comment: http://stackoverflow.com/comment/82104351
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47573159

http://stackoverflow.com/a/47693313
type: AcceptedAnswer
type: Answer
score: 0
has body: On Raspberry PI I am using Kivy for GUI. You can do it in that way: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button import threading import time class ButtonDemo(BoxLayout): def __init__(self, **kwargs): super(ButtonDemo, self).__init__(**kwargs) self.orientation = "vertical" self.add_widget(Button(text = "Action #1", on_press = self.def_1)) self.add_widget(Button(text = "Action #2", on_press = self.def_2)) self.add_widget(Button(text = "Stop", on_press = self.stop)) loop_thread_1 = threading.Thread() loop_thread_2 = threading.Thread() loop_running_1 = False loop_running_2 = False def def_1(self, instance): print("DEF 1") self.loop_thread_1 = threading.Thread(target = self.loop_1) self.loop_thread_1.start() def def_2(self, instance): self.loop_thread_2 = threading.Thread(target = self.loop_2) self.loop_thread_2.start() def stop(self, instance): if self.loop_running_1: self.loop_running_1 = False if self.loop_running_2: self.loop_running_2 = False def loop_1(self): self.loop_running_1 = True while self.loop_running_1: print("loop 1") time.sleep(1) def loop_2(self): self.loop_running_2 = True while self.loop_running_2: print("loop 2") time.sleep(1) class TestButtonApp(App): def build(self): return ButtonDemo() if __name__ == '__main__': TestButtonApp().run() Each loop starts in new thread, so program will not freeze. Stop button stops running threads as you wanted.
answers question: http://stackoverflow.com/q/47692049
accepted answer of: http://stackoverflow.com/q/47692049
has comment: http://stackoverflow.com/comment/82347681

http://stackoverflow.com/comment/82330313
score: 0
comment on: http://stackoverflow.com/q/47685251
type: Comment
has text: @zwer: Well from my (admittedly very little) experience (can I can probably find a stackoverflow reference as well), you are wrong. Omitting the windows shebang line from my script and attempting to run it on Windows results in a complaint of libraries not being found, or a python not found in path. If I do put the line back, the scripts run fine.
type: QuestionComment

http://stackoverflow.com/comment/82111923
type: Comment
comment on: http://stackoverflow.com/a/47572573
score: 0
type: AnswerComment
has text: Alright, thank you! You may insert your comment in your answer and I accept it.

http://stackoverflow.com/comment/82183321
comment on: http://stackoverflow.com/a/47612435
has text: The number of iterations the for loop goes through. `range(0,n)` basically goes from 0, 1, 2, .., n-1 (because zero-indexing), so the simulation is repeated n times.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82253798
score: 0
type: Comment
type: QuestionComment
has text: Yes I see that. The extra stuff after 0.5.0 might be their build numbers or commit numbers, just some extra information showing it's a stable build. Do as the doc says, `pip install folium` .
comment on: http://stackoverflow.com/q/47647365

http://stackoverflow.com/q/47658901
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82276477
has answer: http://stackoverflow.com/a/47658992
has comment: http://stackoverflow.com/comment/82276544
has title: How do I check if an input is an integer or not in python?
has body: So I am trying for my program to print the message "That is not an integer!" if the user inputs something that is not an integer basically, I thought this was how you would do that but apparently isn't, could anyone tell me what I am doing wrong please? user_number = input() if type(user_number) != int: print("That's not an integer number.")
answer count: 1
has comment: http://stackoverflow.com/comment/82276390
linked to: http://stackoverflow.com/q/5424716
accepted answer: http://stackoverflow.com/a/47658992
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82276411
upvote count: 2
duplicate of: http://stackoverflow.com/q/5424716
tagged with: types
downvote count: 0
has comment: http://stackoverflow.com/comment/82276414
tagged with: input
tagged with: python

http://stackoverflow.com/comment/82100129
has text: what have you tried, what errors are you getting?
score: 0
comment on: http://stackoverflow.com/q/47571489
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82064062
has text: It would look awful in a SO comment. Why don't you try to run it in a Python interpreter?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47552767

http://stackoverflow.com/comment/82303520
type: AnswerComment
has text: I want to use ML because all the questions cannot start with wh+ words, it can start with "can you","could you","will you" etc so I want to use ML, is there any way to use RNN/CNN to do so?
comment on: http://stackoverflow.com/a/47671472
type: Comment
score: 0

http://stackoverflow.com/comment/82315992
comment on: http://stackoverflow.com/a/47678479
score: 0
type: Comment
has text: Yes, `ax.yaxis.get_major_locator().base.set_params(nbins=3)` was exactly what I was looking for, thanks a lot!
type: AnswerComment

http://stackoverflow.com/comment/82311191
comment on: http://stackoverflow.com/q/47675349
has text: [[0.,1.,0.],[0.,0.,1.],[0.,0.,0.]]
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82077074
comment on: http://stackoverflow.com/q/47559510
has text: can you provide a link to the csv?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82098215
comment on: http://stackoverflow.com/q/47551983
has text: @electrogas 'dmesg | tail' output the following:
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82279497
type: AnswerComment
type: Comment
has text: BTW: you could create repo on GitHub with all code and then we can download last version, run it and see all code. Now we have to ask you for other elements when we have to see them.
comment on: http://stackoverflow.com/a/47659233
score: 0

http://stackoverflow.com/comment/82059796
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47551279
type: Comment
has text: The dataset fetched by fetch_mldata is the original MNIST dataset. The dataset fetched by load_digits is preprocessed version with some modification. The UCI link specifies what were the changes done.

http://stackoverflow.com/comment/82156423
type: QuestionComment
has text: Do you want a solution that works for any dimension of `lists`?
comment on: http://stackoverflow.com/q/47599047
score: 0
type: Comment

http://stackoverflow.com/comment/82138537
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47584735
has text: Adding the above code will also causes 500 Internal Server Error because of import pyodbc print("Content-Type: text/html") print("") print(" ") print("") print(" ") for row in cursor: print('row = %r' % (row,)) print(" ") @FlipperPA

http://stackoverflow.com/a/47606195
type: Answer
has body: I found a way to draw figures interactively here. plt.ion() and block the process with input() seems to be important. import matplotlib.pyplot as plt plt.ion() fig = plt.figure() ax = plt.subplot(1,1,1) ax.set_xlim([-1, 5]) ax.set_ylim([-1, 5]) ax.grid('on') for i in range(5): lineObject = ax.plot(i,i,'ro') fig.savefig('%02d.png'%i) # plt.draw() # not necessary? input() lineObject[0].remove() I also tried to block the process with time.sleep(1), but it does not work at all.
has comment: http://stackoverflow.com/comment/82180394
answers question: http://stackoverflow.com/q/47605702
score: 0

http://stackoverflow.com/comment/82173515
comment on: http://stackoverflow.com/q/47604195
score: 0
has text: you can't use `time.sleep()` because it stops mainloop which do everthing in prorgam. mainloop has to run and you have to check current time and execute this part after 3 seconds. You can use `pygame.time.get_ticks()` to get current time.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47598311
answer count: 5
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/47598607
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47598607
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47598672
has title: Find closest value in a dict
has answer: http://stackoverflow.com/a/47598884
has answer: http://stackoverflow.com/a/47598390
accepted answer: http://stackoverflow.com/a/47598598
has body: So basically I have a dict with some values in it, and I want to find the closest value to the given one. So it would look something like this: values = {"val": [210418, 211120, 211822, 212523, 213500]} input = 210944 output = find_nearest(input,values["val"]) print output # 210418 and as you can see I want to get the closest value under my value. The min() method was giving me 211120, but I want to get 210418. How can I do this?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47598598
upvote count: 2

http://stackoverflow.com/comment/82240479
score: 1
type: Comment
type: QuestionComment
has text: You can try the method of finite differences: https://en.wikipedia.org/wiki/Numerical_differentiation
comment on: http://stackoverflow.com/q/47641058

http://stackoverflow.com/comment/82278968
type: AnswerComment
has text: @DanielH thanks. I updated. I know it doesn't matter for this case, so I didn't pay much attention to it, but I suppose I should have.
comment on: http://stackoverflow.com/a/47659960
score: 1
type: Comment

http://stackoverflow.com/comment/82050023
has text: I've explained the reasoning behind my question with the edit to my main post. Hopefully that helps clarify.
type: Comment
comment on: http://stackoverflow.com/a/47545913
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82190227
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47561544
has text: replace : `for dirpath, dirname, filenames in os.listdir(mypath): for file in filenames:` with `for file in os.listdir(mypath):`
type: Comment

http://stackoverflow.com/a/47549778
answers question: http://stackoverflow.com/q/47548242
has body: that's expected when a subprocess is running. You're just killing the .bat process. You can use psutil (third party, use pip install psutil to install) to compute the child processes &amp; kill them, like this: import subprocess,time,psutil proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE) time.sleep(5) pobj = psutil.Process(proc.pid) # list children &amp; kill them for c in pobj.children(recursive=True): c.kill() pobj.kill() tested with your example, the window closes after 5 seconds
downvote count: 0
type: AcceptedAnswer
upvote count: 5
score: 5
accepted answer of: http://stackoverflow.com/q/47548242
type: Answer

http://stackoverflow.com/a/47657268
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47657051
type: Answer
has body: You need to use __init__, not __init Also, if you're using BooleanVar, you must set it to True or False, not None: self.Actions.set(False) Also, you have a method named addAction but you are calling it like self.AddAction, and you have a method named Add_to_dict that you are calling like Add_to_dict rather than self.Add_to_dict. And finally, you don't appear to be creating an instance of GameCreation anywhere.

http://stackoverflow.com/comment/82137712
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47590099
has text: Thanks for your answer, but the actual tag that I'm looking for doesn't have unique class attributes or might not have any class attribute at all. (I just picked the default bs4 sample html code.)
score: 0

http://stackoverflow.com/a/47563782
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47563682
has comment: http://stackoverflow.com/comment/82085722
downvote count: 0
upvote count: 7
has body: You can use pandas for that: import matplotlib.pyplot as plt import pandas as pd decemberMeans = [ {'year': 1948, 'temp': 271.24}, {'year': 1949, 'temp': 271.28}, {'year': 1950, 'temp': 268.52}, {'year': 1951, 'temp': 269.63}, {'year': 2015, 'temp': 277.23}, {'year': 2016, 'temp': 271.25} ] df = pd.DataFrame(decemberMeans) plt.figure(1) plt.plot(df['year'], df['temp'], 'k-')

http://stackoverflow.com/comment/82069340
comment on: http://stackoverflow.com/q/47556046
score: 0
type: Comment
type: QuestionComment
has text: https://docs.djangoproject.com/en/1.11/topics/db/queries/#lookups-that-span-relationships Might be useful reading if you haven't already seen it.

http://stackoverflow.com/comment/82166309
score: 0
has text: Thanks! What is the code for accessing only the value in a dictionary? without having to put the key in the code and just accessing the value for comparison
type: Comment
comment on: http://stackoverflow.com/a/47603591
type: AnswerComment

http://stackoverflow.com/comment/82325583
has text: Because you I cannot reproduce this...
comment on: http://stackoverflow.com/q/47683022
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47553041
score: 1
downvote count: 0
has body: I'd like to have a Python script that will automatically combine a bunch of RTF files for me. I've come across partial solutions involving opening them as Word application objects, but I don't know how to get to the next step of combining them. I also don't really have the time or the interest to learn how to manually parse RTF formats. I suspect the files won't use different fonts or colours or anything, but that could change, I'm not the one producing them.
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1337446
tagged with: python
tagged with: rtf
has title: Merge RTF files with Python
has comment: http://stackoverflow.com/comment/82063018
has comment: http://stackoverflow.com/comment/82062995
answer count: 0
tagged with: com

http://stackoverflow.com/comment/82492081
type: QuestionComment
comment on: http://stackoverflow.com/q/47652836
score: 0
has text: Answer comment is not a good place for asking new question. But simple answer is -- yes.
type: Comment

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47644742
type: Tag

http://stackoverflow.com/q/47616429
has comment: http://stackoverflow.com/comment/82191197
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82191140
answer count: 1
tagged with: pickle
has title: Error code trying to load student grade menu for individual's and all students
has body: Hello everyone so I am creating a student grade menu that I would like to enter a students name and two quiz grades using pickle. Once those grades are entered I would like to create a report and after I am trying to search for an individual student for my menu option two and show all students with menu option three but I get an error code every time when I am trying to print it. import pickle def menu(): selection = input("0\tExit" "\n1\tEnter Student Name/Grades" "\n2\tIndividual Report" "\n3\tReports" "\nEnter Menu Number: ") if selection == "0": systemExit() if selection == "1": studentData() if selection == "2": singleReport() if selection == "3": studentReports() def systemExit(): exit() def studentData(): name = input("Enter Student Name: ") quiz1 = input("Enter Quiz 1: ") quiz2 = input("Enter Quiz 2: ") with open("pStudent_Quiz_Grades.p", "ab") as pFile: pickle.dump((name, (quiz1, quiz2)), pFile) clearScreen() return() def clearScreen(): print("\n" * 5) return () def singleReport(): pFile = open("pStudent_Quiz_Grades.p", "rb") grades_dict = pickle.load(pFile) search = input("Enter a Name to Search: ") for name in grades_dict: if name.upper() == search.upper(): print(name+": "+str("pStudent_Quiz_Grades.p"[name])) def studentReports(): pFile = pickle.load(open("pStudent_Quiz_Grades.p", "rb")) print(pFile) while True: menu()
downvote count: 1
has comment: http://stackoverflow.com/comment/82191473
favorite count: 0
has answer: http://stackoverflow.com/a/47616823
has comment: http://stackoverflow.com/comment/82191161
has comment: http://stackoverflow.com/comment/82191344
has comment: http://stackoverflow.com/comment/82191213
tagged with: python
tagged with: menu
score: -1
type: Question

http://stackoverflow.com/a/47681331
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47636088
downvote count: 0
type: Answer
has body: You can specify any path for a new file. If you want to replace original file - just use original file path as a new path: from PIL import Image size = (128, 128) original_file_path = 'folder/file.jpg' try: im = Image.open(original_file_path) im.thumbnail(size) im.save(original_file_path) except IOError: print("cannot create thumbnail for", original_file_path)
score: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47636088

http://stackoverflow.com/a/47542713
has comment: http://stackoverflow.com/comment/104856380
has comment: http://stackoverflow.com/comment/104856278
accepted answer of: http://stackoverflow.com/q/47542657
has comment: http://stackoverflow.com/comment/104856092
has comment: http://stackoverflow.com/comment/82063162
type: Answer
has comment: http://stackoverflow.com/comment/104855500
has comment: http://stackoverflow.com/comment/104856368
has comment: http://stackoverflow.com/comment/82095779
has comment: http://stackoverflow.com/comment/104856439
has comment: http://stackoverflow.com/comment/82098366
downvote count: 0
answers question: http://stackoverflow.com/q/47542657
has body: df = df.round(decimals=6).astype(object) Converting to object will allow mixed representations. But, keep in mind that this is not very useful from a performance standpoint. df A B 0 0.149724 -0.770352 1 0.606370 -1.194557 2 10.000000 10.000000 3 10.000000 10.000000 4 0.843729 -1.571638 5 -0.427478 -2.028506 6 -0.583209 1.114279 7 -0.437896 0.929367 8 -1.025460 1.156107 9 0.535074 1.085753 df.round(6).astype(object) A B 0 0.149724 -0.770352 1 0.60637 -1.19456 2 10 10 3 10 10 4 0.843729 -1.57164 5 -0.427478 -2.02851 6 -0.583209 1.11428 7 -0.437896 0.929367 8 -1.02546 1.15611 9 0.535074 1.08575
has comment: http://stackoverflow.com/comment/104856358
type: AcceptedAnswer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/104856189
has comment: http://stackoverflow.com/comment/104856307

http://stackoverflow.com/comment/82070352
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47554658
has text: yes `func.now` indeed work, how can I know mysql in default uses utc? Do you have any documentation for that?
score: 0

http://stackoverflow.com/comment/82150484
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47595771
has text: So what is the value of `len(chargeAccounts)`?

http://stackoverflow.com/comment/82240568
comment on: http://stackoverflow.com/q/47640913
type: Comment
type: QuestionComment
score: 2
has text: Your `.Prank(...)` call returns `None` (the default return value). You can't assign `None` to two target names.

http://stackoverflow.com/q/47645501
tagged with: list
answer count: 3
has comment: http://stackoverflow.com/comment/82249840
has answer: http://stackoverflow.com/a/47645807
possible better answer: http://stackoverflow.com/a/47645807
has answer: http://stackoverflow.com/a/47646106
score: 1
tagged with: subset-sum
has body: Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible. For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]]. subsets = [] def subset_sum(numbers, target, partial=[]): s = sum(partial) if s == target: subsets.append(partial) if s &gt;= target: return for i in range(len(numbers)): n = numbers[i] remaining = numbers[i + 1:] subset_sum(remaining, target, partial + [n]) subsets.sort() subsets.reversed() How can I remove values that are once mentioned in the subsets' list? In the example above, how can I hay only one [2,2]. And that, show the values of the initial array that are not in this final list? In the example above [1].
downvote count: 0
has comment: http://stackoverflow.com/comment/82250027
upvote count: 1
has comment: http://stackoverflow.com/comment/82249981
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82249693
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/82249899
has answer: http://stackoverflow.com/a/47645658
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47645658
tagged with: python
type: AnsweredQuestion
has title: Filtering the duplicates in subset sum combinations
has comment: http://stackoverflow.com/comment/82249897

http://stackoverflow.com/q/47600448
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: boxapiv2
tagged with: python
tagged with: box-api
has body: I'm pretty new to Python and programming and I am trying to figure out how to automate the box.com authentication process and it's kicking my butt. Any help would be appreciated! I have this code below, which obviously wasn't mine but came from a tutorial. I am trying to figure out the keyring.get_password('Box_Auth', 'mybox@box.com') I'm thinking the mybox@box.com is my redirect URI? But I'm not sure what it is looking for when it asks for the Box_Auth. Here is the full code """An example of Box authentication with external store""" import keyring from boxsdk import OAuth2 from boxsdk import Client CLIENT_ID = '' CLIENT_SECRET = '' def read_tokens(): """Reads authorisation tokens from keyring""" # Use keyring to read the tokens auth_token = keyring.get_password('Box_Auth', 'mybox@box.com') refresh_token = keyring.get_password('Box_Refresh', 'mybox@box.com') return auth_token, refresh_token def store_tokens(access_token, refresh_token): """Callback function when Box SDK refreshes tokens""" # Use keyring to store the tokens keyring.set_password('Box_Auth', 'mybox@box.com', access_token) keyring.set_password('Box_Refresh', 'mybox@box.com', refresh_token) def main(): """Authentication against Box Example""" # Retrieve tokens from secure store access_token, refresh_token = read_tokens() # Set up authorisation using the tokens we've retrieved oauth = OAuth2( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token=access_token, refresh_token=refresh_token, store_tokens=store_tokens, ) # Create the SDK client client = Client(oauth) # Get current user details and display current_user = client.user(user_id='me').get() print('Box User:', current_user.name) Again, I would really appreciate any help!
score: 2
has answer: http://stackoverflow.com/a/47906733
has title: How can I use Python Keyring in conjunction with Box API OAuth2?
tagged with: python-keyring
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47643041
has body: [lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)] Here, lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) only defines a function and does not call it. Instead, you can directly access BasicLSTMCell() function: [tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)] You can then further shorten it by having MultiRNNCell and BasicLSTMCell imported this way: from tensorflow.contrib.rnn import MultiRNNCell, BasicLSTMCell lstm_stacks = [BasicLSTMCell(lstm_size) for _ in range(number_of_layers)] stacked_lstm = MultiRNNCell(lstm_stacks)
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47642991
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47642991
type: Answer

http://stackoverflow.com/q/47585513
tagged with: python
has answer: http://stackoverflow.com/a/47586208
type: Question
score: 0
has title: Python logging writing to multiple separate log files
answer count: 1
tagged with: django
type: AnsweredQuestion
has body: I have a Django web application that runs a bunch of helper scripts. Each of these scripts writes its own log. I am noticing that the scripts are writing to each others logs. These scripts are launched by separate users/sessions. Whats going on? Here is the implementation of the logger within ScriptA import logging logging.basicConfig(format='%(asctime)s %(message)s',filename='/var/logs/scriptA.log',level=logging.DEBUG) logging.info("INFO: test log from scriptA")) same for scriptB but say someone runs scriptB, it writes to scriptA.log instead of scriptB.log it seems logging is created a shared global module. How can I stop this EDIT: most solutions here are for 2 separate logs within the same class. my issue is separate scripts/classes writing to each others logs
accepted answer: http://stackoverflow.com/a/47586208

http://stackoverflow.com/q/47544099
upvote count: 2
tagged with: euclidean-distance
answer count: 1
tagged with: k-means
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has title: Trying to understand what is happening in this Python Function
tagged with: python
has body: def closest_centroid(points, centroids): """returns an array containing the index to the nearest centroid for each point""" distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2)) return np.argmin(distances, axis=0) Can someone explain the exact working of this function? I currently got points which looks like: 31998888119 0.94 34 23423423422 0.45 43 .... And so on. In this numpy array, points[1] would be the long ID while points[2] is 0.94 and points[3] would be 34 for their first entry. Centroids is just a random selection from this particular array: def initialize_centroids(points, k): """returns k centroids from the initial points""" centroids = points.copy() np.random.shuffle(centroids) return centroids[:k] Now I want to get the Euclidean distance from the values of points ignoring the first column of IDs and centroids (once again ignoring the first column). I don't exactly understand the syntax from the line distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2)). Why exactly are we summing across the third column, while there being a decleration for a new axis: np.newaxis? Also along what axis am I supposed to make the np.argmin work?
accepted answer: http://stackoverflow.com/a/47733016
type: Question
score: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/47733016

http://stackoverflow.com/comment/82286529
has text: With pure Python this can't be done faster. Look at external libraries like numpy.
score: 2
comment on: http://stackoverflow.com/q/47663579
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47545353
answers question: http://stackoverflow.com/q/47544115
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47544115
has comment: http://stackoverflow.com/comment/133994035
has body: Modified PHP code $key = 'pqrstuvwxyz$abcdefghijAB12345678'; I got new encrypted string is: 4a3d8b7449fb45c521b04314382670e9c4255682cde4fda51d715a3631718ccb Then, I modified Python code for key, key = "pqrstuvwxyz$abcdefghijAB12345678" I received the below. b'abcdefghijklmnopqrstuvwxyz\x06\x06\x06\x06\x06\x06' I added to remove unpad = lambda s: s[:-ord(s[len(s) - 1:])] unpad(decrypted).decode('utf-8') I resolved!!
score: 2

http://stackoverflow.com/q/47659048
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82276888
type: Question
has comment: http://stackoverflow.com/comment/82276986
tagged with: opencv
has title: Rectangles uneven in CV2 grid
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82277236
has body: I am trying to draw a grid on a (very) large image. I am using cv2 and Python 3 for reference. See the following code: output_image = np.zeros((23000, 23000), dtype=np.int) output_image = np.uint8(np.stack((output_image, output_image, output_image), 2)*255) ... import cv2 def visualise_tiles(image, num_tiles): X = image[:,0] Y = image[:,1] x_range = int(max(X) - min(X)) y_range = int(max(Y) - min(Y)) x_step = int((max(X) - min(X)) // num_tiles) y_step = int((max(Y) - min(Y)) // num_tiles) for i in tqdm(range(num_tiles)): for j in range(num_tiles): x_left, y_left = x_step * i, y_step * (j + 1) x_right, y_right = x_step * (i + 1), y_step * j cv2.rectangle(output_image, (x_left, y_left), (x_right, y_right), (255, 255, 0), 100) When given a specific image, the x_range is 9786 and y_range is 21674. The x_step thus evaluates to 489, and the y_step to 1083. This is fine, and we expect the resultant rectangles to be non-square, which they are. All good. My problem is that there is some weird 'stretching' that goes on in the output and the rectangles are uneven, whereas I want a perfect grid. See in particular the attached image at 15000 on the y-axis and 5000 on the x-axis: I am not sure why this is - can anyone explain?
tagged with: python
answer count: 0

http://stackoverflow.com/comment/82216222
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47629124
has text: Hi @VinodBhavnani this is the consolo.log for selected_status `["new", "bid", "inprogress", "completed"]`
score: 0

http://stackoverflow.com/comment/82208556
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47625074
has text: You might just need to pass in request.user - that is an actual user object, request.user.pk is the user's primary key not an object.

http://stackoverflow.com/a/47614768
accepted answer of: http://stackoverflow.com/q/47614229
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47614229
has body: There are two mistakes which together give problem First: player.pos.y = hit[0].rect.top - hit[0].rect.height It makes no sense. top - height give the same as bottom so you have player.pos.y = hit[0].rect.bottom but you need hit[0].rect.top with player.rect.bottom player.rect.bottom = hit[0].rect.top player.pos.y = player.rect.y (and here I don't know why you use player.pos if it always has the same value as player.rect, and rect has many useful fields like rect.bottom, rect.center, etc. and it automatically recalculates rect.x, rect.y when you change rect.bottom, rect.center, etc.) So first correction is if hit: if player.rect.bottom &gt;= hit[0].rect.top: #player.pos.y = hit[0].rect.top - hit[0].rect.height player.rect.bottom = hit[0].rect.top player.pos.y = player.rect.y player.vel.y = 0 Second: You should do all moves before checking collisionts # player movement player.move(pg.key.get_pressed()) # update player player.update() #update block group Asset.GROUP.update() # check for collision - after all moves block_collision(player, Asset.GROUP) Full code import pygame as pg import os #vector VEC = pg.math.Vector2 def paint(parent, color=None): """ fills the background for surfaces. color: for none sprite surfaces optional parameter if given """ #set background color based on surface type if color: #class based surfaces or sprites background = pg.Color(color) else: #none sprite surfaces usuallly not class background = pg.Color(parent.background) #check for image attribure #if found fill the image's backround if hasattr(parent, "image"): parent.image.fill(background) #if "image" not found fill the surface itself else: parent.fill(background) class Asset(pg.sprite.Sprite): """ asset class functions as base class for various assets in this case either a player asset or a block asset group """ #if the given family name(see bellow in constructor) is block, #all instances of block will be added to this group else its ignored GROUP = pg.sprite.Group() def __init__(self, …
type: Answer

tfrecord
tags question: http://stackoverflow.com/q/47679859
tag name: tfrecord
type: Tag

http://stackoverflow.com/q/47556046
has comment: http://stackoverflow.com/comment/82071445
type: Question
has comment: http://stackoverflow.com/comment/82069292
has comment: http://stackoverflow.com/comment/82069423
has comment: http://stackoverflow.com/comment/82069755
tagged with: django
tagged with: django-models
tagged with: python
has body: Let's say I have a model_a that has foreign key to model_b and I am accessing model_b's properties like so: model_a = ModelA.objects.get(id=id) x = model_a.model_b.x y = model_a.model_b.y z = model_a.model_b.z Is Django going to the DB and joining the tables to get x, y, and z fields on each line? Or does Django store the result of the first join and then no more joins are needed? Is this in any way different, performance-wise? model_b = model_a.model_b # only one join x = model_b.x y = model_b.y z = model_b.z Just curious
has answer: http://stackoverflow.com/a/47556545
has comment: http://stackoverflow.com/comment/82071562
type: AnsweredQuestion
score: 0
has title: are django model queries cached?
has comment: http://stackoverflow.com/comment/82071075
answer count: 1
has comment: http://stackoverflow.com/comment/82070379
has comment: http://stackoverflow.com/comment/82069340
accepted answer: http://stackoverflow.com/a/47556545

http://stackoverflow.com/comment/82211485
type: QuestionComment
comment on: http://stackoverflow.com/q/47626314
score: 0
type: Comment
has text: But *how* are you running postgres? How are you starting it? Where is it running? Is is on the same host as your flask project? Ideally, rather than responding in comments, update your question to include more information, and replace the image link with the actual text of your error.

http://stackoverflow.com/a/47649036
has body: you can use pd.Series(['20-21 May 2008', '19 March 2008', '16-17 September 2010', '5 September 2011']).str.extract('(\w{3,}\s\d{4})', expand=False) This will extract the required string and would create a new Series object.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47648515

http://stackoverflow.com/comment/125237010
type: Comment
comment on: http://stackoverflow.com/a/59226957
score: 0
type: AnswerComment
has text: Hi Gitau, Check this solution out, https://stackoverflow.com/a/69152121/644384.

http://stackoverflow.com/q/47567233
tagged with: python
has comment: http://stackoverflow.com/comment/82092702
has comment: http://stackoverflow.com/comment/82092195
duplicate of: http://stackoverflow.com/q/8405723
tagged with: pandas
answer count: 0
score: 1
has title: Calling / Executing Python Script from Java is not getting completed
tagged with: java
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I am calling a Python script from Java by mentioning the Python script name in the ProcessBuilder method within Java code. Code snippet for the same is given below : String[] commandToProcessDocument = { "python", "C:\\Users\\User_Name\\sample_integration.py"}; ProcessBuilder pb = new ProcessBuilder(commandToProcessDocument); Process process = pb.start(); And the Python script has the following lines in it : import pandas as pd if __name__ == '__main__': print("Welcome To Python") a = 5 b = 10 c = a+b print(c) df = pd.read_csv("Test_Dataset.csv") print("came after reading") When I execute this python script either in Spyder IDE or in Command Prompt, I am able to see the 3rd print statement which is "came after reading". Attached is the screenshot that shows the Command Line output But when I try to execute the same python script from Java using Netbeans IDE, the execution doesn't go beyond the pd.read_csv line. It just prints "15" which is the value of sum of 'a' and 'b' variables and keeps on getting executed without ending. Is there anything I need to do specially for invoking Pandas from java or am i missing anything very basic here ?
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8405723

http://stackoverflow.com/comment/82348737
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47693867
has text: again please have a read [MCVE](https://stackoverflow.com/help/mcve). and I also think you at least learn how to use the text editor of SO as well; for everyone's benefits your codes, sample data should be formatted correctly, and it's easy to do as well. please do that next time, thanks.
score: 0

http://stackoverflow.com/comment/82328648
type: Comment
comment on: http://stackoverflow.com/a/47684477
type: AnswerComment
has text: This works great except the loop is only good for one error. So when I input two names in a row which are not in the csv it only works 1 time and then stops.
score: 0

http://stackoverflow.com/q/47629640
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82217001
has answer: http://stackoverflow.com/a/47629749
accepted answer: http://stackoverflow.com/a/47629699
answer count: 5
has answer: http://stackoverflow.com/a/47629699
has body: Apologies for the potentially noobish question. I have this dict: info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []} I need to make a query with each value. In Python what is the best way to get the values? I currently do this: keys = info.keys () for i in keys: for j in info [i]: # Make query with j I think it can be done better. Thank you very much!
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82217250
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47629742
score: 0
has answer: http://stackoverflow.com/a/47629694
possible better answer: http://stackoverflow.com/a/47629722
has answer: http://stackoverflow.com/a/47629722
upvote count: 1
has title: Best way to get values from a dictionary in Python
downvote count: 1

http://stackoverflow.com/a/47661266
upvote count: 30
has body: UPDATE: The feature is now added. Do this: YouTube('http://youtube.com/watch?v=9bZkp7q19f0') .streams.first() .download(filename='filename') Old answer: This is not possible in the current latest (v7.0.18) release. The feature has been added, but no new release has been released since then. If you want to have this feature, you need to download the pytube repository: https://github.com/NFicano/pytube If you have done so, you can use YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download(filename='filename') It will automatically add the filename extension, so you don't have to include that. I found it by reading the source. There, I found the declaration of the function download in the file streams.py: def download(self, output_path=None, filename=None): So you can obviously also specify a path. For a good workaround, see landogardner's answer.
answers question: http://stackoverflow.com/q/47649536
type: Answer
score: 30
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47649536
downvote count: 0

http://stackoverflow.com/comment/82277383
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47659071
score: 0
has text: Thanks PM 2Ring that helped a lot. I had no idea the text file contained empty lines!

http://stackoverflow.com/comment/82148527
type: Comment
has text: Did you run it on the file linked in my comment or the example posted in my question? I'm getting this error `TypeError: 'values' is not ordered, please explicitly specify the categories order by passing in a categories argument`. I haven't found very much guidance as to what this error means.
type: AnswerComment
comment on: http://stackoverflow.com/a/47560106
score: 0

http://stackoverflow.com/comment/82320800
has text: @ericleasemorgan Ah, ok. That looks reasonable. As said, I just played a bit around and wasn't aware that you wanted to create XML. Attributes makes sense there. Never mind. And thank you for showing me another interesting module. :-)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47661977

firebase-realtime-database
tags question: http://stackoverflow.com/q/47618804
tag name: firebase-realtime-database
tags question: http://stackoverflow.com/q/47643805
tags question: http://stackoverflow.com/q/47687307
type: Tag
tags question: http://stackoverflow.com/q/47553823

http://stackoverflow.com/comment/82334747
type: QuestionComment
has text: so what should i do now @Ilja Everilä
score: 0
comment on: http://stackoverflow.com/q/47673271
type: Comment

http://stackoverflow.com/q/47568211
favorite count: 0
linked to: http://stackoverflow.com/q/2835559
type: AnsweredQuestion
has body: I have a dictionary in python. I want to modify that dictionary and then save the dictionary to an external file so that when I load up the python program again it grabs the dictionary data from the external file. class Data: """ Data handling class to save and receive json data, parent of User for data purposes. """ def saveData(data, file): with open(file, 'r+') as dataFile: dataFile.write(json.dumps(data)) def getData(file): with open(file, 'r+') as dataFile: return json.loads(dataFile.readline()) def deleteContent(file): file.seek(0) file.truncate() But when I write to the file and then try to read it reads it as a string and I can't use the read data to set a dictionary. How can I get data in a dictionary from an external JSON file as dictionary data, not string data? data = Data.getData("chatbotData.json") dataDict = data dataDict["age"] = 2 Here is what I want to do with the data and I get this error: TypeError: 'str' object does not support item assignment
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/2835559
type: Question
tagged with: python-3.x
has title: How to read and write dictionaries to external files in python?
accepted answer: http://stackoverflow.com/a/47568348
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47568348
linked to: http://stackoverflow.com/q/7100125
downvote count: 1
has comment: http://stackoverflow.com/comment/82093945

http://stackoverflow.com/a/47631765
downvote count: 0
answers question: http://stackoverflow.com/q/47541749
upvote count: 2
type: Answer
score: 2
has body: If you are willing to (re-)enter states every cycle, this should do the trick: from transitions import Machine from random import choice class Model(object): def on_enter_manual(self): # do_user_input_actions() print('manual') def on_enter_auto(self): # do_automatic_actions() print('auto') def event_detected(self): # return gpio.event_detected() # For simulation purposes randomise the return value return choice([True, False]) states = ['manual', 'auto'] transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'], 'dest': 'manual', 'conditions': 'event_detected'}, {'trigger': 'loop', 'source': ['manual', 'auto'], 'dest': 'auto'}] model = Model() machine = Machine(model=model, states=states, transitions=transitions, initial='manual') for i in range(10): model.loop() transitions processes possible transitions in the order they were added. This means that the first transition is executed when event_detected returns True. If this is not the case, the second transition will be chosen as it has no condition. For this solution, some tweaks are possible: a) You could replace source:[..] with source:'*' to allow a loop transitions from all states. If you want to add states in the future this might be useful, but it can also backfire if you plan to use more than one trigger. b) In case do_user_input_actions, gpio.event_detected, do_automatic_actions are static methods, you can more or less omit the model by using the following transitions: transitions = [{'trigger': 'loop', 'source': ['manual', 'auto'], 'dest': 'manual', 'conditions': gpio.event_detected, 'after': do_user_input_actions}, {'trigger': 'loop', 'source': ['manual', 'auto'], 'dest': 'auto', 'after': do_automatic_actions}] machine = Machine(states=states, transitions=transitions, initial='manual') Note that I passed function references rather than strings. Strings are considered to be model functions while function references can originate from anywhere. Since our model would be more or less empty, we can use th…

http://stackoverflow.com/comment/82256093
has text: No way, It did work like charm. Btw, the loading thing was happening perhaps at my end.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47648273
type: AnswerComment

http://stackoverflow.com/q/47631081
has title: Html parser to dataframe
downvote count: 1
favorite count: 0
score: -1
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47632690
upvote count: 0
type: UnansweredQuestion
tagged with: python
has body: I am struggled trying to convert a html table to a dataframe. I would like to write the table in a csv file. from requests import session import sys import csv from bs4 import BeautifulSoup c = session() outfile = open("Weather2017.csv", 'wb') response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&amp;monthend=12&amp;yearend=2017&amp;req_city=NA&amp;req_state=NA&amp;req_statename=NA') soup = BeautifulSoup(response.text, "html.parser") soup = soup.find(id="obsTable").text.replace('\n','',1) outfile.write(soup.replace('\n',',London\n')) the type error is the following --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-11-1e149d844e15&gt; in &lt;module&gt;() 11 soup = BeautifulSoup(response.text, "html.parser") 12 soup = soup.find(id="obsTable").text.replace('\n','',1) ---&gt; 13 outfile.write(soup.replace('\n',',London\n')) 14 15 TypeError: a bytes-like object is required, not 'str' this is the table I want to covert in to a csv file Can anyone help me? Thanks in advance!
answer count: 2
has comment: http://stackoverflow.com/comment/82221164
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47638349

http://stackoverflow.com/q/47627298
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10165405
has comment: http://stackoverflow.com/comment/82212362
accepted answer: http://stackoverflow.com/a/47627417
linked to: http://stackoverflow.com/q/27566391
tagged with: python
has comment: http://stackoverflow.com/comment/82212334
has comment: http://stackoverflow.com/comment/82212456
has comment: http://stackoverflow.com/comment/82212533
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82212699
upvote count: 3
has body: Please see the following code: #! /usr/bin/env python3 class MyTupleT(tuple): def __init__(self, contents): tuple.__init__(contents) self.len = len(contents) class MyTupleS(tuple): def __init__(self, contents): super().__init__(contents) self.len = len(contents) t = MyTupleT([0, 1, 2]) print(t.len, t) s = MyTupleS([0, 1, 2]) print(s.len, s) The output is: 3 (0, 1, 2) Traceback (most recent call last): File "tuple_init.py", line 16, in &lt;module&gt; s = MyTupleS([0, 1, 2]) File "tuple_init.py", line 10, in __init__ super().__init__(contents) TypeError: object.__init__() takes no parameters The docs say that super() will: Return a proxy object that delegates method calls to a parent or sibling class of type IIUC here super() is the same as super(MyTupleS, self). Now the docs further say that The search order is same as that used by getattr() except that the type itself is skipped. The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). Ohkay but then: $ MyTupleS.__mro__ (__main__.MyTupleS, tuple, object) So the super() line should first look within tuple to find __init__ and tuple's __init__ can certainly take one parameter (other than self of course) and is what is being called by the explicit tuple.__init__ line. So why doesn't the super().__init__ call work identical to that? Why is it trying to invoke object.__init__ and failing? IIUC one should only need to explicitly specify the superclass when one is worried that the inheritance hierarchy can change in a "dynamic execution environment" (phrase from the docs) and wants the method of a particular superclass to be called. But this error effectively makes it mandatory for the superclass to be specified. Why? NOTE: This is different from another similarly titled question.
has title: How is `tuple.__init__` different from `super().__init__` in a subclass of tuple?
has answer: http://stackoverflow.com/a/47627417
answer count: 1
has comment: http://stackoverflow.com/comment/82212564
downvote count: 1

http://stackoverflow.com/comment/82228712
comment on: http://stackoverflow.com/q/47635210
type: QuestionComment
score: 0
has text: That's what I messed up. I thought it was the way I was passing the arguments to the function. Thanks
type: Comment

http://stackoverflow.com/comment/82097333
type: AnswerComment
has text: @AlexanderReynolds Yeah that's true, I assumed that it doesn't because it's "some other items" as in from someplace else.
comment on: http://stackoverflow.com/a/47569884
type: Comment
score: 0

http://stackoverflow.com/q/47639983
has answer: http://stackoverflow.com/a/47640025
has answer: http://stackoverflow.com/a/47640046
type: UnansweredQuestion
has title: how to remove spaces in a list that has a specific character
has comment: http://stackoverflow.com/comment/82238375
has answer: http://stackoverflow.com/a/47641204
has body: how do you get a list to fix the spaces in the list m. m = ['m, a \n', 'l, n \n', 'c, l\n'] for i in m: if (' ') in i: i.strip(' ') I got: 'm, a \n' 'l, n \n' 'c, l\n' and I want it to return: ['m, a\n', 'l, n\n', 'c, l\n']
has comment: http://stackoverflow.com/comment/82238379
tagged with: python
has comment: http://stackoverflow.com/comment/82238365
has answer: http://stackoverflow.com/a/47640095
answer count: 4
tagged with: python-2.7
score: 0
tagged with: list
tagged with: strip
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82238348
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47663135
type: Answer
score: 15
upvote count: 15
answers question: http://stackoverflow.com/q/47659782
downvote count: 0
has body: First of all, the line you gave as example is not parsable! … 'Edie's Finneran' … contains a syntax error, not matter what. Assuming that you have control over the input, you could simply use eval() to read in the file. (Although, in that case one would wonder why you can't produce valid JSON in the first place…) &gt;&gt;&gt; f = open('list.txt', 'r') &gt;&gt;&gt; s = f.read().strip() &gt;&gt;&gt; l = eval(s) &gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(l) [{'cast_id': 23, 'character': "Roger 'Verbal' Kint", ... 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}] &gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(l) '[{"cast_id": 23, "character": "Roger \'Verbal\' Kint", "credit_id": "52fe4260ca36847f8019af7", "gender": 2, "id": 1979, "name": "Kevin Spacey", "order": 5, "rofile_path": "/x7wF050iuCASefLLG75s2uDPFUu.jpg"}, {"cast_id": 27, "character":"Edie\'s Finneran", "credit_id": "52fe4260c3a36847f8019b07", "gender": 1, "id":2179, "name": "Suzy Amis", "order": 6, "profile_path": "/b1pjkncyLuBtMUmqD1MztDSG80.jpg"}]' If you don't have control over the input, this is very dangerous, as it opens you up to code injection attacks. I cannot emphasize enough that the best solution would be to produce valid JSON in the first place.

http://stackoverflow.com/comment/82290854
type: Comment
type: QuestionComment
has text: I think you could use point returned from `collide_mask` and object's center point to create direction vector .
comment on: http://stackoverflow.com/q/47665777
score: 0

http://stackoverflow.com/a/47684342
upvote count: 2
downvote count: 0
has body: NaN is used to represent missing data. NaN is also a floating-point value. So for a Series to contain NaN, it must have a dtype capable of holding floating-point values (such as float64 or object, but not int64).
has comment: http://stackoverflow.com/comment/82328289
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47684267

http://stackoverflow.com/a/47686253
score: 2
upvote count: 2
has body: Instead of iterating over d1's items, iterate over d2: for a, b in d2.items(): if a in d1: d1[a] += b else: d1[a] = b
downvote count: 0
answers question: http://stackoverflow.com/q/47686224
has comment: http://stackoverflow.com/comment/82332147
has comment: http://stackoverflow.com/comment/82332271
has comment: http://stackoverflow.com/comment/82332239
has comment: http://stackoverflow.com/comment/82332207
type: Answer

http://stackoverflow.com/comment/82334347
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47687432
type: QuestionComment
has text: @ScottBoston Index of dataframe

http://stackoverflow.com/q/47691512
downvote count: 0
has body: I would like to exclude a list (about 5 items) of tests with py.test. I would like to give this list to py.test via the command line. I would like to avoid to modify the source. How to do that?
has title: Exclude a list of tests with py.test but on the command line?
upvote count: 24
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47700320
tagged with: pytest
tagged with: python-unittest
tagged with: python
score: 24
has comment: http://stackoverflow.com/comment/82343734
possible better answer: http://stackoverflow.com/a/47700320
accepted answer: http://stackoverflow.com/a/47719505
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76106142
answer count: 3
has answer: http://stackoverflow.com/a/47719505
has comment: http://stackoverflow.com/comment/82341963

http://stackoverflow.com/comment/82292032
has text: But suppose I have "code" in the alt tag, how would I be able to find_element_by_tag_name if it is not explicitly a tag?
score: 0
comment on: http://stackoverflow.com/a/47666437
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82199048
has text: I see that you repeatedly perform the same re.search for the same line. You might consider storing the result in a variable, and use that variable in stead.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47620444

http://stackoverflow.com/a/47689173
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47689007
has body: It's hard to answer, without knowing more of how this method load_image_file works. But here are 2 educated guesses which might be accurate: {} would be an empty dictionary. Dictionaries are very important and useful in Python and work with key:value pairs. For instance, the following would be a more useful dictionary than the empty one given: phone_nums = {'home': '867-5309', 'work': '555-1212'} would create a dictionary that has 2 keys ('home' and 'work'), which are associated with the 2 phone numbers. For instance, phone_nums['home'] would yield 867-5309. "{}" would be a JSON representation of an empty "Python dictionary". I put Python dictionary in quotes because a key aspect of the JSON representation is that it can "talk" across different languages. You can write an object to a JSON structure in Python, then open it up in Javascript, or many other languages. (I mention Javascript because that is where JSON originally comes from.) But back to your question of what it's doing in that method. If I were to guess, I'd say that the method: Looks for a string that is in a JSON representation. Looks for some relevant key name in that representation, such as something like 'filename': 'C:\\Users\\my_file.jpeg'. If it cannot find the 'filename' keyword, then it uses a default path. In this case, that's what's happening, and what the author of that snippet of code wanted. However, s/he couldn't simply pass null or an empty string, if indeed there was some requirement of a JSON representation of an object/dictionary. That's all entirely conjecture, though.
type: Answer
accepted answer of: http://stackoverflow.com/q/47689007
upvote count: 2
score: 1

installation
tags question: http://stackoverflow.com/q/47690770
tags question: http://stackoverflow.com/q/47582624
tags question: http://stackoverflow.com/q/47652286
tags question: http://stackoverflow.com/q/47592516
tags question: http://stackoverflow.com/q/47592881
tags question: http://stackoverflow.com/q/47577505
tags question: http://stackoverflow.com/q/47628940
tags question: http://stackoverflow.com/q/47620222
tags question: http://stackoverflow.com/q/47587088
tag name: installation
tags question: http://stackoverflow.com/q/47638934
tags question: http://stackoverflow.com/q/47630802
tags question: http://stackoverflow.com/q/47612640
tags question: http://stackoverflow.com/q/47566955
tags question: http://stackoverflow.com/q/47579954
tags question: http://stackoverflow.com/q/47626541
tags question: http://stackoverflow.com/q/47585674
tags question: http://stackoverflow.com/q/47659318
tags question: http://stackoverflow.com/q/47568237
type: Tag

http://stackoverflow.com/q/47640501
has title: ImportError: No module named objdem
answer count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47640707
has body: I have a python package that is intended to be used as a command line script. The file directory of the package (before dist) is: /bin/ objdem /objdem/ __init__.py objdem.py LICENSE README.md requirements.txt setup.py The objdem file contains: #!/usr/bin/env python import objdem main() And objdem.py is the script that I want to run by typing objdem on the command line. Where am I going wrong? On windows instead of an error it opens the objdem file. EDIT: You can try it here https://pypi.python.org/pypi/objDEM/1.0.6 EDIT: setup.py: from setuptools import setup setup( name='objDEM', version='1.0.3', description='Generates an .obj file representing a digital elevation map from coordinate input', license="MIT", author='Kevin Forrest Connors', author_email='kevinforrestconnors.com@gmail.com', url="https://github.com/kevinforrestconnors/objdem", packages=['objDEM'], install_requires=['numpy', 'scipy', 'utm'], scripts=['bin/objdem'] )
tagged with: package
has comment: http://stackoverflow.com/comment/82240108
has comment: http://stackoverflow.com/comment/82239783
tagged with: python
type: Question
score: 0
has answer: http://stackoverflow.com/a/47640707
tagged with: bash

http://stackoverflow.com/comment/82326852
has text: https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question
score: 0
comment on: http://stackoverflow.com/q/47683571
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47694844
accepted answer: http://stackoverflow.com/a/47695027
has comment: http://stackoverflow.com/comment/82349015
possible better answer: http://stackoverflow.com/a/47695159
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47695027
tagged with: comparison-operators
has title: Confusing comparison output
tagged with: python
has comment: http://stackoverflow.com/comment/82349296
has comment: http://stackoverflow.com/comment/82349027
type: Question
has answer: http://stackoverflow.com/a/47695159
has comment: http://stackoverflow.com/comment/82350315
has body: I am confused about the following: &gt;&gt;&gt; 1,2 == 1,2 (1, False, 2) The == operator should return only a bool (or at least I thought so). I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2). Can anyone explain what is going on here?
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/82349088

http://stackoverflow.com/comment/82091652
type: Comment
has text: @PiyushDivyanakar: The `+=` is basically guaranteed to be faster (slicing operations involve temporary `list` objects, and the surprisingly expensive `len` call). `+=` is more readable, and the fastest option available.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47566946

http://stackoverflow.com/comment/82255152
has text: @DanielRoseman I am trying to render the index.html. Is there a way to allow me display both registration form and login form on a single page?
type: Comment
comment on: http://stackoverflow.com/q/47648276
type: QuestionComment
score: 0

http://stackoverflow.com/comment/129979025
comment on: http://stackoverflow.com/a/47787279
has text: This works, however in json file you need to drop 'auth' from all path e.g "issuer": "http://<YOUR_DOMAIN>/realms/<YOUR_REALM_ID>",
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/82340690
comment on: http://stackoverflow.com/q/47690558
has text: Why should that pseudo-code print "yay"? You need to give us a better explanation of what you're trying to do, showing us a bunch of invalid code isn't very useful. It would help if you post the equivalent `if..elif...else` code, and then we can show you a more compact way of doing it (if there is one).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47612791
has title: How to convert Dic Post to Serialized Object in Django?
type: Question
tagged with: python-3.x
tagged with: serialization
has comment: http://stackoverflow.com/comment/82184879
answer count: 1
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47613686
has body: How to convert Dic Post to Serialized Object? I do not know if the output is correct. Someone could help with this doubt. Thank you very much. Post html form { 'pergunta[4][item][11][quarto][0]': 'AA', 'pergunta[4][item][11][quarto][1]': 'AA', 'pergunta[4][item][11][segundo][0]': '123' } As should { 'pergunta':[ 'item': [ {'quarto':[ 0: 'AA', 1: 'AA' ]}, { 'segundo': [ 0: '123' ]} ] ] } Edit &lt;input class="form-control" placeholder="Total" type="number" name="pergunta[{{ pergunta.id }}][item][{{ opcao.id }}][]"&gt;
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47613686
score: 0
has comment: http://stackoverflow.com/comment/82184954

http://stackoverflow.com/q/47644274
has body: So I'm lost ... again. I have a QMainWindow with a empty QStackedWidget. I would like to dynamically populate the QStackedWidget using a custom widget that I created in Qt Creator. I tried following Creating a custom widget in PyQT5 in another thread, but that doesn't really cover importing from a UI file in this case. I keep receiving: AttributeError: 'QStackedWidget' object has no attribute 'addItemWidget' Here is the code for the Widget... # ItemWidget.py from PyQt5 import uic from PyQt5.QtWidgets import QWidget class Widget: def __init__(self): self.text = None self.data = None class ItemWidget(QWidget): def __init_(self, parent = None): self.WidgetList = [] QWidget.__init__(self, parent = parent) uic.loadUi(r'interface/ItemWidget.ui', self) def addItemWidget(self, index, text): widget = Widget() widget.text = text self.WidgetList.append([]) self.WidgetList[index].append(widget) # TESTING print(self.WidgetList) Relevant code from main.py: from ItemWidget import * for key, value in self.ItemIndexList.items(): self.ItemStackedWidget.addItemWidget(value, key) I understand that I'm getting this error because QStackedWidget has no defined attribute called 'addItemWidget, but I don't know what I need to do to get this to work as intended. When I try overriding the method using 'addWidget', I get an unexpected value error. Any ideas? I'm fairly new to Python and still learning, so if I'm missing some important information please let me know. I have a few different revisions of my MainWindow.ui. One just has a QStackedWidget where I want the pages to go, the other is completely laid out how I would imagine the final product to look. The ItemWidget.ui file just contains the elements I want to add to each QStackedWidget page. I have not promoted any of them to a custom class, which I suspect I will need to do. I'm currently using Python 3.6 and PyQt5 ** EDIT TO ADD MVCE ** TestApp.py from PyQt5.QtWidgets import QApplication import TestMain import sys class MCVE(QApplicati…
has comment: http://stackoverflow.com/comment/82247289
accepted answer: http://stackoverflow.com/a/47646332
has comment: http://stackoverflow.com/comment/82248416
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47646332
has comment: http://stackoverflow.com/comment/82250979
linked to: http://stackoverflow.com/q/47600467
has title: Dynamically adding pages to QStackedWidget using a custom widget designed in Qt Creator
answer count: 1
has comment: http://stackoverflow.com/comment/82248474
has comment: http://stackoverflow.com/comment/82248644
has comment: http://stackoverflow.com/comment/82247591
has comment: http://stackoverflow.com/comment/82247265
has comment: http://stackoverflow.com/comment/82248300
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82251238
has comment: http://stackoverflow.com/comment/82250987
type: Question
has comment: http://stackoverflow.com/comment/82250703
tagged with: qstackedwidget
has comment: http://stackoverflow.com/comment/82248464
score: 0
has comment: http://stackoverflow.com/comment/82251015
has comment: http://stackoverflow.com/comment/82247534
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/82250832
tagged with: qt-creator
tagged with: python
has comment: http://stackoverflow.com/comment/82250944
has comment: http://stackoverflow.com/comment/82250671
linked to: http://stackoverflow.com/q/44380202

http://stackoverflow.com/q/47672410
possible better answer: http://stackoverflow.com/a/62739168
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82304302
has body: Is it possible to dynamically add periodic tasks to celery? I'm using Flask, not django, and I am building an app that is supposed to allow users to define recurrent tasks through a web interface. I've tried using Periodic Tasks from Celery 4.1, but to add new tasks I have to stop celery server, change the config (even if done through python), and start it again. Maybe there's a way to dynamically load the config (without having to re-start it)? I've considered to have a crontab that re-starts celery service every 5mins. but it seems highly contra-nature. Among other reasons because the reason I wanted to use celery was not to use crontab. Does anyone has some lights on this? ps.: I'm aware of another similar question, but it's from 2012. I was hoping things had changed since then, namely with the introduction of beat in v4.1
has answer: http://stackoverflow.com/a/48318984
accepted answer: http://stackoverflow.com/a/48318984
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82304898
has comment: http://stackoverflow.com/comment/82308561
linked to: http://stackoverflow.com/q/10194975
score: 13
has title: dynamically add periodic tasks celery
tagged with: flask
has comment: http://stackoverflow.com/comment/82304821
has answer: http://stackoverflow.com/a/62739168
tagged with: celery
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82304500
has comment: http://stackoverflow.com/comment/82310123
has comment: http://stackoverflow.com/comment/82304009
upvote count: 13
tagged with: python
has comment: http://stackoverflow.com/comment/82311007

http://stackoverflow.com/a/47684394
has body: You're asking for input inside the while loop that never checks any row other then the current row. It looks like you're trying to iterate over the entire list to see if the name is anywhere in there (which is rough performance wise but I won't confuse you by getting into that xD) so your input check and loops need to be moved around a bit like so: import csv with open('Report1.csv') as csvfile: hour_summation = {} read_csv = csv.reader(csvfile, delimiter=',') name_found = False while not name_found: # take user input for name full_name = input('Enter your full name: ').lower() # start search at top of file. Have to do this or each loop will # start at the end of the file after the first check. csvfile.seek(0) for row in read_csv: # check to see if row matches name if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower(): name_found = True hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3])) # name wasn't found, so repeat process if not name_found: # name wasn't found, go back to start of while loop print('Name is not in system') else: # break out of while loop. Technically not required since while # will exit here anyway, but clarity is nice break print('This is {} full hours report:'.format(full_name)) for k, v in hour_summation.items(): print(k + ': ' + str(v) + ' hours')
type: Answer
answers question: http://stackoverflow.com/q/47684058
has comment: http://stackoverflow.com/comment/82328764
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82328635
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47684058
has comment: http://stackoverflow.com/comment/82328718

http://stackoverflow.com/a/47685198
score: 0
has comment: http://stackoverflow.com/comment/82399338
has comment: http://stackoverflow.com/comment/82358803
has comment: http://stackoverflow.com/comment/82720188
accepted answer of: http://stackoverflow.com/q/47684075
has comment: http://stackoverflow.com/comment/82425617
has body: I'm not going to address all your three sub-questions directly because it would wind-up being a whole mini-tutorial on tkinter. However I can show you how to add a Button to do the plotting. Note especially the lines with the comment # ADDED on them. Below a modified version of your code with a number of things added showing where and how to put a plotting function function could be put in. I've also changed the coding style so it follows the PEP 8 - Style Guide for Python Code more closely and is much more readable. In a several spots I also changed the name of variables to make it clearer how this kind of gui architecture based on tkinter operates. import tkinter as tk from tkinter import filedialog LARGE_FONT=('Verdana', 12) class XPSPlotApp(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) container = tk.Frame(self) container.pack(side='top', fill='both', expand=True) container.grid_rowconfigure(0, weight=1) # 0 is min size container.grid_columnconfigure(0, weight=1) # Add menubar and subcommands. self.menuBar = tk.Menu(master=self) self.filemenu = tk.Menu(self.menuBar, tearoff=0) self.filemenu.add_command(label="Open", command=self.browse_file) self.filemenu.add_command(label="Plot", command=self.plot_file) # ADDED self.filemenu.add_command(label="Quit!", command=self.quit) self.menuBar.add_cascade(label="File", menu=self.filemenu) self.config(menu=self.menuBar) self.frames={} for FrameSubclass in (HRXPSPlotter, SurveyXPSPlotter): frame = FrameSubclass(container, self) # create class instance. self.frames[FrameSubclass] = frame frame.grid(row=0, column=1, sticky='nsew') self.show_frame(HRXPSPlotter) def show_frame(self, subclass): frame = self.frames[subclass] frame.tkraise() def browse_file(self): self.filename = filedialog.askopenfilename( initialdir="E:/Images", title="Choose your file", filetypes=(("text files", "*.txt"), ("all files", "*.*")) ) print(self.filename) def plot_file(self): # ADDED try: print('Plotting:', self.filen…
has comment: http://stackoverflow.com/comment/82363703
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82364578
has comment: http://stackoverflow.com/comment/82360321
answers question: http://stackoverflow.com/q/47684075
has comment: http://stackoverflow.com/comment/82400507

http://stackoverflow.com/comment/82075112
comment on: http://stackoverflow.com/q/47558488
score: 1
has text: Also, see a [multiline demo](https://regex101.com/r/UN75Mr/1).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82355217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47692119
has text: FYI: The first argument to `linkage` must be either the 1-D array of *condensed* (aka *compressed*) distance data (see, e.g. https://stackoverflow.com/questions/13079563/how-does-condensed-distance-matrix-work-pdist/13079806#13079806), or the original array of points. To convert a symmetric distance array to the condensed form, use `squareform(distArray)`, where `squareform` is imported from `scipy.spatial.distance`.
score: 0

http://stackoverflow.com/comment/82285886
comment on: http://stackoverflow.com/a/47651598
score: 0
type: Comment
type: AnswerComment
has text: The second solution (Edit) is really good: code-wise and database-wise, because you don't need to override a CRUD function here and the relation is just one table now.

http://stackoverflow.com/comment/82300985
score: 0
comment on: http://stackoverflow.com/q/47656071
type: QuestionComment
type: Comment
has text: I already tried removing migrations directory but i didn´t solve the issue.

http://stackoverflow.com/comment/85108197
type: AnswerComment
comment on: http://stackoverflow.com/a/49048039
has text: @AndriiKrupka you are right. The source of the problem is not what I thought it was so I added the correct answer. Hopefully this will be fixed soon. because putting the reshape operation in the model is not ideal.
score: 0
type: Comment

http://stackoverflow.com/a/47614953
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47614396
has body: imread() is used to read from file, not from memory. But you don't have to convert it. PyGame gives image which you can use in cv2. You have to only: convert from RGB (used in PyGame) to BGR (used in CV2). transpose image - swap width with height. PyGame uses (X,Y) but CV2 use (Y,X) like matrix in math (other words (row, column)). I think this code shows all what you may need. create image in PyGame display image in PyGame convert image from PyGame to CV2 display image in CV2 modify image in CV2 display modified image in CV2 convert modified image from CV2 to PyGame display modified image in PyGame . import pygame import cv2 pygame.init() # --- create PyGame image --- pg_img = pygame.Surface((400, 200)) pygame.draw.circle(pg_img, (255,0,0), (0,0), 200) # --- display PyGame image --- screen = pygame.display.set_mode((400, 400)) screen.fill((255,255,255)) screen.blit(pg_img, pg_img.get_rect()) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: running = False pygame.quit() # --- move from PyGame to CV2 --- color_image = pygame.surfarray.array3d(pg_img) color_image = cv2.transpose(color_image) color_image = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR) # --- display CV2 image --- cv2.imshow('Color', color_image) cv2.waitKey(0) cv2.destroyAllWindows() # --- change CV2 image --- color_image = cv2.rotate(color_image, cv2.ROTATE_90_CLOCKWISE) gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY) # --- display CV2 image --- cv2.imshow('Gray', gray_image) cv2.waitKey(0) cv2.destroyAllWindows() # --- save in file in CV2 --- cv2.imwrite('test.png', color_image) # --- move back from CV2 to PyGame --- gray_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2RGB) gray_image = cv2.transpose(gray_image) pg_img = pygame.surfarray.make_surface(gray_image) # --- display PyGame image --- screen = pygame.display.set_mode((400, 400)) screen.fill((255,255,255)) screen.blit(pg_i…
type: Answer
answers question: http://stackoverflow.com/q/47614396
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/47690535
has comment: http://stackoverflow.com/comment/82388719
score: 0
has comment: http://stackoverflow.com/comment/82370344
type: AcceptedAnswer
has body: I would have a different model, Like: class Like(models.Model): user = models.ForeignKey(User) physician = models.ForeignKey(Physician) This table will have a relation between a user and a physician. You can know if a user has liked a physician. Like.objects.filter(user=user, physician=physician).exists() Delete the relation if the user un-favorites the physician and so on. To get all the ids of physicians liked by the user, you could do: physicians_liked = Like.objects.filter(user=user).values_list('physician', flat=True) And later in your template is as easier as checking: {% if physician.id in physicians_liked %} ... {% endif %}
accepted answer of: http://stackoverflow.com/q/47687149
type: Answer
answers question: http://stackoverflow.com/q/47687149

http://stackoverflow.com/comment/82274759
has text: I understand that SerialException is covered in the documentation. This is more of a general question about interpreting output. I saw PermissionError in the output and found that it was a built-in exception type and so tried to catch that. My question should have been "Should I have been able to tell from the output that I needed to catch SerialException instead of PermissionError. Or, should I have gone straight to the documentation?
type: QuestionComment
comment on: http://stackoverflow.com/q/47635828
type: Comment
score: 1

for-loop
tags question: http://stackoverflow.com/q/47583704
tags question: http://stackoverflow.com/q/47552200
tags question: http://stackoverflow.com/q/47602922
tags question: http://stackoverflow.com/q/47621670
tags question: http://stackoverflow.com/q/47626495
tags question: http://stackoverflow.com/q/47553487
tags question: http://stackoverflow.com/q/47663911
tags question: http://stackoverflow.com/q/47660825
tags question: http://stackoverflow.com/q/47596270
tags question: http://stackoverflow.com/q/47683349
tags question: http://stackoverflow.com/q/47623221
tags question: http://stackoverflow.com/q/47626372
type: Tag
tags question: http://stackoverflow.com/q/47655958
tags question: http://stackoverflow.com/q/47586491
tags question: http://stackoverflow.com/q/47612209
tags question: http://stackoverflow.com/q/47599128
tags question: http://stackoverflow.com/q/47635484
tags question: http://stackoverflow.com/q/47582442
tags question: http://stackoverflow.com/q/47544027
tags question: http://stackoverflow.com/q/47622471
tags question: http://stackoverflow.com/q/47627015
tags question: http://stackoverflow.com/q/47610103
tags question: http://stackoverflow.com/q/47639215
tags question: http://stackoverflow.com/q/47649453
tags question: http://stackoverflow.com/q/47634410
tags question: http://stackoverflow.com/q/47626773
tags question: http://stackoverflow.com/q/47561961
tags question: http://stackoverflow.com/q/47624751
tags question: http://stackoverflow.com/q/47684739
tag name: for-loop
tags question: http://stackoverflow.com/q/47643247
tags question: http://stackoverflow.com/q/47656153
tags question: http://stackoverflow.com/q/47678688
tags question: http://stackoverflow.com/q/47604094
tags question: http://stackoverflow.com/q/47695333
tags question: http://stackoverflow.com/q/47683265
tags question: http://stackoverflow.com/q/47621435
tags question: http://stackoverflow.com/q/47633213
tags question: http://stackoverflow.com/q/47608312
tags question: http://stackoverflow.com/q/47665984
tags question: http://stackoverflow.com/q/47545116
tags question: http://stackoverflow.com/q/47561177
tags question: http://stackoverflow.com/q/47653475
tags question: http://stackoverflow.com/q/47641986
tags question: http://stackoverflow.com/q/47664653
tags question: http://stackoverflow.com/q/47620895
tags question: http://stackoverflow.com/q/47581582
tags question: http://stackoverflow.com/q/47602645

http://stackoverflow.com/comment/82120403
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47581134
score: 0
has text: I'm still getting the "EPOLLERR" flag set along with "EPOLLPRI" in the event I get back when the poll() returns. However, it sounds like this might be normal behaviour... See: https://groups.google.com/forum/#!topic/quick2wire-users/ka-V_85ePtE

http://stackoverflow.com/comment/82248956
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47644987
has text: `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"` Source : [brew.sh](http://brew.sh)
type: Comment

http://stackoverflow.com/comment/82064343
type: QuestionComment
has text: @Phil I want `print "abc" in ("abc ver 1","abc ver 1.1")` to return FALSE because "abc" is not listed as string in the in (,) in case `print "abc" in ("abc ver 1","abc ver 1.1", "abc")` then it should be TRUE
comment on: http://stackoverflow.com/q/47553821
score: 0
type: Comment

http://stackoverflow.com/a/58869692
upvote count: 10
downvote count: 0
score: 10
type: Answer
answers question: http://stackoverflow.com/q/47580716
has comment: http://stackoverflow.com/comment/108737232
has body: For those working with TensorFlow 2 and looking for an answer I found the following to work directly with ragged tensors. which should be much faster than generator, as long as the entire dataset fits in memory. t = [[[4,2]], [[3,4,5]]] rt=tf.ragged.constant(t) dataset = tf.data.Dataset.from_tensor_slices(rt) for x in dataset: print(x) produces &lt;tf.RaggedTensor [[4, 2]]&gt; &lt;tf.RaggedTensor [[3, 4, 5]]&gt; For some reason, it's very particular about having at least 2 dimensions on the individual arrays.

http://stackoverflow.com/comment/82176964
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47608865
score: 0
has text: in `gate_path_B()` can you put `print(XOR)` to see if it actually is defined

http://stackoverflow.com/comment/82247265
type: Comment
has text: Show your ItemWidget.ui
type: QuestionComment
comment on: http://stackoverflow.com/q/47644274
score: 0

kivy-language
tags question: http://stackoverflow.com/q/47652782
type: Tag
tags question: http://stackoverflow.com/q/47592032
tags question: http://stackoverflow.com/q/47609028
tags question: http://stackoverflow.com/q/47607951
tags question: http://stackoverflow.com/q/47628023
tags question: http://stackoverflow.com/q/47682906
tags question: http://stackoverflow.com/q/47611733
tag name: kivy-language
tags question: http://stackoverflow.com/q/47610336
tags question: http://stackoverflow.com/q/47662872
tags question: http://stackoverflow.com/q/47686791
tags question: http://stackoverflow.com/q/47674518
tags question: http://stackoverflow.com/q/47671606
tags question: http://stackoverflow.com/q/47547164

http://stackoverflow.com/q/47592280
has comment: http://stackoverflow.com/comment/82141522
answer count: 2
tagged with: python
tagged with: regex
has title: Python regex unable to remove content between [%~ abcd ~%]
duplicate of: http://stackoverflow.com/q/159118
accepted answer: http://stackoverflow.com/a/47592357
has comment: http://stackoverflow.com/comment/82141757
has answer: http://stackoverflow.com/a/47592357
type: AnsweredQuestion
score: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/47592392
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47592392
has body: I have raw HTML and am trying to remove this whole block like this [%~ as..abcd ~%] from the output string. Using re library of python teststring = "Check the direction . [%~ MACRO wdwDate(date) BLOCK; SET tmpdate = date.clone(); END ~%] Determine if both directions." cleanM = re.compile('\[\%\~ .*? \~\%\]') scleantext = re.sub(cleanM,'', teststring) what is wrong in the code ?
type: Question
linked to: http://stackoverflow.com/q/159118

http://stackoverflow.com/q/47609843
has title: Using pytesseract on cropped image
answer count: 1
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48265974
upvote count: 1
tagged with: opencv
score: 1
has body: I am cropping an image and then using pytesseract on it to read digits from it. However, I have to first save the cropped image and then load it again for this code to work. Is there a way I can avoid doing this and improve efficiency? If I pass cropped directly to the image_to_string it crashes with: in image_to_string if len(image.split()) == 4: AttributeError: 'numpy.ndarray' object has no attribute 'split' cropped = image[1044:2000, 100:1025] cv2.imwrite("thumbnail.png", cropped) img = Image.open("thumbnail.png") print(pytesseract.image_to_string(img, config='-psm 6')) print("--- %s seconds ---" % (time.time() - start_time))

forms
tags question: http://stackoverflow.com/q/47545508
tags question: http://stackoverflow.com/q/47618357
type: Tag
tags question: http://stackoverflow.com/q/47636145
tags question: http://stackoverflow.com/q/47607297
tags question: http://stackoverflow.com/q/47592828
tags question: http://stackoverflow.com/q/47556684
tag name: forms
tags question: http://stackoverflow.com/q/47628735
tags question: http://stackoverflow.com/q/47611721
tags question: http://stackoverflow.com/q/47552700

http://stackoverflow.com/comment/82235167
score: 0
has text: If the image files are located in your home folder, then absolute path is `~/image/counts1.png`. If they are located in the folder inside the same folder as notebook, then relative path is the path relative to the notebook location. E.g. if notebooks are in `~/notebooks/` then file located in `~/notebooks/images/name` would have relative path like `./images/name`. More on the topic: https://stackoverflow.com/questions/21306512/difference-between-relative-path-and-absolute-path-in-javascript
type: Comment
comment on: http://stackoverflow.com/a/47637980
type: AnswerComment

http://stackoverflow.com/comment/82323462
comment on: http://stackoverflow.com/q/47666825
type: QuestionComment
has text: Not really - I wouldn't use versioning to implement environments to start with ;) Primarily because I'd be losing (or at least making very difficult) to version both the environments and the app code itself: would a certain version string represent an environment (and, if so - which version of that environment?) or a certain version of the app code?
score: 1
type: Comment

http://stackoverflow.com/a/47545762
has comment: http://stackoverflow.com/comment/82048702
has body: Your form_upload_2 class don't have field y. Change it to class form_upload_2(ModelForm): class Meta: model = file_upload fields = ('y',) widgets={ 'y': FileInput(attrs={'class': 'form-control'}), Also follow naming conventions while naming a class. file_upload is not a good class name. Use FileUpload. https://www.python.org/dev/peps/pep-0008/#class-names Also your form, please try to change like this if request.method == "POST": form = form_upload2(request.FILES,request.POST,instance=data_upl_instance) if form.is_valid(): print(form.cleaned_data['y']) form.save() else: form = form_upload2(instance=data_upl_instance) mydata['form'] = form return render(request, "status.html", mydata)
type: Answer
answers question: http://stackoverflow.com/q/47545508
has comment: http://stackoverflow.com/comment/82051023
has comment: http://stackoverflow.com/comment/82050844
has comment: http://stackoverflow.com/comment/82050367
has comment: http://stackoverflow.com/comment/82051965
score: 0
has comment: http://stackoverflow.com/comment/82050092
has comment: http://stackoverflow.com/comment/82049841
has comment: http://stackoverflow.com/comment/82048894

http://stackoverflow.com/a/47591602
type: Answer
has comment: http://stackoverflow.com/comment/82140306
has body: Because summing along the axis of a ND array yields a (N-1)D array. This makes sense if you consider that np.sum([1,2,3]) == 6 # a 0D 'array' If you want to turn your arr.sum(1) into a (1, 3) or (3, 1) 2D array, then use s = arr.sum(0)[np.newaxis, :] # (1, 3) or s = arr.sum(1)[:, np.newaxis] # (3, 1)
has comment: http://stackoverflow.com/comment/82140211
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47591481

http://stackoverflow.com/a/47541390
has body: Build a regex that searches for 'normal' lines. Maybe something like "^U0.0[1-5] - \n$"? Then use something like if not re.search(x): before you print the error. with open('filename.csv','rb') as csvfile: reader = csv.reader(csvfile) for row in reader: tag_name = row[0] bit_num = row[1] error_name = row[2] # Regular expressions term0 = '\[(\d)\].*' term1 = '(\d+)' term2 = r'.*-\s([\w\s]+)\\n' term3 = '^U0.0[1-5] - \n$' capture0 = list(re.search(term0, tag_name).groups()) capture1 = list(re.search(term1, bit_num).groups()) temp = re.search(term2, error_name) if temp: result = list(temp.groups()) else: None result[-1] = '_'.join(result[-1].split()).upper() capture2 = ','.join(result) tp = (capture0[0], capture1[0], capture2) # Tuple if not re.search(temp3,error_name): f.write('{2} {0},{1},\n'.format(tp[0], tp[1], tp[2])) #I assume this is the print line?
has comment: http://stackoverflow.com/comment/82040263
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82040323
has comment: http://stackoverflow.com/comment/82042416
answers question: http://stackoverflow.com/q/47541237
has comment: http://stackoverflow.com/comment/82040289

http://stackoverflow.com/q/47639001
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82236249
has title: File "<stdin>", line 1 in python 3.6 version
upvote count: 1
has comment: http://stackoverflow.com/comment/82236685
has comment: http://stackoverflow.com/comment/82236321
downvote count: 1
linked to: http://stackoverflow.com/q/13961140
favorite count: 0
has comment: http://stackoverflow.com/comment/82236397
type: Question
has comment: http://stackoverflow.com/comment/82236589
duplicate of: http://stackoverflow.com/q/13961140
tagged with: python
has comment: http://stackoverflow.com/comment/82236255
has body: I am a beginner in using python. I created a file script.py which the code is only one line: print("hello"), but when I executed it on windows command prompt (I use windows 10), it results error File "&lt;stdin&gt;", line 1 python script.py ^ SyntaxError: invalid syntax I have set the variable paths so when I typed python on CMD, it shows the version of the python that I installed. I saved the script.py in the folder where Python 3.6 installed (Programs/Python 3.6/) but it couldn't work. I also tried to write the address path of the file, e.g ./F/Data/script.py but the result was the same. How do I fix this?
has comment: http://stackoverflow.com/comment/82236495
has comment: http://stackoverflow.com/comment/82236943
has comment: http://stackoverflow.com/comment/82236555
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82236436

http://stackoverflow.com/q/47625499
has title: calculation gradients of tf.nn.embedding_lookup
has body: import tensorflow as tf types_lookup_table = tf.get_variable("types_lookup_table", shape=[234, 10],initializer=tf.random_normal_initializer(0, 1), dtype=tf.float32, trainable=True) embedding_types = tf.nn.embedding_lookup(types_lookup_table,[[2,3,4],[1,2,3]]) opt = tf.train.GradientDescentOptimizer(0.1) gradients = tf.gradients(embedding_types, xs=types_lookup_table) train = opt.apply_gradients([(gradients[0], types_lookup_table)]) with tf.Session() as sess: tf.global_variables_initializer().run() h = sess.run(gradients) print(sess.run(train)) #right print(sess.run(opt.apply_gradients([(h[0],types_lookup_table)]))). # wrong I tried to calculate the gradients of tf.nn.embedding_lookup, but the result shown is an IndexedSliceValue with 3 elements. However the corresponding gradient(without sess.run) is an indexSliceValue with 1 elements.I don't know why. And therefore I can't sess.run(opt.apply_gradients([(h[0],types_lookup_table)]) because the shape of calculation value doesn't match the shape of _types_lookup_table_, however, when I didn't calculate the intermediate value, and directly sess.run(train) (ps:train = opt.apply_gradients([(gradients, types_lookup_table)])) There is no problem. But I need to calculate the intermediate value and do an add. I don't know how. Thanks
score: 2
answer count: 0
downvote count: 0
tagged with: embedding-lookup
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82209345
has comment: http://stackoverflow.com/comment/82209144
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82256107
type: QuestionComment
comment on: http://stackoverflow.com/q/47648886
has text: Don't use `dict` as a variable name. And if you print the results you would see the difference; from `str`: `"{'first': 42, 'second': 21}"` and from json: `'{"first": 42, "second": 21}'`. Notice the double quotes around the strings for keys.
type: Comment
score: 1

http://stackoverflow.com/comment/82185604
has text: I added my variables
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47613561

http://stackoverflow.com/comment/139074232
type: AnswerComment
score: 1
has text: absolutely, you shall inspect the content of `item.keywords`:). Do not hesitate to correct me If it is not true in general. At least, I observed this behaviour from my side.
comment on: http://stackoverflow.com/a/61193490
type: Comment

http://stackoverflow.com/comment/82240480
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47640745
has text: I could delete this answer, but it really isn't clear what you are trying to do.
score: 0

http://stackoverflow.com/comment/115348900
comment on: http://stackoverflow.com/q/47632855
score: 2
type: Comment
type: QuestionComment
has text: Unfortunately the second part of your question was never answered, and I am also wondering how it can be done, if it even can at all.

http://stackoverflow.com/comment/82189955
score: 0
type: Comment
type: QuestionComment
has text: `vstack` uses `bmat`, which joins the `coo` attributes of the blocks to create new matrix. I'd call `vstack` once on a list of matrices, not iteratively.
comment on: http://stackoverflow.com/q/47615473

http://stackoverflow.com/q/47665812
has title: index out of bound when iterrow() how is this possible?
tagged with: pandas
has answer: http://stackoverflow.com/a/47665982
has body: I got error message: 5205 (5219, 25) 5221 (5219, 25) Traceback (most recent call last): File "/Users/Chu/Documents/dssg2018/sa4.py", line 44, in &lt;module&gt; df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\ IndexError: index 5221 is out of bounds for axis 0 with size 5219 when I'm traversing the data frame, the index comes from the iterators. I don't know how is this even possible? idx directly comes from the dataframe bt = BallTree(df'lat','lng', metric="haversine") indices = bt.query_radius(df'lat','lng',r=(float(10)/40000)*360) for idx,row in df.iterrows(): for word in bag_of_words: if word in row['caption']: print(idx) print(df.shape) df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\ np.max([1,len(df.iloc[indices[idx]][df[word]!=1])]) changing iloc to loc gives /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/Chu/Documents/dssg2018/sa4.py (-124.60334244261675, 49.36453144316216, -121.67106179949566, 50.863501888419826) 27 (5219, 25) /Users/Chu/Documents/dssg2018/sa4.py:42: FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\ /Users/Chu/Documents/dssg2018/sa4.py:42: UserWarning: Boolean Series key will be reindexed to match DataFrame index. df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\ Traceback (most recent call last): File "/Users/Chu/Documents/dssg2018/sa4.py", line 42, in &lt;module&gt; df.loc[idx,word]=len(df.loc[indices[idx]][df[word]==1])/\ File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2133, in __getitem__ return self._getitem_array(key) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 2173, in _getitem…
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 5
score: 5
type: UnansweredQuestion
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/47601190
type: Answer
answers question: http://stackoverflow.com/q/47601029
score: 1
has body: If is_prime were a function, then it would not be False, so not is_prime would always return False, regardless of what is_prime is. Note that there's a difference between a function and a function return; if is_prime were a function, then is_prime() would be what is_prime() returns, which could be False, but is_prime would be the function object itself, which is not False. A function can return False, but it can't be False.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47612528
has body: You can easily do that with a list comprehension and two .join calls. data = [ {u'Value': u'nine', u'Key': u'nine'}, {u'Value': u'six', u'Key': u'six'}, {u'Value': u'four', u'Key': u'four'}, {u'Value': u'one', u'Key': u'one'}, {u'Value': u'seven', u'Key': u'seven'}, {u'Value': u'ten', u'Key': u'ten'}, {u'Value': u'two', u'Key': u'two'}, {u'Value': u'three', u'Key': u'three'}, {u'Value': u'five', u'Key': u'five'}, {u'Value': u'eight', u'Key': u'eight'} ] row = ' '.join([':'.join([d[u'Key'], d[u'Value']]) for d in data]) print(row) output nine:nine six:six four:four one:one seven:seven ten:ten two:two three:three five:five eight:eight A variation of that technique can be used if you don't actually want the colons: row = ' '.join([s for d in data for s in ([d[u'Key'], d[u'Value']])]) print(row) output nine nine six six four four one one seven seven ten ten two two three three five five eight eight This is probably slightly faster, since it requires only a single .join call.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47612440
type: Answer

http://stackoverflow.com/comment/82199589
comment on: http://stackoverflow.com/q/47620300
score: 0
has text: This works exactly as expected. Please read the guidance on how to provide an [mcve].
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82197641
type: Comment
comment on: http://stackoverflow.com/q/47618170
type: QuestionComment
has text: did you use Google to find help ? With Google I found this ["mouse position in pygame with piTFT"](https://www.raspberrypi.org/forums/viewtopic.php?t=131889&p=879999) and this ["PyGame and touchscreen"](https://stackoverflow.com/questions/24875682/pygame-and-touchscreen)
score: 0

http://stackoverflow.com/q/47688220
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82335649
has title: How to update multiple things in collection in Pymongo?
upvote count: 1
tagged with: python
tagged with: pygame
score: 1
tagged with: pymongo
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: collection.find_one_and_update( {'username': hero.name}, {'$set': {'exp': hero.exp}}) collection.find_one_and_update( {'username': hero.name}, {'$set': {'level': hero.level}}) I have two updates like this. Is there any way to combine them into one?
has answer: http://stackoverflow.com/a/47688402

http://stackoverflow.com/q/47588786
has title: Tensorflow MNIST using csv: low accuracy
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47655254
has body: I am trying to implement MNIST image classification in Tensorflow using CSV input. The accuracy is very low at around 10 percent. I am using 3 fully connected layers with softmax entropy at the output. I converted the mnist datasets from here into csv to use as input using the below code: import idx2numpy import numpy as np # Reading filename = 'train-images' flext1 = '.idx3-ubyte' flext2 = '.csv' ndarr = idx2numpy.convert_from_file(filename+flext1).reshape(60000, 784) np.savetxt(filename,ndarr,delimiter=',') Then I one-hot encoded the labels as below: import tensorflow as tf import numpy as np import pandas as pd trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values trainlabels=pd.read_csv("train-labels.csv",header=None,delimiter=',').values testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',').values testlabels=pd.read_csv("t10k-labels.csv",header=None,delimiter=',').values label_ph=tf.placeholder(tf.int64,shape=(None,1)) reshapeval=tf.Variable(100) onehotencoding=tf.one_hot(label_ph,depth=10) datalabels=tf.reshape(onehotencoding,shape=(reshapeval,10)) with tf.Session() as sess: onehottrainlabels=sess.run(datalabels,feed_dict={label_ph:trainlabels,reshapeval:trainlabels.shape[0]}) onehottestlabels=sess.run(datalabels,feed_dict={label_ph:testlabels,reshapeval:testlabels.shape[0]}) print("datalabels:",onehottrainlabels) print("datalabels:",onehottestlabels) #sess.run(datalabels) np.savetxt("mnist_train_labels_onehot.csv",onehottrainlabels,delimiter=',') np.savetxt("mnist_test_labels_onehot.csv",onehottestlabels,delimiter=',') I tried to use the csv files generated as shown above to try and train a image classification model as shown below: import tensorflow as tf import pandas as pd import numpy as np trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values trainlabels=pd.read_csv("mnist_train_labels_onehot.csv",header=None,delimiter=',').values testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',…
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/82235798
score: 2
has answer: http://stackoverflow.com/a/47611821
answer count: 2
tagged with: mnist

http://stackoverflow.com/comment/82069447
type: QuestionComment
comment on: http://stackoverflow.com/q/47555934
score: 0
has text: Yes, I understand that. I'm asking if there is a way to make this work, short of writing a custom meta class.
type: Comment

http://stackoverflow.com/a/47704513
downvote count: 0
score: 1
upvote count: 1
has body: I tried with this solution and it runs faster. df = df.resample('Min').last() offset_mc = df.index[0].microseconds offset_sec = df.index[0].seconds % 60 if not (offset_mc == 0 and offset_sec == 0): df.index += pd.tslib.Timedelta(str(59-offset_sec)+'seconds '+str(1000000-offset_mc)+'microseconds')
type: Answer
answers question: http://stackoverflow.com/q/47684057

http://stackoverflow.com/a/47562243
has body: I'm not sure exactly what the best practice is but I like using JSON files. I use the following class as a layer of abstraction for interfacing with the config (properties) file. You can create one JSONPropertiesFile and pass it around your application. import json from collections import OrderedDict import os from stat import * # ST_SIZE etc from datetime import datetime from copy import deepcopy class JSONPropertiesFileError(Exception): pass class JSONPropertiesFile(object): def __init__(self, file_path, default={}): self.file_path = file_path self._default_properties = default self._validate_file_path(file_path) def _validate_file_path(self, file_path): if not file_path.endswith(".json"): raise JSONPropertiesFileError(f"Must be a JSON file: {file_path}") if not os.path.exists(file_path): self.set(self._default_properties) def set(self, properties): new_properties = deepcopy(self._default_properties) new_properties.update(properties) with open(self.file_path, 'w') as file: json.dump(new_properties, file, indent=4) def get(self): properties = deepcopy(self._default_properties) with open(self.file_path) as file: properties.update(json.load(file, object_pairs_hook=OrderedDict)) return properties def get_file_info(self): st = os.stat(self.file_path) res = { 'size':st[ST_SIZE], 'size_str':str(round(st[ST_SIZE]/1000,2)) + ' KB', 'last_mod': datetime.fromtimestamp(st[ST_MTIME]).strftime("%Y-%m-%d") } return res In your case you might use it like this: file_path = "path/to/your/config/file" default_properties = { 'PROD': 'production', 'DEV': 'dev', 'ENVIRONMENT': "" } config_file = JSONPropertiesFile(file_path, default_properties) config = config_file.get() print(config["PROD"]) config["PROD"] = "something else" config_file.set(config) # save new config
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82082422
has comment: http://stackoverflow.com/comment/82082638
accepted answer of: http://stackoverflow.com/q/47561835
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47561835
downvote count: 0

http://stackoverflow.com/q/47562032
accepted answer: http://stackoverflow.com/a/47562984
tagged with: oracle-database
has title: Python ORA-12504 error when using EZConnect syntax
has comment: http://stackoverflow.com/comment/82083700
tagged with: python
has comment: http://stackoverflow.com/comment/82084712
type: Question
has comment: http://stackoverflow.com/comment/82084381
has body: I'm using the python Oracle driver and Easy Connection syntax, but receiving an error: DatabaseError: ORA-12514: TNS:listener does not currently know of service requested in connect descriptor import cx_Oracle as cx_Oracle def query_route(): con = cx_Oracle.connect('user/pwd@10.1.1.24:1521/service') The server is version 11.2.0.4.0. Following Christopher Jones's answer below, I tried: con = cx_Oracle("oracle+cx_oracle://user:pwd@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) (ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.1.24)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = service)))") which failed with the same error I found a link that suggested I need the service name, but I'm using the service after the slash. What am I doing wrong? Update: as Christoper Jones said, the problem was the service name, and my mistake was assuming I knew how that was determined. I had copied from a jdbc datasource: jdbc:oracle:thin:@10.1.1.24:1521:foo however, in the python code, I needed to use: mgowner/mgowner@10.1.1.24/foo.mycompany.com
answer count: 1
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47562984

http://stackoverflow.com/comment/82076002
comment on: http://stackoverflow.com/q/47558488
score: 0
type: Comment
type: QuestionComment
has text: @Topto Ok, added with explanations. I hope the regex details will help you tweak it further.

http://stackoverflow.com/q/47612440
has answer: http://stackoverflow.com/a/47612496
has answer: http://stackoverflow.com/a/47612534
type: Question
tagged with: python
type: UnansweredQuestion
has body: Trying in python to create single line output from multiple dict with same keys. [{u'Value': u'nine', u'Key': u'nine'}, {u'Value': u'six', u'Key': u'six'}, {u'Value': u'four', u'Key': u'four'}, {u'Value': u'one', u'Key': u'one'}, {u'Value': u'seven', u'Key': u'seven'}, {u'Value': u'ten', u'Key': u'ten'}, {u'Value': u'two', u'Key': u'two'}, {u'Value': u'three', u'Key': u'three'}, {u'Value': u'five', u'Key': u'five'}, {u'Value': u'eight', u'Key': u'eight'}] Output I'm looking for: nine nine six six four four one one...... eight eight or nine:nine six:six.............eight:eight I tried various options single expression
has title: python converting multiple dict with same keys to one line CSV
answer count: 4
linked to: http://stackoverflow.com/q/38987
score: 0
has answer: http://stackoverflow.com/a/47612528
has answer: http://stackoverflow.com/a/47613025

http://stackoverflow.com/comment/82107939
comment on: http://stackoverflow.com/q/47572853
has text: I'd see [this](https://stackoverflow.com/questions/7616541/get-selected-item-in-listbox-and-call-another-function-storing-the-selected-for).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47583479
has body: filters.threshold_otsu does not care about the shape of the array passed in, so you can also do: threshold_otsu(z[z &gt; -1])
type: AcceptedAnswer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47579297
type: Answer
answers question: http://stackoverflow.com/q/47579297
downvote count: 0

http://stackoverflow.com/comment/82073291
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47557311
type: QuestionComment
has text: Thanks @PaulPanzer and Ev.Kounis

http://stackoverflow.com/q/47649906
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47667399
favorite count: 0
has answer: http://stackoverflow.com/a/47667399
has title: How read .mat openmodelica result file in python correctly?
type: AnsweredQuestion
tagged with: openmodelica
tagged with: python
type: Question
tagged with: mat
has body: I tried to read modelica resul file (.mat) in python and used code like this: data = scipy.io.loadmat('TPPSim.Boilers.Tests.EMA_028_HRSG_Test_res.mat') print data.keys() ['Aclass', 'dataInfo', 'name', 'data_2', 'data_1', 'description'] names = [''.join(s).rstrip() for s in zip(*data['name'])] len(names) 899 But it's not all variables that i can see in 'OMEdit plotting'. I think that's only variables that have derivatives in simulation. And data['data_1'] have more than 899 sets of data: data['data_2'][0] 4192L How I can get all results in Python? Sorry for my bad English. Artyom.
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/99523851
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47669910
has text: Possible duplicate of ["Could not run curl-config: \[Errno 2\] No such file or directory" when installing pycurl](https://stackoverflow.com/questions/23937933/could-not-run-curl-config-errno-2-no-such-file-or-directory-when-installing)

http://stackoverflow.com/comment/82071789
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47556339
has text: I can't speak to your particularities without knowing more. S3 was just an example, but far from the only choice. Kinesis is an option, MongoDB has a fire-forget mode and an expiration date. You would have to research what works best in your situation. The important point is that you want to place your data somewhere that isn't subject to the scaling down of an instance. If latency is your concern, choose some sort of queue or in-memory cache that is very fast to write to from your web server, and use an external app to process it later.

http://stackoverflow.com/comment/82106236
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47574672
has text: I'm confused by what exactly should be in the test and training file. All the @ symbol lines should be in both. Then you want lines without the @ symbol to just be in the test file?

http://stackoverflow.com/comment/82087546
type: Comment
has text: hehe, thank you. I knew there was a better way, I wanted to put it out there because it explains clearly how the underlying works, withou much complication. I was looking for the proper bitwise op when you posted your comment. I amended the answer to reflect your suggestion.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47564577

generator
type: Tag
tags question: http://stackoverflow.com/q/47626195
tag name: generator
tags question: http://stackoverflow.com/q/47580407
tags question: http://stackoverflow.com/q/47577245
tags question: http://stackoverflow.com/q/47652787
tags question: http://stackoverflow.com/q/47651529
tags question: http://stackoverflow.com/q/47681818
tags question: http://stackoverflow.com/q/47683745

http://stackoverflow.com/comment/82139399
type: Comment
comment on: http://stackoverflow.com/a/47591027
score: 0
type: AnswerComment
has text: The code I wrote will work even if you import `date`. I didn't realize you were using it elsewhere. The code `datetime.now().date()` will also work.

http://stackoverflow.com/comment/82167808
score: 0
comment on: http://stackoverflow.com/q/47604561
type: QuestionComment
has text: show your code.
type: Comment

http://stackoverflow.com/comment/82333529
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47682726
has text: @chappie, you could edit your question to augment it or start a new question. Depends on whether we're dealing with a new issue or another aspect of the current question.

http://stackoverflow.com/comment/83745114
comment on: http://stackoverflow.com/a/47712281
type: Comment
has text: I added the reference for task method execution order, ie §9.3.4 in current waf book. §9.3.6 might be of interest too, it explains how to set abstract dependencies between taskgens.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47544324
has comment: http://stackoverflow.com/comment/82055006
downvote count: 0
score: 1
has body: You can try the tf.train.AdamOptimizer and increase your learning rate (maybe around 0.1). This will increase the convergence rate.
type: Answer
has comment: http://stackoverflow.com/comment/82054072
has comment: http://stackoverflow.com/comment/82055173
answers question: http://stackoverflow.com/q/47543589
upvote count: 1

http://stackoverflow.com/q/47621792
type: AnsweredQuestion
tagged with: pandas
has body: I have a DataFrame df with informations about elements, for instance: df = pd.DataFrame([[1,45,12],[1,8,13],[1,3,4],[2,5,1],[2,7,3]], columns=['group', 'value1', 'value2']) I have used something like dfGroups = df.groupby('group').apply(my_agg).reset_index(), so now I have dfgroup, say dfGroup = pd.DataFrame([[1,4],[2,27]], columns=['group', 'valuegroup']) Now I need to bring back the group information to the elements, to be able to build new columns taking into account elements data and group data. So to make it simple, let's say I need to build a valuegroupcolumn in df identical dfGroup data. So I would obtain group value1 value2 valuegroup 0 1 45 12 4 1 1 8 13 4 2 1 3 4 4 3 2 5 1 27 4 2 7 3 27 What's the best way to do that? (If possible, something that would work with Python 2 and 3)
has answer: http://stackoverflow.com/a/47621851
has title: Getting back data in a Pandas DataFrame after a groupby
tagged with: dataframe
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/47621816
favorite count: 0
has answer: http://stackoverflow.com/a/47621816
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47621851
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47659478
has body: I am launching a series of subprocess one after the other, something like for variables in my_list: proc = subprocess.Popen(**variables) proc.wait() however if one of them crashes Windows pops up a window saying that the program has stopped working; since the process hasn't been killed yet, the program waits until I click the "close program" button I'm wondering if there is a way to tell Python to open this process without UI or make it so that if it crashes it doesn't pop up error reports. The documentation doesn't seem to address any of this. I'm using python 2.7, so I can't make use of the timeout flag that is present in python 3.
has title: how to get a subprocess to not get stuck if application crashes?
tagged with: python-2.7
tagged with: subprocess
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: windows
accepted answer: http://stackoverflow.com/a/47660609
tagged with: python
has answer: http://stackoverflow.com/a/47660609

http://stackoverflow.com/a/58314210
has body: You can also go into the directory where you have your pip.exe or pip3.exe located. For me it was on my D drive so here is what I did: D:\&gt;cd python D:\python&gt;cd Scripts D:\python\Scripts&gt;pip3.exe install tweepy Hope it helps
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47632891

http://stackoverflow.com/q/47618426
has answer: http://stackoverflow.com/a/47618537
tagged with: python
accepted answer: http://stackoverflow.com/a/47618537
tagged with: pygame
type: AnsweredQuestion
score: 0
has body: New to python and pygames. My first game is dumb. When the mouse is clicked the background color changes. The error I got: Traceback (most recent call last): File ".\main.py", line 72, in &lt;module&gt; main() File ".\main.py", line 50, in main displayScreen.fill(otherColors) TypeError: invalid color argument I've linked my code here: https://pastebin.com/YFhCduEd Any help is much appreciated even an explanation on what I am doing wrong.
answer count: 1
type: Question
has title: TypeError: invalid color argument

http://stackoverflow.com/a/47642667
type: Answer
answers question: http://stackoverflow.com/q/47642577
has body: Add global dict_ip_attempts at the beginning of sortattempts function. Edit: Basically, what you try to do is described here in a much more pythonic way.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82243954
has comment: http://stackoverflow.com/comment/82243951
score: 1

http://stackoverflow.com/comment/82080792
type: Comment
has text: what if I have a variable which stores the url like var = "http://test.com" then how do I add the url using the variable pulls_url = var +
type: AnswerComment
comment on: http://stackoverflow.com/a/47561279
score: 0

http://stackoverflow.com/comment/82284242
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47648207
score: 0
has text: Thank you to everyone how commented - abccd “sorry I did know about parentheses, but I just missed it after lots of looking!!

http://stackoverflow.com/comment/82267996
type: Comment
type: QuestionComment
has text: `NameError: name 'true' is not defined` Other than that, this code works fine.
comment on: http://stackoverflow.com/q/47654911
score: 0

http://stackoverflow.com/comment/82283246
comment on: http://stackoverflow.com/q/47661476
score: 0
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160540/discussion-between-coal-and-therutubeify).
type: Comment

http://stackoverflow.com/comment/82109898
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47564075
has text: Not exactly. If that were true, it would be modeled as a stochastic process with interarrival time lambda and service time normally distributed. I would never have written an exercise to be this overly- complicated if the learning objective was to pull from a queue.

http://stackoverflow.com/comment/82322048
type: AnswerComment
has text: Because `0` means `False` in python, and anything else is true. This means that the code will keep deleting the values until the statement is false (when there are no values in the list).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47681117

http://stackoverflow.com/q/47653475
type: Question
has answer: http://stackoverflow.com/a/47653655
tagged with: for-loop
type: UnansweredQuestion
tagged with: python
score: -1
has title: How to iterate through bytes in python
upvote count: 0
tagged with: byte
has body: I'm trying to iterate through bytes in python. I have: new[0]=b'\x00' but I want to iterate from '\x00' to '\xFF' in this new[0] element in a for loop. I mean: new[0]=b'\x01' new[0]=b'\x02' My target is not to view bytearray, but to change the first byte in this statement: XX:32:38:B3:89:E9:D2:E6:88:1F:FF:A9:96:AF:26:CB:C6:06:2F:E0:08:21:7C:12:4D:31 I want to change XX by iterating through bytes. How can I do that?
answer count: 1
downvote count: 1
tagged with: loops
favorite count: 0

http://stackoverflow.com/a/47604701
has comment: http://stackoverflow.com/comment/82169574
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82169464
accepted answer of: http://stackoverflow.com/q/47604621
answers question: http://stackoverflow.com/q/47604621
has body: You can try something like this without using any external module, with just one loop: Data is : your_data = [[1,2,3,4,5,6], [1,1,3,4,5,6], [1,4,3,4,5,6], [1,2,3,2,5,6], [1,4,3,2,5,6], [1,2,3,2,7,6], [1,2,3,5,5,6], [1,1,3,5,5,6], [1,2,3,4,5,6], [1,7,3,4,5,6]] One line solution: result={} [result.__setitem__((item[3],item[4]),item) for item in your_data if (item[3],item[4]) not in result] print(result.values()) Detailed solution: result={} for item in your_data: if (item[3],item[4]) not in result: result[(item[3],item[4])]=[item] print(result.values()) output: dict_values([[[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 2, 7, 6]], [[1, 2, 3, 2, 5, 6]], [[1, 2, 3, 5, 5, 6]]])
type: Answer
score: 0

http://stackoverflow.com/comment/82131001
has text: I have updated the question to state clearly that I cannot read the entire dataset.@Aymen
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47586666
type: AnswerComment

http://stackoverflow.com/comment/82230748
has text: Why can't you import it? Please edit your question and explain more clearly what you are trying to achieve, and make sure you include **all** the relevant information.
comment on: http://stackoverflow.com/q/47596831
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47541327
has comment: http://stackoverflow.com/comment/82040638
type: Answer
accepted answer of: http://stackoverflow.com/q/47541166
has comment: http://stackoverflow.com/comment/82040156
has comment: http://stackoverflow.com/comment/82040798
score: 3
answers question: http://stackoverflow.com/q/47541166
has comment: http://stackoverflow.com/comment/82040463
has comment: http://stackoverflow.com/comment/82040683
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82040560
downvote count: 0
has body: You can use numpy's broadcasting to compute the euclidean distance between each pair and find the minimum value with argmin. v = ((df1.iloc[:, :-1].values[:, None] - df2.values) ** 2).sum(-1).argmin(0) df2.assign(Label=df1.Label.iloc[v].values) A B C Label 0 2 2 2 1 1 3 3 3 2 2 4 4 4 3 3 3 3 3 2

http://stackoverflow.com/comment/82086390
comment on: http://stackoverflow.com/a/47564153
type: AnswerComment
score: 0
has text: @Katie Assign the result above to `g`. Then, do something like `g.plot(); plt.show()`
type: Comment

http://stackoverflow.com/comment/82167058
score: 0
has text: Have you got any code you can include in your question? Or are you asking the community to provide code from scratch? Or, well what's your question?
type: QuestionComment
comment on: http://stackoverflow.com/q/47604046
type: Comment

http://stackoverflow.com/q/47615196
has comment: http://stackoverflow.com/comment/82189002
linked to: http://stackoverflow.com/q/5329586
answer count: 1
has title: Django Model Forms set possible values of foreign key dropdown
tagged with: django-forms
type: Question
duplicate of: http://stackoverflow.com/q/5329586
has body: I have a form ReviewForm that extends ModelForm. ReviewForm's model is Review, which has the fields: class Review(models.Model): message = models.TextField(max_length = 4000) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(null = True) rating = models.IntegerField( default = 5, validators = [MaxValueValidator(5), MinValueValidator(0)] ) prof = models.ForeignKey(Prof, related_name = 'reviews') course = models.ForeignKey(Course, related_name = 'reviews') user = models.ForeignKey(User, related_name = 'reviews') and for forms.py class ReviewForm(ModelForm): rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5})) class Meta: model = Review fields = ['message', 'rating', 'prof', 'course', 'user'] I'm trying to pass initial values to the form before rendering it. Here's my code for views.py def review(request, prof_id=None): """ Review a prof """ # If there's an input prof, return review page for that prof if prof_id: user = User.objects.get(pk=request.user.id) prof = prof_views.prof(prof_id) course = prof.course_set.all() data = {'user': user, 'prof': prof, 'course': course} review_form = ReviewForm(initial=data) return render(request, 'reviews/review_form.html', {'review_form': review_form}) review_form = ReviewForm() return render(request, 'reviews/review_form.html', {'review_form': review_form}) The initial values of prof and user are set successfully. I'm trying to pass in the courses of a prof, and have the form display that queryset. However, Django doesn't seem to accept it. I'm not sure how to code this function. Setting the initial value of prof and user works because it selects the initial value. I'm sure that the code to get a prof's courses: course = prof.course_set.all() works properly, I've tested it in shell. So what I need to do is set the possible values of the form's courses, based on the queryset input.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47615386
tagged with: django
tagged with: python
score: 0
tagged with: django-views

http://stackoverflow.com/a/47559086
score: 2
has comment: http://stackoverflow.com/comment/82404729
has comment: http://stackoverflow.com/comment/82404268
has comment: http://stackoverflow.com/comment/82076052
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47557989
has comment: http://stackoverflow.com/comment/82403945
has comment: http://stackoverflow.com/comment/82077048
has body: Here is how I would solve this: from lxml import html as html_parser from requests import Session HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" } def dig_up_products(url, session=Session()): html = session.get(url, headers=HEADERS).text page = html_parser.fromstring(html) # if it appears to be a categories page, recurse for link in page.xpath('//h2[contains(., "CATEGORIES")]/' 'following-sibling::div[@id="carouselSegment1b"]//li//a'): yield from dig_up_products(link.attrib["href"], session) # if it appears to be a products page, return the links for link in page.xpath('//ul[@id="prodResult"]/li//div[@class="imgWrapper"]/a'): yield link.attrib["href"] def main(): start = 'https://www.richelieu.com/us/en/category/custom-made-cabinet-doors-and-drawers/1000128' for link in dig_up_products(start): print(link) if __name__ == '__main__': main() There is nothing wrong with iterating over an empty XPath expression result, so you can simply put both cases (categories page/products page) into the same function, as long as the XPath expressions are specific enough to identify each case.
upvote count: 2
answers question: http://stackoverflow.com/q/47557989
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82076208

http://stackoverflow.com/a/47559643
answers question: http://stackoverflow.com/q/47559551
has body: The problem is not the sub-list, but the fact that you're modifying your original list while you're iterating it. Iterate a copy instead: messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] for val in list(messy_list): if type(val) != int: messy_list.remove(val) print(messy_list) # [2, 3, 1]
type: Answer
score: 0

http://stackoverflow.com/q/47598954
has body: I'm not sure why I get this error when I test this function. Can anyone please help me fix this? cur.execute(q, args) sqlite3.OperationalError: near "FROM": syntax error This is my desired output: print(get_course_time(db, "MGEB02H3F")) # [('MGEB02H3F', '214', '17-12-14', '14:00'), ('MGEB02H3F', '215', '17-12-14', '14:00'), # ('MGEB02H3F', '216', '17-12-14', '14:00'), ('MGEB02H3F', '217', '17-12-14', '14:00'), # ('MGEB02H3F', '218', '17-12-14', '14:00')] And current code: def get_course_time(db, course): """Return the course number, ID, the date and start time of the given course's exam for all sections. Note there are only multiple sections if the course IDs are different.""" return run_query(db, '''SELECT Courses.Course FROM Courses JOIN Time on Time.Course, ID, Date, Start FROM Time WHERE course = ?''', (course,))
type: UnansweredQuestion
tagged with: database
has answer: http://stackoverflow.com/a/47600399
tagged with: python
has title: returning courses from times
score: 0
has answer: http://stackoverflow.com/a/47599025
tagged with: sql
type: Question
answer count: 2

http://stackoverflow.com/q/47614591
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47614748
accepted answer: http://stackoverflow.com/a/47614748
favorite count: 0
has body: I am trying to load the data inside the table trial and it says Invalid Column name - Name. I am passing values inside Name and Area dynamically. cursor.execute("insert into trial (NameofTheProperty, AreaofTheProperty) values (Name, Area)") cnxn.commit()
type: Question
tagged with: python
tagged with: pyodbc
has title: Pyodbc - loading data inside a table causing error
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/82290993
type: Comment
comment on: http://stackoverflow.com/a/47665267
type: AnswerComment
score: 0
has text: @Axil I've added to my answer to use your models `as_dict` method so it will display as you wish.

http://stackoverflow.com/a/47691494
answers question: http://stackoverflow.com/q/47691425
downvote count: 0
has body: How about: with open ('temp.csv', 'wb') as outfile: outfile.writelines(data_in[0]) outfile.writelines(data_in[5:])
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47691425
type: Answer

http://stackoverflow.com/comment/82042143
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47542493
has text: Possible duplicate of [Turning off logging in Selenium (from Python)](https://stackoverflow.com/questions/9226519/turning-off-logging-in-selenium-from-python)
score: 0

http://stackoverflow.com/q/47590857
has title: Django Postgresql JsonField query related dictionary keys
favorite count: 0
type: Question
tagged with: postgresql-json
linked to: http://stackoverflow.com/q/42675803
tagged with: django-jsonfield
tagged with: postgresql
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47591218
tagged with: python
has body: A part of the model that I have, which uses Django Model field, is like the following: class SalesModel(models.Model): some_data = models.PositiveIntegerField(db_index=True) some_other_data = models.CharField(max_length=50) json_data = JSONField(blank=True, null=True) Now following is the format of the JsonData field: [{"id": val, "contribution": "some_val", }, {"id": some_val, "contribution": "some_other_val",}, {"id": other_val, "contribution": "some_another_val"}] i.e., the format is: [{'id':XX, 'contribution':XX},{'id':YY, 'contribution':YY},{'id':ZZ, 'contribution':ZZ}] Currently I can filter the Django table with the val of ID. I would now, like to know the contribution of that particular ID. For eg, if val = 1, I would like to filter the model SalesModel which has JsonField with id = 1, and I want to show the related contribution. So, that would mean, out of the 3 possible dictionaries (as per the field construction), I would only show one dictionary (filtered by the 'ID' key of that dictionary). That would mean, if the 2nd dictionary has a matching ID, show only the 2nd contribution, if the 1st ID is matching show only the 1st contribution, and similarly for the 3rd dictionary. Is there a way that can be done?
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47591139
has answer: http://stackoverflow.com/a/47591805
accepted answer: http://stackoverflow.com/a/47591805
possible better answer: http://stackoverflow.com/a/47591218
tagged with: django

http://stackoverflow.com/q/47561779
has body: I'm new to networkx in python and I had a problem in creating a DiGraph. I specify create_using=nx.DiGraph when I try to create a DiGraph using the adjacency matrix in pd dataframe, but I got a Graph instead of a DiGraph. Can anyone explain why?
has answer: http://stackoverflow.com/a/47569594
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has title: Why do I get a Graph when I specify create_using=nx.DiGraph
favorite count: 0
tagged with: networkx
score: 2
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/82155800
score: 0
comment on: http://stackoverflow.com/q/47598760
type: QuestionComment
type: Comment
has text: If you are a newbie and don't understand why the answers posted here works, the topic you are after is **list slicing** in python. Example [here](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python)

http://stackoverflow.com/a/47610916
upvote count: 1
has comment: http://stackoverflow.com/comment/82243485
score: 1
downvote count: 0
has body: I see few general errors in your code: You call function Num1() for entering num1, but num1 is the local variable. So you can see and use it only in Num1() function. Same with num2. So, I suggest to use Num1 and Num2 but to return the num1 and num2. I recommend to use 1 function, there is no need to use 2. Looks like with num1 = int.num1() you want to convert num1() to int. This is wrong. Correct will be something like num1 = int(num1). This will convert num1 from string to int and save it to num1. But better to use different names for strings and int's: num1 = int(num1_str). And when you use bracket num1(), this means you call num1 function to complete. But num1 is not a function, so it's not callable. You use converting strings to int two times. In programming, when you see two code, which is just copy/paste, you better to make a function for it. Here we have the function, so just insert converting to int in function. Don't forget about indentation. This is the most important thing in Python. In other languages, you use something like {} to define the beginning and the end of some logical block. But in Python, it all depends on indentation. So, using this, it can look like this way: def main(): while True: # just call NumEntering - one general function for entering numbers, # and give to it attribute - message for user. num1 = int(NumEntering("What is the first number? ")) num2 = int(NumEntering("What is the second number? ")) # Executing the specified calculations with the 'Operation' function (row 13) Operation(num1, num2) And the function: def NumEntering(message): # message - this what function get from outer function. while True: num_str = input(message) # show given message if num_str.isdigit(): return int(num_str) # convert to int and return to outer function elif num_str == 'exit': print("Thank you using the SimpleCalculator. Bye!") time.sleep(3) exit() else: print("I don't understand. Please input a valid number") continue
answers question: http://stackoverflow.com/q/47610493
type: Answer

http://stackoverflow.com/comment/82061764
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47551759
type: Comment
has text: Thank you very much! What is tokenize?

http://stackoverflow.com/q/47567780
tagged with: swap
has title: Python, swap variables every loop
has body: I have part of code that looks like this: for i in [0,1]: ... print('{} used {} words that {} did not use.'.format(a[i], 50 , a[i+1])) For the first iteration, I want it to do, print('{} used {} words that {} did not use.'.format(a[0], 50 , a[1])) but for the second iteration, I want this: print('{} used {} words that {} did not use.'.format(a[1], 50 , a[0])) How can this be done?
type: Question
has comment: http://stackoverflow.com/comment/82093052
score: 0
has answer: http://stackoverflow.com/a/47567841
has answer: http://stackoverflow.com/a/47567847
has comment: http://stackoverflow.com/comment/82093031
tagged with: python
has comment: http://stackoverflow.com/comment/82093184
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47567850
has answer: http://stackoverflow.com/a/47567954
has comment: http://stackoverflow.com/comment/82093004
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82093092

http://stackoverflow.com/q/47626299
tagged with: python-2.7
favorite count: 0
has answer: http://stackoverflow.com/a/47640147
type: Question
tagged with: multiprocessing
answer count: 2
has body: Here is my demo code. It contains two scripts. The first is main.py, it will call print_line.py with subprocess module. The second is print_line.py, it prints something to the stdout. main.py import subprocess p = subprocess.Popen('python2 print_line.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, shell=True, universal_newlines=True) while True: line = p.stdout.readline() if line: print(line) else: break print_line.py from multiprocessing import Process, JoinableQueue, current_process if __name__ == '__main__': task_q = JoinableQueue() def do_task(): while True: task = task_q.get() pid = current_process().pid print 'pid: {}, task: {}'.format(pid, task) task_q.task_done() for _ in range(10): p = Process(target=do_task) p.daemon = True p.start() for i in range(100): task_q.put(i) task_q.join() Before, print_line.py is written with threading and Queue module, everything is fine. But now, after changing to multiprocessing module, the main.py cannot get any output from print_line. I tried to use Popen.communicate() to get the output or set preexec_fn=os.setsid inPopen(). Neither of them work. So, here is my question: Why subprocess cannot get the output with multiprocessing? why it is ok with threading? If I comment out stdout=subprocess.PIPE and stderr=subprocess.PIPE, the output is printed in my console. Why? How does this happen? Is there any chance to get the output from print_line.py?
tagged with: subprocess
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47629593
tagged with: python
possible better answer: http://stackoverflow.com/a/47640147
has answer: http://stackoverflow.com/a/47629593
type: AnsweredQuestion
score: 2
has title: How to get output from python2 subprocess which run a script using multiprocessing?

xcode
tag name: xcode
tags question: http://stackoverflow.com/q/47643901
type: Tag

http://stackoverflow.com/a/57154052
type: Answer
has body: ATTENTION: Following solution is not for production, your lead will punish you if saw this in your code :) My packages version are old: django-storages==1.1.8 boto==2.38.0 boto3==1.2.1 But main idea (I hope) will be understood Place following patching(or if you wish - class could be extended) on some "start" level of your application(on your taste). from storages.backends import s3boto def monkey_init(self, name, mode, storage, buffer_size=None): """Only 'validate=mode != "rb"' was added in 'get_key' method's call""" self._storage = storage self.name = name[len(self._storage.location):].lstrip('/') self._mode = mode self.key = storage.bucket.get_key(self._storage._encode_name(name), validate=mode != "rb") if not self.key and 'w' in mode: self.key = storage.bucket.new_key(storage._encode_name(name)) self._is_dirty = False self._file = None self._multipart = None # for files larger than this. if buffer_size is not None: self.buffer_size = buffer_size self._write_counter = 0 s3boto.S3BotoStorageFile.__init__ = monkey_init In my version of django-storages call of method get_key doesn't pass validate variable into it. And I didn't find any way to force/change it except explicitly redefining __init__ method. PS: If your setting doesn't containt explicit boto section in logging -> logs will not be shown for GET/HEAD/etc. requrests from boto. Just add boto section into logging setting part. 'boto': { 'handlers': LOGGING_HANDLERS, 'level': 'DEBUG', 'propagate': False, },
answers question: http://stackoverflow.com/q/47674464
score: 0

http://stackoverflow.com/comment/82045290
comment on: http://stackoverflow.com/a/47544145
score: 0
type: AnswerComment
type: Comment
has text: @ShadowRanger it's the poor copy/paste job... sorry

http://stackoverflow.com/comment/82046961
comment on: http://stackoverflow.com/a/47543591
type: AnswerComment
has text: `ValueError: Error when checking target: expected activation_1 to have 3 dimensions, but got array with shape (50, 2)`
score: 0
type: Comment

http://stackoverflow.com/q/47659417
tagged with: pandas
score: 0
answer count: 1
tagged with: neural-network
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82277907
type: Question
has body: Hi I want to prepare my data, which will be then used to learn LSTM network. I use pandas and numpy arrays. I have csv file which i read like df = pd.read_csv("data.csv",....) That csv file contains values of wind direction and hour of day and some other values... Hour of day is represented as integer from 0 to 24. I need it to be represented by values of sinus and cosinus. Wind direction is represented as one or two characters like: NW, N, SE, etc.. (NW - northwest, N - north, ... etc) - I need it to be represented by values of sinus and cosinus as well. I am a newbie in pandas, python and everything mentioned here... Thak you for any help.
type: UnansweredQuestion
has title: prepare data for CNTK LSTM
tagged with: python
has comment: http://stackoverflow.com/comment/82323121
has answer: http://stackoverflow.com/a/47682082
tagged with: lstm

http://stackoverflow.com/q/47639331
possible better answer: http://stackoverflow.com/a/47639384
answer count: 3
upvote count: 2
score: 1
has body: When I put oursum outside of the loop it infinitely multiplies it by 2 usernum=float(input('Enter a number: ')) if usernum&lt;=0 or usernum&gt;1000: print('Your number is '+str(usernum)) else: oursum=usernum*2 while oursum&lt;=1000: print('Multiplied by 2 equals '+str(oursum)) When inside, it's not defined. usernum=float(input('Enter a number: ')) if usernum&lt;=0 or usernum&gt;1000: print('Your number is '+str(usernum)) else: while oursum&lt;=1000: oursum=usernum*2 print('Multiplied by 2 equals '+str(oursum)) I understand the problems I'm making but I don't know how to rectify this without making it unnecessarily long and complicated. Thanks in advance.
tagged with: nested
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47639369
has answer: http://stackoverflow.com/a/47648737
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47639369
has answer: http://stackoverflow.com/a/47639384
tagged with: python
has title: Python, program that multiplies number by 2 til it's greater than 1000, having issue with syntax

http://stackoverflow.com/comment/82311788
comment on: http://stackoverflow.com/q/47673889
score: 0
has text: @chilun what if there are more than one pair of items which match?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47665491
upvote count: 6
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49841791
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47665596
answer count: 2
downvote count: 0
tagged with: pyspark
score: 6
tagged with: python
accepted answer: http://stackoverflow.com/a/47665596
has title: pyspark throws TypeError: textFile() missing 1 required positional argument: 'name'
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49841791
tagged with: apache-spark
has body: I googled this problem, yet no direct answer related to spark-2.2.0-bin-hadoop2.7. I am trying to read a text file from local directory, but I always get TypeError that name argument is missing. This is the code in jupyter notebook with Python3: from pyspark import SparkContext as sc data = sc.textFile("/home/bigdata/test.txt") When I run the cell, I get this error: TypeError Traceback (most recent call last) &lt;ipython-input-7-2a326e5b8f8c&gt; in &lt;module&gt;() 1 from pyspark import SparkContext as sc ----&gt; 2 data = sc.textFile("/home/bigdata/test.txt") TypeError: textFile() missing 1 required positional argument: 'name' Your help is appreciated.
tagged with: rdd

http://stackoverflow.com/comment/82162682
type: AnswerComment
has text: Collisions are guaranteed to exist for any hash function, regardless of the existence of one-way functions.
comment on: http://stackoverflow.com/a/47601889
score: 2
type: Comment

http://stackoverflow.com/a/47666449
type: Answer
has body: You need to move the variables to before the while loop. That way the values don't get reset each time the loop runs. Try something like: import random def homeScreen(): print('Welcome to your bank application \n 1. Create Account \n 2. Make a Deposit \n 3. Make a Withdrawal \n' ' 4. View Accounts \n 5. View Transactions \n 6. Transfer Money \n 7. Loans \n 8. Close an Account') def loopScreen(): menu_choice = int(input('Please enter a number to select an option')) loop_set = 1 cacc_check = 0 sacc_check = 0 while loop_set &lt; 5: if menu_choice == 0: homeScreen() if menu_choice == 1: print('Creating Account') name = str(input('Please enter your name: ')) acc_choice = int(input('Type 1 for a checking account and 2 for a savings account')) if acc_choice == 1 and cacc_check == 0: cacc_num = random.randint(1000, 9999) cacc_check += 1 print('Hello ', name, 'your checking account number is', cacc_num) homeScreen() if acc_choice == 1 and cacc_num != 0: print("It looks like you already have a checking account with us") homeScreen() if acc_choice == 2 and sacc_check == 0: sacc_num = random.randint(1000, 9999) print('Hello ', name, 'your savings account number is', sacc_num) if loop_set == 1: loop_set = loop_set + 1 print('loop_set = ', loop_set) homeScreen() loopScreen()
answers question: http://stackoverflow.com/q/47666395
score: 0

http://stackoverflow.com/comment/82173363
score: 0
type: Comment
type: QuestionComment
has text: @EricDuminil exactly my thinking, I've been thrown curve-balls before where the expectation is completely unknown but not in this field. They stress you out. In this case, I think it would be safer to assume that the answer is along the lines of "Did you want it O(1) <for clarification>? The closest you can get is an approximation that probabilistically gets better with longer inputs. However, here's a correct O(n) answer". Not safe to assume the asker is simply dumb as some answers suggest.
comment on: http://stackoverflow.com/q/47581326

http://stackoverflow.com/q/47627832
has answer: http://stackoverflow.com/a/47627954
has title: Python one-liner to print text converted from ASCII numbers?
accepted answer: http://stackoverflow.com/a/47627942
tagged with: ascii
has answer: http://stackoverflow.com/a/47627942
tagged with: ordinal
has comment: http://stackoverflow.com/comment/82213277
score: 2
upvote count: 2
type: AnsweredQuestion
has body: The following command print text from it's ASCII representative. python -c "print unichr(72)" E.g. [user@linux ~]$ python -c "print unichr(72)" H [user@linux ~]$ But this is only for a single character. If I have an ASCII string, let say 72 101 108 108 111 32 87 111 114 108 100 for Hello World, is it possible to convert it in Python in one line? I've been trying the following commands but it didn't work. [user@linux ~]$ python -c "print unichr(72)" "unichr(72)" H [user@linux ~]$ ... [user@linux ~]$ python -c "print unichr(72) unichr(72)" File "&lt;string&gt;", line 1 print unichr(72) unichr(72) ^ SyntaxError: invalid syntax [user@linux ~]$ ... [user@linux ~]$ python -c "print unichr(72)(72)" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; TypeError: 'unicode' object is not callable [user@linux ~]$
answer count: 3
downvote count: 0
tagged with: code-snippets
has comment: http://stackoverflow.com/comment/82213385
favorite count: 0
tagged with: idioms
type: Question
possible better answer: http://stackoverflow.com/a/47627954
tagged with: python
has answer: http://stackoverflow.com/a/47627970

class
tags question: http://stackoverflow.com/q/47541141
tags question: http://stackoverflow.com/q/47616790
tags question: http://stackoverflow.com/q/47603286
tags question: http://stackoverflow.com/q/47682576
tags question: http://stackoverflow.com/q/47626733
type: Tag
tags question: http://stackoverflow.com/q/47666853
tags question: http://stackoverflow.com/q/47548524
tags question: http://stackoverflow.com/q/47558120
tags question: http://stackoverflow.com/q/47635949
tags question: http://stackoverflow.com/q/47651416
tags question: http://stackoverflow.com/q/47654548
tags question: http://stackoverflow.com/q/47590867
tags question: http://stackoverflow.com/q/47571842
tags question: http://stackoverflow.com/q/47613891
tags question: http://stackoverflow.com/q/47591482
tags question: http://stackoverflow.com/q/47569389
tags question: http://stackoverflow.com/q/47620815
tags question: http://stackoverflow.com/q/47585074
tags question: http://stackoverflow.com/q/47613403
tags question: http://stackoverflow.com/q/47678352
tags question: http://stackoverflow.com/q/47684075
tag name: class
tags question: http://stackoverflow.com/q/47643956
tags question: http://stackoverflow.com/q/47644434
tags question: http://stackoverflow.com/q/47545910
tags question: http://stackoverflow.com/q/47555265
tags question: http://stackoverflow.com/q/47634894
tags question: http://stackoverflow.com/q/47686473
tags question: http://stackoverflow.com/q/47687912
tags question: http://stackoverflow.com/q/47671795
tags question: http://stackoverflow.com/q/47666238
tags question: http://stackoverflow.com/q/47633133
tags question: http://stackoverflow.com/q/47683244
tags question: http://stackoverflow.com/q/47616191
tags question: http://stackoverflow.com/q/47541623
tags question: http://stackoverflow.com/q/47640913
tags question: http://stackoverflow.com/q/47688059
tags question: http://stackoverflow.com/q/47684222
tags question: http://stackoverflow.com/q/47664319
tags question: http://stackoverflow.com/q/47645963
tags question: http://stackoverflow.com/q/47620179
tags question: http://stackoverflow.com/q/47551392
tags question: http://stackoverflow.com/q/47663090

http://stackoverflow.com/comment/82043507
comment on: http://stackoverflow.com/a/47543074
score: 0
has text: Andrea, thank you for your answer. This is exactly what I was looking for.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47628061
accepted answer of: http://stackoverflow.com/q/47627934
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82215383
answers question: http://stackoverflow.com/q/47627934
has body: Extend arrays to have more dimensions and then leverage broadcasting - output = a1[...,None,None] + a2[...,None,None,:,:] Sample run - In [38]: # Setup input arrays ...: N = 3 ...: M = 4 ...: a1 = np.random.rand(2,2,N,M) ...: a2 = np.random.rand(2,2,N,M) ...: ...: output = np.zeros((2,2,N,M,N,M)) ...: for x1 in range(N): ...: for x2 in range(N): ...: for y1 in range(M): ...: for y2 in range(M): ...: output[:,:,x1,y1,x2,y2] = a1[:,:,x1,y1] + a2[:,:,x2,y2] ...: ...: output1 = a1[...,None,None] + a2[...,None,None,:,:] ...: ...: print np.allclose(output, output1) True

http://stackoverflow.com/q/47627478
type: Question
has body: When a GBDT is built with the sklearn.ensemble.GradientBoostingClassifier, I have a set of trees. I can figure out the structure of a single tree. But for a set of trees, how do I know in which way the trees are accessed? Take the following codes for example, from sklearn.datasets import load_iris from sklearn import tree from sklearn.ensemble import GradientBoostingClassifier clf = GradientBoostingClassifier(n_estimators=4) iris = load_iris() clf = clf.fit(iris.data, iris.target) Then, I have 4 trees, that is, for i in range(4): print(clf.estimators_[i,0].tree_) And, I can do this with the trees, clf.predict( array([0,1,2,3]).reshape(1, -1) ) But in which turn, the clf.estimators_[0,0].tree_ .. clf.estimators_[3,0].tree_ are accessed? and how the results are put together? In the manual, it is said that, ``now expose an apply method for retrieving the leaf indices each sample ends up in under each try". clf.apply( array([0,1,2,3]).reshape(1, -1) ) I obtained the following array, [[ 1., 7., 10.], [ 1., 7., 10.], [ 4., 7., 10.], [ 1., 1., 10.]] But how to read it? Update: ------ I have read some source code from here: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ensemble/gradient_boosting.py#L1247 It seems that, the indices are merely indices, but encoded with the non-leaf nodes. That explains why there are only 8 leaves, but the incides can be larger than 8. Another update: ------ After reading the codes here and here, I have finally figured it out that, GBDT's decision_function returns init_value+sum_{for each leaf}(learning_rate*leaf_value), and the prediction probablity is a simple function of decision_function.
type: UnansweredQuestion
tagged with: boosting
downvote count: 0
upvote count: 1
tagged with: scikit-learn
tagged with: python
tagged with: tree
answer count: 0
has title: How to obtain whole decision process of a sklearn GBDT?
score: 1
favorite count: 0

http://stackoverflow.com/q/47697697
answer count: 2
downvote count: 0
tagged with: selenium
tagged with: web-scraping
has body: How do I create a page count down for python for each page it navigates to. I have included my attempts below. How do I get desired result? I am using (len(elem_href1) so I can try and create page count down so easily informed of where my script is progressing. Trying to do that - a value each loop. driver = webdriver.Chrome() driver.get('https://stackoverflow.com/questions') elements = driver.find_elements_by_css_selector("#questions .question-hyperlink") elem_href1 = [element.get_attribute("href") for element in elements] print(elem_href1) print (len(elem_href1)) shuffle(elem_href1) for link in elem_href1:#(2) driver.get(link) print(len(link)) import numbers #number = number -= 1 #print (len(elem_href1-(number))) print (len(elem_href1)) gives total number of pages to navigate to. print(len(link)) gives random number due to shuffle. Current output: 15 83 101 112 72 107 106 84 Desired: 50 #When at page 50 49 #when at page 49.. 48 #when at page 48.. 42 #Counting down... .. Maybe then: number = number -= 1 print (len(elem_href1-(number))) #SyntaxError: invalid syntax Or: count = len(elem_href1) def countdownList(l): # 3. prints number of files left to process global count count = count - 1 print(count, " pages left to go.") if count == 0: Output: 15 43 Any ideas how this might be achieved
has answer: http://stackoverflow.com/a/47698442
favorite count: 0
accepted answer: http://stackoverflow.com/a/47698442
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47698357
possible better answer: http://stackoverflow.com/a/47698357
linked to: http://stackoverflow.com/q/47710581
tagged with: python
has title: Python page count down print (len(elem_href1-(number)))
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/118748490
score: 0
type: AnswerComment
has text: I’m struggling with this at the moment. Because it’s hard to reason about the size of the central plot region, Bokeh figures are not very compositional. As per the comment above, a stepwise improvement would be the ability to calculate the width of (axes + labels), or set it to some fixed size (with content clipped).
comment on: http://stackoverflow.com/a/47582228
type: Comment

http://stackoverflow.com/a/47653489
has comment: http://stackoverflow.com/comment/82265276
answers question: http://stackoverflow.com/q/47651811
has comment: http://stackoverflow.com/comment/82265373
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82266257
has comment: http://stackoverflow.com/comment/82266597
has comment: http://stackoverflow.com/comment/82265696
has comment: http://stackoverflow.com/comment/82265658
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47651811
has body: To Flask (or to any backend for that matter) those parameters are sent as individual form arguments called time[1], time[2] and time[3], not as some sort of a magical list. If you want to turn them into a list, or rather a dict as it's a sparse list, then you'll have to loop through your request.form and extract them. Something like: form = request.form # a short-hand for readability time = {p[5:-1]: form[p] for p in form if p[:4] == "time" and p[4] == "[" and p[-1] == "]"} Then you can use the newly created time dictionary to loop through each of the parameters in an index:value manner: for i, v in time.items(): print("index={}, value={}".format(i, v)) Or you can access your index directly to obtain the value, i.e. time['3']. Notice that we're using strings as indexes here, if sent 'indexes' are always integers, you can use int(p[5:-1]) when setting the key and then access the value with time[3]. If you want to use request.form.getlist() you'll need to name all your inputs the same (e.g. time[]) but then you won't have sparse lists.

http://stackoverflow.com/a/47630281
answers question: http://stackoverflow.com/q/47592698
type: Answer
has body: You should upgrade to the current development version from the repository. If you still have this issue, you should report it as a bug.
score: 0

http://stackoverflow.com/comment/82145358
score: 2
has text: Also, your "simple `O(n)` solution" is actually `O(10**d * n)` with `d` the number of searched digits and `n` the total length of the string. The second one is `O(n)` time and `O(10**d + n)` space.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47581589

http://stackoverflow.com/q/47629083
has comment: http://stackoverflow.com/comment/86075986
has title: Install caffe/pycaffe on MacOSX High Sierra
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/50003176
answer count: 1
tagged with: macos
downvote count: 1
favorite count: 0
type: Question
has body: I'm following this tutorial to install caffe on my OSX High Sierra. I followed all steps but I'm stucked when installing R-CNN example at this step: $ make -j8 &amp;&amp; make pycaffe LD -o .build_release/lib/libcaffe.so clang: warning: argument unused during compilation: '-pthread' [-Wunused-command-line-argument] ld: cannot link directly with /System/Library/Frameworks//vecLib.framework/vecLib for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [.build_release/lib/libcaffe.so] Error 1 But the library veclib is present: $ ls /System/Library/Frameworks//vecLib.framework/vecLib /System/Library/Frameworks//vecLib.framework/vecLib Can you help me please to solve this issue ?
tagged with: pycaffe
type: UnansweredQuestion
tagged with: caffe
tagged with: python

http://stackoverflow.com/a/47789187
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47677334
type: Answer
has body: Recall adopted for recommendation systems measures the ratio of products that were actually bought by customers (hits) in relation to their number of products in the test set (|T|). This measure is first calculated for each test customer and then averaged for all users in the test set. More information about the basic idea can be found in the paper of Cremonesi et al. (2010) “Performance of Recommender Algorithms on Top-n Recommendation Tasks” or in an early paper of Herlocker et al. (2004) “Evaluating collaborative filteringrecommender systems” Other metrics which may be suitable can take both into account, precision and recall. E.g., F1-Score is the harmonic mean of both measures and can be calculated by However, some studies have shown that customers usually look at the recommendation lists from top to bottom, often only perceiving the few products at the top of the list. To overcome this issue ranking-based measure e.g., Mean Average Precision (MAP) can be used.
answers question: http://stackoverflow.com/q/47677334
score: 1

http://stackoverflow.com/comment/82188484
type: QuestionComment
comment on: http://stackoverflow.com/q/47614844
score: 0
type: Comment
has text: Ok, my webapp is running 3.6, same as the associated virtual environment, even though the server bash is 2.x

http://stackoverflow.com/q/47542752
tagged with: time-series
type: UnansweredQuestion
has title: Python: Generate random time series data with trends (e.g. cyclical, exponentially decaying etc)
tagged with: python
linked to: http://stackoverflow.com/q/56466979
has comment: http://stackoverflow.com/comment/82042601
has comment: http://stackoverflow.com/comment/82042831
tagged with: random
tagged with: pandas
has answer: http://stackoverflow.com/a/48359952
score: 7
answer count: 1
downvote count: 0
upvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/82042725
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/99601522
has body: I am trying to generate some random time series with trends like cyclical (e.g. sales), exponentially decreasing (e.g. facebook likes on a post), exponentially increasing (e.g. bitcoin prices), generally increasing (stock tickers) etc. I can generate generally increasing/decreasing time series with the following import numpy as np import pandas as pd from numpy import sqrt import matplotlib.pyplot as plt vol = .030 lag = 300 df = pd.DataFrame(np.random.randn(100000) * sqrt(vol) * sqrt(1 / 252.)).cumsum() plt.plot(df[0].tolist()) plt.show() But I don't know how to generate cyclical trends or exponentially increasing or decreasing trends. Is there a way to do this ?

http://stackoverflow.com/comment/82116414
comment on: http://stackoverflow.com/q/47579442
type: Comment
type: QuestionComment
score: 0
has text: All nodes are closer to each other and generated image is small compared to data set. I am newbie, I hope there is some setting to resolve it

http://stackoverflow.com/comment/83034386
type: QuestionComment
has text: http://www.pygame.org/wiki/GettingStarted this website can help me too
score: 0
comment on: http://stackoverflow.com/q/47566955
type: Comment

http://stackoverflow.com/comment/82184422
comment on: http://stackoverflow.com/q/47612009
has text: Ok sorry. Shall I post full code of my program?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47692106
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: Trying to save a downloaded image to a path (inside a folder). It works with no folder, and I have tried relative and absolute paths. import requests import os import progressbar b_url = "http://cdn2-img.pressreader.com/pressdisplay/docserver/getimage.aspx?file=9b342017090100000000001001&amp;page={}&amp;scale=100" print("Format your url like this:") print(b_url) print("Note the {}\n") print("Images will be written to the directory `PressReader`") url = input("URL: ") if url == "": url = b_url name = input("Article name: ") page_length = 84 bar = progressbar.ProgressBar() for page in bar(range(0, page_length+1)): if not os.path.exists("PressReader"): os.makedirs("PressReader") r = requests.get(url.format(page), stream=True) if r.status_code == 200: with open(r'"PressReader\{}-Page-{}.png"'.format(name, page), 'wb') as f: for chunk in r: f.write(chunk) This should make a folder PressReader (which it does), then download the images to that folder. It however breaks, with this error: line 23, in &lt;module&gt; with open(r'"PressReader\{}-Page-{}.png"'.format(name, page), 'wb') as f: OSError: [Errno 22] Invalid argument: '"PressReader\\e-Page-1.png"'
score: 0
has comment: http://stackoverflow.com/comment/82343216
has title: OSError: [Errno 22] Invalid argument: Upon Folder Path
type: Question
has comment: http://stackoverflow.com/comment/82343371

http://stackoverflow.com/comment/82164006
type: AnswerComment
type: Comment
has text: I only have 2 countries- UK and US
comment on: http://stackoverflow.com/a/47585424
score: 0

http://stackoverflow.com/q/47614973
has answer: http://stackoverflow.com/a/47614992
score: 0
answer count: 1
tagged with: web-scraping
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Locating the right tag in HTML while webscraping in python
has body: Im working on a project for school were I display the current price for bitcoin, eth and maybe another and im web scraping https://cryptowat.ch/ but I cant find the tag used to store the live price. when i parse the div tag it returns the price but im not able to isolate it so i can display it in python BTC usd 10857.00

http://stackoverflow.com/comment/82188580
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47615017
type: Comment
has text: I confirm that it has to do with numpy.array. I could reproduce. And it only does it with 2D arrays.

http://stackoverflow.com/a/47610280
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47610123
has body: You could do without levelOne = print ("level 1") and just do print("level 1") because print() returns None. To confirm this, try levelOne == None. After the if-statement, you need to add all the numbers and print the sum. Otherwise, your code is working as is. You may want to insert a prompt argument into input(), like so: choice = input('Choose a level: ') Hope that helps.
upvote count: 2

http://stackoverflow.com/a/47657926
accepted answer of: http://stackoverflow.com/q/47624762
has body: sphinx.build_main() calls sphinx.cmdline.main(), which in turn creates a sphinx.application.Sphinx object. You could create such an object directly (instead of "making system calls within python"). Use something like this: import os from sphinx.application import Sphinx # Main arguments srcdir = "/path/to/source" confdir = srcdir builddir = os.path.join(srcdir, "_build") doctreedir = os.path.join(builddir, "doctrees") builder = "html" # Write warning messages to a file (instead of stderr) warning = open("/path/to/warnings.txt", "w") # Create the Sphinx application object app = Sphinx(srcdir, confdir, builddir, doctreedir, builder, warning=warning) # Run the build app.build()
answers question: http://stackoverflow.com/q/47624762
type: AcceptedAnswer
score: 5
upvote count: 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82076697
has text: @Dalvenjia "Uncaught ReferenceError: los_mostrarficha is not defined" This is what I get
comment on: http://stackoverflow.com/q/47558723
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/82184099
has text: @GrzegorzOledzki - THANK YOU!!!!!! I know it's all caps... and I mean every bit of it. It won't let me accept your answer at this point (the one you did below), but it worked! I mean, of course it worked, but I'm so excited. As soon as I saw your response, it made perfect sense. Thank you so very much. And thank you for your advice above, I was getting tired when I was coming up with variable names, and just trying to make the code work.
score: 0
comment on: http://stackoverflow.com/q/47612803
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82085409
score: 1
type: Comment
type: QuestionComment
has text: Your system's timezone is likely set to UTC. What values do [`time.tzname` and friends](https://docs.python.org/3/library/time.html#timezone-constants) have?
comment on: http://stackoverflow.com/q/47563103

http://stackoverflow.com/comment/82167911
has text: i have seen the link. Any clue how to implement it python?
comment on: http://stackoverflow.com/q/47602610
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47565616
has comment: http://stackoverflow.com/comment/82089451
downvote count: 0
tagged with: api
tagged with: reddit
type: UnansweredQuestion
answer count: 1
tagged with: data-science
favorite count: 0
type: Question
has title: Historical data using Reddit API
tagged with: python
has body: I am trying to access historical data of mentions of a few keywords for a data analysis project using Reddit API. Utilizing python's wonderful easy-to-use PRAW package to fetch the data. Does anyone know if Reddit api has any functionality that allows historical access to data from a subreddit?
tagged with: praw
has answer: http://stackoverflow.com/a/56454036
upvote count: 2
score: 2

http://stackoverflow.com/q/47620611
tagged with: collections
has body: I am writing a script to query a mongoDB collection using pymongo. My database has three collections and I am asking the user to pick a collection and then want to return all confirmed guests from that collection. Currently, I have: collectiontosearch = input("What event would you like to display? : ") collection = db.collectiontosearch print(collection) for people in collection.find({"Confirmed": "Yes"}): pprint.pprint(people) But instead of searching on the assigned value of 'collectiontosearch', it is searching on the plain text 'collectiontosearch' which obviously is not a collection in my database. Any idea how I can get pymongo to take my variable value here instead of the strict text of my variable name? I realize this is probably pretty basic stuff.
type: Question
has title: Python3 Replace module call with variable
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47654625
tagged with: mongodb
score: 0
answer count: 1
tagged with: pymongo

http://stackoverflow.com/comment/82235309
score: 0
comment on: http://stackoverflow.com/q/47638161
type: Comment
type: QuestionComment
has text: HI, no the chart is not shown in the tutorial. Its a chart where teh volume is added into the different candles. Shown here http://stockcharts.com/school/doku.php?id=chart_school:chart_analysis:candlevolume It fail to generate the individuel thickness of each candlestick. I dont know exactly how to do it. I know you could do it with a for loop within a panda dataframe but the module candlestick_ohlc doesnt support (i think) a itereation within width. width should be change for every candlestick

http://stackoverflow.com/comment/82250919
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47633325
type: AnswerComment
has text: **The code works for some time and then the following error occurs.** Traceback (most recent call last): File "stack.py", line 21, in <module> pool = ThreadPool(processes=2) File "W:\Tools\Python27\lib\multiprocessing\pool.py", line 732, in __init__ Pool.__init__(self, processes, initializer, initargs) File "W:\Tools\Python27\lib\multiprocessing\pool.py", line 187, in __init__ self._result_handler.start() File "W:\Tools\Python27\lib\threading.py", line 736, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread

http://stackoverflow.com/a/47667164
type: Answer
has comment: http://stackoverflow.com/comment/82356076
has comment: http://stackoverflow.com/comment/82324307
score: 1
has body: Since you're using ReLUs, one possibility is that you're suffering from the Dying ReLU Problem; you could fix this by switching to something like leaky ReLUs. Beyond that, your model is quite deep and complex; in order to make sure it's working properly you might want to scale it back considerably, test it to see if it gives you reasonable results, and then add things back in stages. In any event, it seems like your model is much too complex for the problem. A model producing a label for each individual pixel should be pretty simple, since a given pixel's label probably only depends on nearby pixels, and probably not in a very complex way.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82335828
answers question: http://stackoverflow.com/q/47638633

http://stackoverflow.com/comment/82342917
comment on: http://stackoverflow.com/a/47688771
type: Comment
type: AnswerComment
has text: Sorry but remote debugging is getting complicated, i don't think i can help you from here on, but poking around you should find my thread useful. Good Luck.
score: 0

http://stackoverflow.com/a/47684352
has comment: http://stackoverflow.com/comment/82328506
has comment: http://stackoverflow.com/comment/82328645
has comment: http://stackoverflow.com/comment/82328509
type: Answer
has comment: http://stackoverflow.com/comment/82329253
has comment: http://stackoverflow.com/comment/82328594
score: 0
has comment: http://stackoverflow.com/comment/82329278
has comment: http://stackoverflow.com/comment/82328547
has body: You can use dictionary comprehension to iterate over s, which now contains the length of its original elements: s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary'] final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)} Output: {1: 2, 6: 2, 8: 1, 2: 1, 10: 1} Simply: new_d = {} for i in s: new_d[len(i)] = 0 for i in s: new_d[len(i)] += 1 Output: {8: 1, 1: 2, 2: 1, 10: 1, 6: 2}
answers question: http://stackoverflow.com/q/47684302

http://stackoverflow.com/q/47545052
has comment: http://stackoverflow.com/comment/82047115
answer count: 2
linked to: http://stackoverflow.com/q/40690854
has comment: http://stackoverflow.com/comment/82047233
linked to: http://stackoverflow.com/q/11144513
has comment: http://stackoverflow.com/comment/82047319
tagged with: set
has comment: http://stackoverflow.com/comment/82047174
downvote count: 1
has comment: http://stackoverflow.com/comment/82047165
has comment: http://stackoverflow.com/comment/82047348
has answer: http://stackoverflow.com/a/47545241
favorite count: 0
type: Question
has body: I have this dataset: import pandas as pd import itertools A = ['A','B','C'] M = ['1','2','3'] F = ['plus','minus','square'] df = pd.DataFrame(list(itertools.product(A,M,F)), columns=['A','M','F']) print(df) The example output is like this: A M F 0 A 1 plus 1 A 1 minus 2 A 1 square 3 A 2 plus 4 A 2 minus 5 A 2 square I want to pairwise comparison (jaccard similarity) of each row from this data frame, for example, comparing A 1 plus and A 2 square and get the similarity value between those both set. I have wrote a jaccard function: def jaccard(a, b): c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) Which is only work on set because I used intersection I want the output like this (this expected result value is just random number): 0 1 2 3 45 0 1.00 0.43 0.61 0.55 0.46 1 0.43 1.00 0.52 0.56 0.49 2 0.61 0.52 1.00 0.48 0.53 3 0.55 0.56 0.48 1.00 0.49 45 0.46 0.49 0.53 0.49 1.00 What is the best way to get the result of pairwise metrics? Thank you,
score: 5
tagged with: pandas
has comment: http://stackoverflow.com/comment/82047346
tagged with: similarity
has answer: http://stackoverflow.com/a/47545491
possible better answer: http://stackoverflow.com/a/47545491
upvote count: 6
tagged with: dataframe
tagged with: python
has title: Convert dataframe rows to Python set
accepted answer: http://stackoverflow.com/a/47545241
type: AnsweredQuestion

http://stackoverflow.com/comment/82072039
comment on: http://stackoverflow.com/q/47556992
type: Comment
type: QuestionComment
score: 0
has text: @killereks Moving is relatively simple. When you create an object an id is returned. If you want to move that object you'd write `canvas.coords(objectId,new_coords)`. It is well documented [here](http://effbot.org/tkinterbook/canvas.htm)

http://stackoverflow.com/a/47625730
answers question: http://stackoverflow.com/q/47625294
score: 1
type: Answer
has body: This code will split every 1000 lines, resetting when it hits a .: words = s.split() new_text = "" word_count = 0 for word in words: new_text += word + " " word_count += 1 if word_count == 1000 or "." in word: new_text += "\n" word_count = 0 Where s is the string read from the file. Simply write new_text to the file afterwards.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82203896
type: QuestionComment
comment on: http://stackoverflow.com/q/47622666
score: 0
has text: ohhh, then that might be the issue. I have django 2.0 and that's why I am getting this error.
type: Comment

http://stackoverflow.com/q/47627879
has title: Overlay video with custom graphics using Phonon & PyQt
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has body: I am building a eye-tracking data visualization tool using PyQt4 and Phonon module. Essentially, I have a video that a subject was watching while the subject's eye movements were tracked. The eye tracking data is in the form of x,y coordinates. I want to be able to play the video of interest and overlay that video with circles indicating where the subject was looking at. Does anyone have any idea? According to this link: Play a video with custom overlay graphics there seems to be a way by placing Phonon.VideoWidget inside a QGraphicsProxyWidget but I am unsure of a method to implement the suggestion. Any help would be greatly appreciated! I am also interested to know if there are ways to achieve my desired functionaility using pyqtgraph.
tagged with: qt
type: AnsweredQuestion
tagged with: phonon
score: 1
accepted answer: http://stackoverflow.com/a/47629016
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/82215571
tagged with: python
has answer: http://stackoverflow.com/a/47629016
type: Question
linked to: http://stackoverflow.com/q/4473709
tagged with: pyqt

http://stackoverflow.com/comment/82195006
has text: Thanks for the suggestion. After testing this out it seems to me that this isn't working, seemingly because the os.system commands do not recognise the {} as an input variable... For example when I ran the command import.os Obsid = input('please enter a 5 digit observation ID: ') print(Obsid) os.system("donwload_chandra_obsid {}").format(Obsid)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47618096
type: AnswerComment

http://stackoverflow.com/a/47656562
answers question: http://stackoverflow.com/q/47656361
score: 0
has body: All non-empty strings are (unfortunately) True in Python. That means that this will always be True: if something or "string": Because or "string" will always be True.
type: Answer
has comment: http://stackoverflow.com/comment/82271256

http://stackoverflow.com/comment/82131520
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47586996
has text: Sample of acutal dataframe would be really helpful. Since you are saying `gdp > shift1` we need to see `gdp` and `shift 1` and `shift2` .

http://stackoverflow.com/q/47620820
answer count: 0
downvote count: 0
favorite count: 0
type: Question
upvote count: 4
tagged with: serialization
has comment: http://stackoverflow.com/comment/82201892
tagged with: rest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82200686
tagged with: django
has body: How to make Django serializer to serialize nested objects as json instead of ordereddict? class SummaryGroupContract: class Serializer(serializers.Serializer): total = serializers.DecimalField(max_digits = 10, decimal_places = 2) def __init__(self, total: Decimal): self.total = total class SummaryResponse: class Serializer(serializers.Serializer): income = SummaryGroupContract.Serializer(required=False) expenses = SummaryGroupContract.Serializer(required=False) def __init__(self, income: SummaryGroupContract, expenses: SummaryGroupContract): self.income = income; self.expenses = expenses; class SummaryViewSet(viewsets.ViewSet): def list(self, request): income = SummaryGroupContract(10.0) expenses = SummaryGroupContract(-90.0) return Response(SummaryResponse.Serializer(SummaryResponse(income, expenses)).data) returns {'income': OrderedDict([('total', '10.00')]), 'expenses': OrderedDict([('total', '-90.00')])} expected {'income': {'total': '10.00'}, 'expenses': {'total': '-90.00'}} EDIT: !!!! I have resolved my issue and now everything works fine. Problem was that in my test I was inspecting response.data, which is not fully rendered response response = self.client.get("/api/summary", format="json") print(response.data) instead I switched to response.content and now I get proper json (I also mistaken python object with json response).
tagged with: python
score: 4
has title: Django rest serializer nested objects serialized as OrderedDict instead of pure JSON

http://stackoverflow.com/comment/82069406
comment on: http://stackoverflow.com/q/47555934
type: Comment
type: QuestionComment
score: 0
has text: You have to define `async def func()` again in class `Bar`. `@abc.abstractmethod` does not take in considerate if `func()` is async or not.

http://stackoverflow.com/a/47618776
answers question: http://stackoverflow.com/q/47618336
has body: The answer by GarfieldCat is good for its use case, but doesn't directly address your request of having the stock name as the CSV file name. It's just the ticker name. What you can do is define a dictionary key-value data structure to hold the company name as well as the stock name. For example, adapt your existing list to something like: stocks = [ { 'ticker': 'aapl', 'company: 'Apple' }, { 'ticker: 'goog', 'company: 'Google' }, ... ... ] Then use the code from GarfieldCat, just adapted to extract data from the dict: for item in stocks: url = 'https://finance.google.com/finance/historical?q={}&amp;output=csv'.format(item.get('ticker')) req = requests.get(url) with open('{}.csv'.format(item.get('company')), 'wb') as f: f.write(req.text) If you continue to have questions about this, I would suggest you look in to the request library documentation for how to get data from a request, and then read about Python writing to files.
has comment: http://stackoverflow.com/comment/82197296
has comment: http://stackoverflow.com/comment/82197149
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82197536
has comment: http://stackoverflow.com/comment/82197524

http://stackoverflow.com/a/47552249
has body: The problem was in indentation, i used tabs and quad spaces together, this caused problems which made it so that python couldn't identify the code.
has comment: http://stackoverflow.com/comment/82061749
type: Answer
has comment: http://stackoverflow.com/comment/82061257
score: 0
answers question: http://stackoverflow.com/q/47551392

http://stackoverflow.com/comment/82226552
type: Comment
type: QuestionComment
has text: Thanks for the info. I am not concerned about the indentation, but rather about encapsulation and the proper interface between the extracted function and its scope. Am I misunderstanding the term "inner function"? I think of it as a nested subfunction, i.e., a function inside a function. Note the different signature of b) vs. c).
comment on: http://stackoverflow.com/q/47633807
score: 0

http://stackoverflow.com/a/47680683
answers question: http://stackoverflow.com/q/47679834
upvote count: 1
downvote count: 0
has body: So I'm not exactly sure what you're trying to do here since you posted mostly pseudo code but you definitely don't want to use a while loop. A while loop there will lock your program if the first line happens to match the string you're looking for forever (unless you're running multi-threaded but you don't seem to be). I also think you're using the wrong conditional operator there but as I said, not 100% sure what you're going for here. This is what I think you're going to need: import json row_counter = 0 start_now = 0 with open('file.json') as f: for row in f: row_counter += 1 if row_counter &gt; start_now: try: # check to ensure we're not messing with a blank row if not row: continue # load the row. This line might throw an exception if the # line isn't perfect json row = json.loads(row) print(row) comment_id = row['id'] if(comment_id == 'The_String_I_Wanna_Match'): print('Execute code here') except Exception as e: import traceback print(traceback.print_exc()) if (row_counter % 100000 == 0): print('no. of rows gone by {}'.format(row_counter))
score: 1
type: Answer

http://stackoverflow.com/a/47697839
has comment: http://stackoverflow.com/comment/82358224
score: 4
has comment: http://stackoverflow.com/comment/82356374
accepted answer of: http://stackoverflow.com/q/47697775
has comment: http://stackoverflow.com/comment/82360641
answers question: http://stackoverflow.com/q/47697775
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/82357004
has body: You can use itertools.permutations: import itertools input = [3, 8, 2] final_list = ["{}-{}".format(*i) for i in itertools.permutations(input, 2)] Output: ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8'] However, if you want all operations up-to and including the length of the list, you can try this: final_list = list(itertools.chain(*[['-'.join(["{}"]*b).format(*i) for i in itertools.permutations(input, b)] for b in range(2, len(input)+1)])) Output: ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8', '3-8-2', '3-2-8', '8-3-2', '8-2-3', '2-3-8', '2-8-3'] Edit: for all possible operands: import re def tokenize(s): converter = {"-":lambda x, y:x-y, '+':lambda x, y:x+y} total = 0 stack = re.findall('\d+|[\-\+]', s) operator = None for i in stack: if i.isdigit(): if not operator: total += int(i) else: total = converter[operator](total, int(i)) operator = None else: operator = i return total new_list = set(list(itertools.chain(*list(itertools.chain(*[[[''.join([''.join('{}'+i) for i in b]+['{}']).format(*c) for b in itertools.permutations(['-', '+'], len(c)-1)] for c in itertools.permutations(input, x)] for x in range(2, len(input)+1)]))))) final_list = {tokenize(a):a for a in new_list} new_final_list = [b for a, b in final_list.items()] Output: ['3-2', '8-3', '8-2', '8-3+2', '8-2+3', '8+2', '8+3', '2-8', '3-8', '3+2-8', '2-3']
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82356528

http://stackoverflow.com/q/47557947
has comment: http://stackoverflow.com/comment/84427457
has comment: http://stackoverflow.com/comment/82075720
upvote count: 2
has comment: http://stackoverflow.com/comment/82075799
has comment: http://stackoverflow.com/comment/82075255
has title: Slow Django Model Formset Rendering
downvote count: 0
has comment: http://stackoverflow.com/comment/82073995
tagged with: django-debug-toolbar
has comment: http://stackoverflow.com/comment/82073841
favorite count: 0
has comment: http://stackoverflow.com/comment/82076009
has comment: http://stackoverflow.com/comment/82074612
type: Question
has comment: http://stackoverflow.com/comment/84427692
has comment: http://stackoverflow.com/comment/82074064
has comment: http://stackoverflow.com/comment/82074209
has comment: http://stackoverflow.com/comment/82084576
has comment: http://stackoverflow.com/comment/82074305
has comment: http://stackoverflow.com/comment/82076484
linked to: http://stackoverflow.com/q/47559245
type: UnansweredQuestion
tagged with: inline-formset
has comment: http://stackoverflow.com/comment/82084652
tagged with: http://stackoverflow.com/tag/html
has body: I have a Django Model Formset that is rendered with a crispy-forms in a custom table inline formset template. The formset is a list of alerts with entities, logic, and comments. Entity and logic are populated in each form, and the user writes a comment prior to submitting the form. The formset currently has 140 forms (i.e. 140 records in the Alert model), and it will need to handle more than that number. It takes 4-5 minutes for alerts.html to render. I can use Django-based pagination to limit the queryset and reduce rendering time, but this precludes me from using something like jQuery datatables to paginate and quickly add JS functionality. I used django-debug-toolbar to review. The queries are definitely funky and duplicated per form (i.e. the query grabbing entity information is duplicated for each form and also includes duplicate where statements). However, it only takes 3-4 seconds for the queries to run, so the problem must be elsewhere. I used Chrom dev tools to record the performance, and the Waiting (TTFB) time is the cause of the performance issue. I understand that this involves server-side processing, which leads me to believe it is a Django issue. Why is the render taking so long? Is there anything in my code below that could be optimized? I know caching is an option, but I believe this mostly affects query performance which doesn't appear to be the driving issue. Is there any other piece of django-debug-toolbar that might shed more light on timing, outside of just the queries? EDIT: Based on the comments, I determined the include tags in the table_inline_formset.html template are causing the issue because they are rendering hundreds of the same templates. I created another question here to address this problem: Crispy-Forms Include Tag Causing Many Duplicate Templates. models.py: class Logic(models.Model): logic = models.CharField(max_length=50) def __str__(self): return self.logic class Entity(models.Model): entity = models.CharField(primary_key=True…
has comment: http://stackoverflow.com/comment/82074157
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82074210
has comment: http://stackoverflow.com/comment/82076403
score: 2
has comment: http://stackoverflow.com/comment/82073706
answer count: 0

http://stackoverflow.com/comment/82073172
score: 0
type: Comment
has text: Thanks ! But it tells me: 'DataFrame' object has no attribute 'text' ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47557782

http://stackoverflow.com/q/47556726
has comment: http://stackoverflow.com/comment/82073771
tagged with: eigen
tagged with: tensor
accepted answer: http://stackoverflow.com/a/47558349
has comment: http://stackoverflow.com/comment/82071156
tagged with: python
tagged with: c++
type: AnsweredQuestion
score: 1
has title: What causes different results by interchanging the tensors in an Eigen::Tensor contraction?
downvote count: 0
answer count: 1
tagged with: numpy-einsum
has answer: http://stackoverflow.com/a/47558349
upvote count: 1
has body: I am working on a C++ library that relies on tensor contractions. I won't post the full application here, but I've distilled it down to the following. We define a toy rank-4 tensor, which is nothing but (0, 1, ..., 15) reshaped: Eigen::Tensor&lt;double, 4&gt; T (2, 2, 2, 2); for (size_t i = 0; i &lt; 2; i++) { for (size_t j = 0; j &lt; 2; j++) { for (size_t k = 0; k &lt; 2; k++) { for (size_t l = 0; l &lt; 2; l++) { T(i, j, k, l) = l + 2 * k + 4 * j + 8 * i; } } } } and a rank-2 tensor to contract with, which is nothing but (1, 2, 3, 4) reshaped: Eigen::Tensor&lt;double, 2&gt; A (2, 2); for (size_t i = 0; i &lt; 2; i++) { for (size_t j = 0; j &lt; 2; j++) { A(i, j) = 1 + j + 2 * i; } } To contract two tensors in Eigen, we have to specify a contraction pair. Our goal is to contract the first two indices of the tensors, as in T(ijkl)*A(ib)=M(bjkl). With my current understanding of the Tensor module in Eigen, we will write the contraction pair as Eigen::array&lt;Eigen::IndexPair&lt;int&gt;, 1&gt; contraction_pair = {Eigen::IndexPair&lt;int&gt;(0, 0)}; However, I think it should be possible to use the exact same contraction pair to perform the contraction A(ib)*T(ijkl)=N(bjkl). Unfortunately, this is not the case, and the elements of M are 0 0 0 0 24 0 0 0 1 32 0 0 1 0 28 0 0 1 1 38 0 1 0 0 32 0 1 0 1 44 0 1 1 0 36 0 1 1 1 50 1 0 0 0 40 1 0 0 1 56 1 0 1 0 44 1 0 1 1 62 1 1 0 0 48 1 1 0 1 68 1 1 1 0 52 1 1 1 1 74 while these of N are 0 0 0 0 24 0 0 0 1 28 0 0 1 0 32 0 0 1 1 36 0 1 0 0 40 0 1 0 1 44 0 1 1 0 48 0 1 1 1 52 1 0 0 0 32 1 0 0 1 38 1 0 1 0 44 1 0 1 1 50 1 1 0 0 56 1 1 0 1 62 1 1 1 0 68 1 1 1 1 74 I have tested the same toy tensors in numpy, using einsum: T = np.arange(16).reshape(2, 2, 2, 2) A = np.arange(1, 5).reshape(2, 2) contraction1 = np.einsum('ijkl,ia-&gt;ajkl', integrals, C) contraction2 = np.einsum('ia,ijkl-&gt;ajkl', C, integrals) and both contraction1 and contraction2 are 0 0 0 0 24 0 0 0 1 28 0 0 1 0 32 0 0 1 1 36 0 1 0 0 40 0 1 0 1 44 0 1 1 0 48 0 …
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82073667

flask
tags question: http://stackoverflow.com/q/47672410
tags question: http://stackoverflow.com/q/47599341
tags question: http://stackoverflow.com/q/47551818
tags question: http://stackoverflow.com/q/47614548
tags question: http://stackoverflow.com/q/47675691
tags question: http://stackoverflow.com/q/47617346
tags question: http://stackoverflow.com/q/47569162
tags question: http://stackoverflow.com/q/47679434
tags question: http://stackoverflow.com/q/47650768
tags question: http://stackoverflow.com/q/47558827
tags question: http://stackoverflow.com/q/47581053
tags question: http://stackoverflow.com/q/47606587
tags question: http://stackoverflow.com/q/47615741
tags question: http://stackoverflow.com/q/47584412
tags question: http://stackoverflow.com/q/47651811
tags question: http://stackoverflow.com/q/47694736
tags question: http://stackoverflow.com/q/47691262
tags question: http://stackoverflow.com/q/47610682
tags question: http://stackoverflow.com/q/47571786
tags question: http://stackoverflow.com/q/47602205
tags question: http://stackoverflow.com/q/47680369
tags question: http://stackoverflow.com/q/47670785
tags question: http://stackoverflow.com/q/47661591
tags question: http://stackoverflow.com/q/47593452
tags question: http://stackoverflow.com/q/47588402
tags question: http://stackoverflow.com/q/47602842
tags question: http://stackoverflow.com/q/47618885
tags question: http://stackoverflow.com/q/47544955
tags question: http://stackoverflow.com/q/47599637
tags question: http://stackoverflow.com/q/47561124
tags question: http://stackoverflow.com/q/47603264
tags question: http://stackoverflow.com/q/47616694
tags question: http://stackoverflow.com/q/47568565
tags question: http://stackoverflow.com/q/47621904
tags question: http://stackoverflow.com/q/47682966
tags question: http://stackoverflow.com/q/47684182
tags question: http://stackoverflow.com/q/47641127
tags question: http://stackoverflow.com/q/47543099
tags question: http://stackoverflow.com/q/47602356
tags question: http://stackoverflow.com/q/47560489
tags question: http://stackoverflow.com/q/47678353
tags question: http://stackoverflow.com/q/47611844
tags question: http://stackoverflow.com/q/47627035
tags question: http://stackoverflow.com/q/47594571
tags question: http://stackoverflow.com/q/47674583
tags question: http://stackoverflow.com/q/47668829
tags question: http://stackoverflow.com/q/47593195
tags question: http://stackoverflow.com/q/47597407
tags question: http://stackoverflow.com/q/47683839
tags question: http://stackoverflow.com/q/47668766
tags question: http://stackoverflow.com/q/47620829
tags question: http://stackoverflow.com/q/47656071
tags question: http://stackoverflow.com/q/47620190
tags question: http://stackoverflow.com/q/47608212
tags question: http://stackoverflow.com/q/47614844
tags question: http://stackoverflow.com/q/47627918
tags question: http://stackoverflow.com/q/47618532
tags question: http://stackoverflow.com/q/47670349
tags question: http://stackoverflow.com/q/47624686
tag name: flask
tags question: http://stackoverflow.com/q/47573733
tags question: http://stackoverflow.com/q/47575665
tags question: http://stackoverflow.com/q/47658559
tags question: http://stackoverflow.com/q/47590906
tags question: http://stackoverflow.com/q/47544474
tags question: http://stackoverflow.com/q/47630517
tags question: http://stackoverflow.com/q/47608374
tags question: http://stackoverflow.com/q/47670382
tags question: http://stackoverflow.com/q/47651016
tags question: http://stackoverflow.com/q/47697465
tags question: http://stackoverflow.com/q/47632838
type: Tag
tags question: http://stackoverflow.com/q/47688964
tags question: http://stackoverflow.com/q/47543812
tags question: http://stackoverflow.com/q/47646624
tags question: http://stackoverflow.com/q/47570623
tags question: http://stackoverflow.com/q/47603699
tags question: http://stackoverflow.com/q/47585381
tags question: http://stackoverflow.com/q/47567263
tags question: http://stackoverflow.com/q/47611793

http://stackoverflow.com/comment/133135227
comment on: http://stackoverflow.com/a/47562412
type: Comment
score: 0
type: AnswerComment
has text: @DirkSchiller Interesting question. Since this kind of class is big to begin with, I don't think it came up often. There are twoish options - (1) Have the method defined in the class itself, not a separate module (i.e., __init__.py). Whether this makes sense depends on your design. (2) Use the explicit super instantiation, `super(type(MyObject), MyObject)`. (3) Have super method of the class, doing (1) but returning the super so you can use it in other modules.

http://stackoverflow.com/q/47654491
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82269468
has comment: http://stackoverflow.com/comment/82268081
tagged with: scipy
favorite count: 0
has title: scipy.optimize.minimize('Newton-CG') doesn't always return lowest objective function it finds
has comment: http://stackoverflow.com/comment/82267338
has body: Strange behavior in the Newton-CG minimization function with scipy: every time I make a call to the objective function calculation, I print out the value. I find that often, the minimizer finds a lower value than it ends up reporting in the end. Example output is shown below. "Iter" is the iteration number from the minimize function, while "call" is which time the minimizer called a calculation of the objective function "J". "dJ" is how much J changed from the previous call. "f" is an object class that contains all the calculations, including the callback function 'iternum': res=scipy.optimize.minimize(f.J,f.z,args=(F),tol=1.e-4,method='Newton-CG', \ jac=f.Jacobian,hessp=f.Hessian, callback=f.iternum) Iter 1 , call 30 J=3.73e+09 dJ=3.58e+09 Iter 1 , call 31 J=1.78e+09 dJ=-1.95e+09 Iter 1 , call 32 J=5.23e+08 dJ=-1.26e+09 Iter 1 , call 33 J=1.76e+08 dJ=-3.47e+08 Iter 1 , call 34 J=1.33e+08 dJ=-4.29e+07 Iter 1 , call 35 J=1.44e+08 dJ=1.14e+07 Iter 2 , call 36 J=1.42e+08 dJ=-1.85e+06 Iter 2 , call 37 J=1.42e+08 dJ=5.19e+04 res.fun = 1.42e+08 However, note that the lowest J value is actually 1.33e+08, so those parameters and that objective function value should have been returned. Anyone else experience this? Ideas?
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/82268128
type: Question
score: 2
downvote count: 2
answer count: 0
has comment: http://stackoverflow.com/comment/82268254

http://stackoverflow.com/q/47581181
tagged with: sqlalchemy
favorite count: 0
type: Question
answer count: 1
duplicate of: http://stackoverflow.com/q/9667138
tagged with: python
duplicate of: http://stackoverflow.com/q/6699360
upvote count: 4
has answer: http://stackoverflow.com/a/47581335
accepted answer: http://stackoverflow.com/a/47581335
type: AnsweredQuestion
has body: I have a model: class Announcements(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(150), nullable=False) text = db.Column(db.Text(), nullable=False) category = db.Column(db.Integer(), nullable=False) subcategory = db.Column(db.Integer(), nullable=False) offer_type = db.Column(db.Integer(), nullable=False) url = db.Column(db.String(150), nullable=True) status = db.Column(db.Integer(), nullable=False) def __repr__(self): return '&lt;Announcement %r&gt;' % self.name And public function: def update(id): // UPDATE HERE How to update note by passed id in function update() using Flask-SQLAlchemy? I dont see any examples of updating rows in documentation
downvote count: 3
has title: How to update row using Flask-SQLAlchemy?
score: 1

http://stackoverflow.com/comment/82194849
type: Comment
comment on: http://stackoverflow.com/a/47618249
score: 0
type: AnswerComment
has text: One question at a time ... but you can add an if clause to the comprehensions: `[x for y in lst if condition(x)]`

http://stackoverflow.com/a/47635289
has comment: http://stackoverflow.com/comment/82256396
type: Answer
answers question: http://stackoverflow.com/q/47635210
has comment: http://stackoverflow.com/comment/82231035
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47635210
has comment: http://stackoverflow.com/comment/82232199
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82255810
has body: I think you need for one attribute: def calc_slope(row): a = scipy.stats.linregress(row, y=axisvalues) return a.slope df["slope"]=df.apply(calc_slope,axis=1) print (df) A B C D slope 0 0.444640 0.024624 -0.016216 0.228935 -2.553465 1 1.226611 1.962481 1.103834 0.645562 -1.455239 2 -0.259415 0.971097 0.124538 -0.704115 -0.718621 3 1.938422 1.787310 -0.619745 -2.560187 -0.575519 4 -0.986231 -1.942930 2.677379 -1.813071 0.075679 5 0.611214 -0.258453 0.053452 1.223544 0.841865 6 0.685435 0.962880 -1.517077 -0.101108 -0.652503 7 0.368278 1.314202 0.748189 2.116189 1.350132 8 -0.322053 -1.135443 -0.161071 -1.836761 -0.987341 9 0.798461 0.461736 -0.665127 -0.247887 -1.610447 And for all atributes convert named tuple to dict and then to Series. Output is new DataFrame, so if is necessaryjoin to original: np.random.seed(1997) df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')) axisvalues=list(range(1,len(df.columns)+1)) def calc_slope(row): a = scipy.stats.linregress(row, y=axisvalues) return pd.Series(a._asdict()) print (df.apply(calc_slope,axis=1)) slope intercept rvalue pvalue stderr 0 -2.553465 2.935355 -0.419126 0.580874 3.911302 1 -1.455239 4.296670 -0.615324 0.384676 1.318236 2 -0.718621 2.523733 -0.395862 0.604138 1.178774 3 -0.575519 2.578530 -0.956682 0.043318 0.123843 4 0.075679 2.539066 0.127254 0.872746 0.417101 5 0.841865 2.156991 0.425333 0.574667 1.266674 6 -0.652503 2.504915 -0.561947 0.438053 0.679154 7 1.350132 0.965285 0.794704 0.205296 0.729193 8 -0.987341 1.647104 -0.593680 0.406320 0.946311 9 -1.610447 2.639780 -0.828856 0.171144 0.768641 df = df.join(df.apply(calc_slope,axis=1)) print (df) A B C D slope intercept rvalue \ 0 0.444640 0.024624 -0.016216 0.228935 -2.553465 2.935355 -0.419126 1 1.226611 1.962481 1.103834 0.645562 -1.455239 4.296670 -0.615324 2 -0.259415 0.971097 0.124538 -0.704115 -0.718621 2.523733 -0.395862 3 1.938422 1.787310 -0.619745 -2.560187 -0.575519 2.578530 -0.956682 4 -0.986231 -1.942930 2.677379 -1.813071 0.075679 …

http://stackoverflow.com/comment/82450072
type: QuestionComment
has text: i have found the pc name had been changed in zh-cn, i've modified it to en, then it works without error
score: 0
comment on: http://stackoverflow.com/q/47666109
type: Comment

http://stackoverflow.com/comment/82313078
score: 0
has text: @glibdud Would you please give me more details of fixing this problem?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47676852

http://stackoverflow.com/q/47582217
answer count: 1
score: 6
upvote count: 6
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47582253
accepted answer: http://stackoverflow.com/a/47582253
tagged with: python
duplicate of: http://stackoverflow.com/q/1538832
type: Question
linked to: http://stackoverflow.com/q/1538832
has body: First line once Python 2.7 interpreter is started on Windows: &gt;&gt;&gt; dir() ['__builtins__', '__doc__', '__name__', '__package__'] Having entered the dir() command, the special variable _ should be defined: &gt;&gt;&gt; _ ['__builtins__', '__doc__', '__name__', '__package__'] But, even after entering _, it does not show up when I attempt to list all names in the interactive namespace using dir(): &gt;&gt;&gt; dir() ['__builtins__', '__doc__', '__name__', '__package__'] How does the interpreter recognize this variable if it is not in the interpreter's namespace?
downvote count: 0
has title: Why doesn't the last command variable "_" appear in dir()?

http://stackoverflow.com/comment/82304052
has text: Seems to be, that access is denied. But how can that be, when I'm executing as admin?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47650886

http://stackoverflow.com/q/47683676
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/19937210
accepted answer: http://stackoverflow.com/a/47700079
type: Question
has answer: http://stackoverflow.com/a/47700079
has title: Automatically Add Layers to a Dictionary in Python
downvote count: 0
has body: I'm creating a program that uses a dictionary to store large trees of web links in Python. Basically, you start with the root URL, and that creates a dictionary based on the URLs found from the HTML of the root. In the next step, I want to get the pages of each of those URLs and grab the links on those URLs. Eventually, I want to have a dictionary with all the links in it and their relation to each other. This is what I have for the first two depths for link in soup.find_all('a'): url = link.get('href') url_tree[siteurl][url] #Get page source for link in soup.find_all('a'): url = link.get('href') url_tree[siteurl][secondurl][url] This system works, but as you can tell, if I want a dictionary N layers deep, that gets to be a lot of blocks of code. Is there a way to automatically add more layers? Any help is appreciated!
upvote count: 1
tagged with: python
tagged with: dictionary
answer count: 1
tagged with: tree
type: AnsweredQuestion

http://stackoverflow.com/comment/82328925
has text: @Goyo, I wasn't really sure how to add a csv to the question so I just pulled it from python.
type: Comment
comment on: http://stackoverflow.com/q/47684058
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82083797
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47562769
has text: @r0the not entirely, it's more so that I want all my programs I need to run to be able to access the same file without manually selecting it every single time, only when it updates. And for ease of use, I would like to not have to modify the code every time I need to access the file.
score: 0

http://stackoverflow.com/comment/82109381
score: 1
has text: You don't have to install `getpass`. That's part of the standard library.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47576217

http://stackoverflow.com/comment/82130203
has text: added error log too @asakryukin
score: 0
comment on: http://stackoverflow.com/q/47585817
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82240406
has text: @AmitTripathi I think he didn't produce it correctly in the question. Maybe he did do it properly on his editor since he got some output.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47640962

http://stackoverflow.com/comment/82184304
score: 0
comment on: http://stackoverflow.com/q/47613002
has text: Ok this makes me feel dumb hahah thanks you can post it in answers :) @zvone
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82344399
type: QuestionComment
has text: cany you elaoborate a bit i tried putting 'Anshuman Misra' in quotes before but it didnt work .I tried to work it externally on cmd it does show File till anshuman only @georgexsh
score: 0
comment on: http://stackoverflow.com/q/47686252
type: Comment

http://stackoverflow.com/a/47780274
accepted answer of: http://stackoverflow.com/q/47690548
has body: Use --add-binary to bundle the driver in the application: pyinstaller -F --add-binary "C:\drivers\chromedriver.exe";"." script.py and use sys._MEIPASS to get the folder where the driver is extracted: import sys, os, time from selenium import webdriver if __name__ == "__main__": if getattr(sys, 'frozen', False): # executed as a bundled exe, the driver is in the extracted folder chromedriver_path = os.path.join(sys._MEIPASS, "chromedriver.exe") driver = webdriver.Chrome(chromedriver_path) else: # executed as a simple script, the driver should be in `PATH` driver = webdriver.Chrome() driver.get("https://stackoverflow.com") time.sleep(5) driver.quit()
type: Answer
has comment: http://stackoverflow.com/comment/82521898
answers question: http://stackoverflow.com/q/47690548
upvote count: 14
has comment: http://stackoverflow.com/comment/82521944
has comment: http://stackoverflow.com/comment/82521845
type: AcceptedAnswer
downvote count: 0
score: 14

http://stackoverflow.com/q/47555539
has answer: http://stackoverflow.com/a/47557054
possible better answer: http://stackoverflow.com/a/47555693
answer count: 3
has comment: http://stackoverflow.com/comment/82068534
has title: Efficient way to convert numpy matrix into a nested dictionary
upvote count: 3
has comment: http://stackoverflow.com/comment/82068135
downvote count: 0
accepted answer: http://stackoverflow.com/a/47555701
favorite count: 0
has answer: http://stackoverflow.com/a/47555701
linked to: http://stackoverflow.com/q/46107169
type: Question
tagged with: numpy
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/47555693
has comment: http://stackoverflow.com/comment/82068091
has body: I have a NumPy2d array that is a symmetric matrix (square matrix where the numbers above the diagonal are the same as the number below the diagonal) Example input matrix: edgeMatrix = np.array([[0., 2., 9.], [2., 0., 1.], [9., 1., 0.]]) I am looking for a very efficient way to convert this large matrix into a nested dictionary where the first key is the row index of the matrix and the second dict key is the column index of the matrix. ex: Desired resulting nested dict format: edgeDict[0][0] = 0 edgeDict[0][1] = 2 edgeDict[0][2] = 9 edgeDict[1][0] = 2 edgeDict[1][1] = 0 edgeDict[1][2] = 1 edgeDict[2][0] = 9 edgeDict[2][1] = 1 edgeDict[2][2] = 0 I have tried using dict(enumerate(edgeMatrix.flatten(), 1)), but failed to figure out how to get the nested aspect of this working.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47624986
downvote count: 0
has comment: http://stackoverflow.com/comment/82207941
score: 3
has comment: http://stackoverflow.com/comment/82208103
answers question: http://stackoverflow.com/q/47624830
type: Answer
has body: The plot method of Matplotlib connects the (x, poly(x)) dots that you provide, in the order that you provide them. Your array x appears to be unsorted, which makes the plot go left and right many times. Sort it before plotting, for example: x = np.array([1,7,2,6,3,5,4]) y = np.array([1,3,2,4,3,5,4]) poly=np.poly1d(np.polyfit(x, y, 2)) plt.scatter(x,y) sorted = np.sort(x) plt.plot(sorted, poly(sorted)) plt.show() Usually this doesn't come up because one plots the fitted model not against the points (which can make a rough plot shown above) but against some finer linspace, which makes a smoother plot. Then sorting is not an issue. xx = np.linspace(x.min(), x.max(), 500) plt.plot(xx, poly(xx)) plt.show()
accepted answer of: http://stackoverflow.com/q/47624830
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/82314535
score: 2
type: AnswerComment
has text: nice , thanks a lot @Erik Šťastný ! But my reason is that I have a CPU-bound task , so I think I should use multiprocessing
type: Comment
comment on: http://stackoverflow.com/a/47650321

http://stackoverflow.com/comment/82125728
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47544532
has text: @Tony I made some edits to hopefully take your post off of "On Hold". If I offended you by doing this, I promise that wasn't my intention.

http://stackoverflow.com/comment/82315462
type: AnswerComment
comment on: http://stackoverflow.com/a/47677409
has text: Yes. Thank you so much.
type: Comment
score: 0

http://stackoverflow.com/comment/82337227
comment on: http://stackoverflow.com/q/47686252
has text: there is space in `working_directory`, you should either quote it, or construct cmd as a sequence.
type: Comment
type: QuestionComment
score: 0

multithreading
tags question: http://stackoverflow.com/q/47615105
tags question: http://stackoverflow.com/q/47687349
tags question: http://stackoverflow.com/q/47616963
tags question: http://stackoverflow.com/q/47658588
tags question: http://stackoverflow.com/q/47647065
tags question: http://stackoverflow.com/q/47654338
type: Tag
tags question: http://stackoverflow.com/q/47588182
tags question: http://stackoverflow.com/q/47621525
tags question: http://stackoverflow.com/q/47554560
tags question: http://stackoverflow.com/q/47610229
tags question: http://stackoverflow.com/q/47655075
tags question: http://stackoverflow.com/q/47600957
tags question: http://stackoverflow.com/q/47557340
tags question: http://stackoverflow.com/q/47607463
tags question: http://stackoverflow.com/q/47603644
tags question: http://stackoverflow.com/q/47562879
tags question: http://stackoverflow.com/q/47641181
tags question: http://stackoverflow.com/q/47562457
tags question: http://stackoverflow.com/q/47639137
tags question: http://stackoverflow.com/q/47634922
tags question: http://stackoverflow.com/q/47545223
tags question: http://stackoverflow.com/q/47568998
tags question: http://stackoverflow.com/q/47620303
tags question: http://stackoverflow.com/q/47585367
tags question: http://stackoverflow.com/q/47630517
tags question: http://stackoverflow.com/q/47653048
tags question: http://stackoverflow.com/q/47696010
tags question: http://stackoverflow.com/q/47664234
tags question: http://stackoverflow.com/q/47636699
tags question: http://stackoverflow.com/q/47665944
tags question: http://stackoverflow.com/q/47675124
tags question: http://stackoverflow.com/q/47547731
tags question: http://stackoverflow.com/q/47618385
tags question: http://stackoverflow.com/q/47556284
tags question: http://stackoverflow.com/q/47623219
tags question: http://stackoverflow.com/q/47615395
tags question: http://stackoverflow.com/q/47613460
tags question: http://stackoverflow.com/q/47653632
tags question: http://stackoverflow.com/q/47614548
tag name: multithreading
tags question: http://stackoverflow.com/q/47563556
tags question: http://stackoverflow.com/q/47566763
tags question: http://stackoverflow.com/q/47553415
tags question: http://stackoverflow.com/q/47578486
tags question: http://stackoverflow.com/q/47650768
tags question: http://stackoverflow.com/q/47588655
tags question: http://stackoverflow.com/q/47692566
tags question: http://stackoverflow.com/q/47565315
tags question: http://stackoverflow.com/q/47654665

http://stackoverflow.com/comment/82255134
has text: The best selenium guru I've ever come across in my entire life @ sir Andersson. Although I didn't execute your script I'm sure it will lead me to the right direction. I've two questions on this: 1. why my select option failed? 2. As the first page (when opened) takes a lot of time to display it's content, sometimes browser fails to move on. Any idea for that, i meant, should I increase the waiting time or something? Very grateful to you sir and once again thanks a lot.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47648273

http://stackoverflow.com/comment/82119064
comment on: http://stackoverflow.com/q/47580772
type: Comment
type: QuestionComment
has text: I'm running 2.7.13 too
score: 0

http://stackoverflow.com/q/47632891
tagged with: pip
has answer: http://stackoverflow.com/a/57552298
linked to: http://stackoverflow.com/q/8548030
has answer: http://stackoverflow.com/a/47633060
has comment: http://stackoverflow.com/comment/82223405
has answer: http://stackoverflow.com/a/58314210
has title: pip install returning invalid syntax
has body: I've just installed python 3.6 which comes with pip However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word. Typing 'python' returns the version, which means it is installed correctly. What could be the problem?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47635832
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82223721
has comment: http://stackoverflow.com/comment/82223477
has answer: http://stackoverflow.com/a/47633144
duplicate of: http://stackoverflow.com/q/8548030
has answer: http://stackoverflow.com/a/66718207
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47632918
score: 26
has answer: http://stackoverflow.com/a/47633215
has answer: http://stackoverflow.com/a/50752448
has comment: http://stackoverflow.com/comment/82223582
has answer: http://stackoverflow.com/a/69875607
has answer: http://stackoverflow.com/a/73992937
has comment: http://stackoverflow.com/comment/82223389
answer count: 18
tagged with: python
upvote count: 26
has answer: http://stackoverflow.com/a/51194147
has answer: http://stackoverflow.com/a/55854110
has comment: http://stackoverflow.com/comment/82223623
has answer: http://stackoverflow.com/a/61982911
downvote count: 0
has answer: http://stackoverflow.com/a/62507390
has answer: http://stackoverflow.com/a/62642631
has answer: http://stackoverflow.com/a/67148250
has answer: http://stackoverflow.com/a/56846027

http://stackoverflow.com/comment/82256695
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47648852
has text: Of course I tested it. Just check your linked example - it does have the same problem (now the empty group is group 2 instead of group 4, but it's there just as well).
type: Comment

http://stackoverflow.com/comment/82151578
type: AnswerComment
comment on: http://stackoverflow.com/a/47596008
score: 0
type: Comment
has text: Can you show me also how to order them ? They are being saved "wildly".

http://stackoverflow.com/comment/82277932
comment on: http://stackoverflow.com/q/47659558
type: QuestionComment
score: 0
has text: `Permission denied` means you don't have enough privileges to access some path on your computer. What do you do in such cases? Try to obtain higher privileges. How do you do that? You can either log in as root (which may be dangerous _AF_ if you aren't experienced enough) or just _use `sudo`_.
type: Comment

http://stackoverflow.com/comment/82328895
score: 0
has text: Ok, my fault. Thanks again.
type: Comment
comment on: http://stackoverflow.com/a/47684350
type: AnswerComment

http://stackoverflow.com/a/47620341
downvote count: 0
score: 1
upvote count: 1
has body: You should go with loop.It will work definitely.This is tested code. element = 'noodles' for i in dict1.values(): if(element in i): print(True) count+=1 print(count) Count will count the number of occurrence of your element.If it is 0 then element is not available in dictionary's values and if it is more than 0 then it is available in dictionary's values.Count is just for your reference.
type: Answer
answers question: http://stackoverflow.com/q/47619946

http://stackoverflow.com/q/47657349
answer count: 2
possible better answer: http://stackoverflow.com/a/79322929
upvote count: 2
has comment: http://stackoverflow.com/comment/82273261
has comment: http://stackoverflow.com/comment/82273820
has answer: http://stackoverflow.com/a/79322929
has comment: http://stackoverflow.com/comment/82274016
downvote count: 0
tagged with: clang
accepted answer: http://stackoverflow.com/a/47660925
has comment: http://stackoverflow.com/comment/82273919
favorite count: 0
type: Question
tagged with: macos-high-sierra
has answer: http://stackoverflow.com/a/47660925
has comment: http://stackoverflow.com/comment/82280843
has body: I am running pip install scrypt==0.8.0. I get the following error: error: command '/usr/bin/clang' failed with exit status 1. I have xcode-select, gcc etc. installed. when i try to cd into that folder it doesn't exist and running clang --version it gives me: Apple LLVM version 9.0.0 (clang-900.0.38) Target: x86_64-apple-darwin17.2.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin full error: https://pastebin.com/JZW1jRCy
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82273638
type: AnsweredQuestion
score: 2
has title: clang fails with pip install on macos

http://stackoverflow.com/comment/82105847
type: QuestionComment
comment on: http://stackoverflow.com/q/47574518
has text: What does `0` represent? You might just want `(month_int - 1) % 12`. Add `1` again if you want to go back to 1-based numbers. I.e. `(month_int - 1) % 12 + 1`.
score: 1
type: Comment

http://stackoverflow.com/q/47665285
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: ldap
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/47665323
has body: If I already have an LDAP DN, how do I get the attributes for that DN with ldap3.Connection.search()? There is no other search criteria, I already have the DN... I tried searching for dn attribute, but it returned no objects found. I also tried forcing search_filter to '', '()' or None and they all returned malformed filter string. I also couldn't find a way to do this with the abstract Reader... In ldapsearch you don't need to specify a search filter if you are doing a baseDN lookup... import ldap3 ldap_conn = ldap3.Connection('ldapserver', raise_exceptions=True, auto_bind=True, user='me', password='mypassword') my_dn = "attrib1=blahblah, ou=org1, dc=dc1, dc=dcroot" ldap_conn.search( search_base=my_dn, search_filter= '(????)', # required search_scope=ldap3.BASE, attributes='*' ) print(ldap_conn.response)
has title: how to read attributes for given DN in ldap3 (how to search with ldap3 if no filter)
has answer: http://stackoverflow.com/a/47665323
upvote count: 4
type: AnsweredQuestion
tagged with: ldap3

http://stackoverflow.com/a/47688954
type: Answer
has body: From your comments, i am assuming you need to calculate a short distance less than 50 miles, The easiest less accurate method would be to coordinate point distance formula, `aka, pythagorean distance formula where a,b is obviously the latitude, longitude pair. Now one degree of latitude = 68~69miles or 111km. Remember this is just an approximation. Just multiply the result of the equation with the latitude miles. This gives a rather crude filter when coming to short distance, i use this to filter by distance when i need to make to make to many calculations, using google api to show results can be rather expensive(time, bandwidth, quota wise) considering my application needs to filter about 100 results per search. Also i suggest to add in a 20~30% variation to include actual road distance. Ok. If your still reading this then you need more accurate result. Then use this, remember to convert this code to python format. I just used the javascript code with me. function getDistanceLatLong(lat1,Long1,lat2,Long2) { var RK = 6371; // Radius of the earth in km var RM = 3959; var dLat = deg2rad(lat2-lat1); // deg2rad below var dLong = deg2rad(Long2-Long1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLong/2) * Math.sin(dLong/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = RK * c; // Distance in kiloMeters choose this or var d = RM * c; // Distance in Miles return d; } function deg2rad(deg) { return deg * (Math.PI/180) }
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47688277
upvote count: 2
answers question: http://stackoverflow.com/q/47688277
downvote count: 0

http://stackoverflow.com/comment/82201157
type: QuestionComment
has text: oh : `sample.count(C1)` counts `c` as a word
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47621607

http://stackoverflow.com/q/47679326
has comment: http://stackoverflow.com/comment/82318080
type: Question
has comment: http://stackoverflow.com/comment/82318011
has answer: http://stackoverflow.com/a/47680891
score: 0
tagged with: filter
has title: How to filter a dataframe by multiple columns and add a value
tagged with: pandas
has comment: http://stackoverflow.com/comment/82320593
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47679799
has comment: http://stackoverflow.com/comment/82328481
answer count: 2
has body: df = mdb.read_table(mdbfile, "table") invoices = pd.read_csv(file, delimiter=';') lst = df[(df['El4'] == el4)] #contains specific rows of df for i, row in lst.iterrows(): prop = row['propertyid'] mouvement = (row['Mouvements']*-1) a = invoices[(invoices['propertyReference'] == prop) &amp; (invoices.invoiceGrossAmount == mouvement)] invoiceid = a['invoiceId'].values mouvement = (mouvement*-1) if df[(df.propertyid == prop) &amp; (df.Mouvements == mouvement)]: df['id'] = invoiceid I receive the following error: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I would like to fill in specific values (invoiceId) in the rows of the dataframe where propertyid equals prop and mouvements equals mouvement.
has comment: http://stackoverflow.com/comment/82318167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82318520

http://stackoverflow.com/comment/82193221
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47617506
type: QuestionComment
has text: Please ensure that you are using the correct indentation for your script. For example, the indentation on the conditional inside the loop is not consistent between the `if` and `else` branches.

http://stackoverflow.com/comment/113057063
has text: WARNING: The errors disappear but that is because it doesn't find the definition `testenv` any more. Renaming `testenv` to `env` is NOT the way to go! Your tests just won't be executed from that point onwards.
type: Comment
comment on: http://stackoverflow.com/a/58508301
type: AnswerComment
score: 4

http://stackoverflow.com/comment/82296510
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47651869
has text: The proposed answer solved the issue on my side. Given your comments above stating that my code works for you, might depend on configuration

http://stackoverflow.com/a/47650893
answers question: http://stackoverflow.com/q/47650542
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: It's because zip returns an iterator and you can iterate over it only once. You can make a list of the zip and use that instead. shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47650542

http://stackoverflow.com/comment/82283461
comment on: http://stackoverflow.com/a/47661478
score: 0
type: AnswerComment
type: Comment
has text: regarding the MCVE. I wasn't sure if the number of colours or the way I specified the colours could've been responsible for this behaviour so I included everything. ps. python 2.7.14 matplotlib 2.1.0, numpy 1.13.3 all from pip on win10.

http://stackoverflow.com/a/47553775
accepted answer of: http://stackoverflow.com/q/47553613
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47553613
has body: You can install tensorflow with conda for Python 3.6: conda install -c conda-forge tensorflow Currently, this will give you version 1.3.0.
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/82244443
type: Comment
has text: Great. Now I just need to make sure the Totals column is included in the final result!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47642734

http://stackoverflow.com/comment/82338303
comment on: http://stackoverflow.com/q/47689566
type: Comment
type: QuestionComment
score: 2
has text: Could you show an exmaple using array of what you want to achieve by editing the question.

http://stackoverflow.com/comment/82061257
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47552249
has text: That _is_ weird. Python 3 should throw an error if you mix tabs and spaces. OTOH, if you're using Python 2, then there are a few things you ought to change in your code. But it'd be better to migrate to Python 3.

http://stackoverflow.com/q/47625126
has comment: http://stackoverflow.com/comment/82208262
has title: Printing out list with proper if conditions in python
has answer: http://stackoverflow.com/a/47625168
accepted answer: http://stackoverflow.com/a/47625168
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82208199
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
tagged with: list
tagged with: printing
has answer: http://stackoverflow.com/a/47625395
possible better answer: http://stackoverflow.com/a/47625395
answer count: 2
downvote count: 1
favorite count: 0
type: Question
has body: k1 = ['UCF', 'Mario', 'JonnnyStorm'] k2 = [10, 14, 5] k3 = [300, 700, 600] for p,g,h in zip(k1,k2,k3): if k2 &gt; 10 and k3 &gt; 400: print p,g,h What I want to see is Output: Mario 14 700 What i get is Output: UCF 10 300 Mario 14 700 JonnnyStorm 5 600 Even when I switch and play with the conditions, I still get totally wrong answers I do not expect. I must be missing something Vital. Also if I could print it out as Mario has 14 Points and is at Rank 700. That would be great. I tried that to with %s and %d with the normal print syntax and was getting wild errors. If anyone could not only get me an answer but a detailed explanation of what your doing that would be great. I really want to understand why.
tagged with: if-statement

http://stackoverflow.com/comment/82290518
comment on: http://stackoverflow.com/q/47665631
score: 0
type: Comment
type: QuestionComment
has text: you should use `or` - now it works like `and`

http://stackoverflow.com/q/47641949
tagged with: file
tagged with: pickle
has comment: http://stackoverflow.com/comment/82244154
has comment: http://stackoverflow.com/comment/82242368
has comment: http://stackoverflow.com/comment/82242428
has comment: http://stackoverflow.com/comment/82242450
tagged with: file-io
score: 1
downvote count: 1
has title: Pickle object with very different size in disk compared to size in memory
tagged with: python
has comment: http://stackoverflow.com/comment/82242550
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82242582
answer count: 0
type: UnansweredQuestion
has body: Problem Description: I am having performance issues with a piece of code that I am writing, and I noticed a very weird behavior of pickle that might have something to do with it. I am saving a really simple dict to disk using pickle to retrieve it later. This dictionary is created through a lot of iterations. And it looks like this: {'start_date': Timestamp('2007-09-07 05:42:00'), 'timeFunction': &lt;bound method Extremist.get_hour of &lt;observer.extremist.Extremist object at 0x000001FADD41EC88&gt;&gt;, 'timeReference': None, 'min': None, 'max': None} The saved file has 5.863kb on disk, which is completely absurd as it is a really simple dictionary, when I load it and use the sys.getsizeof() method to check the size of the object I loaded with pickle (which has 5.863kb on disk) it shows me a value of 240 (bytes), which is inline with the amount of data the object holds. The pickle object seems to grow in size according to the number of iterations my code does. I saw some of these pickle objects with more than 10mb after a larger number of iterations. Code that saves the dictionary try: os.remove('data/observer_states/' + obs_id + '.pkl') except: pass with open('data/observer_states/' + obs_id + '.pkl', 'wb') as f: pickle.dump(observer_state, f, pickle.HIGHEST_PROTOCOL) Attempted Solution I did try to use os.remove() a prior pickle file instead of just overwriting it. This approach didn't work and I don't have much of a clue on how to deal with this. Desired Result I want to save this simple dictionary to disk without having it occupy 5.863kb of memory, and understand why is it happening so I can better debug the performance issues I am currently having.

http://stackoverflow.com/comment/82259478
comment on: http://stackoverflow.com/q/47644824
type: QuestionComment
score: 0
has text: Its not me, but I'm guessing its supposed to be rendered like `Bed` and `Almirah`, again I quote from the line under the image.
type: Comment

http://stackoverflow.com/comment/82362737
score: 0
comment on: http://stackoverflow.com/q/47652836
has text: Look on your example. You explicitly wrapped `preprocess_request` by `@asyncio.coroutine` decorator.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47664265
tagged with: pygame
has answer: http://stackoverflow.com/a/47664402
has comment: http://stackoverflow.com/comment/82287939
has comment: http://stackoverflow.com/comment/82288115
has body: This question has been asked a lot around the Internet but until now I haven't found someone who's getting the same error as I am (maybe I'm not looking hard enough, who knows). I'm using a Windows 10 64-bit Acer laptop (I don't know any other specs, it isn't mine) and trying to install pygame‑1.9.3‑cp36‑cp36m‑win32.whl (I've been told it's better to get the 32-bit versions of both Python and Pygame). I receive this error when I go into PowerShell: PS C:\Program Files (x86)\Python36-32\Scripts&gt; pip3 install pygame-1.9.3-cp36-cp36m-win32.whl Processing c:\program files (x86)\python36-32\scripts\pygame-1.9.3-cp36-cp36m-win32.whl Installing collected packages: pygame Exception: Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files (x86)\python36-32\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\Lib\\site-packages\\pygame' Not too sure wha…
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82287729
linked to: http://stackoverflow.com/q/26091530
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/82288131
has comment: http://stackoverflow.com/comment/82288060
has title: Error when installing Pygame (1.9.3) on Windows
answer count: 1

http://stackoverflow.com/a/47607122
type: Answer
answers question: http://stackoverflow.com/q/47603418
downvote count: 0
upvote count: 1
has body: You can't do it on the instance alone, you'll need to look at the class attributes for this to work. If you look up the attribute on the class with the same name you can either check the type or do an isinstance check on the class-attribute. Example, given you have a table1 instance &gt;&gt;&gt; table1.__class__.regular_field.__class__.__mro__ (sqlalchemy.orm.attributes.InstrumentedAttribute, sqlalchemy.orm.attributes.QueryableAttribute, sqlalchemy.orm.interfaces._MappedAttribute, sqlalchemy.orm.interfaces._InspectionAttr, sqlalchemy.orm.interfaces.PropComparator, sqlalchemy.sql.operators.ColumnOperators, sqlalchemy.sql.operators.Operators, object) You can then check for a particular class like this field = table1.__class__.field_synonym if isinstance(field, sqlalchemy.orm.attributes.propertyProxy): # overwriting vars is bad style, just for illustration purposes! field = field.original_property
has comment: http://stackoverflow.com/comment/82282365
has comment: http://stackoverflow.com/comment/82278057
score: 1

http://stackoverflow.com/comment/82244882
comment on: http://stackoverflow.com/a/47639942
type: AnswerComment
score: 0
has text: Do you have any ideas on how I could trouble shoot this error?
type: Comment

http://stackoverflow.com/comment/82294551
comment on: http://stackoverflow.com/q/47665774
type: Comment
type: QuestionComment
has text: Hi Stephen.. I included the code.
score: 0

http://stackoverflow.com/comment/82326213
type: Comment
type: QuestionComment
has text: Use [`os.path.realpath()`](https://docs.python.org/2/library/os.path.html#os.path.realpath) to unwrap your links and check against the actual path.
score: 1
comment on: http://stackoverflow.com/q/47683359

http://stackoverflow.com/comment/82241153
comment on: http://stackoverflow.com/q/47641246
type: QuestionComment
has text: I'm not sure I'm understanding the question, or if there even is one, really.
type: Comment
score: 0

http://stackoverflow.com/q/47653948
type: Question
type: UnansweredQuestion
score: 0
tagged with: django
has answer: http://stackoverflow.com/a/47654046
has body: Here is my view.py: def dublinbus(request): template = loader.get_template('park_at_dcu/dublinbus.html') busstop = request.GET.get('busstop', '') busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&amp;format=json' bus_time_info = requests.get(busstop_url) return HttpResponse(template.render(bus_time_info.json(), request)) Here is the JSON data: {"errorcode": "0", "errormessage": "", "numberofresults": 1, "stopid": "1644", "timestamp": "05\/12\/2017 12:22:09", "results":[{"arrivaldatetime": "05\/12\/2017 13:11:49", "duetime": "49", "departuredatetime": "05\/12\/2017 13:11:49", "departureduetime": "49", "scheduledarrivaldatetime": "05\/12\/2017 13:12:00", "scheduleddeparturedatetime": "05\/12\/2017 13:12:00", "destination": "Clontarf Road ", "destinationlocalized": " ", "origin": "DCU", "originlocalized": "DCU", "direction": "Inbound", "operator": "bac", "additionalinformation": "", "lowfloorstatus": "no", "route": "104", "sourcetimestamp": "05\/12\/2017 12:15:24", "monitored": "true"}] }
has title: How can I display this nested json object neatly and structured for the results object in django?
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: python

http://stackoverflow.com/q/47642160
has title: How to null N indices following a number in pandas?
answer count: 2
has body: I have a Series containing values and NaN's like so: 0 NaN 1 1.0 2 NaN 3 2.0 4 3.0 5 NaN 6 NaN 7 4.0 8 5.0 9 NaN dtype: float64 And say for example I'd like to null out the next four indices after each initial value, like so: 0 NaN 1 1.0 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 4.0 8 NaN 9 NaN dtype: float64 (The four directly after the first 1.0 are null'd, as well as the last two directly after the next value, 4.0.)
accepted answer: http://stackoverflow.com/a/47642995
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82243340
has comment: http://stackoverflow.com/comment/82243456
has answer: http://stackoverflow.com/a/47642995
linked to: http://stackoverflow.com/q/40084931
possible better answer: http://stackoverflow.com/a/47642723
tagged with: python
has answer: http://stackoverflow.com/a/47642723
has comment: http://stackoverflow.com/comment/82243571
type: AnsweredQuestion

http://stackoverflow.com/q/47648044
answer count: 3
accepted answer: http://stackoverflow.com/a/47648164
has answer: http://stackoverflow.com/a/75554245
tagged with: matrix
has answer: http://stackoverflow.com/a/47648164
downvote count: 0
has body: What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0?
score: 6
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/47650216
tagged with: diagonal
tagged with: python
upvote count: 6
has title: Python: Non diagonal elements of a matrix to 0
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47650216

http://stackoverflow.com/comment/82220142
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47631200
has text: did you set the `app_metrics` to installed_apps list in your settings file ?

http://stackoverflow.com/comment/82270495
score: 0
comment on: http://stackoverflow.com/q/47656073
type: QuestionComment
has text: Does that updated code give you the same error? What version of Qt5 do you currently have?
type: Comment

http://stackoverflow.com/comment/82184552
type: Comment
type: QuestionComment
has text: if you mean : libmumps-scotch-dev, i have no problem in using others. if you mean other pymumps: can you give what other libs are available.
comment on: http://stackoverflow.com/q/47613053
score: 0

http://stackoverflow.com/a/47656625
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47655938
has comment: http://stackoverflow.com/comment/82272875
answers question: http://stackoverflow.com/q/47655938
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82273732
type: Answer
has body: Starting by the end, you don't have to switch to the working dir to iterate. I suppose you want to list the target dir right? So you either change the dir to current with chdir or you specify the dir to listdir. You are using the first one, but chdir changes dir as a lateral effect not as a result. chdir is returning None. So you call listdir with None, which by mere luck accepts None as an hint to use current dir. You can write os.chdir(target_dir) for file in os.listdir(): tp_parser(file) or for file in os.listdir(target_dir): tp_parser(file) As for the first problem, notice that you assign start_line and end_line with conditional statements. I suspect your problem is that sometimes one of the conditions is not met and using the unassigned name later in code brings up the error. Edit: There is also another problem with this code, you are writing your output file into the same dir that you are listing. Next time you run the code the code will parse also your last output file. I suppose this is not intended behaviour; but if you go on you'll see that your output files don't have the end marker, as your condition for output excludes it: if start_line &lt;= i &lt; end_line: # use of &lt; instead of &lt;= end_line excludes end marker from output So the error in that case is just malformed new input files appearing amongst the others. And this are erraneous coincidences (user error), not Python code unexpected behaviour.

http://stackoverflow.com/comment/82149356
comment on: http://stackoverflow.com/q/47593255
type: Comment
type: QuestionComment
score: 0
has text: `sch` is a complex regex and matching them would probably involve backtracking, but I am treating each regex independently, so I fail to get why is it relevant.

http://stackoverflow.com/comment/82274946
type: Comment
type: AnswerComment
has text: ok, so should i have the `credential.helper=wincred' in the .gitconfig file?
comment on: http://stackoverflow.com/a/47657864
score: 0

http://stackoverflow.com/q/47582033
downvote count: 0
has body: I am used to programming in python and am trying to teach a friend how to program in c. I was able to teach him the basics but he has an exam coming up soon that I would love to be able to help him with, however I myself am having trouble converting some code from python to c. One question he was given for example.. the program should read the greyscale pixel values from the pixelsIn.txt.file using a loop. The lines of the file are read in by the program. The body of the image contains the grey scale value of each body in the picture and the program should determine whether the pixel value is equal to 110, if so, the program should convert this pixel value to 225 (white) otherwise it should be converted back to 0 (black). If I was to do that in python I would read in each line, split the line and then use a for loop to check if the number is 110 or not. However I am extremely unsure if this is how it would be done in C? Sorry if I am being vague but I will answer any questions if I wasn't clear enough. Any help would be greatly appreciated. For example in the following tiny image on the left, the letter H is encoded using the pixel value 110. This is not very clear on the left hand image as the surrounding pixels have a greyscale value which is very close. If the message pixel values are changed to 255 (white) and the non-message pixel values changed to 0 (black) the image on the right hand side then shows the hidden H clearly
upvote count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/82122027
has answer: http://stackoverflow.com/a/47582391
has comment: http://stackoverflow.com/comment/82122127
tagged with: pixel
score: 1
has comment: http://stackoverflow.com/comment/82121953
has title: Convert Pixels to Black and White
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82121665
has comment: http://stackoverflow.com/comment/82121761
has comment: http://stackoverflow.com/comment/82121810
type: UnansweredQuestion
tagged with: message
has comment: http://stackoverflow.com/comment/83032403
answer count: 1

http://stackoverflow.com/a/47640619
has comment: http://stackoverflow.com/comment/82239685
has body: Assign your value to a variable then call the variable.split() it defaults to comma delimited which in your instance would result in list['[1,[2,[]],[3,[]]]'] another example of this could be this: a = "test, 1, testing2, alpha, beta, Zulu, 23" a.split() Result: ['test,', '1,', 'testing2,', 'alpha,', 'beta,', 'Zulu,', '23']
answers question: http://stackoverflow.com/q/47640523
type: Answer
upvote count: 0
score: -2
downvote count: 2

http://stackoverflow.com/a/47576726
has comment: http://stackoverflow.com/comment/82110578
has body: While looping over NumPy arrays is often not a good solution, you can do it like this: for i in range(len(my_data)): do something with my_data[i] You might be better off reading your data into a list, process the strings, and convert into NumPy array afterwards.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82110471
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47576618
has comment: http://stackoverflow.com/comment/82110820
accepted answer of: http://stackoverflow.com/q/47576618
type: Answer

intel
tags question: http://stackoverflow.com/q/47619154
tag name: intel
type: Tag

http://stackoverflow.com/a/47648536
type: Answer
has body: You can flatten the transposed array, create a new axis, and transpose again. &gt;&gt;&gt; np.ravel(a.T)[None].T array([[1], [3], [1], [3], [2], [7], [5], [5], [3], [2], [6], [6], [3], [7], [5]])
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47648139

http://stackoverflow.com/a/47563839
answers question: http://stackoverflow.com/q/47563811
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82085794
type: Answer
has body: Is this what you want? ages = [] for i in range(1,76): input('Enter name for guest'+str( i)+': ') ages.append(int(input('Enter age for guest '+str(i)+':'))) n = len([a for a in ages if 20 &lt;= a &lt; 30]) print('Number of people in 20s is ' + str(n) )
score: 2

http://stackoverflow.com/q/47599469
linked to: http://stackoverflow.com/q/12414043
has answer: http://stackoverflow.com/a/47599824
tagged with: statistics
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: distribution
has title: Mapping each value in a list to its percentile of a different distribution
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I have a list scores and a list distribution. I need to map each score in scores to what its corresponding percentile would be in distribution. Example: distribution=[4,10,3,5,1] scores = [1,6,11] The result of the operation should be [20,80,100] Map each list value to its corresponding percentile This similar question has been asked but in my case, making use of scipy.stats.rankdata is not possible because I need to find the percentile of each item in relation to a different distribution. The natural way to solve it is [scipy.stats.percentileofscore(distribution,s) for s in scores] but this is extremely slow when scores or distribution is large (length higher than about 10,000 for each). Is there any way to speed this up considerably? I've tried sorting the distribution list first and then doing a standard search, but the worst case is still quite bad.

http://stackoverflow.com/comment/82062235
comment on: http://stackoverflow.com/a/47551485
score: 0
type: AnswerComment
type: Comment
has text: Alright! That was some pre-processing that needed to be done on your end. Hope I was able to help.

http://stackoverflow.com/q/47600973
score: -1
duplicate of: http://stackoverflow.com/q/10695139
has answer: http://stackoverflow.com/a/47601017
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47601017
downvote count: 1
has title: How do you find the minimum value of a 2d list and remove it
answer count: 1
has body: I have a 2d list with all of the lists having the same format and I want to arrange it so it is going up in numerical order. Here is the list: list = [["a", -50], ["b", 23], ["c", 5], ["d", 44], ["e", 23]] How do i end up with something which prints data_list = [["a", -50], ["c", 5], ["b", 23], ["e", 23], ["d", 44]] I'm avoiding using .sort() or any other built in functions as I want to keep the strings with the appropriate number
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10695139
has comment: http://stackoverflow.com/comment/82160565
tagged with: python

http://stackoverflow.com/comment/82166861
comment on: http://stackoverflow.com/q/47603964
score: 1
type: Comment
type: QuestionComment
has text: The `x>=0` creates an infinite loop. `x` will never go negative.

http://stackoverflow.com/a/47598534
answers question: http://stackoverflow.com/q/47598442
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82155355
has comment: http://stackoverflow.com/comment/82155553
has body: It seems like Panda is truncating the output for displaying purpose. The default max_colwidth is 50. You can set this value yourself like this: pd.set_option('display.max_colwidth', -1) -1 here basically turns off the truncating.
type: Answer
has comment: http://stackoverflow.com/comment/82155486
accepted answer of: http://stackoverflow.com/q/47598442
score: 0
has comment: http://stackoverflow.com/comment/82155388

http://stackoverflow.com/comment/82330223
type: AnswerComment
has text: skrx, thank you for the help, but I want to make a button that is activated when my sprite goes on top of it, not when my mouse clicks it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47666505

http://stackoverflow.com/a/47717145
score: 0
has body: You're looking for #attr. Example: #attr className = "CustomClassName"
type: Answer
answers question: http://stackoverflow.com/q/47659289

http://stackoverflow.com/comment/82299443
score: 0
type: Comment
type: QuestionComment
has text: @Grasshopper No. Already tried that...
comment on: http://stackoverflow.com/q/47668840

http://stackoverflow.com/a/47570711
score: 0
answers question: http://stackoverflow.com/q/47570338
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82098712
has body: I guess maybe is your file.txt is not unix format, try execute dos2unix file.txt first
type: Answer
accepted answer of: http://stackoverflow.com/q/47570338

http://stackoverflow.com/comment/82159843
score: 0
comment on: http://stackoverflow.com/a/47599336
type: AnswerComment
has text: thank you so much for your help. fairly simple answers but i never would have got them. saved me many hours of pain :D
type: Comment

qwidget
tag name: qwidget
type: Tag
tags question: http://stackoverflow.com/q/47544669
tags question: http://stackoverflow.com/q/47583630

http://stackoverflow.com/comment/82289856
score: 1
type: Comment
type: QuestionComment
has text: @sascha I changed my original post and include the content of t1. Please have a look
comment on: http://stackoverflow.com/q/47665176

http://stackoverflow.com/comment/82384788
type: Comment
comment on: http://stackoverflow.com/a/47696685
score: 0
type: AnswerComment
has text: Thank you for your polite advise. But my understanding of "tf.boolean_mask" is insufficient. So I don't know what to do next. I would like to study again and think about it.

http://stackoverflow.com/q/47588655
tagged with: python-multiprocessing
has body: I have a code that works with Thread in python, but I wanna switch to Process as if I have understood well that will give me a speed-up. Here there is the code with Thread: threads.append(Thread(target=getId, args=(my_queue, read))) threads.append(Thread(target=getLatitude, args=(my_queue, read))) The code works putting the return in the Queue and after a join on the threads list, I can retrieve the results. Changing the code and the import statement my code now is like that: threads.append(Process(target=getId, args=(my_queue, read))) threads.append(Process(target=getLatitude, args=(my_queue, read))) However it does not execute anything and the Queue is empty, with the Thread the Queue is not empty so I think it is related to Process. I have read answers in which the Process class does not work on Windows is it true, or there is a way to make it work (adding freeze_support() does not help)? In the negative case, multithreading on windows is actually executed in parallel on different cores? ref: Python multiprocessing example not working Python code with multiprocessing does not work on Windows Multiprocessing process does not join when putting complex dictionary in return queue (in which is described that fork does not exist on Windows) EDIT: To add some details: the code with Process is actually working on centOS. EDIT2: add a simplified version of my code with processes, code tested on centOS import pandas as pd from multiprocessing import Process, freeze_support from multiprocessing import Queue #%% Global variables datasets = [] latitude = [] def fun(key, job): global latitude if(key == 'LAT'): latitude.append(job) def getLatitude(out_queue, skip = None): latDict = {'LAT' : latitude} out_queue.put(latDict) n = pd.read_csv("my.csv", sep =',', header = None).shape[0] print("Number of baboon:" + str(n)) read = [] for i in range(0,n): threads = [] my_queue = Queue() threads.append(Process(target=getLatitude, args=(my_queue, read))) for t in threads: freeze_support(…
linked to: http://stackoverflow.com/q/39896807
has comment: http://stackoverflow.com/comment/82135968
tagged with: multithreading
answer count: 1
downvote count: 1
has title: Multiprocessing with Python and Windows
favorite count: 0
has answer: http://stackoverflow.com/a/47597828
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/27277063
has comment: http://stackoverflow.com/comment/82135345
tagged with: python-multithreading
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47597828
linked to: http://stackoverflow.com/q/21198857
type: Question
upvote count: 2

http://stackoverflow.com/comment/82076633
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47559233
score: 0
has text: Noted! I added comments to my code to hopefully make it more readable. :)

http://stackoverflow.com/comment/82218084
type: AnswerComment
type: Comment
has text: thanks i will take your advice in my next questrions
comment on: http://stackoverflow.com/a/47603043
score: 0

http://stackoverflow.com/q/47622593
has body: I am new to Tensorflow and I have problems with combining shapes (n,) with shapes (n,1). I have this code: if __name__ == '__main__': trainSetX, trainSetY = utils.load_train_set() # create placeholders &amp; variables X = tf.placeholder(tf.float32, shape=(num_of_features,)) y = tf.placeholder(tf.float32, shape=(1,)) W, b = initialize_params() # predict y y_estim = linear_function(X, W, b) y_pred = tf.sigmoid(y_estim) # set the optimizer loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=y_pred) loss_mean = tf.reduce_mean(loss) optimizer = tf.train.GradientDescentOptimizer(learning_rate=alpha).minimize(loss_mean) # training phase init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for idx in range(num_of_examples): cur_x, cur_y = trainSetX[idx], trainSetY[idx] _, c = sess.run([optimizer, loss_mean], feed_dict={X: cur_x, y: cur_y}) I am trying to implement a stochastic gradient descent by feeding one example at the time. The problem is that it seems to feed the data in shape (num_of_features,), while I need (num_of_features,1) for the correct usage of the other functions. For example, the code given before causes error when it comes to calculating the prediction of y with this function: def linear_function(x, w, b): y_est = tf.add(tf.matmul(w, x), b) return y_est The error is: ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [1,3197], [3197]. I was trying to use tf.reshape with X and y to somehow solve this problem, but it caused errors in other places. Is it possible to feed the data in feed_dict={X: cur_x, y: cur_y} in "correct" shape? Or what is the way to properly implement this? Thanks.
tagged with: tensorflow
type: Question
has title: Shapes in Tensorflow
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47623308
accepted answer: http://stackoverflow.com/a/47623308
answer count: 1

http://stackoverflow.com/comment/82152357
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47590847
has text: Thank you. Can you explain it a bit more specific about each line of code. The solution was great and glad to know that numpy has many features. @PaulPanzer

http://stackoverflow.com/q/47673889
type: Question
has title: pyspark how can I combine column values if columns have a same value
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47677871
has comment: http://stackoverflow.com/comment/82306617
has comment: http://stackoverflow.com/comment/82311815
has comment: http://stackoverflow.com/comment/82311330
tagged with: pyspark
has comment: http://stackoverflow.com/comment/82313604
has comment: http://stackoverflow.com/comment/82313526
tagged with: python
has body: I have an idea to combine dataframe values (a list) in different rows with the same key. The combination must have a same value or more in different rows, so I can not just use df.groupBy('id') to get the result. Following is the example: +---------+--------------------+ |id |num_list | +---------+--------------------+ |apple |[11, 12] | |apple |[11, 13 ,14] | |apple |[10, 22, 25] | |banana |[15, 26] | |banana |[15, 29] | |banana |[15, 27] | +---------+--------------------+ we can find id=apple have two record and two lists like: [11, 12],[11, 13, 14], so they would be combined to a new record id=apple,num_list=[11, 12, 13, 14] But id=apple,num_list=[10, 22, 25] will not be combined. and this is the answer i want: +---------+--------------------+ |id |num_list | +---------+--------------------+ |apple |[11, 12, 13, 14] | |apple |[10, 22, 25] | |banana |[15, 26, 27, 29] | +---------+--------------------+ Edit: There are some rules that I have to explain. Just as @Usernamenotfound commented, Assuming apple have three values [11, 12, 14], [9, 13 ,14], and [12,13,27], the answer will be [9, 11, 12, 13 ,14, 27] not [9, 11, 12, 13 ,14] and[12,13,27]. There are some new example: +--------------------+------------+ | id|num_list | +--------------------+------------+ |apple | [0]| |apple | [0]| |apple | [1]| |apple | [1]| |apple | [2]| |apple | [3]| |apple | [4]| |apple | [5]| |apple | [6]| |apple | [6]| |apple | [7]| |apple | [7, 8]| |apple | [9]| |apple | [9]| |apple | [9]| |apple | [9, 10]| |apple | [9, 17, 18]| |apple | [10]| |apple | [10]| |apple | [10]| +--------------------+------------+ and if i tried the code from @mayank would get wrong answer. +--------------------------------+---------------------------------------------------------------------------------------+ | id|num_list | +--------------------------------+---------------------------------------------------------------------------------------+ |apple |[0] | |apple |[0] | |apple |[1] | |apple |[2] | |apple |…
has comment: http://stackoverflow.com/comment/82311307
has comment: http://stackoverflow.com/comment/82311788
has comment: http://stackoverflow.com/comment/82313989
type: AnsweredQuestion
tagged with: python-2.7
tagged with: apache-spark
score: 1
has answer: http://stackoverflow.com/a/47677871
has comment: http://stackoverflow.com/comment/82312414
has comment: http://stackoverflow.com/comment/82339581
has comment: http://stackoverflow.com/comment/82308330
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82308379
has comment: http://stackoverflow.com/comment/82311519
favorite count: 0

http://stackoverflow.com/comment/82087543
has text: unfortuanly this does display anything in my notebook
type: AnswerComment
comment on: http://stackoverflow.com/a/47564195
score: 0
type: Comment

http://stackoverflow.com/comment/82325932
score: 0
has text: most of your code is `numpy`/`scipy`, so that would likely be the problem. What versions are you using on each of the interpreters? You are getting over-flow warnings, and you aren't using explicit types for your `numpy` arrays, are your interpreters running as the same type of process? E.g. both 64bit?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47683224

lookup
tags question: http://stackoverflow.com/q/47643952
tag name: lookup
type: Tag

http://stackoverflow.com/q/47542255
linked to: http://stackoverflow.com/q/3054315
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82041917
has answer: http://stackoverflow.com/a/47542499
downvote count: 0
upvote count: 1
tagged with: python
tagged with: jquery
tagged with: css
has title: Write an email in HTML form containing jQuery and CSS through a Python script.
score: 1
has body: I am trying to write a python program that sends an email to me depending on some condition. I would like the value to be printed in red if it matches certain criteria and green otherwise. Below is a small snippet of my code. I'm unsure on how to add this jquery/Javascript part to it. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText me = "my@email.com" you = "you@email.com" msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" #a=0 #if a==0: # color="blue" #else: # color="red" html = """ Hi! How are you? Here is the link you wanted. """ part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) s = smtplib.SMTP('localhost') s.sendmail(me, you, msg.as_string()) s.quit()
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: email
has comment: http://stackoverflow.com/comment/82042021

http://stackoverflow.com/comment/82172747
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47607115
type: Comment
has text: Try : `$pip3 install schedule ` you might be running Python3 but you installed `schedule` for python2

http://stackoverflow.com/q/47613830
tagged with: utc
downvote count: 0
has body: I'm trying to convert a UTC time to the appropriate local time in a flask application. I'm wondering if I can detect the user's timezone and dynamically set it. This is my code so far which works for everyone in the US/Pacific timezone only (datetimefilter pulled from this SO question) from flask import Flask, render_template_string import datetime import pytz app = Flask(__name__) @app.template_filter('datetimefilter') def datetimefilter(value, format='%b %d %I:%M %p'): tz = pytz.timezone('US/Pacific') # timezone you want to convert to from UTC (America/Los_Angeles) utc = pytz.timezone('UTC') value = utc.localize(value, is_dst=None).astimezone(pytz.utc) local_dt = value.astimezone(tz) return local_dt.strftime(format) @app.route('/') def index(): dt = datetime.datetime.utcnow() return render_template_string( ''' UTC --> Local Time Datetime right now is: (utc --> local) ''', dt=dt, now=now) if __name__ == '__main__': app.run(debug=True) I imagine this can't be handled server-side because the timezone will always be set to wherever the server is located? Is there a way to handle this by changing datetimefilter?
accepted answer: http://stackoverflow.com/a/47614665
favorite count: 0
linked to: http://stackoverflow.com/q/10434599
linked to: http://stackoverflow.com/q/8153631
type: Question
has answer: http://stackoverflow.com/a/47614665
type: AnsweredQuestion
has title: flask: convert utc time to user's local time
upvote count: 9
tagged with: timezone
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/12145847
tagged with: pytz
possible better answer: http://stackoverflow.com/a/75271114
score: 9
answer count: 2
has answer: http://stackoverflow.com/a/75271114
linked to: http://stackoverflow.com/q/34803906

http://stackoverflow.com/q/47638161
has comment: http://stackoverflow.com/comment/82242504
answer count: 0
tagged with: python
type: UnansweredQuestion
has body: My question is about matplotlib. Is there any tool to plot Volumecandle charts or ist it possible to change the width value within a for loop? I tried it by myself and failed alot. candlestick_ohlc(ax1, df_ohlc.values, width=5, colorup='g') The chart I want to produce is calles Volumecandle chart. It's a chart where the volume is added into the different candles. Shown here: However, the command from above fails to generate the individuel thickness of each candlestick. I dont know exactly how to do it. I know you could do it with a for loop within a pandas dataframe but the module candlestick_ohlc does not (as far as I can tell) support an itereation within width. Width should be change for every candlestick. OK thx guys i think i have it df = web.DataReader('AMD','yahoo','2012-01-01','2013-03-30') # get new column df['VC'] =0# set all to 0 x=0 for i in df['VC']: df.ix[x,'VC']=df.ix[x,'Volume']*0.00000004 #to expand the size of each x+=1 #plot from tutorial df_ohlc = df['Adj Close'].resample('10D').ohlc() df_volume = df['VC'].resample('10D').sum() df_ohlc.reset_index(inplace=True) df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num) ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1) ax1.xaxis_date() solution to plot volumecharts x=0 for i in df_volume: candlestick_ohlc(ax1, df_ohlc.values[x:x+1], width=i, colorup='g',colordown='r') x += 1 ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0) plt.show() Volumechart
has comment: http://stackoverflow.com/comment/82235351
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82261784
has comment: http://stackoverflow.com/comment/82234514
has comment: http://stackoverflow.com/comment/82235153
has comment: http://stackoverflow.com/comment/82235309
has title: Python matplotlib Volumecandle chart
type: Question
has comment: http://stackoverflow.com/comment/82253543

http://stackoverflow.com/a/47687276
answers question: http://stackoverflow.com/q/47687203
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Python string.replace doesn't do an in-place replace, but instead returns a new string which contains the replacement. Since you are not using the return value from the first replace, it is discarded and the second iteration of your loop with the character - replaces just this character and not ", in the original string. For the intended effect, you can use the following snippet: MyString = '--"I like salami. "-I want to walk to the shops"' b = '"-' for char in b: MyString = MyString.replace(char,"") print(MyString) #Outputs: I like salami. I want to walk to the shops

http://stackoverflow.com/comment/82228419
type: AnswerComment
score: 0
has text: @pstatix You are right, but the code example the OP is giving suggests that he means odd indexes.
type: Comment
comment on: http://stackoverflow.com/a/47634665

http://stackoverflow.com/comment/82332341
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47686088
has text: Moved it and it still calls an error - Also forgot to change bind when I wrote it on here. The problem only occurs when dragging mouse.
type: Comment

http://stackoverflow.com/q/47542667
has title: How parse xml in python?
has comment: http://stackoverflow.com/comment/82042463
tagged with: xml-parsing
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47553191
has body: I have this xml file: <?xml version="1.0" encoding="utf-8" ?> V Representava A2 ela A1 uma jibóia A0 que V engolia A1 uma fera How do I extract just this block in python? I'm using Beautiful Soup. uma jibóia A0 que V engolia A1 uma fera I tried this: soup = bs(open(xml, 'r'), 'lxml') texts = soup.find_all('txt') for t in texts: print t.text
has comment: http://stackoverflow.com/comment/82042634
upvote count: 1
has comment: http://stackoverflow.com/comment/82042760
has comment: http://stackoverflow.com/comment/82042483
favorite count: 0
type: Question
score: 1
has comment: http://stackoverflow.com/comment/82042427
has comment: http://stackoverflow.com/comment/82042489
has comment: http://stackoverflow.com/comment/82042555
tagged with: python
has comment: http://stackoverflow.com/comment/82042458
tagged with: http://stackoverflow.com/tag/xml

http-post
tags question: http://stackoverflow.com/q/47662496
type: Tag
tags question: http://stackoverflow.com/q/47587297
tag name: http-post

http://stackoverflow.com/comment/82354276
comment on: http://stackoverflow.com/a/47696949
type: AnswerComment
has text: I haven't seen your answer, but the 'nearest'-method does not give you a mean.
score: 0
type: Comment

http://stackoverflow.com/comment/82163736
comment on: http://stackoverflow.com/q/47602422
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47584787
has answer: http://stackoverflow.com/a/47585115
has comment: http://stackoverflow.com/comment/82129747
has comment: http://stackoverflow.com/comment/82127284
has comment: http://stackoverflow.com/comment/82133693
tagged with: input
tagged with: python
has body: I've tried searching for pyHook documentation but failed to understand it... I've also tried watching many tutorials on youtube but they won't explain how to do it, instead they just do it. I've also searched on StackOverflow posts BUT they are mostly related to games, and store keystrokes made on the python interpreter instead of Windows.
has comment: http://stackoverflow.com/comment/82129683
has title: How could i store keyboard input in Windows using Python 3?
has comment: http://stackoverflow.com/comment/82127376
has comment: http://stackoverflow.com/comment/82127332
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: keylogger
type: UnansweredQuestion

http://stackoverflow.com/comment/82199910
type: AnswerComment
has text: @Hiddenguy What do you mean? You can look at the documentation for details on how to use it. Briefly, pass it a signal and the sampling rate, and it will return the frequencies and power at those frequencies.
score: 0
comment on: http://stackoverflow.com/a/47620098
type: Comment

http://stackoverflow.com/comment/82188561
score: 0
type: Comment
type: QuestionComment
has text: Those are np.array, does that make a difference?
comment on: http://stackoverflow.com/q/47615017

http://stackoverflow.com/q/47626799
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/82211448
has body: I would like to vectorize a function that takes 2 objects as argument such that it takes 2 ndarrays (of length m and n) and returns a matrix of shape (m x n). Kinda like a tensor product. I've tried to use numpy.vectorize without much success: vFunc = np.vectorize(myFunc) arg1 = np.asmatrix(a) arg2 = np.transpose(np.asmatrix(b)) test = vFunc(arg1,arg2) The above doesn't work, so for now I have to iterate on one of the arrays, which is an ugly solution. How do I fix this? vFunc = np.vectorize(myFunc) arg1 = np.asmatrix(a) arg2 = np.transpose(np.asmatrix(b)) for i in range(arg1.size): cMat[i,] = vFunc(arg1[i],arg2)
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82211405
has comment: http://stackoverflow.com/comment/82212985
has answer: http://stackoverflow.com/a/47628059
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82211411
has title: vectorize a function on 2 python objects
answer count: 1
accepted answer: http://stackoverflow.com/a/47628059

http://stackoverflow.com/comment/82221292
comment on: http://stackoverflow.com/q/47631594
score: 0
type: Comment
type: QuestionComment
has text: Ok so if you do `print(u'\xf1')`, you get: `ñ`, which is basically not ascii and it works. So why do you wish to convert exactly? Like I worked with Hindi recently and had no need to convert and worked with it natively, that's why I'm asking

http://stackoverflow.com/comment/82078762
has text: `time.sleep(300)` will cause the entire GUI to freeze.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47560511
type: AnswerComment

http://stackoverflow.com/comment/82199382
type: QuestionComment
has text: Possible duplicate of [Python: get a frequency count based on two columns (variables) in pandas dataframe](https://stackoverflow.com/questions/33271098/python-get-a-frequency-count-based-on-two-columns-variables-in-pandas-datafra)
comment on: http://stackoverflow.com/q/47620346
score: 0
type: Comment

devops
tags question: http://stackoverflow.com/q/47684308
type: Tag
tag name: devops
tags question: http://stackoverflow.com/q/47671514

sklearn-pandas
tags question: http://stackoverflow.com/q/47610516
tags question: http://stackoverflow.com/q/47666438
tags question: http://stackoverflow.com/q/47675520
tags question: http://stackoverflow.com/q/47565963
type: Tag
tag name: sklearn-pandas
tags question: http://stackoverflow.com/q/47646093

http://stackoverflow.com/comment/82144696
comment on: http://stackoverflow.com/a/47593565
score: 0
type: Comment
type: AnswerComment
has text: Thanks @Sam, thats' exactly what I was looking for!

openstack-nova
tags question: http://stackoverflow.com/q/47693548
tags question: http://stackoverflow.com/q/47632015
tag name: openstack-nova
type: Tag

http://stackoverflow.com/a/47691082
answers question: http://stackoverflow.com/q/47690463
score: 1
type: Answer
has body: @Sneha has a nice and succinct answer, but if you're going to have a lot of combinations then it might be better to to not go too far in creating combinations. This solution is longer but will run faster for long lists of letters with large goal scores: letters = ['C', 'N', 'O', 'S'] weights_of_l = [1, 1, 2, 2] def get_combos(letters, weights, goal): weighted_letters = list(zip(letters, weights)) combos = set() def get_combos(letters, weight): for letter, next_weight in weighted_letters: total = weight + next_weight if total == goal: combos.add(''.join(sorted(letters + letter))) elif total &gt; goal: pass else: get_combos(letters + letter, weight+next_weight) get_combos('',0) return combos print(get_combos(letters, weights_of_l, 3)) EDIT: I think this one might be even faster: letters = ['C', 'N', 'O', 'S'] weights_of_l = [1, 1, 2, 2] def get_combos(letters, weights, goal): weighted_letters = sorted(zip(weights, letters)) combos = [] def get_combos(letters, weight, weighted_letters): for i, (next_weight, letter) in enumerate(weighted_letters): total = weight + next_weight if total == goal: combos.append(letters + letter) elif total &gt; goal: return else: get_combos(letters+letter, weight+next_weight, weighted_letters[i:]) get_combos('',0,weighted_letters) return combos print(get_combos(letters, weights_of_l, 3))
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47581087
has body: That's not how Django filters work. You can't | them because they are not actually expressions, just keyword arguments. In this case, correct syntax would be: Docs.objects.filter( Name__contains=request.POST['Name'], Type_Type=request.POST['Type'], Part_Name=request.POST['Part'], )`
type: Answer
answers question: http://stackoverflow.com/q/47580947
score: 0

http://stackoverflow.com/comment/84160772
type: AnswerComment
comment on: http://stackoverflow.com/a/47650238
has text: I'm not suggesting you should pack everything in one big file, your use-case seems very reasonable to me. The problem I'm pointing out is, if you shuffle just the file names you'll still have the data inside each file read in the same order. I agree that shuffling that too doesn't hurt, but you'll still need a `shuffle()` with a buffer after you decode the samples, unless you're OK with having them always in the same order.
score: 1
type: Comment

http://stackoverflow.com/q/47679678
has comment: http://stackoverflow.com/comment/82318551
has comment: http://stackoverflow.com/comment/82318701
has comment: http://stackoverflow.com/comment/82319962
has comment: http://stackoverflow.com/comment/82319790
accepted answer: http://stackoverflow.com/a/47680323
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/82319215
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47680323
has comment: http://stackoverflow.com/comment/82319552
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82322411
tagged with: http://stackoverflow.com/tag/json
has title: Efficient way to append a generated object within an existing list on a JSON file?
score: 1
favorite count: 0
type: Question
has body: I have a json file as follows: { "counts": [ { "date": "date", "day": { "failed": "0", "success": "0", "total": "0" }, "night": { "failed": "0", "success": "0", "total": "0" } }, { "date": "05/12/2017", "day": { "failed": "0", "success": "0" }, "night": { "failed": "1", "success": "1" } } ] } This json file i access and edit with: import json from operator import itemgetter today = '05/15/2017' shift = 'night' def count_save_json(today, shift, status): with open('count.json') as f: data = json.load(f) if today in map(itemgetter('date'), data['counts']): index = map(itemgetter('date'), data['counts']).index(today) #if today in map(itemgetter('date'), data['counts']) else None data['counts'][index][shift][status] = int(data['counts'][index][shift][status]) + 1 print data else: new_count = { "date": today, "day": { "success": 0, "failed": 0 }, "night": { "success": 0, "failed": 0 } } new_count[shift][status] = 1 data['counts'].append(new_count.copy()) print data with open('count.json', 'w+') as fd: json.dump(data, fd, sort_keys=True, indent=4) count_save_json(today, shift, 'success') Its is functional and it does what i intend it to do, which is if variable today's value exists then update the corresponding value if not the push new object too array and start updating that new object until today changes again, but the issue is that i feel is not or may not be the most efficient way to do so, as everytime the today variable changes and i need to add a new object to the array in the json file, the variable data from reading the json initially for processing will become bigger and bigger. Say when i have a month of data the data = json.load(f) variable will be huge (technically containing the entire contents of the json file at that moment) since then i have to open the json file again remove contents and place the new data completely instead of the portion i needed to add that is the new_count object. Is there a better way of doing this? Hope all that made sense. As sugg…

http://stackoverflow.com/q/47560460
has body: There's a class in a library I'm using that I want to override. It looks like this, and I can't change it: class A(Q): def __init__(self): super().__init__() self.data = {} for x in range(10): self.data[x] = x * x In my child class, I want data to behave differently based on rules that apply at runtime: class B(A): @property def data(self): return {x: x*x for x in super().data if x not in some_list_that_changes_at_runtime} @data.setter def data(self, value): super().data = value Unfortunately, this doesn't work, for at least two reasons: 1) super().data doesn't seem to actually work for accessing the version of data that's defined on A. 2) A.__init__ crashes on the self.data = {} line, because it can't assign to the version of data that B defines. 3) Theoretically, even if I could get this to work, the loop in A.__init__ would also not work, because it's getting data in order to assign key/value pairs inside it. But doing that get will result in the @property being accessed, and returning a different object than A.data, meaning that A.data won't be altered. I can't edit A, and I need the @property to have the same name as the original dict attribute, because various other code in the library accesses data, and that code also can't be changed. I also can't really override A.__init__ to make it not mess with data, because I need Q.__init__ to run. Is there any viable way to do what I'm trying to do, here?
answer count: 1
has comment: http://stackoverflow.com/comment/82078879
type: Question
tagged with: python-3.x
has title: Overriding a dictionary attribute with a @property in a child class
has answer: http://stackoverflow.com/a/47560581
has comment: http://stackoverflow.com/comment/82078691
tagged with: python
has comment: http://stackoverflow.com/comment/82078841
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/82079140
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47560581

http://stackoverflow.com/comment/82277917
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47639772
type: Comment
has text: ctypes is being used to *enable* Ctrl+C in Python, not *disable* it. This has no effect on any other existing process that's attached to the console. Ctrl+C will still be disabled in the parent CMD shell that executes the batch script. Processes spawned by Python, however, will inherit Ctrl+C in an enabled state.

http://stackoverflow.com/a/47623780
answers question: http://stackoverflow.com/q/47623565
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47623565
has body: With udf: from scipy.spatial.distance import euclidean as euclidean_ from pyspark.sql.functions import array, lit df = spark.createDataFrame( [(0, [1, 2, 0]), (1, [1, 5, 0]), (2, [1, 9, 0])], ["index", "distribution"]) euclidean = lambda x: udf(lambda y: euclidean_(x, y).tolist(), "double") df.withColumn("dis", euclidean(a)("Distribution")) ## +-----+------------+---+ ## |index|distribution|dis| ## +-----+------------+---+ ## | 0| [1, 2, 0]|2.0| ## | 1| [1, 5, 0]|5.0| ## | 2| [1, 9, 0]|9.0| ## +-----+------------+---+
upvote count: 2
type: AcceptedAnswer
downvote count: 0

qcombobox
tags question: http://stackoverflow.com/q/47569433
tags question: http://stackoverflow.com/q/47638300
tag name: qcombobox
type: Tag

http://stackoverflow.com/q/47581248
tagged with: python
score: 2
upvote count: 2
answer count: 1
downvote count: 0
has body: I've read some documentation online about how to do remote debugging with PyCharm - https://www.jetbrains.com/help/pycharm/remote-debugging.html But there was one key issue with that for what I was trying to do, with my setup - Nginx connecting to uWSGI, which then connects to my Flask app. I'm not sure, but setting up something like, import sys sys.path.append('pycharm-debug.egg') import pydevd pydevd.settrace('localhost', port=11211, stdoutToServer=True, stderrToServer=True, suspend=False) print 'connected' from wsgi_configuration_module import app My wsgi_configuration_module.py file is the uWSGI file used in Production, i.e. no debug. Connects the debugger to the main/master process of uWSGI, which is run once only, at uWSGI startup / reload, but if you try to set a breakpoint in code blocks of your requests, I've found it to either skip over it, or hang entirely, without ever hitting it, and uWSGI shows a gateway error, after timeout.
tagged with: uwsgi
favorite count: 0
type: Question
has title: How to remote debug Flask request behind uWSGI in PyCharm
has answer: http://stackoverflow.com/a/47581250
type: UnansweredQuestion
tagged with: remote-debugging

http://stackoverflow.com/q/47600298
type: UnansweredQuestion
has title: Python 3 Keyboard simulation for a variable
tagged with: python
has body: How would I make the keyboard write Keyboardsimulationme using Keyboard simulation myVarible = Keyboardsimulationme
score: 0
answer count: 0
tagged with: keyboard-events
has comment: http://stackoverflow.com/comment/82159414
type: Question
has comment: http://stackoverflow.com/comment/82159484
tagged with: python-3.x

http://stackoverflow.com/comment/82242673
has text: `scipy.approx_fprime` is exactly what I was looking for! Thanks! But why not choosing the minimum float value for epsilon everytime? What could be a good generic epsilon?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47641368
type: AnswerComment

http://stackoverflow.com/q/47556025
linked to: http://stackoverflow.com/q/39801691
has answer: http://stackoverflow.com/a/47558232
has title: pyspark add new row to dataframe
downvote count: 1
favorite count: 0
score: 13
type: Question
has comment: http://stackoverflow.com/comment/82070052
tagged with: python
accepted answer: http://stackoverflow.com/a/47556546
has body: I am trying to add a new row to dataframe but cant. my code: newRow = Row(id='ID123') newDF= df.insertInto(newRow) or newDF= df.union(newRow) errors: AttributeError: _jdf AttributeError: 'DataFrame' object has no attribute 'insertInto'
possible better answer: http://stackoverflow.com/a/53967316
has answer: http://stackoverflow.com/a/47556546
type: AnsweredQuestion
tagged with: apache-spark
upvote count: 14
answer count: 3
has answer: http://stackoverflow.com/a/53967316

http://stackoverflow.com/a/47613863
accepted answer of: http://stackoverflow.com/q/47613812
score: 0
answers question: http://stackoverflow.com/q/47613812
type: Answer
has body: You can use the BETWEEN keyword in MySQL. So your query should be something like: SELECT * FROM calendar WHERE start_date BETWEEN %(start_date)s AND %(end_date)
type: AcceptedAnswer

http://stackoverflow.com/q/47585046
accepted answer: http://stackoverflow.com/a/47585264
has comment: http://stackoverflow.com/comment/82128076
has title: Is there a faster method for bin file to numpy array?
has answer: http://stackoverflow.com/a/47585264
favorite count: 0
has comment: http://stackoverflow.com/comment/82128026
score: 2
type: AnsweredQuestion
tagged with: binaryfiles
has comment: http://stackoverflow.com/comment/82128098
answer count: 1
has comment: http://stackoverflow.com/comment/82127978
has body: I am importing data from a .bin file to a numpy array using this code: dt = np.dtype([('ShotNum', np.uint32), ('X', np.float32), ('Y', np.float32),\ ('Z', np.float32),('inten', np.float32), ('refl', np.float32),\ ('dopp', np.float32),('range', np.float32),('theta', np.float32),\ ('phi', np.float32)]) data=np.fromfile('Data.bin',dtype=dt) #Flatten Array and then recreate into array of desired dimension flatdata=list(itertools.chain.from_iterable(data)) flatdata1=np.asarray(flatdata,dtype=float) workdata=flatdata1.reshape(flatdata1.size//10,10) it works, but it is slow. Specifically unpacking the tuple within the data structure in the line flatdata=list(itertools.chain.from_iterable(data)) is super slow. Is there a way I can avoid creating this nested structure in the first place when importing data? and if not, is there a faster way to flatten?
tagged with: python
has comment: http://stackoverflow.com/comment/82127959
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/82128052
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82127932
upvote count: 2
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/82127841
downvote count: 0

http://stackoverflow.com/comment/82097113
has text: In the code you show, you would get an error `local variable 'la' referenced before assignment`. It is hence not clear what code you are really using and talking about here. See [mcve]. The memory leak could be because `la` is never actually in the global scope, but only local. You would hence also never remove it. But even if you did, removing an artist from the figure does not delete it, so it sticks around in memory. Please look for other solution on how to update plots in animations. They rarely remove anything, but instead set new data to existing artists.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47569054

package
tags question: http://stackoverflow.com/q/47562695
tag name: package
tags question: http://stackoverflow.com/q/47598869
tags question: http://stackoverflow.com/q/47677807
tags question: http://stackoverflow.com/q/47689265
tags question: http://stackoverflow.com/q/47640501
type: Tag
tags question: http://stackoverflow.com/q/47567982
tags question: http://stackoverflow.com/q/47569075
tags question: http://stackoverflow.com/q/47645828
tags question: http://stackoverflow.com/q/47676721
tags question: http://stackoverflow.com/q/47645024

http://stackoverflow.com/q/47646789
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
has body: I have the following: import numpy as np XYZ_to_sRGB_mat_D50 = np.asarray([ [3.1338561, -1.6168667, -0.4906146], [-0.9787684, 1.9161415, 0.0334540], [0.0719453, -0.2289914, 1.4052427], ]) XYZ_1 = np.asarray([0.25, 0.4, 0.1]) XYZ_2 = np.random.rand(100,100,3) np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) # valid operation np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2) # makes no sense mathematically How do I perform the same operation on XYZ_2 that I would on XYZ_2? Do I somehow reshape the array first?
favorite count: 0
tagged with: matrix-multiplication
possible better answer: http://stackoverflow.com/a/47646904
accepted answer: http://stackoverflow.com/a/47646944
type: Question
has answer: http://stackoverflow.com/a/47646944
has title: numpy - matrix multiple 3x3 and 100x100x3 arrays?
tagged with: python
tagged with: numpy
linked to: http://stackoverflow.com/q/41870228
has answer: http://stackoverflow.com/a/47646904

http://stackoverflow.com/q/47661606
answer count: 2
has body: I am trying to get the first int value from all of the tuples in my dictionary keys. The problem is I keep getting the error: "ValueError: invalid literal for int() with base 10: 'Population'" The code I am using is print([int(item[0]) for item in self.countryCat.values()]) Is there any way I can skip over the first value in my tuple which is "Population" so I will not get this error anymore? I have been stuck on this forever. Thanks!
downvote count: 1
linked to: http://stackoverflow.com/q/1265665
has answer: http://stackoverflow.com/a/47661799
linked to: http://stackoverflow.com/q/15474933
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47661691
has title: Getting the first int value of a tuple but the first value is a string (Error) Python
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82282317
has comment: http://stackoverflow.com/comment/82282310
upvote count: 0

http://stackoverflow.com/comment/82052634
type: Comment
comment on: http://stackoverflow.com/a/47547897
type: AnswerComment
has text: @TahreemIqbal I would look at a package like [pyminizip](https://pypi.python.org/pypi/pyminizip/).
score: 0

http://stackoverflow.com/q/47620891
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82199823
has answer: http://stackoverflow.com/a/47620981
possible better answer: http://stackoverflow.com/a/47620981
tagged with: python
has answer: http://stackoverflow.com/a/47620987
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/47620987
has comment: http://stackoverflow.com/comment/82201277
has body: I've been working on a project where I have a file which needs to call a function from a file in a sub package/directory, which in turn is calling a function from another file in the same sub package. As such, I have a main file which is importing a sub file. This sub file is also importing another sub file which is in the same package. The first sub file has no issue whatsoever importing the second sub file. The main file also has no issue importing the first sub file. However, when I put it all together and run the main file, Python thinks that the second sub file doesn't exist, which I find strange. I've simplified and visualised my problem with an example below: I have the following file hierarchy: test_package\ __init__.py main_file.py test_sub_package\ __init__.py subfile1.py subfile2.py main_file code: import test_sub_package.subfile1 subfile1 code: import subfile2 subfile2 code: def get_string(): return ("Hello, World!") So, I would expect main_file to import subfile2 via subfile1. However this doesn't seem to be the case because I get an error: Traceback (most recent call last): File "...\Test\main_file.py", line 1, in &lt;module&gt; import test_package.subfile1 File "...\Test\test_sub_package\subfile1.py", line 1, in &lt;module&gt; import subfile2 ModuleNotFoundError: No module named 'subfile2' I was a little surprised that I got this error before I even attempted to call the functionality in subfile2. Either way, I'm confused why this doesn't work. Am I just doing something stupid here or am I trying to do something Python fundamentally doesn't support. If anyone can give me a solution it would be most appreciated. I suspect this is probably a duplicate but I couldn't find an answer to my specific problem. So, sorry in advance.
answer count: 2
has title: How to import a file from a package which is importing another file from the same package
has comment: http://stackoverflow.com/comment/82200464
linked to: http://stackoverflow.com/q/14132789

http://stackoverflow.com/comment/82178875
score: 0
type: Comment
has text: Typically one would use `global` in a function to identify a variable outside the scope of that function which he would want to be able to write to. By default, all variables (global and local) are readable, but only local variables are writeable. So, if you try to assign to a variable, it assumes it is local. That's why trying to assign to a global variable fails by default: Python is looking for a local, writeable variable by that name and doesn't find one. The `global` statement tells Python that you want to be able to assign to an external variable that would otherwise be 'missing'.
type: QuestionComment
comment on: http://stackoverflow.com/q/47610008

http://stackoverflow.com/q/47671602
has title: Run DJango server from outside of virtual environment by using script
has body: I have created DJango Project inside virtual environment. Let's say virtual environment DJangoProject project name is Mysite I am tired of running ./manage.py runserver everytime so that I wanted to automate running server when I was logged into ubuntu.I tried many ways but was always failing to access the path of virtual environment. So help me to run manage.py runserver from outside of virtual environment using bash or shell scripting. any help can be appreciate!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47671696
has answer: http://stackoverflow.com/a/69909415
tagged with: django
tagged with: python
tagged with: manage.py
score: 3
has answer: http://stackoverflow.com/a/47673367
tagged with: bash
tagged with: virtual-environment
answer count: 3
downvote count: 1
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/a/47729712
answers question: http://stackoverflow.com/q/47619814
type: Answer
has body: You need to preserve user_options from the class install: class vboxcustom(install): user_options = install.user_options + [ ("disk-path=", "d", "Location where vbox disk files will be stored."), ]
has comment: http://stackoverflow.com/comment/82552337
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82467068
accepted answer of: http://stackoverflow.com/q/47619814
has comment: http://stackoverflow.com/comment/82552886

http://stackoverflow.com/comment/82299842
has text: @AdamJensen: Automating it depends on the scale of usage. At the simplest considering it scheduling on 'Windows Scheduler'. You can control the time/days your scripts needs to run.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47654588

http://stackoverflow.com/comment/82284168
has text: Do you know the 2 functions you define are never called?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47662410
score: 1

http://stackoverflow.com/q/47618321
has answer: http://stackoverflow.com/a/47618565
tagged with: dataframe
tagged with: python
has title: How do I iterate over a dataframe with non-integer values in python
has body: I'm very new to python and am trying to to iterate a dataframe with values from two dataframes. For example: Dataframe A(dfA) looks like this and gives me the values that I need to iterate with. NP 1:123 5:657 4:789 Dataframe B(dfB) looks like this DataframeB From the values in Dataframe A I want to iterate over columns in Dataframe B and if the value matches then copy the entire column to Dataframe C (dfC). I have 1500 columns and hence cannot do this manually. I am currently using this code to accomplish this with no luck. for ip in dfA.values: dfC[dfA.iloc[ip]]= dfB[dfA.iloc[ip]] This code gives the following error: ValueError: invalid literal for int() with base 10: '1:2234' How do I accomplish this?
tagged with: pandas
score: 0
answer count: 1
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/82043197
type: QuestionComment
has text: The ``socket-user`` option was only added in 4.4.1. The latest version is 4.5.22.
score: 0
comment on: http://stackoverflow.com/q/47542260
type: Comment

http://stackoverflow.com/comment/82241223
comment on: http://stackoverflow.com/a/47637468
type: AnswerComment
score: 0
has text: Thanks Furas! But the number of rows/columns won’t always be the same. Is it possible to adjust this so it works in those cases? Thanks
type: Comment

http://stackoverflow.com/comment/82294596
type: AnswerComment
comment on: http://stackoverflow.com/a/47657361
type: Comment
score: 0
has text: check my update section, you have missed few things.

http://stackoverflow.com/q/47692386
has answer: http://stackoverflow.com/a/47694170
answer count: 1
tagged with: scikit-learn
score: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82347333
has comment: http://stackoverflow.com/comment/82346176
tagged with: python
has comment: http://stackoverflow.com/comment/82344015
has comment: http://stackoverflow.com/comment/82345697
tagged with: numpy
type: AnsweredQuestion
has title: How do I view model.feature_importances_ output with the names of the features?
has body: I've built a DecisionTreeClassifier model in python and would like to see the importance of each feature. As I'm using sklearn I've converted all my classes to numbers. Here's how I've imported the data: raw_data = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv') no_na_df = raw_data.dropna(how='any') after getting rid of NAs I created my DF for numeric conversion: numeric_df = no_na_df.copy() cols = ['Platform','Genre','Publisher','Developer','Rating'] numeric_df[cols] = numeric_df[cols].apply(lambda x: pd.factorize(x)[0]+1) Once that's done, I created the test and train split: X = numeric_df.drop(['Name','Global_Sales_Bin','Global_Sales','NA_Sales','EU_Sales','JP_Sales','Other_Sales'], axis = 1) y = numeric_df['Global_Sales_Bin'] X = np.array(X) y = np.array(y) X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0) ran the model etc, got my results, and then I wanted to see the importance of each feature: model.feature_importances_ which output this: array([ 0.08518705, 0.07874186, 0.06322593, 0.08446309, 0.08410844, 0.08097326, 0.07744228, 0.1851621 , 0.23597441, 0.02472158]) I don't know how to match up the features in the model with the numbers above. both 'X' and 'model' are stored as numpy arrays and the orginal dataframe has been cut down to fit the model so the features don't align properly. I think I might have to use a for loop and zip, but not sure how. Thanks.
accepted answer: http://stackoverflow.com/a/47694170
upvote count: 2

http://stackoverflow.com/comment/82074830
has text: Thank you all for responding to this thread. @Scott Boston, I want a date and time format output.
score: 0
comment on: http://stackoverflow.com/q/47556851
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82330070
type: Comment
comment on: http://stackoverflow.com/a/47685000
type: AnswerComment
has text: @JAG2024 Yw~ :-), btw: consider the speed , op3 should be the fast
score: 1

http://stackoverflow.com/comment/82284983
has text: This works! Thank you. I have a question about the finding of r numerator part. Is this taking the sum of each product from the same position (position of i) in each list? Wouldn't this be an issue since the list contains strings and not floats/ints? Why is it that it does not need mapped out first?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47661728

http://stackoverflow.com/a/47684994
answers question: http://stackoverflow.com/q/47684961
downvote count: 0
upvote count: 1
has body: Using stack df.set_index('Name').stack().reset_index(1,drop = True) Name apple 2016 W1 orange 2016 W1 orange 2017 W2 banana 2016 W2 banana 2017 W3 pear 2016 W3 pear 2016 W4 pear 2016 W5 melon 2016 W2 melon 2016 W4 melon 2017 W5 melon 2017 W6 melon 2017 W7 dtype: object Or using melt with some cleaning df.melt(id_vars='Name').sort_values('Name').dropna()
score: 1
type: Answer

http://stackoverflow.com/a/47609561
has comment: http://stackoverflow.com/comment/82179671
has comment: http://stackoverflow.com/comment/82178787
type: Answer
has comment: http://stackoverflow.com/comment/82180826
has comment: http://stackoverflow.com/comment/82179763
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82178576
has comment: http://stackoverflow.com/comment/82179115
accepted answer of: http://stackoverflow.com/q/47609265
has body: From the quick look it appears that in the upper code snippet you're forgeting to divide by N. It's a math probelm, not a code problem. In general, if you're after spectra/power spectra use a WOSA(=overlapped segment averaging) method that applies window functions and averages if the sample size allows it. The welch method is included in scipy.signals, you should explore the scipy.signal library as it is extremely convenient in signal analysis. For your datasets following code should work: from scipy.signal import welch plt.figure() for dataset in [Bx, By]: dataset = np.asarray(dataset) freq, psd = welch(dataset, fs=dataset.size/300, return_onesided=True) plt.semilogy(freq, psd/2) Note the psd is divided by 2 for return_onesided, if False division by 2 is not required. Hope this helps to produce good looking graphs. Above plots the power spectral density. Pass an argument scaling='spectrum' in case you want power spectra instead of power spectral density. You can also pass arguments for window functions, the default is hanning but it includes most common windows like blackman, hamming, boxcart etc. You can find more about this at https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.welch.html
downvote count: 0
has comment: http://stackoverflow.com/comment/82178992
has comment: http://stackoverflow.com/comment/82178296
has comment: http://stackoverflow.com/comment/82178926
has comment: http://stackoverflow.com/comment/82177759
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82179997
has comment: http://stackoverflow.com/comment/82180506
answers question: http://stackoverflow.com/q/47609265
has comment: http://stackoverflow.com/comment/82178374
has comment: http://stackoverflow.com/comment/82180403

http://stackoverflow.com/q/47592755
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47592843
linked to: http://stackoverflow.com/q/25330959
has comment: http://stackoverflow.com/comment/82142639
has comment: http://stackoverflow.com/comment/82156177
duplicate of: http://stackoverflow.com/q/25330959
duplicate of: http://stackoverflow.com/q/18448469
has answer: http://stackoverflow.com/a/47592844
linked to: http://stackoverflow.com/q/18448469
favorite count: 0
tagged with: selection
type: Question
tagged with: numpy
has title: Python excluding indexes from array
answer count: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82142680
tagged with: arrays
score: -3
has body: I have an array a=[0, 10, 20, 30, 40, 50, 60] I selected the 2nd and 3rd element with a[[1,2]] obtaining array([10, 20]) How do I select the other elements of a except the elements I've already selected? That is, I want to obtain: array([0, 30, 40, 50, 60]) Logically, should be something like a[![1,2]]

http://stackoverflow.com/a/47584164
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47583282
type: Answer
accepted answer of: http://stackoverflow.com/q/47583282
has body: If you want to know the available attributes and methods of a list, you can print the online help: help(list) If you want the documentation of a method, you can do, for instance: help(list.append) If you want the number of items you can use Len function: l = [True, None, "Hi", 5, 3.14] print("Length of the list is {0}".format(len(l))) # -&gt; Length of the list is 5 If you want the memory size of your list reference, you can try sys.getsizeof function: import sys print(sys.getsizeof(l)) # -&gt; 104 For the memory size of the items, just sum the individual sizes: print(sum(sys.getsizeof(i) for i in l)) # -&gt; 147 To list the type of each item, use the type function: for item in l: print(type(item)) You get: &lt;class 'bool'&gt; &lt;class 'NoneType'&gt; &lt;class 'str'&gt; &lt;class 'int'&gt; &lt;class 'float'&gt;

http://stackoverflow.com/a/47625960
downvote count: 0
has body: In Python 3 __cmp__ is deprecated. For sorting use __lt__ instead: class Student(object): def __init__(self, name, mark): self.name = name self.mark = mark def __lt__(self, other): return self.name &lt; other.name def __repr__(self): return self.name student_list = [ Student(name="cccc", mark=10), Student(name="aaaa", mark=5), Student(name="dddd", mark=7) ] print(sorted(student_list)) # [aaaa, cccc, dddd]
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47625920
type: Answer

http://stackoverflow.com/comment/82080315
score: 0
comment on: http://stackoverflow.com/q/47560476
has text: Is that the *actual* error message, with `__int__` instead of `__init__`, and literally `< Something >` instead of a module name??? We are expecting you to copy & paste error messages, so that we can see *exactly* what is going wrong.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82298733
comment on: http://stackoverflow.com/q/47669582
score: 0
type: Comment
type: QuestionComment
has text: Well then, it seems that `'HRYS'` and `'WAVS'` are *not directories*.

http://stackoverflow.com/q/47583532
score: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82124830
type: UnansweredQuestion
has title: Numpy dotproduct weird behaviour
has body: I am using python3.5 and i have question: Why np.dot() is behaving like this? &gt;&gt; a = np.array([[1,2,3,4]]) &gt;&gt; b = np.array([123]) &gt;&gt; np.dot(a,b) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; ValueError: shapes (1,4) and (1,) not aligned: 4 (dim 1) != 1 (dim 0) &gt;&gt;np.dot(b,a) array([123, 246, 369, 492])
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/47583631
has answer: http://stackoverflow.com/a/47583628

http://stackoverflow.com/comment/82348707
has text: Problem has solved with restarting the kernel) Thank you!
score: 1
comment on: http://stackoverflow.com/a/47693797
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47559157
upvote count: 1
has body: There are multiple optimization possibilities. I assume all vectors are Numpy objects. move e/(hc) out of the sum replace WaveL[i+1]-WaveL[i] by numpy.diff use numpy.dot to calculate the inner products of vectors (you'll need two calls) Numpy is going to be much more efficient than the explicit loop.
score: 1
answers question: http://stackoverflow.com/q/47558902
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82112037
score: 1
type: QuestionComment
type: Comment
has text: Could you update the question with the code you have tried so far?
comment on: http://stackoverflow.com/q/47577245

http://stackoverflow.com/q/47625859
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Perform update query after delete in django cbv
score: 0
has body: I'm trying to update other table after successful delete of of data. Below is my views.py class AttendeeDeleteView(DeleteView): model = Attendee success_url = reverse_lazy('index') def get_form_kwargs(self): id = self.kwargs['id'] # get value of enr Payment.objects.filter(pk=id).update(registered=0) In my urls.py url(r'^delete/(?P&lt;pk&gt;\d+)$', AttendeeDeleteView.as_view(template_name="includes/attendee_delete.html"), name='attendee_delete',), My Current code successfully delete the item but failed to update the other table. my model class Payment(models.Model): id = models.AutoField(primary_key=True) payee = models.CharField(max_length=200, blank=True, null=True) contact = models.CharField(max_length=200,blank=True, null=True) batch = models.CharField(max_length=200, null=True, blank=True) ticketNumber = models.CharField(max_length=200) ticketType = models.CharField(max_length=200, choices=TICKET_CHOICES, default='paid') date = models.DateField('Date Paid (MM/DD/YYYY)', max_length=200, null=True, blank=True) remarks = models.CharField(max_length=200 ,blank=True, null=True) registered = models.BooleanField(default=False) def __str__(self): return self.payee class Attendee(models.Model): id = models.AutoField(primary_key=True) payment = models.OneToOneField(Payment, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200) batch = models.CharField(max_length=200, blank=True, null=True) department = models.CharField(max_length=200, choices=DEPT_CHOICES, default='') remarks = models.CharField(max_length=200, blank=True, null=True) UPDATE 1: I followed this came up with def get(self, request, *args, **kwargs): id = kwargs['pk'] # get value of enr context = Payment.objects.filter(pk=id).update(registered=0) return self.render_to_response(context) but it returned context must be a dict rather than int.
accepted answer: http://stackoverflow.com/a/47625924
has answer: http://stackoverflow.com/a/47625924
type: Question
answer count: 1

http://stackoverflow.com/q/47584306
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82126357
has title: Don't understand why these bitwise operations aren't working
tagged with: bitwise-operators
favorite count: 0
has comment: http://stackoverflow.com/comment/82154881
tagged with: zero
type: Question
accepted answer: http://stackoverflow.com/a/47585027
has answer: http://stackoverflow.com/a/47585027
tagged with: python
has comment: http://stackoverflow.com/comment/82145891
score: -2
has body: i wrote this simple code: bitwise operators. The output is very strange. If I change bitwise operation (mask) from 1&lt;&lt;i to 1&gt;&gt;i and is always 0. See output. reg=31272 #binreg=111101000101000 print bin(reg) for i in range(0,15): mask=1&lt;&lt;i c=reg &amp; mask print "i:", i ,"c:", c ,"-", bin(c) Output: bitwise_little_endian(): 0b111101000101000 i: 0 c: 0 - 0b0 i: 1 c: 0 - 0b0 i: 2 c: 0 - 0b0 i: 3 c: 8 - 0b1000 i: 4 c: 0 - 0b0 i: 5 c: 32 - 0b100000 i: 6 c: 0 - 0b0 i: 7 c: 0 - 0b0 i: 8 c: 0 - 0b0 i: 9 c: 512 - 0b1000000000 i: 10 c: 0 - 0b0 i: 11 c: 2048 - 0b100000000000 i: 12 c: 4096 - 0b1000000000000 i: 13 c: 8192 - 0b10000000000000 i: 14 c: 16384 - 0b100000000000000 bitwise_big_endian(): 0b111101000101000 i: 0 c: 0 - 0b0 i: 1 c: 0 - 0b0 i: 2 c: 0 - 0b0 .... ....
answer count: 1

http://stackoverflow.com/comment/82320809
type: QuestionComment
has text: The extension will be built with distutils. The library will not. Do you know how to build a C library?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47563101

gmail
type: Tag
tags question: http://stackoverflow.com/q/47629308
tags question: http://stackoverflow.com/q/47635162
tag name: gmail
tags question: http://stackoverflow.com/q/47666883

http://stackoverflow.com/comment/82322867
score: 0
has text: show your code.
comment on: http://stackoverflow.com/q/47681774
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82142680
score: 0
type: Comment
type: QuestionComment
has text: Tag `numpy` if that is what you're asking about.
comment on: http://stackoverflow.com/q/47592755

http://stackoverflow.com/a/47550150
type: Answer
score: 2
downvote count: 0
has body: You are initializing the dictionary for each loop. Please initialize the dictionary outside of for loop. Or you can use list to store each dictionary using the following code. exDatas = [] for i in range(3, lastRow): exData = {} exData["param1"] = sheet.cell(row=i, column=1).value exData["param2"] = float(sheet.cell(row=i, column=2).value) exData["param3"] = float(sheet.cell(row=i, column=3).value) exData["param4"] = float(sheet.cell(row=i, column=4).value) exData["param5"] = float(sheet.cell(row=i, column=5).value) exData["param6"] = float(sheet.cell(row=i, column=6).value) exData["param7"] = float(sheet.cell(row=i, column=7).value) exData["param8"] = float(sheet.cell(row=i, column=8).value) exData["param9"] = float(sheet.cell(row=i, column=9).value) exData["param10"] = float(sheet.cell(row=i, column=10).value) exDatas.append(exData)
answers question: http://stackoverflow.com/q/47550041
upvote count: 2
has comment: http://stackoverflow.com/comment/82056881

http://stackoverflow.com/q/47660954
has answer: http://stackoverflow.com/a/47660980
has comment: http://stackoverflow.com/comment/82280982
tagged with: python
has comment: http://stackoverflow.com/comment/82280917
type: AnsweredQuestion
score: 0
has title: Usage of '@@' syntax in python
answer count: 1
upvote count: 1
tagged with: decorator
has body: I ran into the double @@ symbol in the following code: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py I understand that the @ is used as a decorator. But I can't seem to find any information on the use of @@?
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82281098
type: Question
accepted answer: http://stackoverflow.com/a/47660980

http://stackoverflow.com/comment/82239891
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47640568
type: QuestionComment
has text: As @AnkitaGupta asked, will need to see the full `events.models` file because it sounds to me like one of your other models is attempting to make use of `Test` before it gets created but I'm not sure.

http://stackoverflow.com/comment/82396613
has text: Thanks for all your help, i'm appreciated!! When i havea problem i will share it in commands.Btw, i was looking your OOP Button project and i noticed something weird. Your button colors is not defined with RGB or there is any picture to make button colors dodgerblue1,lightskyblue and aquamarine1. Are these colors self defined in python with that special keywords or you just made a trick ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47664205
type: Comment

http://stackoverflow.com/comment/82077689
score: 0
type: Comment
type: QuestionComment
has text: If you want us to help you and also understand you better you must provide a [mcve]
comment on: http://stackoverflow.com/q/47557240

http://stackoverflow.com/comment/82202841
score: 0
comment on: http://stackoverflow.com/a/47619536
type: Comment
type: AnswerComment
has text: Please, add more context to your answer.

http://stackoverflow.com/q/47574798
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: dataframe
tagged with: append
type: Question
accepted answer: http://stackoverflow.com/a/47817345
tagged with: python
has body: I have a case, where I am adding UUID columns to .csv files. At the same time, I am checking source files and comparing them to processed ones - in case there are additional lines in source files, I plan to append those new lines to destination file. Reason why I want to append and not overwrite a file is due to need of keeping UUID of previously processed lines same. So for case of appending lines, I check if row count is same for source and destination file. In case it is not, I create new dataframe with data (from source file) from row number that equals row count in destination file. At that point, I try to append newly created dataframe to destination dataframe, but it keeps failing. I recieve the following error: &gt; RuntimeWarning: '&lt;' not supported between instances of 'int' and &gt; 'str', sort order is undefined for incomparable objects result = &gt; result.union(other) Code that I am using is below: import os, uuid import pandas as pd def process_files(): source_dir = "C:\\Projects\\test\\raw" destination_dir = "C:\\Projects\\test\\processed" for file_name in os.listdir(source_dir): if file_name.endswith((".csv", ".new")): df_source = pd.read_csv(source_dir + "/" + file_name, sep=";") if os.path.isfile(destination_dir + "/" + file_name): df_destination = pd.read_csv(destination_dir + "/" + file_name, sep=",", header=None) if df_source.shape[0] != (df_destination.shape[0]): df_newlines = pd.read_csv(source_dir + "/" + file_name, sep=";", skiprows=df_destination.shape[0], header=None) df_newlines.insert(0, "uu_id", pd.Series([uuid.uuid4() for i in range(len(df_newlines))])) df_destination.append(df_newlines, ignore_index=True) df_destination.to_csv(destination_dir + "/" + file_name, sep=",", header=False, mode="w", index=False) else: continue else: df_source.insert(0,"uu_id", pd.Series([uuid.uuid4() for i in range(len(df_source))])) df_source.to_csv(destination_dir + "/" + file_name, sep=",", header=False, mode="w", index=False) else: continue process_f…
has answer: http://stackoverflow.com/a/47817345
type: AnsweredQuestion
score: 0
has title: Python Pandas append dataframe
tagged with: pandas

http://stackoverflow.com/q/47604046
has comment: http://stackoverflow.com/comment/82167193
accepted answer: http://stackoverflow.com/a/47606831
has comment: http://stackoverflow.com/comment/82168089
upvote count: 2
has comment: http://stackoverflow.com/comment/82167058
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/82167384
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82167295
score: 1
has answer: http://stackoverflow.com/a/47606831
answer count: 1
has comment: http://stackoverflow.com/comment/82168364
has title: Python - Diagonal Match in a 2-Dimensional Array
has body: I need help with diagonal matching in a 2D Array in Python when 3 or more elements are the same. In the scenario below, the "2"'s formulate a diagonal match. Thus, I want to make them "-2" since they form a match. Given [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [3, 1, 2, 0, 0], # 2 at index 2 [1, 2, 1, 0, 0], # 2 at index 1 [2, 3, 3, 0, 0]] # 2 at index 0 Result [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [3, 1,-2, 0, 0], # -2 now at index 2 [1, -2, 1, 0, 0], # -2 now at index 1 [-2, 3, 3, 0, 0]] # -2 now at index 0 I presume they are multiple directions for a diagonal match (from the left/right) so I want to cover those cases. Ideally, I want to do this without importing any module. Thanks (:
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47618620
has body: Just follow the link's redirect, and it will goto the right page. Assume your link is in the url variable. import urllib2 url = "/url?q=https://en.wikipedia.org/wiki/Turtle&amp;sa=U&amp;ved=0ahUKEwja-oaO7u3XAhVMqo8KHYWWCp4QFggVMAA&amp;usg=AOvVaw31hklS09NmMyvgktL1lrTN" url = "www.google.com"+url response = urllib2.urlopen(url) # 'www.google.com/url?q=https://en.wikipedia.org/wiki/Turtle&amp;sa=U&amp;ved=0ahUKEwja-oaO7u3XAhVMqo8KHYWWCp4QFggVMAA&amp;usg=AOvVaw31hklS09NmMyvgktL1lrTN' response.geturl() # 'https://en.wikipedia.org/wiki/Turtle' This works, since you are getting back google's redirect to the url which is what you are really clicking everytime you search. This code, basically just follows the redirect until it arrives at the real url.
has comment: http://stackoverflow.com/comment/82195314
score: 1
has comment: http://stackoverflow.com/comment/82195513
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47618469
has comment: http://stackoverflow.com/comment/82195288
answers question: http://stackoverflow.com/q/47618469
has comment: http://stackoverflow.com/comment/82195553
type: Answer

http://stackoverflow.com/comment/82221104
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47594834
has text: Hey, the code works fine. But I still have an issue: in this https://stackoverflow.com/questions/35445424/surface-and-3d-contour-in-matplotlib thread, there you can see black lines as an wireframe on the surface. How do I get those? My jupyter notebook wont show them, even as I execute the exact same code in the thread
score: 0

http://stackoverflow.com/q/47629149
type: Question
has comment: http://stackoverflow.com/comment/82216373
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47630475
accepted answer: http://stackoverflow.com/a/47630475
type: AnsweredQuestion
downvote count: 0
has title: Host Not Allowed 192...224 even though it is already in my django project
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82217066
favorite count: 0
has body: I have a Django project that I have pushed to docker and then a digital ocean server for live testing in a working environment. In the settings file, I have an IP address from my digital ocean server added to the allowed host portion of the settings file, but I am getting the following error: DisallowedHost at / Invalid HTTP_HOST header: '192...244:8000'. You may need to add '192...244' to ALLOWED_HOSTS. Here is the code I have ALLOWED_HOSTS = ['192...244', 'localhost', '127.0.0.1'] I didn't add the full IP, even though I have the full IP in my files.

http://stackoverflow.com/a/47579761
type: AcceptedAnswer
score: 2
has comment: http://stackoverflow.com/comment/98809418
has comment: http://stackoverflow.com/comment/82131147
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82131628
accepted answer of: http://stackoverflow.com/q/47564523
upvote count: 2
has comment: http://stackoverflow.com/comment/82130657
answers question: http://stackoverflow.com/q/47564523
has body: This should do it: import datetime as dt from datetime import datetime import pandas as pd import pandas_datareader.data as web from openpyxl import load_workbook start = dt.datetime.strptime("8/11/2017", "%m/%d/%Y") end = dt.datetime.today() data_file = pd.ExcelFile('Stocks.xlsx',header=0).parse('Sheet1') #1st sheet #print(data_file) #datafile.columns is the excel's header row with stock 1, stock 2, etc. For example: FB, AAPL, etc. stocks = web.DataReader(data_file.columns, 'yahoo', start, end)'Open','Close' #This creates a panel #print(stocks) #Writes to same workbookbook with data, but different tabs, where each column (Open, Close) is in a differen tab #You can't "append" data to an existing sheet, only overwrite it in full including headers- so can't reuse next day book = load_workbook('Stocks.xlsx') writer= pd.ExcelWriter('Stocks.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) stocks.to_excel(writer) writer.save() Alternatively, you can create new excel with results, where each column (Open, Close) is in a different tab: writer= pd.ExcelWriter('Stock Data.xlsx', engine="xlsxwriter") stocks.to_excel(writer) #,index=False) writer.save() You can even create a new file with new data every day you run it, by specifying name +'xslx' in pd.ExcelWriter where now = datetime.datetime.now() name = 'Opportunistic_leads_' + str(now)[:10] Take a look here: iteratively calling pandas datareader at some ways to transform output of stocks. This will apply when you export the panel to excel. Note that I wasn't able to find a way to append data to an existing excel sheet without overwriting it, but this is as close to what you want as I could do it. FYI, when you export a Panel (which is resulted from DataReader) to excel, it creates each "column" in a new tab as per https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.to_excel.html:
has comment: http://stackoverflow.com/comment/82131017

http://stackoverflow.com/comment/82285160
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47659233
has text: Thank you! How do you know which error to debug when a program like mine has so many errors?
score: 0

http://stackoverflow.com/comment/82132795
comment on: http://stackoverflow.com/q/47587497
type: Comment
type: QuestionComment
score: 0
has text: @Jump3r That's hardly appropriate here. How exactly would regular expressions help? It's just a needless complication.

http://stackoverflow.com/comment/82139047
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47590546
has text: @Goralight thanks, I couldn't find it by myself
type: Comment

http://stackoverflow.com/comment/82192829
score: 0
type: AnswerComment
has text: You shouldn't remove them at all. They are part of your codebase.
type: Comment
comment on: http://stackoverflow.com/a/47616707

http://stackoverflow.com/a/47601252
type: Answer
has comment: http://stackoverflow.com/comment/82164916
has comment: http://stackoverflow.com/comment/82161706
score: 2
has body: After validation, the form data is found in form.cleaned_data dictionary. So you can pass that back to the template and display it as you see fit. from django.shortcuts import render from contracts.forms import GenerateContract # Create your views here. def index(request): return render(request, 'contracts/index.html') def contractview(request): form = GenerateContract() if request.method == "POST": form = GenerateContract(request.POST) if form.is_valid(): form.save(commit=True) return render(request,'contracts/contracts.html',{'form_data': form.cleaned_data}) else: print('ERROR') return render(request,'contracts/contracts.html',{'form':form})
answers question: http://stackoverflow.com/q/47601064
has comment: http://stackoverflow.com/comment/82162053
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47601064

http://stackoverflow.com/comment/82185908
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47612435
has text: They look like this. ['164764.89', '144366.97', '366800.85']
score: 0

http://stackoverflow.com/a/47673489
upvote count: 1
has comment: http://stackoverflow.com/comment/82313236
has body: I do know how to catch exceptions but not this particular one Well, just like with any exception actually: &gt;&gt;&gt; import socket &gt;&gt;&gt; try: ... raise socket.gaierror(3, "wtf") ... except socket.gaierror as e: ... print "got gaiesocket error %s" % e ... got gaiesocket error [Errno 3] wtf If you want to special-case errno 3, just test e.errno: &gt;&gt;&gt; e gaierror(3, 'wtf') &gt;&gt;&gt; e.errno 3
type: Answer
answers question: http://stackoverflow.com/q/47670785
score: 1
downvote count: 0

http://stackoverflow.com/comment/82222681
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47632262
type: QuestionComment
has text: yes, I was redefining sim, which was causing this issue. Its resolved now.

http://stackoverflow.com/a/56362360
has body: I met a different situation with the same error. The problem was that I used the same Model name and field name Incorrect code: class Column(models.Model): ... class ColumnToDepartment(models.Model): column = models.ForeignKey(Column, on_delete=models.CASCADE) Solution: class Column(models.Model): ... class ColumnToDepartment(models.Model): referring_column = models.ForeignKey(Column, on_delete=models.CASCADE)
upvote count: 10
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/135952739
score: 9
answers question: http://stackoverflow.com/q/47620487

http://stackoverflow.com/q/47655805
favorite count: 0
has comment: http://stackoverflow.com/comment/82271303
type: Question
has body: The question: Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to find out how many prime numbers (starting with 2 and going in increasing order with successively higher primes [2,3,5,7,11,13,...]) can be added before exceeding n. Associate this number with the variable k. The code: def is_prime(): i = 2 k = 0 Again = True while Again = True: if total &gt; n: Again = False for x in range(2,n): if x % i == 0: total = total k = k i += 1 else: total += x k += 1 return k
type: UnansweredQuestion
score: -3
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47660108
tagged with: primes
has comment: http://stackoverflow.com/comment/82269819
downvote count: 4
has comment: http://stackoverflow.com/comment/82269791
answer count: 1
has title: Is my code correct for an issue involving prime number tracking and consecutive addition?

http://stackoverflow.com/comment/82119216
comment on: http://stackoverflow.com/a/47580201
type: Comment
type: AnswerComment
has text: Hey, thanks, this seems to come close to what I need. So, as mentioned, I have a whole bunch of variables that have a single value per event, not just `HT_jets` (which itself cannot be assumed to be a number unique to each event -- I have the variable `eventNumber` which can be used for this). When I do as you suggest, it nukes all of my other columns of variables. How should I proceed? Should I have a separate DataFrame for array variables and then try to merge it with a DataFrame for single-value variables?
score: 0

http://stackoverflow.com/a/47605030
upvote count: 1
has comment: http://stackoverflow.com/comment/82168659
has body: You can set the output precision using {:.4f} to keep four digits . &gt;&gt;&gt; pi 3.141592653589793 &gt;&gt;&gt; print("{}".format(pi)) 3.141592653589793 &gt;&gt;&gt; print("{:.3f}".format(pi)) 3.142 &gt;&gt;&gt; print("{:.4f}".format(pi)) 3.1416 &gt;&gt;&gt; print("{:.5f}".format(pi)) 3.14159
answers question: http://stackoverflow.com/q/47604989
has comment: http://stackoverflow.com/comment/82168645
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47604989
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47569850
type: UnansweredQuestion
tagged with: sensors
answer count: 1
tagged with: raspberry-pi3
favorite count: 0
has title: Save sensor data in CSV file by using Raspberry pi3
has comment: http://stackoverflow.com/comment/82097717
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82102089
score: 1
tagged with: python
has body: Could you help me to check whether my python code below is correct for saving data in csv format via raspberry pi3? print("Gyro: %f, %f, %f [deg/s]" % (cgx, cgy, cgz)) print("Accel: %f, %f, %f [Gs]" % (cax, cay, caz)) print("Mag: %f, %f, %f [gauss]" % (cmx, cmy, cmz)) file = open("/home/pi/data_log.csv", "a") if os.stat("/home/pi/data_log.csv").st_size == 0: file.write("Time,Gyro,Accel,Mag\n") while True: now = datetime.now()) print &gt;&gt;f,("%s,%f,%f,%f,%f,%f,%f,%f,%f"%(now.datetime("%Y-%m-%d %H:%M:%S"),cgx,cgy,cgz,cax,cay,caz,cmx,cmy,cgz)) file.flush() time.sleep(5) file.close()
has answer: http://stackoverflow.com/a/47596397
type: Question
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47641149
accepted answer of: http://stackoverflow.com/q/47640468
has body: There is a simpler way to do that, without the overhead of zip() and index(): file = open("ip.txt", "r") for index, line in enumerate(file): print("acl ip" + str(index + 1) + " myip " + line.strip()) print("tcp_outgoing_address " + line.strip() + " ip" + str(index + 1)) even nicer (i think): file = open("ip.txt", "r") tpl = """acl ip{index} myip {ip} tcp_outgoing_address {ip} ip {index}""" for index, line in enumerate(file): print(tpl.format(index=index, ip=line.strip())) and the output will be the same that you request: acl ip1 myip 1.1.1.1 tcp_outgoing_address 1.1.1.1 ip1 acl ip2 myip 2.2.2.2 tcp_outgoing_address 2.2.2.2 ip2 acl ip3 myip 3.3.3.3 tcp_outgoing_address 3.3.3.3 ip3
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82282270
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47640468
upvote count: 1

http://stackoverflow.com/comment/82284283
comment on: http://stackoverflow.com/a/47662485
type: Comment
type: AnswerComment
has text: But why did it work when i type everything like he did and then when i decided to change a model name it brings me up with that error
score: 0

http://stackoverflow.com/a/47645709
type: Answer
has comment: http://stackoverflow.com/comment/82251282
accepted answer of: http://stackoverflow.com/q/47645481
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47645481
upvote count: 1
has comment: http://stackoverflow.com/comment/82251552
has comment: http://stackoverflow.com/comment/82250965
has body: You can get the sums using np.bincount with the weights parameter. If I'm not mistaken np.bincount is O(n) as is the rest of the code below: # get the sums cnts = np.bincount(label.ravel(), a.ravel()) # next two lines get indices of the last occurrence of each label psns = np.full(cnts.shape, -1, dtype=int) psns[label.ravel()] = range(label.size) # now plug the sums at the appropriate positions resflat = np.zeros((a.size + 1,), dtype=a.dtype) resflat[psns] = cnts result = resflat[:-1].reshape(a.shape) result # array([[ 0, 0, 0, 0, 0, 0], # [ 0, 0, 0, 0, 0, 10], # [ 0, 0, 0, 0, 0, 0], # [ 2, 0, 0, 6, 0, 0], # [ 0, 0, 0, 0, 0, 9]])
has comment: http://stackoverflow.com/comment/82251381
has comment: http://stackoverflow.com/comment/82250683

http://stackoverflow.com/a/47726126
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47670856
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47670856
has body: ANSWER try: cnxn = pypyodbc.connect('Driver={ODBC Driver 13 for SQL Server};' 'Server=DESKTOP-C6RS3DO;' 'Database=demo2016;' 'uid=sa;pwd=sa') print('connected &lt;br/&gt;') cursor = cnxn.cursor() except : print("could not connect") cursor.close() cnxn.close()

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/47587708

http://stackoverflow.com/comment/82298861
has text: @NavanChauhan How can help you if you don't tell me what the syntax error is?
type: Comment
comment on: http://stackoverflow.com/a/47668530
score: 0
type: AnswerComment

http://stackoverflow.com/q/47650730
type: AnsweredQuestion
has body: I am completely new to Python and would like to display a progress bar while copying data from one database to another (MongoDB). What I am trying to get is a single progressbar displaying the advancement (percentage) of the copy of a database to another. The copy is working just fine, the problem lies within the update of my progressbar, which gets reprinted every loop. Here is the script : coll_names = db_in.collection_names() db_in_size = db_in.command('dbstats')['dataSize'] bar = progressbar.ProgressBar(max_value=db_in_size).start() for X in X_list: for coll in coll_names: db_out_size = db_out.command('dbstats')['dataSize'] bar.update(db_out_size) db_out[coll].delete_many({'X': X}) data_in = db_in[coll].find({'X': X}) if data_in.count() &gt; 0: db_out[coll].insert_many(data_in) bar.finish() X_list contains strings. This code is certainly not optimized nor formatted the right way to display a single progressbar, but please bear with me. Expected result : Single progressbar on one line Current result : One progressbar print for every iteration Current result : tqdm Thanks in advance for any input you may have.
score: 1
has title: Python - Getting a new print of progressbar every update
answer count: 1
accepted answer: http://stackoverflow.com/a/47651134
upvote count: 1
has comment: http://stackoverflow.com/comment/82262748
favorite count: 0
has answer: http://stackoverflow.com/a/47651134
type: Question
downvote count: 0
tagged with: python
tagged with: progress-bar
has comment: http://stackoverflow.com/comment/82259810

http://stackoverflow.com/comment/82104391
has text: that library is deprecated, you should have used pyrebase instead check this library https://github.com/thisbejim/Pyrebase
comment on: http://stackoverflow.com/q/47553823
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82071080
comment on: http://stackoverflow.com/a/47556833
has text: can you please also include `sum(1 for s in l if len(e.intersection(s)) == 2)` after converting `e` to a `set`? Interested to see how it performs.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47580676
has comment: http://stackoverflow.com/comment/97498244
has comment: http://stackoverflow.com/comment/88697146
answers question: http://stackoverflow.com/q/47579641
downvote count: 0
score: 14
has body: Do: p4 -Ztag -F %clientName% info
upvote count: 14
has comment: http://stackoverflow.com/comment/88697353
has comment: http://stackoverflow.com/comment/135366833
type: Answer
has comment: http://stackoverflow.com/comment/97525972

http://stackoverflow.com/a/47591599
score: 5
has body: numpy.sum returns: An array with the same shape as a, with the specified axis removed. With one axis removed in both cases, you are left with a singleton tuple. 2 axes - 1 specified axis = 1 axis However, passing keepdims as True in both gives different shapes, retaining all the axes in the original array with a corresponding change of length along the specified axis: &gt;&gt;&gt; arr.sum(axis=0, keepdims=True) array([[ 9, 12, 15]]) &gt;&gt;&gt; arr.sum(axis=1, keepdims=True) array([[ 3], [12], [21]])
accepted answer of: http://stackoverflow.com/q/47591481
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82221468
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47591481

http://stackoverflow.com/comment/82108377
has text: @vonludi ohhh that's it!! ok I don't get it why you sometimes need and sometimes you don't but thank you anyway!
score: 0
comment on: http://stackoverflow.com/q/47575469
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82168334
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47604819
has text: @Durand sure. Please cross-reference this discussion with the github issue - I would like to keep track of what is happening. Thanks!

http://stackoverflow.com/comment/82239743
has text: You might find your answer here: [Apply a function to a single column of a csv in Spark](https://stackoverflow.com/questions/40977625/apply-a-function-to-a-single-column-of-a-csv-in-spark)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47640590
score: 0

http://stackoverflow.com/comment/82333524
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47686824
has text: sascha, I'm new in Python, could you help me with the 4 and 5 you pointed?

http://stackoverflow.com/comment/82135788
type: QuestionComment
comment on: http://stackoverflow.com/q/47589232
type: Comment
score: 0
has text: Are you working with windows or linux, in linux you should start from the command line. In windows you can change the extention to .pyw: https://stackoverflow.com/questions/34739315/pyw-files-in-python-program

http://stackoverflow.com/q/47612424
tagged with: midi
has body: When I run midi.write_midifile("example.mid", pattern) I get the error Traceback (most recent call last): File "C:\Users\guest01\Desktop\python\audio stuff\onset test.py", line 33, in &lt;module&gt; midi.write_midifile("example.mid", pattern) File "C:\Users\guest01\AppData\Roaming\Python\Python36\site-packages\midi\fileio.py", line 162, in write_midifile return writer.write(midifile, pattern) File "C:\Users\guest01\AppData\Roaming\Python\Python36\site-packages\midi\fileio.py", line 110, in write self.write_track(midifile, track) File "C:\Users\guest01\AppData\Roaming\Python\Python36\site-packages\midi\fileio.py", line 124, in write_track buf += self.encode_midi_event(event) File "C:\Users\guest01\AppData\Roaming\Python\Python36\site-packages\midi\fileio.py", line 152, in encode_midi_event ret += bytearray(event.data) TypeError: an integer is required My code looks like this: with open("new.csv", newline="") as csvfile: file = csv.reader(csvfile) for row in file: if row: print(''.join(row)) ticktime = int(float(''.join(row))*1000) note = midi.NoteOnEvent(tick=ticktime, velocity=100, pitch=random.choice(notes)) track.append(note) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) print(pattern) midi.write_midifile("example.mid", pattern) I'm not sure why it says an integer is required please could anyone suggest a solution?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82183183
has comment: http://stackoverflow.com/comment/82183465
has comment: http://stackoverflow.com/comment/82184221
type: UnansweredQuestion
tagged with: python
has title: Using python midi for python 3 requires an integer when writing to disk?
score: 0
answer count: 0

flask-restful
tags question: http://stackoverflow.com/q/47590906
tags question: http://stackoverflow.com/q/47632838
type: Tag
tags question: http://stackoverflow.com/q/47660378
tag name: flask-restful
tags question: http://stackoverflow.com/q/47670914

http://stackoverflow.com/a/47688687
accepted answer of: http://stackoverflow.com/q/47675138
score: 2
upvote count: 2
downvote count: 0
has body: I got this working by overriding get_backoff_time() of Retry class class RetryRequest(Retry): DEFAULT_METHOD_WHITELIST = frozenset([ 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE']) def __init__(self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, max_backoff=60): super(RetryRequest, self).__init__(total=total, connect=connect, read=read, redirect=redirect, status=status, method_whitelist=method_whitelist, status_forcelist=status_forcelist, backoff_factor=backoff_factor, raise_on_redirect=raise_on_redirect, raise_on_status=raise_on_status, history=history, respect_retry_after_header=respect_retry_after_header) self.backoff_max = max_backoff def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None, reversed(self.history)))) if consecutive_errors_len &lt;= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.backoff_max, backoff_value) and using this class instead of Retry session = session or requests.Session() retry = RetryRequest( total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, method_whitelist=method_whitelist, max_backoff=max_backoff # in my case 60 ) adapter = HTTPAdapter(max_retries=retry) session.mount(BASE_URL, adapter) return session
answers question: http://stackoverflow.com/q/47675138
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/47629865
has comment: http://stackoverflow.com/comment/82220357
accepted answer of: http://stackoverflow.com/q/47629019
score: 0
has body: The Python process will inherit the stdin of its parent process (the shell running the batch script) so just defer the task of reading it to your Python program instead — where it will be much easier to do.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47629019
type: Answer

http://stackoverflow.com/comment/82353120
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47695237
has text: Your approach of calling `reverse(item)` isn't going to work for URL patterns that have arguments. You can't simply call `reverse('post_detail')`, you need a primary key e.g. `reverse('post_detail', args=[5])`.
score: 1

pydub
tags question: http://stackoverflow.com/q/47599106
tags question: http://stackoverflow.com/q/47596007
tag name: pydub
type: Tag

http://stackoverflow.com/a/47579403
upvote count: 1
score: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/82145604
has body: You can use pandas as a clean interface between the two worlds. As an example : import numpy as np import pandas as pd index = np.arange(10) values = np.random.rand(10,2) names= ['a','b'] df= pd.DataFrame(values,index,names) In [217]: df Out[217]: a b 0 0.259787 0.313253 1 0.449761 0.363243 2 0.916497 0.204994 3 0.168862 0.718966 4 0.248206 0.106945 5 0.709540 0.902679 6 0.413442 0.933243 7 0.568530 0.427908 8 0.926834 0.967445 9 0.175371 0.952798 You can then use df.to_sql which will tranfer you data in a SQL database.
answers question: http://stackoverflow.com/q/47571343
type: Answer
has comment: http://stackoverflow.com/comment/82140658

greatest-n-per-group
tag name: greatest-n-per-group
tags question: http://stackoverflow.com/q/47603191
type: Tag

http://stackoverflow.com/a/47607543
has body: Please add "name" attribute to all the HTML input elements matching your form fields, which I think will solve your problem. An example: &lt;input id="email" class="form-control" name="email" placeholder="ایمیل" type="email"&gt; The above input element is given name="email", which matches your form email field. Once you do this for all the input elements, you should receive the data in request.POST and the form will work as expected.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82173567
answers question: http://stackoverflow.com/q/47607297
has comment: http://stackoverflow.com/comment/82173526

http://stackoverflow.com/a/47663166
answers question: http://stackoverflow.com/q/47663040
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47663040
has body: I think you need a couple of things here. First is a custom lookup function: def lookup(obj, keys): for k in keys: obj = obj[k] return obj Then a dictionary of keys to key list tuples: keys = {'ID01': (0,'child',0,'text'), 'ID02': (1,'group')} then you can do this: lookup(x, keys['ID01']) # returns 'ass'
score: 3
upvote count: 3

http://stackoverflow.com/q/47614963
has title: How to confidently validate object detection results returned from Google Cloud Vision
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: machine-learning
has body: I am trying to build a program that can correctly and confidently identify an object with Google Cloud Vision (denoted as GCV henceforth). The results returned are correct most of the times with a certain accuracy score for each label, as such. { "banana": "0.92345", "yellow": "0.91002", "minion": "0.89921", } The environment I am working with has diverse set of lightning condition and objects are expected to placed in random position. When an object with different position is placed, the results returned from GCV will be slightly different because a different image is queried. For example, { "banana": "0.82345", "lemon": "0.82211", "yellow": "0.81102", "minion": "0.79921", } My program is designed in a way that, when object banana is detected with accuracy greater than certain value, then next action will be dispatched. There are 3 clusters of object types. For instance, banana goes to container A, apple goes to container B and orange goes to container C. When I present my work to my professor, he questioned that how can I confidently define and validate the threshold value for each item, as respected to its respective cluster. I tried to obtain a mean score of banana by training hundreds of banana images but eventually I found that this is probably not the correct way of defining a threshold. My professor suggested to use K Nearest Neighbour to find similarity of those images but isn't that already a part of GCV? Even if what he suggested is correct, what is the correct approach to train a post GCV classifier, with the limited data returned from GCV?
favorite count: 0
type: Question
tagged with: google-cloud-vision
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/47621369
tagged with: knn

http://stackoverflow.com/a/47630082
downvote count: 0
answers question: http://stackoverflow.com/q/47629877
upvote count: 4
has body: You may want to put ''' or """ around the string since you have both ' and ". import subprocess COMMAND = '''"df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 &gt;= 80) {printf "Warning! Space usage is %d%%", $5}}"''' subprocess.call(COMMAND, shell=True) There also seems to be a relevant answer already for this as well: awk commands within python script
type: Answer
has comment: http://stackoverflow.com/comment/82219010
score: 4
has comment: http://stackoverflow.com/comment/82218431

http://stackoverflow.com/a/47648294
has body: You can use your approach with minor modifications: def digit_sum(n): if n&lt;10: return n return (digit_sum(n//10) + n%10 - 1) % 9 + 1 Or ignoring the recursion requirement: def digit_sum(n): return n if n&lt;10 else (n-1) % 9 + 1 Or even shorter (thanks @thanasisp): def digit_sum(n): return n and n%9 or 9
downvote count: 0
has comment: http://stackoverflow.com/comment/82255110
has comment: http://stackoverflow.com/comment/82255800
answers question: http://stackoverflow.com/q/47647797
upvote count: 1
has comment: http://stackoverflow.com/comment/82255488
score: 1
has comment: http://stackoverflow.com/comment/82254852
type: Answer

http://stackoverflow.com/comment/82248004
comment on: http://stackoverflow.com/q/47644660
has text: Save yourself with `np.nanmean`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82136224
type: Comment
type: AnswerComment
has text: I see. In the example with 20 other pages, will that data still be appended in the csv. Or will it all overwrite each other.
comment on: http://stackoverflow.com/a/47589536
score: 1

http://stackoverflow.com/comment/82118189
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47580480
has text: You should probably start by learning basic Python syntax, see e.g. https://sopython.com/wiki/What_tutorial_should_I_read%3F

http://stackoverflow.com/q/47635626
has title: How to create mysite.wsgi file?
accepted answer: http://stackoverflow.com/a/47635694
score: 7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47635694
has body: I am following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html to setup django with nginx and uwsgi. But I am confused about this line: uwsgi --http :8000 --module mysite.wsgi In the tutorial there's nothing about mysite.wsgi file. What should be the content of this file?
upvote count: 7
tagged with: uwsgi
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82229117
tagged with: nginx
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47586491
upvote count: 2
has title: How to loop twice over a list in Python
tagged with: python
has body: I have a string containing CSV content. I turned it into a list like so: from StringIO import StringIO import csv f = StringIO(list_csv) my_list = csv.reader(f, delimiter=',') Now I want to loop twice over the list, but the second time I try to loop, the code goes through as if the list was empty: for item in my_list: code = item[1] print "code: "+code for item in my_list: desc = item[2] print "desc: "+desc (this code is simplified for demonstration purposes, I can't combine execution in a single loop) I figured the list is still attached to the StringIO, and when it's done looping it's done reading, so it won't read again. Is there a one-liner to transform that into a regular list in the memory, that I could loop several times? I feel like running a loop manually copying values is reinventing the wheel.... but I can do that if there's no other option. Just asking for something less lengthy code-wise. Thanks!
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47588478
answer count: 3
tagged with: for-loop
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82130612
possible better answer: http://stackoverflow.com/a/47587040
accepted answer: http://stackoverflow.com/a/47586508
favorite count: 0
has answer: http://stackoverflow.com/a/47586508
has answer: http://stackoverflow.com/a/47587040
type: Question
has comment: http://stackoverflow.com/comment/82165871

http://stackoverflow.com/comment/82045153
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47543947
has text: Possible duplicate of [Convert an image RGB->Lab with python](https://stackoverflow.com/questions/13405956/convert-an-image-rgb-lab-with-python)

http://stackoverflow.com/q/47592936
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82143043
tagged with: python
type: Question
answer count: 1
has title: Python Parsing JSON With Strange Format
accepted answer: http://stackoverflow.com/a/47593026
has body: I'm not really sure what to call this it might be a fairly standard JSON format but I've not encountered it before. Simplified example: stock: { 1223581: { shoe_id: 1788, id: 123 } } My standard would be something like: for item in json_data['stock']: print item['shoe_id'] But the integer (the 1223581 in this example) is dynamic and it's throwing me. I've tried: print item[item]['shoe_id'] Since item[item] was dumping the integer. Also tried: print item[0]['shoe_id'] I could parse out anything before the ':' and parse it that way but that seems like an ugly fix to what I imagine would be a straightforward problem. Any suggestions would be much appreciated.
has answer: http://stackoverflow.com/a/47593026
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47557385
score: 1
has answer: http://stackoverflow.com/a/47563396
has comment: http://stackoverflow.com/comment/82073568
tagged with: conda
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/82083168
type: Question
upvote count: 1
accepted answer: http://stackoverflow.com/a/47563396
has comment: http://stackoverflow.com/comment/82073092
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82081567
favorite count: 0
has body: I've created a conda environment: $ conda create --name py3 matplotlib scipy astropy photutils Everything installed properly, including the photutils package that is installed from the http://ssb.stsci.edu/astroconda channel. Now I activate the environment and open a Jupyter notebook: $ source activate py3 (py3) $ jupyter notebook With py3 as the Default environments, and photutils installed I open a new notebook that uses the Default kernel and attempt to load photutils which will not work. What is going on here? The only thing that I find strange is that the name of the photutils package is shown as http://ssb.stsci.edu/astroconda::photutils0.4 by Jupyter in the Conda tab. Is this the issue? If so, how can I fix this?
type: AnsweredQuestion
downvote count: 0
has title: Jupyter notebook can't load installed package in conda environment

http://stackoverflow.com/comment/82229490
has text: Why dont you just catch common exception and then check it in finally block or in catch block only?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47635828

http://stackoverflow.com/a/54511614
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47586526
has body: You have included the $...that stands for the prompt. Copy-paste the commands to your console without the initial symbol $. &ndash;&nbsp;thanasisp
type: Answer

http://stackoverflow.com/q/47615802
type: Question
has title: aws lambda python function requests URL errors
has comment: http://stackoverflow.com/comment/82208105
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: url
has comment: http://stackoverflow.com/comment/82221301
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82244876
has comment: http://stackoverflow.com/comment/82200306
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82206634
has comment: http://stackoverflow.com/comment/82193229
has comment: http://stackoverflow.com/comment/82193220
has body: New to Lambda and trying to figure out something basic. Have a function that is making calls to an external REST server. I can run this Python code on my local test system without issue: payload = {'userName': user_name, 'password': password} r = requests.post(api_base + "/session", data=json.dumps(payload), headers={'accept': 'application/json', 'Content-Type': 'application/json'} ) But when i run it in lambda I get odd errors from the my log message that prints out the exception in CloudWatch (obscured my URL): No connection adapters were found for '""/session' If I hard-code the URL then it works fine. Is there some problem with forming the URL in Python that perhaps has different behaviors between the Python versions (I'm using 2.7.14)? The quoting in the exception string that I logged makes me believe that string concatenation is working differently between systems. I'm was also having a horrible time loading zip files and editing in the browser today but it seems like it perhaps is related to some recent changes effecting Chrome since when i switch to Explorer things work fine. Here is more of the relevant code: try: # Get session key payload = {'userName': user_name, 'password': password} if DEBUG: print("api_base = ", api_base, ", full url = ", api_base + "/session") r = requests.post(api_base + "/session", data=json.dumps(payload), headers={'accept': 'application/json', 'Content-Type': 'application/json'} ) # Check return status if r.status_code != 200: if DEBUG: print("HTTP Request error: ", r.status_code, ", data = ", payload, ", api_base = ", api_base) return "" session_data = r.json() return session_data['token'] except requests.exceptions.RequestException as e: print(e) return "" Executing this code on my local machine works just fine. When I run it in lambda I get the following output: api_base = "https://[redacted].com/rest" , full url = "https://[redacted].com/rest"/session No connection adapters were found for '"https://[redacted].com/rest"/session…
tagged with: aws-lambda
linked to: http://stackoverflow.com/q/16337511
has comment: http://stackoverflow.com/comment/82244118
has comment: http://stackoverflow.com/comment/82253719
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/82105448
has text: Just because I created that function, that function is the problem.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47574270

http://stackoverflow.com/q/47577850
tagged with: mocking
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47578140
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: testing
has title: mock python http requests for testing and development
score: 1
tagged with: python
has body: I am using python "requests" and it works great, but now I want to be able to "mock" responses instead of touching the real servers. I am doing this: r = requests.get(self.url+'/somepath', params=payload) In guzzlephp I could do this: $mock = new MockHandler([ new Response(200, ['X-Foo' =&gt; 'Bar'], 'mocked response') ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' =&gt; $handler]); is there something similar here in requests or in python? Thanks!

http://stackoverflow.com/q/47581914
answer count: 1
has title: Replacing two characters in a string with multiple characters?
downvote count: 1
favorite count: 0
has body: So I'm having trouble with this problem I'm trying to solve. Let's say I have a user input a sequence we want to find in a string. But they're allowed to enter 'X' where it will be replaced by 4 characters and search the string. For example if the user enters AXXT, it would search the string for AGCT, AGGT, etc. So this is what I tried to do: y_re = y.replace('X', '[ACGT]') However this does not overlap so I enter AXX and it only gives me AAC. Does anyone know how I can fix this?
type: Question
has comment: http://stackoverflow.com/comment/82121398
tagged with: bioinformatics
has answer: http://stackoverflow.com/a/47589749
tagged with: python
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/82121361
has comment: http://stackoverflow.com/comment/82121554
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82181504
has text: Have you actually set a REDIS_URL environment variable?
comment on: http://stackoverflow.com/q/47611352
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47553931
upvote count: 1
accepted answer: http://stackoverflow.com/a/47554669
has answer: http://stackoverflow.com/a/47554089
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
has title: Numpy Logarithm works for boolean Pandas Series but not for boolean column in Dataframe
has answer: http://stackoverflow.com/a/47554669
score: 1
possible better answer: http://stackoverflow.com/a/47554089
has comment: http://stackoverflow.com/comment/82067790
tagged with: python
has body: Given a dataframe df: &gt;&gt;&gt; df = pd.DataFrame([[1., -2.5, True], [2.5, -1., False]]) &gt;&gt;&gt; df 0 1 2 0 1.0 -2.5 True 1 2.5 -1.0 False &gt;&gt;&gt; df.dtypes 0 float64 1 float64 2 bool dtype: object Taking the logarithm of the first two columns (a Pandas Dataframe) runs without errors. &gt;&gt;&gt; np.log(df.iloc[:,:2]) 0 1 0 0.000000 NaN 1 0.916291 NaN I know that it does not make sense to take the logarithm of a boolean, but if I try to take the logarithm of the three columns (a Pandas Dataframe), I get the following error: &gt;&gt;&gt; np.log(df) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'float' object has no attribute 'log' However, if I try take the logarithm only of the third column, i.e., a Pandas Series, it runs without errors. &gt;&gt;&gt; np.log(df.iloc[:,2]) __main__:1: RuntimeWarning: divide by zero encountered in log 0 0.000000 1 -inf Name: 2, dtype: float16 Just for the sake of curiosity: why there are these two different behaviors when applying numpy.log in a Pandas boolean Series or in a Pandas Dataframe with a boolean column?
tagged with: numpy
answer count: 2
downvote count: 0

http://stackoverflow.com/a/47685214
type: Answer
has comment: http://stackoverflow.com/comment/82330212
has comment: http://stackoverflow.com/comment/82330130
has comment: http://stackoverflow.com/comment/82330258
has comment: http://stackoverflow.com/comment/82330573
has comment: http://stackoverflow.com/comment/82330382
has body: You can use datetime.datetime.strftime() to build any format you want: import datetime time = datetime.datetime.now().strftime("Posted on %d/%m/%y at - %H:%M") print(time) # Posted on 07/12/17 at - 00:29 Read up more on special classes you can use when building your date: strftime() and strptime() Behavior
upvote count: 1
has comment: http://stackoverflow.com/comment/82330268
answers question: http://stackoverflow.com/q/47685174
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82330493
has comment: http://stackoverflow.com/comment/82330346
has comment: http://stackoverflow.com/comment/82330338
accepted answer of: http://stackoverflow.com/q/47685174
has comment: http://stackoverflow.com/comment/82330107
downvote count: 0
score: 1

http://stackoverflow.com/q/47663109
has body: I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error: views.py", line 90, in orderdetails settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found if request.method == 'POST': # Loop through our files in the files list uploaded if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)): os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid)) for image in request.FILES.getlist('files[]'): # Create a new entry in our database new_image = UploadedImages(client_order=client, image=image.name) # Save the image using the model's ImageField settings filename, ext = os.path.splitext(image.name) new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) new_image.save() If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid. if request.method == 'POST': # Loop through our files in the files list uploaded if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)): os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid)) for image in request.FILES.getlist('files[]'): # Create a new entry in our database new_image = UploadedImages(client_order=client, image=image.name) # Save the image using the model's ImageField settings filename, ext = os.path.splitext(image.name) new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image) new_image.save()
type: Question
tagged with: django
tagged with: python
has title: Django ImageField save to locations
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47679421
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47663253

http://stackoverflow.com/q/47660545
linked to: http://stackoverflow.com/q/29847814
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82282001
downvote count: 0
duplicate of: http://stackoverflow.com/q/29847814
upvote count: 1
has comment: http://stackoverflow.com/comment/82287935
favorite count: 0
has body: Whenever I try to install uwsgi on my Mac OS High Sierra it always exits with the following error code. [thread 1][clang] core/xmlconf.o [thread 2][clang] core/dot_h.o [thread 3][clang] core/config_py.o *** uWSGI compiling embedded plugins *** [thread 0][clang] plugins/python/python_plugin.o core/xmlconf.c:9:10: fatal error: 'libxml/parser.h' file not found #include &lt;libxml/parser.h&gt; 1 error generated. I have libxml installed, and other dependencies installed as well. I am using python 3.6, and this error came when I was using python 3.5 as well.
type: Question
has title: Unable to install uwsgi on Mac OS High Sierra using pip3
score: 1
tagged with: python
tagged with: macos
tagged with: uwsgi

http://stackoverflow.com/comment/92358528
has text: @mrry, I am working on the same idea, the dataset that came from the generator can be batched, I mean make it a small batches?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47721194

http://stackoverflow.com/q/47677813
accepted answer: http://stackoverflow.com/a/47678479
tagged with: polar-coordinates
tagged with: matplotlib
has body: I want a polar plot, but with a reduced number of radial (r dimension) ticks. I already tried the suggested solutions from other questions, such as pyplot.locator_params(axis='y', nticks=6) but it did not seem to change anything. I tried using pyplot.gca().set_rticks([...]) but that requires to know the ticks in advance, while I am interested in just setting the maximum number of them. What else could I try in order to reduce the number of ticks (or circles)?
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47678479
has title: How can I reduce or otherwise influence the number of radial ticks in a polar plot?
downvote count: 0
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47562775
tagged with: pandas
has comment: http://stackoverflow.com/comment/82084545
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47563047
has comment: http://stackoverflow.com/comment/82083593
tagged with: scipy
linked to: http://stackoverflow.com/q/45255236
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: correlation
has comment: http://stackoverflow.com/comment/82085148
upvote count: 2
type: UnansweredQuestion
has title: Scipy Spearman Correlation Coefficient is NaN in Some Cases
has comment: http://stackoverflow.com/comment/82085427
has body: I'm computing Spearman correlation coefficients for interviewers. It works for Interviewer_1... I don't understand how Scipy interrupts interviewer_2 as having no correlation/0/nan. import pandas as pd from pandas import DataFrame import scipy.stats df = pd.DataFrame({'Interviewer': ['Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_1','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2','Interviewer_2'], 'Score_1': [-1,-1,-1,1,1,-1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,-1,1,-1], 'Score_2': [1,-1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1] }) df Sample Data Yields: Interviewer Score_1 Score_2 0 Interviewer_1 -1 1 1 Interviewer_1 -1 -1 2 Interviewer_1 -1 -1 3 Interviewer_1 1 -1 4 Interviewer_1 1 1 5 Interviewer_1 -1 1 6 Interviewer_1 -1 -1 7 Interviewer_1 -1 -1 8 Interviewer_1 1 -1 9 Interviewer_1 1 -1 10 Interviewer_2 -1 -1 11 Interviewer_2 -1 -1 12 Interviewer_2 -1 -1 13 Interviewer_2 -1 -1 14 Interviewer_2 -1 -1 15 Interviewer_2 -1 -1 16 Interviewer_2 -1 -1 17 Interviewer_2 -1 -1 18 Interviewer_2 -1 -1 19 Interviewer_2 -1 -1 20 Interviewer_2 -1 -1 21 Interviewer_2 -1 -1 22 Interviewer_2 -1 -1 23 Interviewer_2 1 -1 24 Interviewer_2 -1 -1 25 Interviewer_2 -1 -1 26 Interviewer_2 -1 -1 27 Interviewer_2 -1 -1 28 Interviewer_2 1 -1 29 Interviewer_2 -1 -1 df.groupby('Interviewer').sum() Yields the Sum: Score_1 Score_2 Interviewer Interviewer_1 -2 -4 Interviewer_2 -16 -20 Using Scipy: def applyspearman(row): row['Cor'] = scipy.stats.spearmanr(row['Score_1'], row['Score_2'])[0] return row df = df.groupby('Interviewer').apply(applyspearman) df Interviewer Score_1…
tagged with: python
has comment: http://stackoverflow.com/comment/82084732
score: 2

algorithm
tags question: http://stackoverflow.com/q/47548289
tags question: http://stackoverflow.com/q/47614739
tags question: http://stackoverflow.com/q/47632684
tags question: http://stackoverflow.com/q/47637111
type: Tag
tag name: algorithm
tags question: http://stackoverflow.com/q/47587246
tags question: http://stackoverflow.com/q/47613657
tags question: http://stackoverflow.com/q/47672231
tags question: http://stackoverflow.com/q/47609324
tags question: http://stackoverflow.com/q/47600280
tags question: http://stackoverflow.com/q/47629449
tags question: http://stackoverflow.com/q/47551567
tags question: http://stackoverflow.com/q/47586428
tags question: http://stackoverflow.com/q/47611949
tags question: http://stackoverflow.com/q/47574277
tags question: http://stackoverflow.com/q/47694053
tags question: http://stackoverflow.com/q/47545339
tags question: http://stackoverflow.com/q/47597545
tags question: http://stackoverflow.com/q/47586269
tags question: http://stackoverflow.com/q/47581326
tags question: http://stackoverflow.com/q/47591105
tags question: http://stackoverflow.com/q/47618944
tags question: http://stackoverflow.com/q/47629377
tags question: http://stackoverflow.com/q/47686207
tags question: http://stackoverflow.com/q/47686971
tags question: http://stackoverflow.com/q/47653090
tags question: http://stackoverflow.com/q/47624555
tags question: http://stackoverflow.com/q/47667719

http://stackoverflow.com/q/47555934
has comment: http://stackoverflow.com/comment/82069406
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47559606
has body: How can I require that an abstract base class implement a specific method as a coroutine. For example, consider this ABC: import abc class Foo(abc.ABC): @abc.abstractmethod async def func(): pass Now when I subclass and instantiate that: class Bar(Foo): def func(): pass b = Bar() This succeeds, although func is not async, as in the ABC. What can I do so that this only succeeds if func is async?
tagged with: abstract-class
accepted answer: http://stackoverflow.com/a/47559606
has title: How require that an abstract method is a coroutine?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82069771
has comment: http://stackoverflow.com/comment/82069447
favorite count: 0
has comment: http://stackoverflow.com/comment/82068971
type: Question
tagged with: python-asyncio
score: 10
upvote count: 10
linked to: http://stackoverflow.com/q/36076619
tagged with: python
has comment: http://stackoverflow.com/comment/82069103
has comment: http://stackoverflow.com/comment/82101602

svd
type: Tag
tag name: svd
tags question: http://stackoverflow.com/q/47600963

http://stackoverflow.com/q/47641698
has comment: http://stackoverflow.com/comment/82242672
accepted answer: http://stackoverflow.com/a/47641971
score: -3
has comment: http://stackoverflow.com/comment/82241931
has comment: http://stackoverflow.com/comment/82241849
tagged with: python
has answer: http://stackoverflow.com/a/47641971
has comment: http://stackoverflow.com/comment/82242370
has comment: http://stackoverflow.com/comment/82242204
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82242647
has comment: http://stackoverflow.com/comment/82242345
tagged with: pandas
upvote count: 0
has title: Extracting superset list from pandas dataframe
answer count: 1
downvote count: 3
linked to: http://stackoverflow.com/q/47641286
has comment: http://stackoverflow.com/comment/82242376
favorite count: 0
type: Question
has body: In the foll. dataframe, I have a collection of year and month values as tuples in a list: state alabama [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)] arkansas [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0)] colorado [(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0)] How can I extract a superset list of year and month combinations? In this case, the soln would be: [(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)] I could potentially do it using a for loop but that would be slow, anything more pythonic? Here is what I tried: for row in df: if all(y in row for x, y in df): tmp = row but I get this error: ValueError: too many values to unpack (expected 2)
has comment: http://stackoverflow.com/comment/82242032
has comment: http://stackoverflow.com/comment/82242284

http://stackoverflow.com/a/47574452
accepted answer of: http://stackoverflow.com/q/47574419
answers question: http://stackoverflow.com/q/47574419
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82105689
has body: Select columns with indexing: print (df.columns[[1,3]]) Index(['b', 'd'], dtype='object') df1 = df.loc[df.iloc[:,0] &gt;= 0, df.columns[[1,3]]] print (df1) b d 0 1.609990 -0.133827 1 0.939479 1.169886 2 -1.188042 -1.874766 3 -0.362167 1.415192 6 1.588225 -0.329412 because solution with iloc is not implemented: df1 = df.iloc[df.iloc[:,0] &gt;= 0, [1,3]] NotImplementedError: iLocation based boolean indexing on an integer type is not available but if convert mask to numpy array it working nice: df1 = df.iloc[df.iloc[:,0].values &gt;= 0, [1,3]] print (df1) b d 0 1.609990 -0.133827 1 0.939479 1.169886 2 -1.188042 -1.874766 3 -0.362167 1.415192 6 1.588225 -0.329412 And with columns names it is simplier: df1 = df.loc[df.iloc[:,0] &gt;= 0, ['b','d']] print (df1) b d 0 1.609990 -0.133827 1 0.939479 1.169886 2 -1.188042 -1.874766 3 -0.362167 1.415192 6 1.588225 -0.329412 EDIT: There is small typo, for second column need df.iloc[:,1]: df1 = df.loc[df.iloc[:,1] &gt;= 0, df.columns[[1,3]]] df1 = df.iloc[df.iloc[:,1].values &gt;= 0, [1,3]] df1 = df.loc[df.iloc[:,1] &gt;= 0, ['b','d']] print (df1) b d 0 1.609990 -0.133827 1 0.939479 1.169886 5 0.939276 1.187436 6 1.588225 -0.329412
upvote count: 1

http://stackoverflow.com/comment/82168802
comment on: http://stackoverflow.com/q/47604564
score: 0
type: Comment
type: QuestionComment
has text: Would you like to see the full code?

http://stackoverflow.com/q/47566009
has answer: http://stackoverflow.com/a/47566035
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82089948
duplicate of: http://stackoverflow.com/q/3899980
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/3899980
accepted answer: http://stackoverflow.com/a/47566035
tagged with: plot
has title: How to change a font size within a plot figure
has body: I can't figure out how to change the objects font size on y ticks. Any suggestions? Here is the screenshot: objects = (maternal_mortality['Country Name']) y_pos = np.arange(len(objects)) width = .5 year_1990 = maternal_mortality['1990'] year_2015 = maternal_mortality['2015'] plt.barh(y_pos +width, year_1990, align='center', alpha=0.5, label='1990') plt.barh(y_pos +width, year_2015, align='center', alpha=0.5, label='2015') plt.yticks(y_pos, objects) plt.xlabel('Percentage') plt.title('Maternal Death Worldwide in 1990 vs 2015') plt.legend() plt.figure(figsize=(10,10)) plt.show()
score: 2

http://stackoverflow.com/q/47677088
type: Question
has comment: http://stackoverflow.com/comment/82313868
type: UnansweredQuestion
tagged with: python
has body: I tried to change datatype in dataframe as below. df.iloc[:,2:8] = df.iloc[:,2:8].apply(pd.to_numeric, errors='coerce').notnull() However, I got the dataframe with boolean not float datatype. Can anyone tell me why? Below is the before and after data Before Reflectance U-Factor with Film [W/m2-K] U-Factor no Film [W/m2-K] \ 0 0.08 0.857 0.984 1 0.08 0.857 0.984 2 0.08 0.857 0.984 3 0.30 0.273 0.283 4 0.30 0.273 0.283 5 0.30 0.273 0.283 6 0.30 0.273 0.283 7 0.08 0.857 0.984 8 0.08 0.857 0.984 9 0.08 0.857 0.984 After Reflectance U-Factor with Film [W/m2-K] U-Factor no Film [W/m2-K] \ 0 True True True 1 True True True 2 True True True 3 True True True 4 True True True 5 True True True 6 True True True 7 True True True 8 True True True 9 True True True
score: 0
has comment: http://stackoverflow.com/comment/82313144
has title: got boolean datatype when apply(pd.to_numeric)
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/82313115

http://stackoverflow.com/q/47682450
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/47682650
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47682943
answer count: 2
has body: I've written a function that works for strings of length 1, but I have no idea how to make it work for longer ones. def function(text, n): dict={} char_count=0 for c in text: keys=dict.keys() if c.isalpha()==True: char_count+=1 if c in keys: dict[c] +=1 else: dict[c]=1 for key in dict: dict[key]=dict[key]/char_count return dict The use of import is not very welcome :/
has answer: http://stackoverflow.com/a/47682943
has comment: http://stackoverflow.com/comment/82329348
has comment: http://stackoverflow.com/comment/82324113
has title: calculate the percentage of substring occurrence in string, python
downvote count: 2
has answer: http://stackoverflow.com/a/47682650
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82103047
has text: I have got my answer by trying cursor.execute('SELECT id,Firstname,LastName FROM employee where FirstName=? and LastName=?',emp_firstname.decode('cp1252'),emp_lastname.decode('cp1252')) Thanks all for your help!!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47570361
type: QuestionComment

http://stackoverflow.com/q/47555887
tagged with: python
has body: I am following this guide to build libtorrent for python 3.6, but i'm stuck at this portion. Change directory to c:\boost_1_55_0\tools\jam\src. Then run the script called build.bat or build.sh on a unix system. First you need to build bjam. You do this by opening a terminal (In windows, run cmd). Change directory to c:\boost_1_55_0\tools\jam\src. Then run the script called build.bat or build.sh on a unix system. This will build bjam and place it in a directory starting with bin. and then have the name of your platform. Copy the bjam.exe (or bjam on a unix system) to a place that's in you shell's PATH. On linux systems a place commonly used may be /usr/local/bin or on windows c:\windows (you can also add directories to the search paths by modifying the environment variable called PATH). I am using the latest build for boost here which is 1.65.1. All i've done is to extract it to a folder. Issue I don't see a build.bat within this specific folder that i should be using to build bjam with. Is there a more clearer way to install libtorrent on windows for python?
score: 0
has title: Building of BBv2 for libtorrent
answer count: 1
has answer: http://stackoverflow.com/a/47569861
type: Question
tagged with: libtorrent
tagged with: libtorrent-rasterbar
type: UnansweredQuestion

http://stackoverflow.com/a/47648584
type: AcceptedAnswer
downvote count: 2
has comment: http://stackoverflow.com/comment/82256007
has body: Because the info you want to remove is all numeric, white space, and possibly a hyphen, you can easily do this for each date with this: month_year = days_month_year.lstrip('0123456789- \t') This should be reasonably reliable, since you want to keep the string starting with the month, which is always going to be alphabetic. There are, of course, many different ways to do this. You could also do regular expressions to extract out what you want, but the above is the simplest. &gt;&gt;&gt; s = '20-21 May 2008' &gt;&gt;&gt; s.lstrip('0123456789- \t') 'May 2008'
upvote count: 1
answers question: http://stackoverflow.com/q/47648515
type: Answer
accepted answer of: http://stackoverflow.com/q/47648515
score: -1
has comment: http://stackoverflow.com/comment/82256160

http://stackoverflow.com/comment/82173862
score: 0
type: AnswerComment
has text: okey, yes it won't work like this. angular bundles the .ts,.html.css files and serves them `/dist` folder where u can access it in the address you mentioned. what do you want to achieve exactly ? if you want have a server side app, create some REST endpoints or start a websocket server, add that at the root and then put angular in a `root_directory/view` folder. In that way you can start your server in another port and angular will run at port `4200`. Check this https://medium.com/@ervib/deploy-angular-4-app-with-express-to-heroku-6113146915ca Then you can easily communicate those two apps
type: Comment
comment on: http://stackoverflow.com/a/47606964

http://stackoverflow.com/q/47631839
tagged with: python
has answer: http://stackoverflow.com/a/47634547
score: 2
type: AnsweredQuestion
upvote count: 2
has title: How to count the number of steel rods in a video
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82221537
favorite count: 0
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/38619382
accepted answer: http://stackoverflow.com/a/47634547
has body: I need to count the number of steel rods , in Python using opencv for the following image. Image with the steel rods at the center I have initially converted the image to grayscale,then used erode function followed with canny edge function to detect the edges as shown below. image after canny edge Later find contours and used bounding rotated rectangle to count the rods. I am not able to get the correct count. kernel = np.ones((4,4),np.uint8) erosion = cv2.erode(gray,kernel,iterations = 1) cv2.imshow('Erode',erosion) canny=cv2.Canny(erosion,100,200) cv2.imshow('Canny',canny) kernele=np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]],np.uint8) dilation = cv2.dilate(canny,kernele,iterations = 1) cv2.imshow('dilate',dilation) c,cnt,h=cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) if cnt: i=0 for cnt in contours: rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) if rect[1][0]&gt;1 and rect[1][0]&lt;15: #width of rod i+=1 Kindly suggest what to modify or how to get the count. Thank You Next Image

http://stackoverflow.com/q/47663040
score: 0
tagged with: list
upvote count: 1
downvote count: 1
has title: How to reference a combination of dict() and list() in Python3?
favorite count: 0
type: Question
tagged with: python-3.x
has body: This is an example of a complexe data structure. The depth of the structure is not fixed. To reference a specific datum in the structure I need a unknown number of indices (for list()) and keys (for dict()). &gt;&gt;&gt; x = [{'child': [{'text': 'ass'}, {'group': 'wef'}]}] &gt;&gt;&gt; x[0]['child'][0]['text'] 'ass' Now I want to have single keys for the values like this. keys = {'ID01': [0]['child'][0]['text'], 'ID02': [1]['group']} But this is not possible. Is there another pythonic way?
has comment: http://stackoverflow.com/comment/82285510
has answer: http://stackoverflow.com/a/47663166
accepted answer: http://stackoverflow.com/a/47663166
answer count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82285327
type: AnsweredQuestion

http://stackoverflow.com/comment/82318526
has text: I might get more variables than equations, but I know for sure the equations can not be solved. There are no multiple equations containing the same set of variables. I can never find the value of Fx or Rx. But I can find if Fx is eqal to Fy and Fz for example, which is what I am trying to achieve. The number of equations and variables depends on how long I run some experiment and the experiment conditions. For the controlled testing environment, I have 128 Forward (F) variables and 128 Reverse (R) variables and 2200 equations.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47660531
score: 0

http://stackoverflow.com/comment/82107613
type: QuestionComment
comment on: http://stackoverflow.com/q/47575201
type: Comment
score: 0
has text: Can you run the script, rename the results file by hand, and only then rerun it?

http://stackoverflow.com/comment/82099549
has text: @EwuramaMinkaAkuoko The `while True` should wrap the entire function body! ANd you shouldn't change the code you try in your question, that will render given answers obsolete.
type: Comment
comment on: http://stackoverflow.com/a/47570468
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82147383
comment on: http://stackoverflow.com/q/47594244
score: 0
has text: I want something like this. https://plot.ly/~RPlotBot/4336/petallength-vs-sepallength.png But it has one variable on x-axis, another on y-axis. I want to use all 4 variables in single plot with different colors based on label value.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82300652
type: QuestionComment
comment on: http://stackoverflow.com/q/47670727
has text: a good (MS) paint job. ;-)
score: 0
type: Comment

http://stackoverflow.com/comment/82207499
score: 0
comment on: http://stackoverflow.com/q/47624211
type: Comment
type: QuestionComment
has text: @DanielPryden yes I know that but I want it to be automatic. When I type something in the console, I want it to be printed immediately after or before it executes. One of those would be fine

homebrew
tags question: http://stackoverflow.com/q/47658596
tags question: http://stackoverflow.com/q/47564043
tag name: homebrew
tags question: http://stackoverflow.com/q/47695128
tags question: http://stackoverflow.com/q/47608683
type: Tag

http://stackoverflow.com/q/47655600
has comment: http://stackoverflow.com/comment/82269948
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82269452
tagged with: sql-server
has comment: http://stackoverflow.com/comment/82303311
has title: Python: data import from MSSQL 'Incorrect syntax' at WHERE statement
tagged with: python
has comment: http://stackoverflow.com/comment/82269413
has comment: http://stackoverflow.com/comment/82269410
type: Question
tagged with: export-to-csv
has body: With Python I want to create multiple csv files with data from MS SQL. In MS SQL I have a table with article names and some article information. Article names show up multiple times in the table with varying article information. The script should create one csv file per article name. I did the same script for article numbers (integer) and it worked fine. But with article names (varchar:letters, numbers) I get this error message: ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'SomeArticleName'. (102) (SQLExecDirectW)") --> I guess the WHERE statement is the problem import pyodbc import csv conn= pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};' r'servername' r'DATABASE = mydatabase;' r'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute("SELECT DISTINCT [ArticleName] from [mydatabase].[dbo]. [mytable]") allarticles = cursor.fetchall() for article in allarticles: anr = article[0] cursor.execute("SELECT * from [mydatabase].[dbo].[mytable] WHERE [ArticleName] = " + str(artikel[0])) rows = cursor.fetchall() myfile = 'mypath'+anr+'.csv' with open(myfile, 'w') as fp: a = csv.writer(fp, lineterminator = '\n') for row in rows: a.writerow(row) conn.close()` I printed the article names from 'allarticles' and they show up.
score: 0
answer count: 0

http://stackoverflow.com/q/47612023
tagged with: url
tagged with: django
score: 0
has title: Prefix Django base URL pattern
tagged with: python
has comment: http://stackoverflow.com/comment/82182787
has body: My service implemented in Django is hosting iCal calendar files. I want this files to be opened as a webcal stream, but this requires URL to be composed in a certain way so that browser/system/another service understands what should it do to handle this file properly. The URL should look like this: webcal://myservice.com/icalfile, but the URL pattern in Django starts only at myservice.com base url, for example: url(r'^/icalfile$', views.ReturnICS.as_view()) is the equivalent of: myservice.com/icalfile Although I can explicitly insert webcal:// to a url for each ical file represented in a template and pass it as variable when rendering view, like this for instance: ics_url = 'webcal://' + icalfileurl I'd very much like to find a way to compose a full url pattern that already has 'webcal://' part included, something like: url(r'webcal://^*/icalfile$', views.ReturnICS.as_view()) * – is where base URL is. but Django does not recognise this construction.
has comment: http://stackoverflow.com/comment/82182866
type: Question
answer count: 0
tagged with: webcal
type: UnansweredQuestion

http://stackoverflow.com/q/47558535
tagged with: pandas
has answer: http://stackoverflow.com/a/47558697
answer count: 1
downvote count: 0
has body: The Scenario I have dataframe df1 which needs to cutdown into different dataframes based on a list y_km. Dataframe df1 holds data as follows: 0 1 2 0 3.000000 4.000000 3.000000 1 3.618555 3.646074 3.923834 2 2.669256 2.769302 2.897346 3 4.340775 4.311200 4.341143 and y_km as [0, 3, 2, 1, 2, 3, 3, 3, 1, 1, 0, 1, 2] My Snippet df1 = pd.DataFrame(X) df1 = df1.iloc[0:5,:10] cl0 = pd.DataFrame() cl1 = pd.DataFrame() cl2 = pd.DataFrame() cl3 = pd.DataFrame() y_km = list(y_kmeans) for i in y_kmeans: rows = df1.iloc[i, :] if i == 0: cl0 = cl0.append(rows, ignore_index=False) elif i == 1: cl1 = cl1.append(rows, ignore_index=False) elif i == 2: cl2 = cl2.append(rows, ignore_index=False) elif i == 3: cl3 = cl3.append(rows, ignore_index=False) Issue with this is, that my clX DFrames are having the same records as of first inserted.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82075564
has title: How to copy a selected row from dataframe from existing dataframe on conditional check? [python]
accepted answer: http://stackoverflow.com/a/47558697
tagged with: dataframe
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/47624926
score: 1
type: Answer
has body: You can take the mean using numpy. import numpy as np import matplotlib.pyplot as plt from scipy import misc img = misc.imread('baboon.png') mean_img = img.mean(axis=2) plt.imshow(mean_img, cmap=plt.cm.gray) plt.show()
accepted answer of: http://stackoverflow.com/q/47624842
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47624842

http://stackoverflow.com/comment/82243571
has text: There might be... what values should be considered when setting nulls?
comment on: http://stackoverflow.com/q/47642160
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82110716
comment on: http://stackoverflow.com/q/47576803
has text: yes its doing its work perfectly .
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47681756
has title: Match exact phrase within a string in Python
has answer: http://stackoverflow.com/a/47681931
has comment: http://stackoverflow.com/comment/82328872
has answer: http://stackoverflow.com/a/59665049
has body: I'm trying to determine whether a substring is in a string. The issue I'm running into is that I don't want my function to return True if the substring is found within another word in the string. For example: if the substring is; "Purple cow" and the string is; "Purple cows make the best pets." This should return False. Since cow isn't plural in the substring. And if the substring was; "Purple cow" and the string was; "Your purple cow trampled my hedge!" would return True My code looks something like this: def is_phrase_in(phrase, text): phrase = phrase.lower() text = text.lower() return phrase in text text = "Purple cows make the best pets!" phrase = "Purple cow" print(is_phrase_in(phrase, text) In my actual code I clean up unnecessary punctuation and spaces in 'text' before comparing it to phrase, but otherwise this is the same. I've tried using re.search, but I don't understand regular expressions very well yet and have only gotten the same functionality from them as in my example. Thanks for any help you can provide!
answer count: 5
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82328760
upvote count: 7
tagged with: string
tagged with: match
has answer: http://stackoverflow.com/a/56987799
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/47681924
has answer: http://stackoverflow.com/a/47681890
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82240528
type: AnswerComment
score: 1
has text: @Lucubrator and you can call dunder methods manually if you wish. I meant `print(e.__cause__())` in my last comment but I can't edit it now. In REPL, you could do `a = 'hello'` and then `a.__str__()`, for example, which is like calling `print(a)`.
type: Comment
comment on: http://stackoverflow.com/a/47638448

http://stackoverflow.com/q/47602048
has answer: http://stackoverflow.com/a/47602212
upvote count: 0
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82162981
has title: Regular expression search file
has comment: http://stackoverflow.com/comment/82163080
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82163690
type: UnansweredQuestion
tagged with: python
has body: I have a csv file and I want to serach a specific word on it in arabic lines = 0 with io.open('path.csv','r',encoding="utf-8") as f: for line in f : lines= lines+1 r=re.search(r'\w''[\u0627\u0644\u0631\u064A\u0627\u0636]',f) print (line,r) f.close() I want to print the line with the word is like extracting the row that contain my word on to new csv file I get this error traceback (most recent call last): File "path.py", line 11, in &lt;module&gt; r=re.search(r'\w''[\u0627\u0644\u0631\u064A\u0627\u0636]',f) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 182, in search return _compile(pattern, flags).search(string) TypeError: expected string or bytes-like object
has comment: http://stackoverflow.com/comment/82162866
score: -2

http://stackoverflow.com/a/47639129
answers question: http://stackoverflow.com/q/47638326
has body: Given what others have said about the order of a dictionary and violating the posters desire to have a dictionary, I return a sorted list. I used the accepted answer at In Python, how do I index a list with another list? d= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]} myList = [max(value) for key,value in d.items()] print(myList) myIndex = sorted(range(len(myList)),key=lambda x:myList[x],reverse=True) L = [(key,value) for key,value in d.items()] [L[i] for i in myIndex]
type: Answer
has comment: http://stackoverflow.com/comment/82236519
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/47671106
has body: Try with pip3 install djangorestframework-jsonapi this command.
answers question: http://stackoverflow.com/q/47670937
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/82301156
has comment: http://stackoverflow.com/comment/82301509
upvote count: 3
downvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82301009
accepted answer of: http://stackoverflow.com/q/47670937

http://stackoverflow.com/comment/108984467
has text: For example in `_plotstuff.py` file, lets say I write following for testing: `f = Fitter(); f.plot() #Imported method` under a `if __name__ == "__main__":`. When I add `from mymodule import Fitter` to top of the file `circular import` error shows up. So I had to carry `from mymodule import Fitter`into the `if __name__ == __main__:`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47562412

http://stackoverflow.com/q/47640949
has title: browser = webdriver.Chrome() not working
has answer: http://stackoverflow.com/a/47641641
downvote count: 1
has answer: http://stackoverflow.com/a/47645726
score: 2
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/47641032
has answer: http://stackoverflow.com/a/51450539
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47646347
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68139441
tagged with: selenium
has body: I am getting started with Selenium for python and have this: from selenium import webdriver browser = webdriver.Chrome() However it gives this error: Traceback (most recent call last): File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site- packages\selenium\webdriver\common\service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in &lt;module&gt; browser = webdriver.Chrome() File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site- packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__ self.service.start() File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site- packages\selenium\webdriver\common\service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home [Finished in 1.0s] Anyone have any idea how to fix this? Thanks
answer count: 6

http://stackoverflow.com/comment/82175226
has text: Yes, you are correct, however even bisect finds the index in log(n) time, the insertion is O(n).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47608356
type: Comment

http://stackoverflow.com/comment/82072324
comment on: http://stackoverflow.com/q/47556992
type: QuestionComment
type: Comment
score: 0
has text: I still can't get it to work :(

http://stackoverflow.com/comment/82238232
type: AnswerComment
has text: Thank you so much, i just return response in call
type: Comment
comment on: http://stackoverflow.com/a/47638611
score: 0

http://stackoverflow.com/comment/82308776
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47673363
has text: Yes, I mean 11 rows 3 columns. Sorry for not making this clear.

http://stackoverflow.com/comment/82313254
comment on: http://stackoverflow.com/q/47676914
score: 0
type: Comment
type: QuestionComment
has text: @ElmoVanKielmo I updated the question

http://stackoverflow.com/a/47697840
upvote count: 3
answers question: http://stackoverflow.com/q/47697775
downvote count: 0
type: Answer
score: 3
has body: just feed your list to itertools.permutations and format accordingly in a list comprehension directly passing the tuple to format using the * operator. import itertools result = ["{}-{}".format(*x) for x in itertools.permutations([3, 8, 2],2)] print(result) result: ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8'] As a side note, don't use input as a variable name as it overrides the interactive text input function.

http://stackoverflow.com/comment/82113852
type: QuestionComment
comment on: http://stackoverflow.com/q/47564621
score: 2
has text: I'm voting to close this question as off-topic because it is crossposted to softwareengineering, where there is an accepted answer.
type: Comment

http://stackoverflow.com/q/47628050
has answer: http://stackoverflow.com/a/47635212
type: UnansweredQuestion
answer count: 1
has title: Python fitting sinus cardinal and LMFIT library
tagged with: physics
tagged with: lmfit
has body: I have a set of data from a physic experiment (simple-slit experiment) in university and i am trying to fit this data to a model that i build from the lmfit library. I want a sinus cardinal square, in this form: I(X)= I0.sinc²(pi.a.X/(lambda.D)) with a : the width of the slit, lambda : wavelenght of the light D : distance camera/slit I0 : original intensity import csv as csv from math import pi import matplotlib.pyplot as plt import numpy as np from lmfit import * # create data to be fitted with open('data_1.csv', 'r') as f: values = list(csv.reader(f, delimiter=',')) values = np.array(values[1:], dtype=np.float) position = values[:, 0] intensity = values[:, 1] #define function model def fct(x, I0, a, D, b): return I0 * np.square(np.sinc(pi * a * (x + b) / (0.00000063 * D))) #b is for the horizontal shift because my experience #was centered on 700 due to the camera # do fit vmodel = Model(fct) vmodel.set_param_hint('I0', min=0., max=300.) vmodel.set_param_hint('a', value=0.0005, min=0.0, max=1.) vmodel.set_param_hint('D', value=0.53, min=0.0, max=1.) vmodel.set_param_hint('b', min=0., max=2000.) pars = vmodel.make_params() result = vmodel.fit(intensity, pars, x=position) # write report print(result.fit_report()) #after we plot the data, with position on x and intensity on y It returns totally wrong values and an error : RuntimeWarning: invalid value encountered in double_scalars spercent = '({0:.2%})'.format(abs(par.stderr/par.value)) Model Model(fct) Fit Statistics # function evals = 7 # data points = 1280 # variables = 4 chi-square = 4058147.794 reduced chi-square = 3180.367 Akaike info crit = 10326.876 Bayesian info crit = 10347.494 Variables I0: 0 +/- 0 (nan%) (init= 0) a: 0.00050000 +/- 0 (0.00%) (init= 0.0005) D: 0.50000000 +/- 0 (0.00%) (init= 0.5) b: 400 +/- 0 (0.00%) (init= 400) Could you help me please ? I tried lots of type models from this library but nothing work correctly and i really need it. I already solved 2D problems with a np.square, …
tagged with: python
type: Question
score: 0

http://stackoverflow.com/comment/87933878
has text: I'm not sure how to do this when using Docker. We deployed our additions as part of a python module on the server that runs superset. Then we changed the superset_config.py as described above. My suggestion would be to have a look at the superset documentation on creating your custom build: https://superset.incubator.apache.org/installation.html#making-your-own-build
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47787279
type: AnswerComment

http://stackoverflow.com/q/47678665
tagged with: dictionary
has answer: http://stackoverflow.com/a/47678905
type: Question
accepted answer: http://stackoverflow.com/a/47678905
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82316520
tagged with: list
has body: I have a python dictionary which describes a set of parameters like this: params = {'V0': 0.040239623194206875, 'theta': 0.2133407345978868, 'omega': 0.8624391468911115, 'kappa': 0.8632687388218084, 'rho': -0.7680944602881048} Each parameter in the set has a constant number which represent its variation. From such set I want to construct a list of dictionaries until I have 100 sets of parameters. The logic behind is that I want for example change params['V0'] to params['V0'] += deltaV0 params['V0'] -= deltaV0 with the other values fixed, obtaining another 2 different dictionaries to add to my list. My problem is that I can't manage to transform my idea in code. The framework should be something like: good_set = [params] while len(good_set) &lt; 100: good_set.append(new params) How can I efficiently obtain new dictionaries from the initial one? I need to simultaneously obtain 2 new dictionaries from the initial one for each parameters ( because the variation is added and subtracted each time), so in total for each iteration I should add to my list 5*2=10 dictionaries. I red some question about dict comprehension but they didn't give me an input to solve my problem
score: 1
has title: Creating a list of dictionaries modifying just one values at each step
tagged with: python

http://stackoverflow.com/q/47566948
has answer: http://stackoverflow.com/a/47572047
has body: Hi I am a newbie in PyQt. Can someone suggest why the below program is not populating the stdout of print.py in real time to the textbox widget.This problem exists when it is running from command line.If we are running the samecode in pycharm we will get realtime outputs. Command line execution will show the data as a chunk(approx 4K) to the text box. from PyQt4 import QtGui,QtCore import sys class gui(QtGui.QMainWindow): def __init__(self): super(gui, self).__init__() self.initUI() def dataReady(self): cursor = self.output.textCursor() cursor.movePosition(cursor.End) cursor.insertText(str(self.process.readAll())) self.output.ensureCursorVisible() def initUI(self): # Layout are better for placing widgets layout = QtGui.QHBoxLayout() self.output = QtGui.QTextEdit() layout.addWidget(self.output) centralWidget = QtGui.QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) # QProcess object for external app self.process = QtCore.QProcess(self) # QProcess emits `readyRead` when there is data to be read self.process.readyRead.connect(self.dataReady) # Run program self.process.start('python', ['./print.py']) #Function Main Start def main(): app = QtGui.QApplication(sys.argv) ui=gui() ui.show() sys.exit(app.exec_()) #Function Main END if __name__ == '__main__': main() Here is the code for print.py import time n=10 while(n): print "Hello world" time.sleep(1) n = n-1
has comment: http://stackoverflow.com/comment/82093644
type: Question
tagged with: pyqt4
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82098795
has title: PyQt program running from command line not routing the console output in real time
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/47572047

http://stackoverflow.com/comment/82145155
score: 0
comment on: http://stackoverflow.com/q/47593452
type: QuestionComment
has text: Thanks. I literally just got it too. Answer below may help others...
type: Comment

http://stackoverflow.com/comment/82191587
has text: you should not ignore the migrations. see here: https://stackoverflow.com/questions/28035119/should-i-be-adding-the-django-migration-files-in-the-gitignore-file
comment on: http://stackoverflow.com/a/47616707
score: 4
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47661443
possible better answer: http://stackoverflow.com/a/47663430
has comment: http://stackoverflow.com/comment/82288754
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
tagged with: python
has body: I have two dataframes df1 and df2. df1: PartNumber 0000D3447E 0000D3447E 0000D3447E12 0000D3447E 0000D3447E 0000D3447E 0000D3447E2345 0000F2892E 0000F2892E 0000F2892E 0000F2892E34 0000F2892E 0000F2892E 0000F2892E12 df2: PartNumber 0000D3447E39S 0000D3447E39S 0000D3447E39S 0000D3447E39S 0000D3447E39S 0000D3447E39S 0000D3447E39S2245 0000F2892EDI1 0000F2892EDI1 0000F2892EDI1 0000F2892EDI124 0000F2892EDI1 0000F2892EDI1 0000F2892EDI1 0000D1617EAD6 0000D1617EAD6 0000D1617EAD6137 0000D1617EAD6 0000D1617EAD6 0000D1617EAD612 0000D1617EAD6 0000D3447EYG1 0000D3447EYG1 0000D3447EYG1 0000D3447EYG1 0000D3447EYG1 0000D3447EYG1 0000D3447EYG1 i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column. the given answer df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts()) may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters. Thanks.
has answer: http://stackoverflow.com/a/47661586
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47661586
has title: get the count of columns contains a string in pandas
downvote count: 0
answer count: 3
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47668359
has answer: http://stackoverflow.com/a/47663430

http://stackoverflow.com/q/47669119
has body: I am building a custom speech recognition and for that I defined a Command interface. The idea is that the speech recognition returns a String and I got a list of all supported commands. Then I would be going through the list and find the best matching one and execute it. In order to keep the code maintainable I want to create a plugin system, where you define a class derived from ICommand in a separate file. The folder structure would be the following: project/ ├── ICommand ├── commands/ │ ├── command1.py (inherits ICommand) │ ├── command2.py (inherits ICommand) I am facing multiple problems with that: How can I import ICommand for inheritance in the command1.py file? How do I create one instance of every class contained in a .py file in the commands folder? Is there any way to ensure that the plugin file only contains a definition for a derived ICommand class?
linked to: http://stackoverflow.com/q/10043485
type: Question
has answer: http://stackoverflow.com/a/47697879
accepted answer: http://stackoverflow.com/a/47697879
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/47334197
upvote count: 1
tagged with: python
tagged with: plugins
favorite count: 0
has title: Python Pluginsystem
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/82285215
has text: Updated the answer.
comment on: http://stackoverflow.com/a/47662677
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82287314
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47663911
type: QuestionComment
has text: @juanpa.arrivillaga thank you sir! i am quite new to python but you helped me out alot :)

http://stackoverflow.com/q/47676638
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47690287
possible better answer: http://stackoverflow.com/a/47677014
has answer: http://stackoverflow.com/a/47690287
favorite count: 0
type: Question
answer count: 2
has body: When a plot is updated with the set_data and draw method, the mouse cursor change few milliseconds from an arrow to a circle. Is it possible to avoid this? Because I update my plot 10 times per second so it is very ugly to see my mouse cursor change so quickly. I am using Python 3.6, PyQt5, and matplotlib 2.1. Thank you in advance ;)
has title: Matplotlib, avoid update mouse cursor when draw
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47677014
tagged with: mouse
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/47680153
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82319604
has body: The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below python manage.py runserver in Python colder and then probably # in the angular2 folder npm start Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it? Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?
favorite count: 0
type: Question
tagged with: frontend
possible better answer: http://stackoverflow.com/a/47680642
has comment: http://stackoverflow.com/comment/82319751
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/47680642
tagged with: backend
has comment: http://stackoverflow.com/comment/82319655
accepted answer: http://stackoverflow.com/a/47680402
has answer: http://stackoverflow.com/a/47680402
type: AnsweredQuestion
has title: Where do I put front-end code in my backend project and how/when to run it?
answer count: 2

http://stackoverflow.com/a/47577259
answers question: http://stackoverflow.com/q/47576897
has comment: http://stackoverflow.com/comment/129798112
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/130037356
upvote count: 3
downvote count: 0
has body: If you just want the values and drop the index, you can for instance: df.loc[df.A == 7].B.values #array([4])

pytorch
tags question: http://stackoverflow.com/q/47690871
tags question: http://stackoverflow.com/q/47618817
tags question: http://stackoverflow.com/q/47635918
tags question: http://stackoverflow.com/q/47581877
tags question: http://stackoverflow.com/q/47645428
tags question: http://stackoverflow.com/q/47642014
tags question: http://stackoverflow.com/q/47588682
tags question: http://stackoverflow.com/q/47563398
tags question: http://stackoverflow.com/q/47587122
tags question: http://stackoverflow.com/q/47544151
tags question: http://stackoverflow.com/q/47645271
tags question: http://stackoverflow.com/q/47624798
tags question: http://stackoverflow.com/q/47553103
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/47645423

http://stackoverflow.com/q/47572853
favorite count: 0
type: Question
has body: I am trying to do a dynamic search function, where the user also can select multiple items in a list. If we consider this example (I added this part, selectmode=MULTIPLE): from Tkinter import * # First create application class class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.create_widgets() # Create main GUI window def create_widgets(self): self.search_var = StringVar() self.search_var.trace("w", self.update_list) self.entry = Entry(self, textvariable=self.search_var, width=13) self.lbox = Listbox(self,selectmode=MULTIPLE, width=45, height=15) self.entry.grid(row=0, column=0, padx=10, pady=3) self.lbox.grid(row=1, column=0, padx=10, pady=3) self.btn = ttk.Button(self, text="Select", command=self.Select) self.btn.grid(column=1, row=1) # Function for updating the list/doing the search. # It needs to be called here to populate the listbox. self.update_list() def update_list(self, *args): search_term = self.search_var.get() # Just a generic list to populate the listbox lbox_list = ['Adam', 'Lucy', 'Barry', 'Bob', 'James', 'Frank', 'Susan', 'Amanda', 'Christie'] self.lbox.delete(0, END) for item in lbox_list: if search_term.lower() in item.lower(): self.lbox.insert(END, item) def Select(self): reslist = list() selecion = self.lbox.curselection() for i in selecion: entered = self.lbox.get(i) reslist.append(entered) print reslist root = Tk() root.title('Filter Listbox Test') app = Application(master=root) print 'Starting mainloop()' app.mainloop() The search function works perfectly fine, however, once a search has been done and an item has been selected, the selections is not saved since the lbox.delete function is used in update_list. Is there a way to keep each item selected while using the search function?
tagged with: tkinter
linked to: http://stackoverflow.com/q/7616541
type: UnansweredQuestion
has title: Selectmode multiple together with dynamic search bar Tkinter
has answer: http://stackoverflow.com/a/55160274
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82112236
has comment: http://stackoverflow.com/comment/82112375
score: 1
has comment: http://stackoverflow.com/comment/82107939
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82110198
has comment: http://stackoverflow.com/comment/82113105

http://stackoverflow.com/a/47561811
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47561443
accepted answer of: http://stackoverflow.com/q/47561443
type: Answer
has comment: http://stackoverflow.com/comment/82081722
has body: Max over axis: If, as suggested by Joe in the comments, you're looking for a maximum along an axis, then, for axis axis, np.moveaxis((np.moveaxis(ar, axis, 0) == ar.max(axis)).astype(int), 0, axis) or, a bit faster, (ar == np.broadcast_to(np.expand_dims(ar.max(axis), axis), ar.shape)).astype(int) Should cover the n-dimensional case. Ex: ar = np.random.randint(0, 100, (2, 3, 4)) ar Out[157]: array([[[17, 28, 22, 31], [99, 51, 65, 65], [46, 24, 93, 4]], [[ 5, 84, 85, 79], [ 7, 80, 27, 25], [46, 80, 90, 3]]]) (ar == np.broadcast_to(np.expand_dims(ar.max(-1), -1), ar.shape)).astype(int) Out[159]: array([[[0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 0]], [[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0]]]) ar.max(-1) Out[160]: array([[31, 99, 93], [85, 80, 90]]) Max over full array: On the off-chance you're trying to identify elements equal to the maximum over the whole array, (ar == ar.max()).astype(int) should give what you're looking for.
score: 1
has comment: http://stackoverflow.com/comment/82081460

http://stackoverflow.com/a/47599153
type: AcceptedAnswer
downvote count: 0
has body: __main__.py modules in a package make the module run as a script when you use the -m command line switch. That switch takes a module name, not a path, so drop the ./ prefix: python3 -m slingshot The current working directory is added to the start of the module search path so slingshot is found first, no need to give a relative path specification here. From the -m switch documentation: Search sys.path for the named module and execute its contents as the __main__ module. Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid absolute Python module name[.] [...] As with the -c option, the current directory will be added to the start of sys.path.
score: 9
accepted answer of: http://stackoverflow.com/q/47598869
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/47598869

mongodb
tags question: http://stackoverflow.com/q/47546585
tags question: http://stackoverflow.com/q/47688095
tags question: http://stackoverflow.com/q/47682233
tags question: http://stackoverflow.com/q/47688845
tags question: http://stackoverflow.com/q/47542168
tags question: http://stackoverflow.com/q/47696980
tags question: http://stackoverflow.com/q/47651587
tags question: http://stackoverflow.com/q/47617718
tags question: http://stackoverflow.com/q/47554062
tags question: http://stackoverflow.com/q/47689664
tags question: http://stackoverflow.com/q/47630881
tags question: http://stackoverflow.com/q/47597560
tags question: http://stackoverflow.com/q/47574565
tag name: mongodb
tags question: http://stackoverflow.com/q/47568878
tags question: http://stackoverflow.com/q/47579272
tags question: http://stackoverflow.com/q/47552131
tags question: http://stackoverflow.com/q/47611583
tags question: http://stackoverflow.com/q/47693969
tags question: http://stackoverflow.com/q/47650139
tags question: http://stackoverflow.com/q/47570247
tags question: http://stackoverflow.com/q/47642731
type: Tag
tags question: http://stackoverflow.com/q/47694534
tags question: http://stackoverflow.com/q/47612612
tags question: http://stackoverflow.com/q/47620611

http://stackoverflow.com/a/76761467
downvote count: 0
upvote count: 1
score: 1
has body: Below code resets the index, so you can loop through it again. rates.reset_index(drop=True, inplace=True)
answers question: http://stackoverflow.com/q/47562604
type: Answer

http://stackoverflow.com/a/48187729
score: 0
answers question: http://stackoverflow.com/q/47640834
type: AcceptedAnswer
type: Answer
has body: Solved it by saving a splitable string to the DB. information = Column(Text, nullable=False) Data saved to information must be splitable on :::, example data: SomeText:::SomeValue:::SomeValue:::SomeValue:::SomeValue In jina2 I can split this string in view and iterate through the list: {% for item in information.split(":::") %} ... {% endfor %} Here is the live result, the content of possible answers have been created this way: https://www.path-of-exile-builds.com/quiz
accepted answer of: http://stackoverflow.com/q/47640834

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/47694103
tags question: http://stackoverflow.com/q/47650886
type: Tag
tags question: http://stackoverflow.com/q/47579954
tags question: http://stackoverflow.com/q/47585686

http://stackoverflow.com/comment/82197506
comment on: http://stackoverflow.com/q/47614883
has text: Thanks David for the comments. After reading it I'm trying now sending to cython a list of strings with all these information, something like ["sku0", "3", "sku0,sku1,sku2", "0.1,0.9,0.8"] but still coudn't find a way to make cython know beforehand it's a list of strings. Do you know if it's possible? I tried with `process_scores(char **input)` or `(array.array input)` but still the python lookups happen.
type: Comment
type: QuestionComment
score: 0

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/47659137

http://stackoverflow.com/a/47685693
has body: A example using Incrementing area of convex hull can be applied to your case. from scipy.spatial import ConvexHull import matplotlib.pyplot as plt import numpy as np gx = [-2, 2, -2, 2, 1, -0.5] gy = [3, 4, -2, -1, -1, 0.5] points = np.array((gx, gy)).T convh = ConvexHull(points) stretchCoef = 1.2 pointsStretched = points[convh.vertices]*stretchCoef gx_new = pointsStretched[..., 0] gy_new = pointsStretched[..., 1]
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82339771
answers question: http://stackoverflow.com/q/47685145

http://stackoverflow.com/comment/82275231
has text: `myObject.__dict__` will give you a dict representation of the object's fields and their values, if that's what you're after. It depends entirely on what you mean be "concisely" and what object you're talking about.
comment on: http://stackoverflow.com/q/47658342
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/82247516
comment on: http://stackoverflow.com/q/47644396
type: Comment
type: QuestionComment
score: 0
has text: Why not groupby `continent` and sum the columns. Then append to that another groupby `country` and sum the columns.

http://stackoverflow.com/comment/108122268
type: Comment
comment on: http://stackoverflow.com/a/61116350
type: AnswerComment
score: 1
has text: https://github.com/NeelRanka/pydub_edited_play-pause-stop.git : check this

http://stackoverflow.com/a/47608348
type: Answer
has comment: http://stackoverflow.com/comment/82175054
has comment: http://stackoverflow.com/comment/82175101
upvote count: 3
has body: You can use default sort method num_list = [5, 10, 15, 20] num_list.append(13) num_list.append(17) num_list.sort() print(num_list)
downvote count: 2
answers question: http://stackoverflow.com/q/47608315
score: 1
has comment: http://stackoverflow.com/comment/82175189

http://stackoverflow.com/a/47686920
has body: You can extract the value portion of the bytes with response_bytes.decode('utf-8') Then you can parse the returned information with Beautiful Soup for whatever part of it you want.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82334581
upvote count: 1
has comment: http://stackoverflow.com/comment/82333578
answers question: http://stackoverflow.com/q/47686827
type: Answer
has comment: http://stackoverflow.com/comment/130229990

http://stackoverflow.com/q/47676466
favorite count: 0
type: Question
tagged with: keyerror
has body: You can check this question for problem description. I create 7 models by a for loop then train them (didn't mention training process in the code): for i in range(1, 8): j=str(i) img_input = Input(shape=(img_width,img_height,1),name='input') x = Conv2D(32, (3,3), activation='relu', padding='same', name='conv1-'+j)(img_input) x = MaxPooling2D((2, 2), strides=(2, 2), name='pool1-'+j)(x) x = Conv2D(64, (3,3), activation='relu', padding='same', name='conv2-'+j)(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='pool2-'+j)(x) x = Conv2D(128, (3,3), activation='relu', padding='same', name='conv3-'+j)(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='pool3-'+j)(x) x = Flatten()(x) x = Dense(512, name='dense1-'+j)(x) x = Dense(512, name='dense2-'+j)(x) predictions = Dense(6, activation='softmax', name='predictions-'+j)(x) model = Model(inputs=img_input, outputs=predictions) model.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy']) Popping the last softmax layer of each model and saving the rest of the models into a list named as models[]: inputTensor = Input(shape=(img_width,img_height,1),name='inputs') for i in range (1,8): #save models into a models[] list j = str(i) models[i] = load_model(path+j+"/weights.best.hdf5") #load models from disk models[i].layers.pop() #Pop last layer models[i].outputs= [models[i].layers[-1].output] #Fix layer pop bug models[i].layers[-1].outbound_nodes = [] #Fix layer pop bug for layer in models[i].layers: #Make intermediate layer.trainable=False #layers untrainable Implementing a concat to all of these models and then trying to save the finalModel: outputTensors= [models[m](inputTensor) for m in models] output = Concatenate()(outputTensors) predictions = Dense(6, activation='softmax', name='predictionss')(output) model=Model(inputTensor, predictions) model.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy']) model.save('model') But when saving occurs it throws an error: Traceback (most recent call…
type: UnansweredQuestion
has title: KeyError when trying to save a concatenated model
tagged with: python
tagged with: keras
linked to: http://stackoverflow.com/q/47653253
has comment: http://stackoverflow.com/comment/82316324
score: 3
answer count: 0
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82317527

http://stackoverflow.com/comment/82064941
has text: That worked absolutely perfectly, exactly what I needed. Thanks very much for your help.
comment on: http://stackoverflow.com/a/47552891
type: Comment
score: 0
type: AnswerComment

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/47569850

http://stackoverflow.com/a/47655395
has comment: http://stackoverflow.com/comment/83144522
answers question: http://stackoverflow.com/q/47582179
has comment: http://stackoverflow.com/comment/83139863
downvote count: 0
upvote count: 4
has comment: http://stackoverflow.com/comment/82673911
type: Answer
has body: Two major things to point out: to avoid timing issues, you need to have "explicit waits" in your script - waiting for elements to be visible or present before proceeding to the next actions this checkbox can and should be clicked by clicking the whole label element containing the input and other auxiliary elements Here is the complete code: from splinter import Browser browser = Browser("chrome") browser.visit("http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w") browser.wait_time = 10 try: browser.is_element_visible_by_css("input[name=commit]", 10) browser.find_by_css("input[name=commit]").first.click() browser.is_element_visible_by_css("a.checkout", 10) browser.find_by_css("a.checkout").first.click() browser.is_element_present_by_css("label.terms", 10) browser.find_by_css('label.terms').click() finally: browser.quit() Here is a working code that goes to the main page, navigates to the third product in the scroller, adds it to cart, checks out and accepts the terms of use, time.sleep() at the end is just for you to see the result: from splinter import Browser browser = Browser("chrome") browser.visit("http://www.supremenewyork.com/shop") browser.wait_time = 10 try: # open a product browser.is_element_visible_by_css("#shop-scroller &gt; li &gt; a", 10) browser.find_by_css("#shop-scroller &gt; li &gt; a")[2].click() # add to cart browser.is_element_visible_by_css("input[name=commit]", 10) browser.find_by_css("input[name=commit]").first.click() # checkout browser.is_element_visible_by_css("a.checkout", 10) browser.find_by_css("a.checkout").first.click() # accept terms and conditions browser.is_element_present_by_css("label.terms", 10) browser.find_by_css('label.terms').click() import time time.sleep(10) finally: browser.quit()
score: 4
has comment: http://stackoverflow.com/comment/85084688

http://stackoverflow.com/comment/82284897
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47652782
has text: Yes I use windows. But the suggestion by KeyWeeUsr didn't seem to fix my issue. I copied his code and it still didn't work at all
type: Comment

http://stackoverflow.com/comment/82332958
comment on: http://stackoverflow.com/q/47686438
score: 0
type: Comment
type: QuestionComment
has text: As arguments to `zeros`, `empty`, `ones`, list and tuple do the same thing. `a,shape` is always a tuple. Experiment with `np.zeros` or `np.ones` first. They are easier to visualize. In general you shouldn't need to create an array with a 0 dimension. It doesn't contain any values, so isn't very useful. Don't treat it like an empty list, `[]`.

http://stackoverflow.com/q/47584876
score: 0
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/23377108
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47585733
accepted answer: http://stackoverflow.com/a/47585733
has title: Plotting percentage of totals with pandas group bys
has body: I am trying to plot a bar chart of a pandas data frame that is the result of two group bys. In particular, my data frame looks exactly like the output from another SO post's answer (https://stackoverflow.com/a/23377155/7243972): import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline np.random.seed(0) df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)]}) state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'}) state = df.groupby(['state']).agg({'sales': 'sum'}) results = state_office.div(state, level='state') * 100 I would like to plot results so that each state is a different color and the office_id is on the x-axis. This is so that each office_id is grouped together and they can be easily compared. I've tried adjusting the plot from results['sales'].plot.bar(), but I am struggling.
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47585561
possible better answer: http://stackoverflow.com/a/47585561
tagged with: python
type: Question

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47586089
tags question: http://stackoverflow.com/q/47615761
type: Tag

http://stackoverflow.com/a/47587121
downvote count: 0
answers question: http://stackoverflow.com/q/47587088
upvote count: 2
type: Answer
score: 2
has body: You can create a file requirements.txt which package names and their version number: Django==1.3 PyYAML==3.09 And then install packages from it: pip install -r /path/to/requirements.txt Or, you can provide multiple package names in one go: pip install django==1.3 pyyaml==3.09

http://stackoverflow.com/comment/82182803
has text: This sounds like a very bad idea. Besides the fact that this is impossible, it will make understanding your code awfully frustrating.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47612274

http://stackoverflow.com/a/47603775
downvote count: 0
has comment: http://stackoverflow.com/comment/82178546
accepted answer of: http://stackoverflow.com/q/47603286
score: 3
answers question: http://stackoverflow.com/q/47603286
type: Answer
upvote count: 3
has body: Your classes should inherit from pygame.sprite.Sprite, so that they can be put into sprite groups, e.g. class Platform(pg.sprite.Sprite):. Don't forget to call the __init__ method of the parent class super().__init__(). Then create the sprite groups (all_sprites = pg.sprite.Group()) and the sprite instances and call the add method of the groups to add the sprite. Then you just have to call all_sprites.update() and all_sprites.draw(screen) in the main loop. from random import randrange import pygame as pg class Platform(pg.sprite.Sprite): def __init__(self, x, y, width, height): super().__init__() self.image = pg.Surface((width, height)) self.image.fill(pg.Color('dodgerblue1')) self.rect = self.image.get_rect(topleft=(x, y)) def main(): screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() all_sprites = pg.sprite.Group() # This group that will contain all sprites. # You probably want to add the platforms to a separate # group as well, so that you can use it for collision detection. platforms = pg.sprite.Group() for _ in range(6): # Create six platforms at random coords. platform = Platform(randrange(600), randrange(440), 170, 20) platforms.add(platform) all_sprites.add(platform) done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True all_sprites.update() screen.fill((30, 30, 30)) all_sprites.draw(screen) pg.display.flip() clock.tick(30) if __name__ == '__main__': pg.init() main() pg.quit()
type: AcceptedAnswer

nltk
tags question: http://stackoverflow.com/q/47584738
tags question: http://stackoverflow.com/q/47554554
tags question: http://stackoverflow.com/q/47663870
tags question: http://stackoverflow.com/q/47616332
tags question: http://stackoverflow.com/q/47624347
tags question: http://stackoverflow.com/q/47585906
tags question: http://stackoverflow.com/q/47683077
tags question: http://stackoverflow.com/q/47605377
tag name: nltk
tags question: http://stackoverflow.com/q/47614975
tags question: http://stackoverflow.com/q/47592566
tags question: http://stackoverflow.com/q/47622946
tags question: http://stackoverflow.com/q/47649987
tags question: http://stackoverflow.com/q/47678688
tags question: http://stackoverflow.com/q/47565963
tags question: http://stackoverflow.com/q/47633919
type: Tag
tags question: http://stackoverflow.com/q/47687797
tags question: http://stackoverflow.com/q/47654298
tags question: http://stackoverflow.com/q/47624742
tags question: http://stackoverflow.com/q/47599575
tags question: http://stackoverflow.com/q/47571213
tags question: http://stackoverflow.com/q/47614999

http://stackoverflow.com/comment/82129068
type: AnswerComment
comment on: http://stackoverflow.com/a/47585648
score: 0
type: Comment
has text: @Kara But this is descending order within the list. Was that expected?

http://stackoverflow.com/comment/87134017
comment on: http://stackoverflow.com/q/47671514
score: 0
type: Comment
type: QuestionComment
has text: Fabric is not really thought for that. But you can use the [scp](https://www.garron.me/en/articles/scp.html) command in a bash script

http://stackoverflow.com/comment/82184879
has text: can you show your form?
comment on: http://stackoverflow.com/q/47612791
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82215253
type: Comment
score: 0
has text: Okay. Sorry I saw the answer a bit late. This seems simple enough. So the url is using a different kind of encoding. I will try it using the new format and give a response. Is there a link you can share to help read more on that? Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/47623736

http://stackoverflow.com/comment/82182330
has text: The comments (especially the last one by StarBucK) seem to suggest he needs 12 **BITS** after all. He just mentioned bytes a few times because he did not know the difference between bits and bytes. I don't think there are many implementations of 12 bit floats in any language.
comment on: http://stackoverflow.com/a/47573898
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82108611
comment on: http://stackoverflow.com/a/47575700
type: Comment
has text: Yeah I meant that only. To make the sample size 20 by creating a threshold.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47677034
upvote count: 2
downvote count: 0
score: 2
has body: You need to pass the information in the function call: def name(): first_name = input("What is your name? ") if len(first_name) == 0: print("\nYou did not enter a name!") return name() else: print("\nHello %s." % first_name) surname(first_name) # pass first_name on to the surname function def surname(first_name): #first_name arrives here ready to be used in this function last_name = input("\nCan you tell my your last name please?") if len(last_name) == 0: print("\nYou did not enter a last name!") surname(first_name) else: print("Nice to meet you %s %s." % (first_name,last_name)) name()
answers question: http://stackoverflow.com/q/47676972
type: Answer

tensorflow
tags question: http://stackoverflow.com/q/47633153
tags question: http://stackoverflow.com/q/47676138
tags question: http://stackoverflow.com/q/47656367
type: Tag
tags question: http://stackoverflow.com/q/47543589
tags question: http://stackoverflow.com/q/47638633
tags question: http://stackoverflow.com/q/47583508
tags question: http://stackoverflow.com/q/47574634
tags question: http://stackoverflow.com/q/47544028
tags question: http://stackoverflow.com/q/47663687
tags question: http://stackoverflow.com/q/47561012
tags question: http://stackoverflow.com/q/47603276
tags question: http://stackoverflow.com/q/47652345
tags question: http://stackoverflow.com/q/47660764
tags question: http://stackoverflow.com/q/47654846
tags question: http://stackoverflow.com/q/47544687
tags question: http://stackoverflow.com/q/47636476
tags question: http://stackoverflow.com/q/47550885
tags question: http://stackoverflow.com/q/47572144
tags question: http://stackoverflow.com/q/47568966
tags question: http://stackoverflow.com/q/47545540
tags question: http://stackoverflow.com/q/47645298
tags question: http://stackoverflow.com/q/47602302
tags question: http://stackoverflow.com/q/47670697
tags question: http://stackoverflow.com/q/47643285
tags question: http://stackoverflow.com/q/47662661
tags question: http://stackoverflow.com/q/47653149
tags question: http://stackoverflow.com/q/47585817
tags question: http://stackoverflow.com/q/47646183
tags question: http://stackoverflow.com/q/47673244
tags question: http://stackoverflow.com/q/47690976
tags question: http://stackoverflow.com/q/47641709
tags question: http://stackoverflow.com/q/47642211
tags question: http://stackoverflow.com/q/47665391
tags question: http://stackoverflow.com/q/47679859
tags question: http://stackoverflow.com/q/47641974
tags question: http://stackoverflow.com/q/47604506
tags question: http://stackoverflow.com/q/47695560
tags question: http://stackoverflow.com/q/47657835
tags question: http://stackoverflow.com/q/47605758
tags question: http://stackoverflow.com/q/47625813
tags question: http://stackoverflow.com/q/47558518
tags question: http://stackoverflow.com/q/47638104
tags question: http://stackoverflow.com/q/47647876
tags question: http://stackoverflow.com/q/47609080
tags question: http://stackoverflow.com/q/47544892
tags question: http://stackoverflow.com/q/47624488
tags question: http://stackoverflow.com/q/47593815
tags question: http://stackoverflow.com/q/47565377
tags question: http://stackoverflow.com/q/47642767
tags question: http://stackoverflow.com/q/47580716
tags question: http://stackoverflow.com/q/47662076
tags question: http://stackoverflow.com/q/47580615
tags question: http://stackoverflow.com/q/47617043
tags question: http://stackoverflow.com/q/47583501
tags question: http://stackoverflow.com/q/47637241
tags question: http://stackoverflow.com/q/47644306
tags question: http://stackoverflow.com/q/47650132
tags question: http://stackoverflow.com/q/47588786
tags question: http://stackoverflow.com/q/47677434
tags question: http://stackoverflow.com/q/47562817
tags question: http://stackoverflow.com/q/47658039
tags question: http://stackoverflow.com/q/47550498
tags question: http://stackoverflow.com/q/47592839
tags question: http://stackoverflow.com/q/47651342
tags question: http://stackoverflow.com/q/47667541
tags question: http://stackoverflow.com/q/47628682
tags question: http://stackoverflow.com/q/47572891
tags question: http://stackoverflow.com/q/47570804
tags question: http://stackoverflow.com/q/47576647
tags question: http://stackoverflow.com/q/47678420
tags question: http://stackoverflow.com/q/47624798
tags question: http://stackoverflow.com/q/47635507
tags question: http://stackoverflow.com/q/47577108
tags question: http://stackoverflow.com/q/47694415
tags question: http://stackoverflow.com/q/47663367
tags question: http://stackoverflow.com/q/47593679
tags question: http://stackoverflow.com/q/47641678
tags question: http://stackoverflow.com/q/47644110
tags question: http://stackoverflow.com/q/47694551

http://stackoverflow.com/comment/82090083
score: 0
comment on: http://stackoverflow.com/q/47565885
type: Comment
type: QuestionComment
has text: @SandeepBalagopal I thinks this solution is make more slot in database. Any solution?

http://stackoverflow.com/q/47686313
has comment: http://stackoverflow.com/comment/82335654
favorite count: 0
type: Question
has title: How to copy a field from a .gz file to a csv
has comment: http://stackoverflow.com/comment/82332380
has body: Is there a way to copy a field, from a .gz file into a txt file without unzipping in either Windows commands or Python? The .gz file is over 15000 lines long If field 1="SVR" i need to output fields 2, 3, 4, 6, 7, 11, 12, 13 and 21. (if $1 = other, ignore) Can be written to any other file type, does not have to be txt.
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82332894
tagged with: windows
score: -3
tagged with: python
upvote count: 0
tagged with: batch-file
downvote count: 3
has comment: http://stackoverflow.com/comment/82332450
has comment: http://stackoverflow.com/comment/82332242
has answer: http://stackoverflow.com/a/47694323
answer count: 1
tagged with: cmd

http://stackoverflow.com/q/47582095
type: Question
has answer: http://stackoverflow.com/a/47582352
has comment: http://stackoverflow.com/comment/82121950
has answer: http://stackoverflow.com/a/47582149
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82121912
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82121862
has comment: http://stackoverflow.com/comment/82122916
has comment: http://stackoverflow.com/comment/82121820
has comment: http://stackoverflow.com/comment/82121790
has body: I'm trying to get a count on, for example, how many a's are in a massive list of passwords out of curiosity. but i think when i'm trying to add a count for a character it's killing the loop that is going through all the characters. #Examine passwords.txt file = open('passwords.txt','r') a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 i = 0 j = 0 k = 0 l = 0 m = 0 n = 0 o = 0 p = 0 q = 0 r = 0 s = 0 t = 0 u = 0 v = 0 w = 0 x = 0 y = 0 z = 0 with open('passwords.txt','r') as fileobj: for line in fileobj: for char in line: if char == a: a += 1 elif char == b: b += 1 print(a) print(b) print(c) print(d) print(e) print(f)
has title: counting individual characters in a large list of passwords without killing loop

http://stackoverflow.com/comment/86334719
type: AnswerComment
comment on: http://stackoverflow.com/a/47667558
score: 0
type: Comment
has text: @paul haha yes, I noticed that ;)

networkx
tags question: http://stackoverflow.com/q/47675349
tags question: http://stackoverflow.com/q/47693001
tags question: http://stackoverflow.com/q/47653306
tags question: http://stackoverflow.com/q/47681617
tags question: http://stackoverflow.com/q/47575469
tags question: http://stackoverflow.com/q/47607685
tag name: networkx
tags question: http://stackoverflow.com/q/47555594
tags question: http://stackoverflow.com/q/47597418
tags question: http://stackoverflow.com/q/47579442
tags question: http://stackoverflow.com/q/47553778
tags question: http://stackoverflow.com/q/47561779
tags question: http://stackoverflow.com/q/47608461
tags question: http://stackoverflow.com/q/47557480
tags question: http://stackoverflow.com/q/47697212
tags question: http://stackoverflow.com/q/47584126
tags question: http://stackoverflow.com/q/47624014
tags question: http://stackoverflow.com/q/47652299
type: Tag

http://stackoverflow.com/a/47685790
has comment: http://stackoverflow.com/comment/82358546
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47685405
downvote count: 0
has body: A solution strategy is to add an element before and to the last so that the buttons remain enabled, we intercept the changes so that instead of going to the last go to the second, and vice versa, instead of going to the first one, you must go to the last one. Example: class StringBox(QSpinBox): def __init__(self, parent=None): super(StringBox, self).__init__(parent) strings = [] texts = ["do", "re", "mi", "fa", "sol", "la", "si"] for key in texts: strings.append(key) self.setStrings([""] + strings + ["-"]) self.setValue(1) def strings(self): return self._strings def setStrings(self, strings): strings = list(strings) self._strings = tuple(strings) self._values = dict(zip(strings, range(len(strings)))) self.setRange(0, len(strings)-1) def textFromValue(self, value): return self._strings[value] def valueFromText(self, text): return self._values[text] def stepBy(self, step): if self.value() == 1 and step == -1: self.setValue(self.maximum()) elif self.value() == self.maximum() -1 and step == 1: self.setValue(0) QSpinBox.stepBy(self, step) if __name__ == "__main__": import sys app = QApplication(sys.argv) w = StringBox() w.show() sys.exit(app.exec_()) Note: Since you are using a dictionary and these can not have repeated keys, I recommend that the elements you add be different from the texts you show.
accepted answer of: http://stackoverflow.com/q/47685405
has comment: http://stackoverflow.com/comment/82364451
upvote count: 2
has comment: http://stackoverflow.com/comment/82364409
has comment: http://stackoverflow.com/comment/82358622
type: AcceptedAnswer

http://stackoverflow.com/comment/110090294
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62247414
has text: This question is already answered, if you think there is something to add to this question, you should put at least a different solution from what is answered here.
type: Comment

http://stackoverflow.com/comment/82204852
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47623228
has text: This is an example of my input file >3ENMA 113E84F72145D181 316 XRAY 2.350 0.215 0.269 no Dual specificity mitogen-activated protein kinase kinase 6 <MP2K6_HUMAN(45-332)> [Homo sapiens] ||3ENMB 3ENMC 3ENMD MSYYHHHHHHDYDIPTTENLYFQGAME-----------------NFEVKADDLEPIMELGRGAYGVVEKMRHVPSGQIMA VKRIRATVNSQEQKRLLMDLDISMRTVDCPFTVTFYGALFREGDVWICMELMDTSLDKFYKQVIDKGQTIPEDILGKIAV SIVKALEHLHSKLSVIHRDVKPSNVLINALGQVKMCDFGISGYLVDDVAKDIDAGCKPYMAPERINPELNQKGYSVKSDI WSLGITMIELAILRFPYDSWGTPFQQLKQVVEEPSPQLPADKFSAEFVDFTSQCLKKNSKERPTYPELMQHPFFTLHESK GTDVASFVKLILA-------

http://stackoverflow.com/a/47656490
has body: That ('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01') syntax is not valid Python. Assuming you actually want a list of dictionaries, it's not too hard to perform that conversion. You first need to grab the time stamp so it can be combined with each of the other items, and then you can drop it from the dict to make it easier to copy the remaining items to the new structure. Note that this modifies the original dict passed to the function. If you don't want that, you can either make a copy of the passed-in dict, or put an if test in the loop that copies the data to the new structure so that the time item is skipped. def convert(old): time_key = 'Time ' # Save the time time_item = (time_key, old[time_key]) # Add remove it del old[time_key] # Copy remaining items to new dicts and save them in a list return [dict([time_item, item]) for item in old.items()] row = { 'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01', 'Voltage [V]': '221.64', 'Current [A]': '0.08', } new_data = convert(row) for d in new_data: print(d) output {'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'} {'Time ': '2017-12-01T13:54:04', 'Voltage [V]': '221.64'} {'Time ': '2017-12-01T13:54:04', 'Current [A]': '0.08'} Here's how to do it if you don't want to mutate or copy the original dict: def convert(old): time_key = 'Time ' # Save the time time_item = (time_key, old[time_key]) # Copy other items to new dicts and save them in a list return [dict([time_item, (key, val)]) for key, val in old.items() if key != time_key] Note that this is less efficient because it has to test every key to ensure it's not the time key. To save the data in a list of OrderedDicts, we need to change the logic slightly. We also need to create the OrderedDicts properly so that the items are in the desired order. from collections import OrderedDict from pprint import pprint def convert(row): time_key = 'Time ' time_value = row[time_key] new_data = [] for key, val in row.items(): if key == time_key: continue new_…
accepted answer of: http://stackoverflow.com/q/47649972
score: 0
has comment: http://stackoverflow.com/comment/82273427
has comment: http://stackoverflow.com/comment/82275413
answers question: http://stackoverflow.com/q/47649972
type: Answer
has comment: http://stackoverflow.com/comment/82274269
type: AcceptedAnswer

http://stackoverflow.com/q/47557983
has body: I have some problem which i cannot find answer to. After installing scikit-video and FFmpeg i got this error: AttributeError: 'FFmpegWriter' object has no attribute '_proc' can you help me to find solution to this. from skvideo.io import FFmpegWriter def main(): ... video_writer = FFmpegWriter('video.mp4') ... if __name__ == '__main__': main() Already tried to install pyaudio, reinstall FFmpeg and skvideo and install different versions of packages. Does not help at all. Edit: an example of the full traceback resulting from /skvideo/io/abstract.py is below. Traceback (most recent call last): File "run_modules.py", line 93, in &lt;module&gt; Pipeline.create_videos(video_attr, args.output_path, args.padded) File "/home/leuko/.local/lib/python3.6/site-packages/skvideo/io/abstract.py", line 474, in close if self._proc is None: # pragma: no cover AttributeError: 'FFmpegWriter' object has no attribute '_proc'
has title: AttributeError: 'FFmpegWriter' object has no attribute '_proc'
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58193087
score: 5
tagged with: ffmpeg
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/82073596

http://stackoverflow.com/comment/82176594
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47609028
has text: @Atto Allas actually it coming from database then how to pass it as string cur.execute("SELECT * FROM `test` WHERE `id`=?", (1,)) rows = cur.fetchone() rows[1]=10 self.abc.text =rows[1]

http://stackoverflow.com/q/47588234
type: Question
tagged with: python-imaging-library
has body: Using PIL to convert a RGB image to a (H, W, 3) numpy array is very fast. im = np.array(PIL.open(path)) However, I cannot find a fast way to convert a grayscale image to a (H, W, 1) array. I tried two approaches but they are both much slower than above: im = np.array(PIL.open(path)) # return an (H, W) array im = np.expand_dims(im, axis=0) im = im.astype(int) This approach is slow too: img = PIL.open(path) im = np.array(img.getdata()).reshape(img.size[1], img.size[0], 1) Please advice...
score: 1
has comment: http://stackoverflow.com/comment/82134437
has comment: http://stackoverflow.com/comment/82135491
tagged with: python
has comment: http://stackoverflow.com/comment/82135138
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82135178
accepted answer: http://stackoverflow.com/a/47588391
has title: Use PIL to convert a grayscale image to a (1, H, W) numpy array
has answer: http://stackoverflow.com/a/47588391
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82135603
favorite count: 0

ajax
tags question: http://stackoverflow.com/q/47695007
tags question: http://stackoverflow.com/q/47610505
tags question: http://stackoverflow.com/q/47548076
tags question: http://stackoverflow.com/q/47588196
tags question: http://stackoverflow.com/q/47661591
tags question: http://stackoverflow.com/q/47629124
type: Tag
tags question: http://stackoverflow.com/q/47548863
tags question: http://stackoverflow.com/q/47570493
tags question: http://stackoverflow.com/q/47566489
tags question: http://stackoverflow.com/q/47687046
tags question: http://stackoverflow.com/q/47652443
tags question: http://stackoverflow.com/q/47659889
tag name: ajax

http://stackoverflow.com/comment/82125422
has text: Ah, perfect, I was heading in a direction like that, but this is much simpler!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47583335
type: Comment

http://stackoverflow.com/q/47598578
tagged with: regex
has body: a = re.sub('"', '-','10’0”') This result is : 10’0” Why won't re.sub affect the 10'0" inside the brackets?
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has title: re.sub not affecting values inside between brackets
has answer: http://stackoverflow.com/a/47598641
answer count: 1
accepted answer: http://stackoverflow.com/a/47598641
has comment: http://stackoverflow.com/comment/82155459
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82155487
score: -2
tagged with: python

http://stackoverflow.com/q/47617499
score: 1
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47618411
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: I have data that looks like this: timestamp value 0 12345 0.0 1 12346 1.0 2 12347 4.0 3 12348 2.0 4 12349 6.0 ... and I want to turn it into e.g something like this: timestamp value 0 12345 0.5 1 12346 0.5 2 12347 3.0 3 12348 3.0 4 12349 6.0 ... I want to reduce the "resolution" of my values by replacing them with the mean of a certain time range. This is similar to: df = df.groupby(df.index // N).mean() Where N is the number of rows to mean, except that: I want to preserve the number of rows (aka in pandas: "pad"/"ffill" those means). Related to (1), the timestamps should remain untouched, rather than get mean'd along with the values. Ideally I don't want to group by N rows, but rather time ranges (e.g. minutes, hours, days) since I can't guarantee that the timestamps are equally spaced. I realise this is a bit complicated, and can be done in a variety of different steps, but I'm new at using pandas and was hoping there are simpler built-in steps. Any pointers much appreciated!
downvote count: 0
tagged with: python
has title: How can I replace values in a range of time with their mean with pandas?
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/86195327
score: 3
has text: You should explain how this is different (or better) than the existing response.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49593825

http://stackoverflow.com/a/47590715
has comment: http://stackoverflow.com/comment/82268423
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47590595
type: Answer
answers question: http://stackoverflow.com/q/47590595
score: 2
has body: If the data is nested two levels deep, We can use the chain function to concatenate the iterables together, and then let sum(..) calculate the sum of the iterable. So: from itertools import chain sum(chain.from_iterable(outer_iter)) chain.from_iterable takes as input an iterable of iterables, and converts this into an iterable that lazily obtains the elements from the iterables one at a time. We can use iterable unpacking on chain, but if the outer iterable is an infinite list, the algorithm would get stuck (and eventually run out of memory).
has comment: http://stackoverflow.com/comment/82267444
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47565769
score: 3
accepted answer of: http://stackoverflow.com/q/47565618
upvote count: 3
answers question: http://stackoverflow.com/q/47565618
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82089939
has comment: http://stackoverflow.com/comment/82089617
has comment: http://stackoverflow.com/comment/82089645
has body: As Sebastian said is == doesn't make sense. You could use an == test to do this task, but it would require a double for loop: in the inner loop you'd have to search through b to find an entry that matches the current dict in the a list, and if a matching item isn't found that means you'd be searching through the whole b list. Also, you don't want to do a.append here: that would add a new item to the a list, but you actually want to modify the existing items inside a. An efficient way to do this is to first create a new dict to hold the data in b so we can look up 'actual_duration' via the 'employee_name' string. When we loop over the a list we use the .get method to retrieve the 'actual_duration' from the temp dict, so if we can't find a matching entry for that name then we set the 'actual_duration' in a to the default value of zero. a = [{'employee_name': 'A', 'total_duration': 0,}, {'employee_name': 'B', 'total_duration': 11.0}, {'employee_name': 'C', 'total_duration': 9.0}, {'employee_name': 'D', 'total_duration':4.0,}, {'employee_name': 'E', 'total_duration': 0}] b = [{'employee_name': 'A', 'actual_duration': 28}, {'employee_name': 'C', 'actual_duration': 22}, {'employee_name': 'D', 'actual_duration': 15}] temp = {d['employee_name']: d['actual_duration'] for d in b} for emp in a: emp['actual_duration'] = temp.get(emp['employee_name'], 0) for row in a: print(row) output {'employee_name': 'A', 'total_duration': 0, 'actual_duration': 28} {'employee_name': 'B', 'total_duration': 11.0, 'actual_duration': 0} {'employee_name': 'C', 'total_duration': 9.0, 'actual_duration': 22} {'employee_name': 'D', 'total_duration': 4.0, 'actual_duration': 15} {'employee_name': 'E', 'total_duration': 0, 'actual_duration': 0}
type: Answer
has comment: http://stackoverflow.com/comment/82089826
has comment: http://stackoverflow.com/comment/82089793
has comment: http://stackoverflow.com/comment/82089561

http://stackoverflow.com/comment/82112153
comment on: http://stackoverflow.com/q/47577395
score: 1
has text: Related: https://stackoverflow.com/questions/3588776/how-is-eq-handled-in-python-and-in-what-order
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82330298
comment on: http://stackoverflow.com/q/47662152
score: 0
has text: a `couchbase.n1ql.N1QLRequest` object
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82175019
type: QuestionComment
comment on: http://stackoverflow.com/q/47608315
score: 4
has text: did you search this before posting your question here ???
type: Comment

http://stackoverflow.com/comment/82154956
type: Comment
comment on: http://stackoverflow.com/a/47594517
type: AnswerComment
score: 0
has text: @Anthon ah yes, I forgot that [the fix](https://github.com/yaml/pyyaml/commit/7b68405c81db889f83c32846462b238ccae5be80) has not yet been released.

http://stackoverflow.com/q/47643249
type: Question
upvote count: 2
has title: How word embeddings work for word similarity?
type: UnansweredQuestion
tagged with: doc2vec
answer count: 1
tagged with: word-embedding
tagged with: word2vec
tagged with: python
has comment: http://stackoverflow.com/comment/82256262
score: 2
downvote count: 0
has body: I am trying to apply word2vec/doc2vec to find similar sentences. First consider word2vec for word similarity. What I understand is, CBOW can be used to find most suitable word given a context, whereas Skip-gram is used to find the context given some word, so in both cases, I am getting words that co-occur frequently. But how does it work to find similar words? My intuition is, since similar words tend to occur in similar contexts, the words similarity is actually measured from the similarity among contextual/co-occuring words. In the neural net, when the vector representation for some word at the hidden layer is passed through to the output layer, it outputs probabilities of co-occuring words. So, the co-occuring words influence the vectors of some words, and since similar words have similar set of co-occuring words, their vector representations are also similar. To find the similarity, we need to extract the hidden layer weights (or vectors) for each word and measure their similarities. Do I understand it correctly? Finally, what is a good way to find tweet text (full sentence) similarity using word2vec/doc2vec?
tagged with: nlp
has answer: http://stackoverflow.com/a/47648764
favorite count: 0

http://stackoverflow.com/q/47685331
favorite count: 0
type: Question
has title: python mock exception handling
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47685619
has answer: http://stackoverflow.com/a/47685619
type: AnsweredQuestion
score: 1
answer count: 1
upvote count: 1
has body: I have couple of tasks in my workflow..Now, I want to mock the output of Task1 returning exception and just test task2.run method is not called. class Task1(): def run(self): try: return 2,2 except Exception as e: print e raise Exception('Task1 Exception') class Task2(): def run(self,x,y): try: return 2 * (x*y) except Exception as e: print e raise Exception('Task2 Exception') class Workflow(): def run(self,task1, task2): x,y = task1.run() print task2.run(x,y) task1 = Task1() task2 = Task2() w = Workflow() w.run(task1,task2) Here is my unittest - import unittest import mock from test2 import Task1, Task2, Workflow class TestWorkflow(unittest.TestCase): def test_workflow(self): self.task1 = mock.MagicMock(Task1()) # mocking task1 self.task2 = mock.MagicMock(Task2()) self.task1.side_effect = Exception() # setting task1 exception to an exception object self.workflow = Workflow() self.workflow.run(self.task1, self.task2) self.task2.run.assert_not_called() # checking task2 is not called. if __name__ == '__main__': unittest.main() Exception:- x,y = task1.run() ValueError: need more than 0 values to unpack

http://stackoverflow.com/q/47577556
accepted answer: http://stackoverflow.com/a/47577722
has body: I have a Python script called renaming.py that I want to use to generate many Bash scripts (over 500). The Python script looks like so: #!/usr/bin/python #Script to make multiple Bash scripts based on a .txt file with names of files #The .txt file contains names of files, one name per line #The .txt file must be passed as an argument. import os import sys script_tpl="""#!/bin/bash #BSUB -J "renaming_{line}" #BSUB -e /scratch/username/renaming_SNPs/renaming_{line}.err #BSUB -o /scratch/username/renaming_SNPs/renaming_{line}.out #BSUB -n 8 #BSUB -R "span[ptile=4]" #BSUB -q normal #BSUB -P DBCDOBZAK #BSUB -W 168:00 cd /scratch/username/renaming_SNPs awk '{sub(/.*/,$1 "_" $3,$2)} 1' {file}.gen &gt; {file}.renamed.gen """ with open(sys.argv[1],'r') as f: for line in f: line = line.strip() if not line: continue line = line.strip(".gen") script = script_tpl.format(line=line) with open('renaming_{}.sh'.format(line), 'w') as output: output.write(script) The .txt file I pass as an argument to this Python script looks like so: chr10.10.merged.no_unwanted.formatted.gen chr10.11.merged.no_unwanted.formatted.gen chr10.12.merged.no_unwanted.formatted.gen chr10.13.merged.no_unwanted.formatted.gen chr10.14.merged.no_unwanted.formatted.gen chr10.15.merged.no_unwanted.formatted.gen etc When I run the Python script, I get the following error message: Traceback (most recent call last): File "renaming.py", line 33, in &lt;module&gt; script = script_tpl.format(line=line) KeyError: 'sub(/' I am not entirely sure what is happening, but here is what I think Something is wrong with line 33 - not sure what is the problem. I have used very similar scripts like this one before. In this line 33, I am replacing all the {line} instances in script_tpl by the entries in the .txt file (this happens 500, once for each line of the .txt file). I am very confused by the KeyError. I am working on Linux HPC server (using a Mac laptop). I have managed to use this awk command with no problem when directly typ…
tagged with: awk
type: Question
has answer: http://stackoverflow.com/a/47577713
possible better answer: http://stackoverflow.com/a/47577713
score: 0
has title: KeyError in Python script used to generate Bash scripts
has answer: http://stackoverflow.com/a/47577722
tagged with: python
tagged with: keyerror
type: AnsweredQuestion
answer count: 2
tagged with: bash

traitsui
tag name: traitsui
type: Tag
tags question: http://stackoverflow.com/q/47692092

python-2.7
tags question: http://stackoverflow.com/q/47563262
tags question: http://stackoverflow.com/q/47640743
tags question: http://stackoverflow.com/q/47645584
tags question: http://stackoverflow.com/q/47614983
tags question: http://stackoverflow.com/q/47641005
tags question: http://stackoverflow.com/q/47618888
tags question: http://stackoverflow.com/q/47664372
tags question: http://stackoverflow.com/q/47673889
tags question: http://stackoverflow.com/q/47569973
tags question: http://stackoverflow.com/q/47672534
tags question: http://stackoverflow.com/q/47672905
tags question: http://stackoverflow.com/q/47642578
tags question: http://stackoverflow.com/q/47610123
tags question: http://stackoverflow.com/q/47624975
tags question: http://stackoverflow.com/q/47598311
tags question: http://stackoverflow.com/q/47672316
tags question: http://stackoverflow.com/q/47550476
tags question: http://stackoverflow.com/q/47592032
tags question: http://stackoverflow.com/q/47613183
tags question: http://stackoverflow.com/q/47626299
tags question: http://stackoverflow.com/q/47609028
tags question: http://stackoverflow.com/q/47640554
tags question: http://stackoverflow.com/q/47645484
tags question: http://stackoverflow.com/q/47657824
tags question: http://stackoverflow.com/q/47540863
tags question: http://stackoverflow.com/q/47578855
tags question: http://stackoverflow.com/q/47644448
tags question: http://stackoverflow.com/q/47646371
tags question: http://stackoverflow.com/q/47544411
tags question: http://stackoverflow.com/q/47638458
tags question: http://stackoverflow.com/q/47622691
tags question: http://stackoverflow.com/q/47623638
tags question: http://stackoverflow.com/q/47600807
tags question: http://stackoverflow.com/q/47671753
tags question: http://stackoverflow.com/q/47683727
tags question: http://stackoverflow.com/q/47630892
tags question: http://stackoverflow.com/q/47624319
tags question: http://stackoverflow.com/q/47654604
tags question: http://stackoverflow.com/q/47572695
tags question: http://stackoverflow.com/q/47603564
tags question: http://stackoverflow.com/q/47628023
tags question: http://stackoverflow.com/q/47652637
tags question: http://stackoverflow.com/q/47630350
tags question: http://stackoverflow.com/q/47586754
tags question: http://stackoverflow.com/q/47687055
tags question: http://stackoverflow.com/q/47577450
tags question: http://stackoverflow.com/q/47561768
tags question: http://stackoverflow.com/q/47626841
tags question: http://stackoverflow.com/q/47636699
type: Tag
tags question: http://stackoverflow.com/q/47685791
tags question: http://stackoverflow.com/q/47621864
tags question: http://stackoverflow.com/q/47552791
tags question: http://stackoverflow.com/q/47559124
tags question: http://stackoverflow.com/q/47578577
tags question: http://stackoverflow.com/q/47609324
tags question: http://stackoverflow.com/q/47564423
tags question: http://stackoverflow.com/q/47647410
tags question: http://stackoverflow.com/q/47673145
tags question: http://stackoverflow.com/q/47619145
tags question: http://stackoverflow.com/q/47566017
tags question: http://stackoverflow.com/q/47585195
tags question: http://stackoverflow.com/q/47545090
tags question: http://stackoverflow.com/q/47620066
tags question: http://stackoverflow.com/q/47551029
tags question: http://stackoverflow.com/q/47599810
tags question: http://stackoverflow.com/q/47599047
tags question: http://stackoverflow.com/q/47584192
tags question: http://stackoverflow.com/q/47542643
tags question: http://stackoverflow.com/q/47576803
tags question: http://stackoverflow.com/q/47588649
tags question: http://stackoverflow.com/q/47544101
tags question: http://stackoverflow.com/q/47552107
tags question: http://stackoverflow.com/q/47627366
tags question: http://stackoverflow.com/q/47648064
tags question: http://stackoverflow.com/q/47575101
tags question: http://stackoverflow.com/q/47688207
tags question: http://stackoverflow.com/q/47670310
tags question: http://stackoverflow.com/q/47605271
tags question: http://stackoverflow.com/q/47664001

http://stackoverflow.com/q/47626019
has answer: http://stackoverflow.com/a/47626058
downvote count: 1
favorite count: 0
type: Question
tagged with: key-value
upvote count: 2
accepted answer: http://stackoverflow.com/a/47626058
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 1
has title: How to test if an XML node has a specific string using Element Tree
answer count: 1
has body: I'm currently using Element Tree to parse some XML and some of it has multiple repeated name/value pairs that look like this. What i'm trying to do is extract the elements of interest i.e. gender = male and colour = red but I can't seem to do this using findall on it's own because of the structure. How do I extract these elements? I thought the correct logic would be to look for a child node where I can find child.text = 'gender' etc then go ahead and print out the name/values from that child node. What is the best way to do this? <a:characteristic> gender male </a:characteristic> <a:characteristic> age 30 </a:characteristic> <a:characteristic> colour red </a:characteristic> <a:characteristic> language python </a:characteristic>

http://stackoverflow.com/a/47575388
upvote count: 1
has body: I think you are writing { 'a':['b'], 'b':['c','d'], 'c':['i'], 'd':['e','l'], 'e':['f','g','h'], 'f':[], 'g':[], 'h':[], 'i':[], 'l':[] } from one json file to another json file. If you could do without a recursive function, try this: import json def generate_subtree(f_in, f_out): with open(f_in) as in_file, open(f_out, 'w') as out_file: json.dump(json.load(in_file), out_file) generate_subtree('from.json', 'to.json') Printing data written to to.json file: from pprint import pprint with open('to.json') as f: pprint(json.load(f)) {'a': ['b'], 'b': ['c', 'd'], 'c': ['i'], 'd': ['e', 'l'], 'e': ['f', 'g', 'h'], 'f': [], 'g': [], 'h': [], 'i': [], 'l': []}
score: 0
answers question: http://stackoverflow.com/q/47574857
downvote count: 1
has comment: http://stackoverflow.com/comment/82110745
type: Answer

http://stackoverflow.com/a/47605391
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47605034
has comment: http://stackoverflow.com/comment/82171445
has comment: http://stackoverflow.com/comment/82177529
has comment: http://stackoverflow.com/comment/82175684
accepted answer of: http://stackoverflow.com/q/47605034
has comment: http://stackoverflow.com/comment/82171596
type: Answer
has body: you have to clearly think about what you want the program to do. think of it this way, as your code will run sequentially , you have to get the user input data and then process it. for example as you want to know about number of apples, you check the sentece for existing , for example: if 'apple' in num1: if '3' in num1: print "he wants 3 apples" as if you wanted to extract the numbers, checkout the str.isdigit() method

http://stackoverflow.com/comment/82297496
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47669206
has text: @PaulPanzer oh, thank you, totally forgot about that. Would not put that in answer, but instead make reference to PM2Ring answer.
score: 0

http://stackoverflow.com/comment/82054278
has text: btw: don't use `except:pass` because you will no see that you have error. At least display message ie. `except Exception as e: print(e)`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47547771
type: QuestionComment

http://stackoverflow.com/q/47585856
has answer: http://stackoverflow.com/a/47586005
has comment: http://stackoverflow.com/comment/82129637
tagged with: export-to-csv
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82129638
has comment: http://stackoverflow.com/comment/82129590
has comment: http://stackoverflow.com/comment/82129912
has comment: http://stackoverflow.com/comment/82129569
has comment: http://stackoverflow.com/comment/82129685
type: Question
linked to: http://stackoverflow.com/q/47579348
has comment: http://stackoverflow.com/comment/82129599
has comment: http://stackoverflow.com/comment/82129601
possible better answer: http://stackoverflow.com/a/47585949
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/47585949
accepted answer: http://stackoverflow.com/a/47586005
has title: Python 3 JSON writing to CSV Error
has body: I am trying to write out a csv file from data in JSON format. I can get the fieldnames to write to the csv file but not the item value I need. This is my first time coding in python so any help would be appreciated. The json file can be found below for reference: https://data.ny.gov/api/views/nqur-w4p7/rows.json?accessType=DOWNLOAD Here is my error: Traceback (most recent call last): File "ChangeDataType.py", line 5, in &lt;module&gt; data = json.dumps(inputFile) File "/usr/lib64/python3.4/json/__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "/usr/lib64/python3.4/json/encoder.py", line 192, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib64/python3.4/json/encoder.py", line 250, in iterencode return _iterencode(o, 0) File "/usr/lib64/python3.4/json/encoder.py", line 173, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: &lt;_io.TextIOWrapper name='rows.json?accessType=DOWNLOAD' mode='r' encoding='UTF-8'&gt; is not JSON serializable Here is my code: import json import csv inputFile = open("rows.json?accessType=DOWNLOAD", "r") data = json.dumps(inputFile) with open("Data.csv","w") as csvfile: writer = csv.DictWriter(csvfile, extrasaction='ignore', fieldnames=["date", "new_york_state_average_gal", "albany_average_gal", "binghamton_average_gal",\ "buffalo_average_gal", "nassau_average_gal", "new_york_city_average_gal", "rochester_average_gal", "syracuse_average_gal","utica_average_gal"]) writer.writeheader() for row in data: writer.writerow([row["date"], row["new_york_state_average_gal"], row["albany_average_gal"], row["binghamton_average_gal"],\ row["buffalo_average_gal"], row["nassau_average_gal"], row["new_york_city_average_gal"], row["rochester_average_gal"], row["syracuse\ _average_gal"],row["utica_average_gal"]])

http://stackoverflow.com/a/47617590
type: Answer
has body: The solution that comes to my mind is to first get a list of table_name sorted by the highest count of the top record. Then sort your df in order of this list. first = df.sort_values(['table_name','count'],ascending=False).groupby('table_name').first() ordered = first.sort_values(['count'], ascending=False) orderedNameList = ordered['table_name'].tolist() df = df.sort_values(['table_name'],ascending=orderedNameList) My syntax is probably not correct but maybe a similar idea to this would work.
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47617188
score: 1

http://stackoverflow.com/q/47604047
downvote count: 0
accepted answer: http://stackoverflow.com/a/47604295
score: 1
upvote count: 1
has title: Merge axes before and after the i^{th} axis
linked to: http://stackoverflow.com/q/33945882
has comment: http://stackoverflow.com/comment/82167126
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82167142
has body: I want to reshape a numpy array arr to a shape of (before, at, after) for any one axis of arr. How to do this faster? The axis has been normalized: 0 &lt;= axis &lt; arr.ndim Program: import numpy as np def f(arr, axis): shape = arr.shape before = int(np.product(shape[:axis])) at = shape[axis] return arr.reshape(before, at, -1) Test: a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5) print(f(a, 2).shape) Result: (6, 4, 5)
has answer: http://stackoverflow.com/a/47604295
has comment: http://stackoverflow.com/comment/82167100
possible better answer: http://stackoverflow.com/a/47604137
tagged with: python
has answer: http://stackoverflow.com/a/47604137
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82161883
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47601533
has text: It might be a good idea to show us your code so that we have a clearer picture of what you're doing
score: 2

django-rest-framework
tags question: http://stackoverflow.com/q/47654662
tags question: http://stackoverflow.com/q/47627293
tags question: http://stackoverflow.com/q/47562387
tags question: http://stackoverflow.com/q/47623021
tags question: http://stackoverflow.com/q/47668564
tags question: http://stackoverflow.com/q/47630356
tags question: http://stackoverflow.com/q/47694599
tags question: http://stackoverflow.com/q/47686971
tags question: http://stackoverflow.com/q/47597750
tags question: http://stackoverflow.com/q/47597560
tags question: http://stackoverflow.com/q/47631764
tags question: http://stackoverflow.com/q/47571647
tags question: http://stackoverflow.com/q/47662496
tags question: http://stackoverflow.com/q/47686045
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/47691718
tags question: http://stackoverflow.com/q/47551989
tags question: http://stackoverflow.com/q/47592229
tags question: http://stackoverflow.com/q/47577304
tags question: http://stackoverflow.com/q/47670937
tags question: http://stackoverflow.com/q/47582764
tags question: http://stackoverflow.com/q/47640057
tags question: http://stackoverflow.com/q/47560003
tags question: http://stackoverflow.com/q/47623155
tags question: http://stackoverflow.com/q/47697473
type: Tag
tags question: http://stackoverflow.com/q/47671468
tags question: http://stackoverflow.com/q/47627057
tags question: http://stackoverflow.com/q/47588585
tags question: http://stackoverflow.com/q/47572321
tags question: http://stackoverflow.com/q/47608843
tags question: http://stackoverflow.com/q/47695466
tags question: http://stackoverflow.com/q/47576635
tags question: http://stackoverflow.com/q/47684775
tags question: http://stackoverflow.com/q/47618289

http://stackoverflow.com/q/47684438
upvote count: 4
answer count: 0
tagged with: setup.py
has title: I pip install a specific package with --global-option. How do I add that package as a dependency in setup.py?
downvote count: 0
linked to: http://stackoverflow.com/q/31805385
tagged with: dulwich
linked to: http://stackoverflow.com/q/25161727
has comment: http://stackoverflow.com/comment/82866678
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I'm using this package called Dulwich. While developing, I install it like this: pip install dulwich --global-option="--pure" I want to add dulwich as a dependency to the setup.py file for my own package, but i'm not sure how to get it to use that pure flag. If my dependencies just looks like this: DEPENDENCIES = [ 'dulwich', ] setup( install_requires=DEPENDENCIES, ... ) it will fail. I've tried all variations of adding --pure and --global-options but they all fail with errors like: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Invalid requirement, parse error at "'--pure'" How am I supposed to correctly add this package as a dependency? The end goal is that I can put my package on PyPi, so that when someone runs pip install my_package it will automatically run the equivalent of pip install dulwich --global-option="--pure" as well
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/17045817

http://stackoverflow.com/comment/82341237
has text: I don't know the specifics, I do know that Django 2.0 updated the admin considerably so I wouldn't be surprised if the way multi-select and other widgets work was changed, and `crispy-forms-foundation` hasn't been updated to reflect that change. As for how you update it, thats possibly another question but you start by raising an issue on that github page, seeing if you get a response, and if not you're left with having to fork the library, rewrite it to work with Django2.0, and then using your forked version in your code
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47689875
score: 0

http://stackoverflow.com/q/47584147
has answer: http://stackoverflow.com/a/74183103
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47584216
answer count: 3
possible better answer: http://stackoverflow.com/a/59472157
linked to: http://stackoverflow.com/q/36569511
tagged with: pypi
favorite count: 0
score: 9
type: Question
has title: Why is Twine 1.9.1 still uploading to legacy PyPi?
tagged with: twine
upvote count: 9
downvote count: 0
has answer: http://stackoverflow.com/a/59472157
tagged with: python
has body: I want to upload packages to pypi.org as mentioned in the Migrating to PyPI.org documentation, but Twine uploads to https://upload.pypi.org/legacy/. It's available on pypi.python.org/pypi/mypolr, but is not found on pypi.org. I've tried to read several other questions, tutorials, and guides. My pip.ini-file (I'm on Windows 10) looks like this: [distutils] index-servers = pypi [pypi] I don't have my username or password stored, so the [pypi] section is empty (as mentioned in migration docs). I've put the .ini-file in my user folder, and confirmed (per this answer) that it's actually using the one I've set (using environment variable PIP_CONFIG_FILE). Afraid that I had got something wrong, I also tried without a pip.ini-file to make Twine use its defaults. I'm using Python 3.6.3 (from Anaconda), and my tools' versions are: Twine 1.9.1 (migration docs says it should be 1.8+) setuptools 38.2.3 (migration docs says it should be 27+) Whether or not it's relevant, here is some more info: Link to my setup.py setup is imported from setuptools and not distutils.core README.rst is used as long description, but in the PyPi page only first 8 asterix of header is shown. (Compare this with this) The package I upload is version is 0.2.1 (at the time of posting this) setuptools_scm is used to fetch versions from git tags build is made with python setup.py sdist bdist_wheel Please let me know if there is any other information that could be useful to figure this out.
accepted answer: http://stackoverflow.com/a/47584216

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/47543983

http://stackoverflow.com/comment/82189062
has text: "The returned value is bound to the function name **instead** of the function object." might be argued as saying the same as the statement in the question, only much clearer. Anyway, excellent answer.
comment on: http://stackoverflow.com/a/47615169
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82066663
has text: There doesn't appear to be a quick fix, see e.g.[here](https://stackoverflow.com/q/5721831/7207392) or [here](https://stackoverflow.com/q/36635238/7207392)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47545251

http://stackoverflow.com/q/47651811
type: Question
has answer: http://stackoverflow.com/a/47653489
tagged with: python
tagged with: flask
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1
has body: How to handle inputs form like these: &lt;input type="text" name="time[1]" value="a"&gt; &lt;input type="text" name="time[2]" value="h"&gt; &lt;input type="text" name="time[3]" value="j"&gt; I tried to get values of inputs using the following approach: for index, time in enumerate(request.form.getlist('time[]')): pass As a result I have to get value and index inside time[]. For example, when I send only a one field: &lt;input type="text" name="time[3]" value="3"&gt; I should get value=j and index=3 How to do that?
accepted answer: http://stackoverflow.com/a/47653489
has title: How to handle input in Flask with indexes inside name?

http://stackoverflow.com/q/47600126
tagged with: pycharm
downvote count: 0
has body: I need to import 1.yaml 2.pypiper modules to the latest PyCharm IDE. I can not find pypiper in the list of available modules. When I am trying to add a new repository for the pypiper: https://github.com/epigen/pypiper.git still the same: typing pypiper in the search field does not yield anything. yaml at the same time can be found, but it is giving me an error when I am trying to add it: Could not find a version that satisfies the requirement yaml (from versions: ) No matching distribution found for yaml
score: 1
upvote count: 1
answer count: 1
has title: PyCharm, can not import modules
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82159455
has answer: http://stackoverflow.com/a/47601687
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82160446
tagged with: python
has comment: http://stackoverflow.com/comment/82159860
linked to: http://stackoverflow.com/q/14261614

http://stackoverflow.com/a/47665700
has comment: http://stackoverflow.com/comment/82304925
score: 71
has comment: http://stackoverflow.com/comment/82306181
type: Answer
has comment: http://stackoverflow.com/comment/82305163
has comment: http://stackoverflow.com/comment/120681167
upvote count: 71
accepted answer of: http://stackoverflow.com/q/47665391
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/114245842
answers question: http://stackoverflow.com/q/47665391
has comment: http://stackoverflow.com/comment/82305369
has body: The problem is input_shape. It should actually contain 3 dimensions only. And internally keras will add the batch dimension making it 4. Since you probably used input_shape with 4 dimensions (batch included), keras is adding the 5th. You should use input_shape=(32,32,1).

selenium-webdriver
tags question: http://stackoverflow.com/q/47644047
tags question: http://stackoverflow.com/q/47694922
tags question: http://stackoverflow.com/q/47542091
tags question: http://stackoverflow.com/q/47668840
tags question: http://stackoverflow.com/q/47573159
tags question: http://stackoverflow.com/q/47658787
tags question: http://stackoverflow.com/q/47581975
tags question: http://stackoverflow.com/q/47634093
tags question: http://stackoverflow.com/q/47692213
tags question: http://stackoverflow.com/q/47551317
tags question: http://stackoverflow.com/q/47633765
tags question: http://stackoverflow.com/q/47690548
tags question: http://stackoverflow.com/q/47543795
tags question: http://stackoverflow.com/q/47639173
tags question: http://stackoverflow.com/q/47549202
tags question: http://stackoverflow.com/q/47682372
type: Tag
tags question: http://stackoverflow.com/q/47575226
tags question: http://stackoverflow.com/q/47681842
tags question: http://stackoverflow.com/q/47599810
tags question: http://stackoverflow.com/q/47607377
tags question: http://stackoverflow.com/q/47647542
tags question: http://stackoverflow.com/q/47647833
tags question: http://stackoverflow.com/q/47616764
tags question: http://stackoverflow.com/q/47649746
tags question: http://stackoverflow.com/q/47615963
tags question: http://stackoverflow.com/q/47601634
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/47657841
tags question: http://stackoverflow.com/q/47594644

http://stackoverflow.com/q/47559154
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82108637
downvote count: 0
has comment: http://stackoverflow.com/comment/82085880
tagged with: python
favorite count: 0
score: 2
has body: I'm attempting to detect when an object is modified in SQLAlchemy's before_update mapper event. From the docs: To detect if the column-based attributes on the object have net changes, and will therefore generate an UPDATE statement, use object_session(instance).is_modified(instance, include_collections=False). However, I'm seeing that is_modified is returning True even if none of the object's columns have been modified and no UPDATE statement is emitted to the database. Below you'll find a working example and the version of SQLAlchemy that I'm using. Any idea on why this is happening? I took a peek at the SQLAlchemy source code for Session.is_modified, and it seems to use the object_state and the history. SQLAlchemy version: $ pip freeze | grep SQLAlchemy SQLAlchemy==1.1.9 Source: import logging from sqlalchemy.event import listens_for from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( backref, class_mapper, relationship, scoped_session, sessionmaker) from sqlalchemy.orm.session import Session from sqlalchemy import ( create_engine, inspect, Column, Integer, ForeignKey, MetaData) logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) Base = declarative_base() class Parent(Base): __tablename__ = "parents" id = Column(Integer, primary_key=True) class Child(Base): __tablename__ = "children" id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey("parents.id")) parent = relationship( "Parent", backref=backref("child", uselist=False), single_parent=True, cascade="all") engine = create_engine("sqlite://", echo=True) metadata = MetaData() with engine.begin() as connection: metadata = Base.metadata metadata.create_all(connection) session = scoped_session(sessionmaker(bind=engine)) @listens_for(Base, "before_update", propagate=True) def before_update(mapper, connection, target): session = Session.object_session(target) if session.is_modified(target, include_collections=False): logger.in…
has comment: http://stackoverflow.com/comment/82166741
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/82121140
type: Question
answer count: 0
has title: SQLAlchemy `Session.is_modified` returns `True`, even when object columns were not modified

http://stackoverflow.com/comment/82179189
type: QuestionComment
has text: Have you looked at https://stackoverflow.com/q/29564018/3088138 as an example of changing Euler to RK4 in LOGO
comment on: http://stackoverflow.com/q/47551526
score: 0
type: Comment

http://stackoverflow.com/comment/82122196
score: 0
has text: @kindall You are right, I can use stdin directly rather than use cat but I would like script2 to reliably distinguish different files like what chepner has indicated. Do you know how this could be done?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47579112

http://stackoverflow.com/a/47721630
has body: Passing a tuple with 0, such as (0, 2) as shape parameter is allowed, but the resulting array is empty since it contains 0*2 = 0 elements. Written out in words, it's "zero rows with 2 elements in each row" where "2 elements in each row" is not of much consequence since there are no rows. Such arrays arise when slicing goes wrong: for example, b = np.ones((2, 2)) a = b[2:, :] makes a an array of shape (0, 2) as there are no values of the first index that fall in the given slice. There is no reason to create such arrays intentionally. There is no difference between np.empty([2, 2]) and np.empty((2, 2)), the array creation method, as many other NumPy methods, accepts a list instead of a tuple. It's still recommended to use tuples for shape parameters, because arr.shape is always a tuple.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47686438
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47686438
downvote count: 0

http://stackoverflow.com/q/47599274
has body: I'm fairly new to python and i'm trying to make a file, move the current script into that file and run it but i keep getting the same problem, it creates a folder, moves the file but when I open the script, it makes a new folder and moves the file. so you'll end up with the file directory being: 'C:somefile\someotherfile\newfile\newfile\newfile\script.py' Please help! Code: import os curpath = ('.\\Test.py') print(curpath) newpath = ('.\\Example Folder\\') if not os.path.exists(newpath) and curpath != ('..\\Example Folder\\Test.py'): os.makedirs(newpath) abspath=os.path.abspath(curpath) print(abspath) os.rename(abspath, newpath + 'Test.py') EDIT: When the answer given didn't work I spent 2 days trying to work it out myself (along with the day of trying before I posted). I finally found out the answer! import os curpath = __file__.lower() abspath=os.path.abspath(curpath) newpath = ('.\\example folder\\') notpath = '..\\example folder\\' if not os.path.exists(newpath) and not os.path.exists(notpath): os.makedirs(newpath) os.rename(abspath, '.\\example folder\\test.py')
has comment: http://stackoverflow.com/comment/82157129
has answer: http://stackoverflow.com/a/47599493
answer count: 2
downvote count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82156981
has comment: http://stackoverflow.com/comment/82157260
type: Question
has comment: http://stackoverflow.com/comment/82156934
type: UnansweredQuestion
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47600397
has title: Creating files and folders with python

http://stackoverflow.com/comment/82112852
score: 0
has text: So I really want the min of the difference, not the min of C
comment on: http://stackoverflow.com/a/47577370
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47652722
type: Answer
score: 2
has body: You need to make the log window the parent of the dialog: messagebox.showerror("error", "try again", parent=log) By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.
upvote count: 2
has comment: http://stackoverflow.com/comment/82263999
has comment: http://stackoverflow.com/comment/82263882
downvote count: 0
has comment: http://stackoverflow.com/comment/82267012
answers question: http://stackoverflow.com/q/47652001

http://stackoverflow.com/comment/82042951
type: QuestionComment
comment on: http://stackoverflow.com/q/47542809
score: 1
type: Comment
has text: Thank you for your help. It works. And @SherylHohman thank you for the suggestion, I will use them to test my expressions first

python-asyncio
tags question: http://stackoverflow.com/q/47577274
tags question: http://stackoverflow.com/q/47555934
tags question: http://stackoverflow.com/q/47673104
tags question: http://stackoverflow.com/q/47603983
tags question: http://stackoverflow.com/q/47652836
tags question: http://stackoverflow.com/q/47675410
tags question: http://stackoverflow.com/q/47620133
tag name: python-asyncio
type: Tag
tags question: http://stackoverflow.com/q/47627900
tags question: http://stackoverflow.com/q/47662040

http://stackoverflow.com/q/47611305
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47611908
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: database
score: -3
tagged with: python
has title: Returning a database with locations
has body: I think I have the right idea to solve this function, but I'm not sure why I get this error when I test it. Can anyone please help me fix this? Error: conn = sqlite3.connect(db) sqlite3.OperationalError: unable to open database file Desired Output: &gt;&gt;&gt; get_locations(db, 'ANTA01H3F') [('ANTA01H3F', 'LEC01', 'AA112'), ('ANTA01H3F', 'LEC01', 'SY110'), ('ANTA01H3F', 'LEC02', 'AC223')] def get_locations(db, course): '''Return the course, section and locations of the exam for the given course.''' return run_query('''SELECT Courses.Course, Courses.Sections, Room.Locations FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = ?''', [course])
upvote count: 0
tagged with: sqlite

http://stackoverflow.com/q/47565780
tagged with: sorting
answer count: 1
has comment: http://stackoverflow.com/comment/82089623
has comment: http://stackoverflow.com/comment/82089589
has comment: http://stackoverflow.com/comment/82089611
accepted answer: http://stackoverflow.com/a/47566025
has comment: http://stackoverflow.com/comment/82089633
tagged with: list
type: Question
has body: I am trying to make a Priority Queue that takes in input that contains a dequeue or enqueue operation then the value followed by the priority might look like: enqueue 2 2 enqueue 1 3 enqueue 5 1 enqueue 6 2 dequeue dequeue dequeue dequeue I have this code at the start that sorts this by the order of priority: from queue import Queue data=[] while True: operation = input() if operation == "": break data.append(operation.split(" ")) data2=[] data3=[] for i in data: #separated into two list as not to get an out of range error when sorting if "enqueue" in i: data2.append(i) else: data3.append(i) data2=sorted(data2,key=lambda x: int(x[2])) data2=data2[::-1] #reversed to make it easier to order it by the highest priority data=data2+data3 #put the enqueue and dequeue inputs together again q=[] for i in data: if "enqueue" in i: #add to the queue by priority q.append(i[1]) if "dequeue" in i: #dequeue by priority print (q[0]) del q[0] My problem right now is that in the case of having the same priority, it should follow the first-in-first-out principle but since I sorted it, the initial order got lost. So I would have a list like: So I would have a list like: [['enqueue', '1', '3'], ['enqueue', '6', '2'], ['enqueue', '2', '2'], ['enqueue', '5', '1']] And it would output: 1 6 2 5 Instead of: 1 2 6 5 How can I change the sorting such that it sorts the items by the highest priority but keep the initial order of those with the same priority? Thank you in advance.
tagged with: python
tagged with: queue
has comment: http://stackoverflow.com/comment/82089777
has title: How do I sort a list of list to retain the item with the highest priority? (Python)
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47566025
has comment: http://stackoverflow.com/comment/82089795
has comment: http://stackoverflow.com/comment/82089676

http://stackoverflow.com/comment/82249840
type: QuestionComment
has text: What I really want is not only removing the subsets the even one of their values has been used before i.e mentioned in the sorted subsets' list.
comment on: http://stackoverflow.com/q/47645501
score: 0
type: Comment

http://stackoverflow.com/a/47581589
type: Answer
has comment: http://stackoverflow.com/comment/82126737
has comment: http://stackoverflow.com/comment/82145358
has comment: http://stackoverflow.com/comment/82120634
upvote count: 15
has body: The simple O(n) solution would be to count each 3-digit number: for nr in range(1000): cnt = text.count('%03d' % nr) if cnt &gt; 1: print '%03d is found %d times' % (nr, cnt) This would search through all 1 million digits 1000 times. Traversing the digits only once: counts = [0] * 1000 for idx in range(len(text)-2): counts[int(text[idx:idx+3])] += 1 for nr, cnt in enumerate(counts): if cnt &gt; 1: print '%03d is found %d times' % (nr, cnt) Timing shows that iterating only once over the index is twice as fast as using count.
downvote count: 2
score: 13
has comment: http://stackoverflow.com/comment/82127715
answers question: http://stackoverflow.com/q/47581326
has comment: http://stackoverflow.com/comment/82120818

http://stackoverflow.com/comment/82119046
score: 0
has text: And if I insert a data1 like: ' 5, data1', ' 8, data2', '13, data3', can I read that two first chars? I'm using that space(' ') with .format {:2}
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47580800

http://stackoverflow.com/comment/82144526
comment on: http://stackoverflow.com/q/47593493
type: Comment
type: QuestionComment
score: 0
has text: @Uvar Hope now it's implementable on individual's machine

http://stackoverflow.com/a/47607129
upvote count: 1
has body: You can solve this using a dictionary comprehension: &gt;&gt;&gt; original = {'I like': 14, 'you like': 12, 'he likes': 2} &gt;&gt;&gt; new_d = {tuple(k.split()): v for k,v in original.items()} &gt;&gt;&gt; new_d {('I', 'like'): 14, ('you', 'like'): 12, ('he', 'likes'): 2}
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47606995

postgresql
tags question: http://stackoverflow.com/q/47638644
tags question: http://stackoverflow.com/q/47634563
tags question: http://stackoverflow.com/q/47683579
tags question: http://stackoverflow.com/q/47590857
type: Tag
tags question: http://stackoverflow.com/q/47543061
tags question: http://stackoverflow.com/q/47655737
tags question: http://stackoverflow.com/q/47627344
tags question: http://stackoverflow.com/q/47626314
tags question: http://stackoverflow.com/q/47686258
tags question: http://stackoverflow.com/q/47591848
tags question: http://stackoverflow.com/q/47594707
tags question: http://stackoverflow.com/q/47546388
tags question: http://stackoverflow.com/q/47573733
tags question: http://stackoverflow.com/q/47545211
tags question: http://stackoverflow.com/q/47644739
tags question: http://stackoverflow.com/q/47585826
tags question: http://stackoverflow.com/q/47685160
tags question: http://stackoverflow.com/q/47685557
tags question: http://stackoverflow.com/q/47694188
tags question: http://stackoverflow.com/q/47541363
tags question: http://stackoverflow.com/q/47671551
tags question: http://stackoverflow.com/q/47598252
tags question: http://stackoverflow.com/q/47593797
tags question: http://stackoverflow.com/q/47555854
tags question: http://stackoverflow.com/q/47615152
tags question: http://stackoverflow.com/q/47665701
tags question: http://stackoverflow.com/q/47659445
tags question: http://stackoverflow.com/q/47630965
tag name: postgresql
tags question: http://stackoverflow.com/q/47571647
tags question: http://stackoverflow.com/q/47551567
tags question: http://stackoverflow.com/q/47628301
tags question: http://stackoverflow.com/q/47674583
tags question: http://stackoverflow.com/q/47593060
tags question: http://stackoverflow.com/q/47675855
tags question: http://stackoverflow.com/q/47564957
tags question: http://stackoverflow.com/q/47614728

http://stackoverflow.com/comment/82339479
comment on: http://stackoverflow.com/a/47690234
score: 0
type: Comment
has text: How strange!! I dropped this table and re-executed my program and it worked as expected. The funny thing is: I had dropped my old table before creating a new one, then this issue in my question happened. Have you encountered a similar issue before?
type: AnswerComment

http://stackoverflow.com/comment/82134346
has text: What if bytesRead is less than the bytes sent by your Python code? There's no guarantee you will receive the full buffer of data in a single receive event. Also, is there a reason why you can't just use the `Image.FromStream(...)` method?
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47588591

http://stackoverflow.com/q/47642211
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82243318
has comment: http://stackoverflow.com/comment/82243218
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82243431
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/82243042
has comment: http://stackoverflow.com/comment/82243142
score: 1
has body: I have a numpy 2D array and I need to call a function on all of its elements. The way I am doing it now is: h, w, c = x.shape for i in range( 0, h ): for j in range( 0, w ): my_func( x[i][j][0], x[i][j][1], x[i][j][2] ) my_func() is a function that determines the nearest colour to the pixels from x, whose R, G and B values are x[i][j][0], x[i][j][1] and x[i][j][2] at any position [i,j]. I am still learning about parallel programming in Python. What is the recommended way to call this function in parallel on different elements of the array x? I am also exploring the way of wrapping this up in Tensorflow to be able to run it on the GPU.
has title: How can I parallelise this nested for loop in Python?
has comment: http://stackoverflow.com/comment/82243178
tagged with: python
has comment: http://stackoverflow.com/comment/82242925
has comment: http://stackoverflow.com/comment/82242966
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/82318158
comment on: http://stackoverflow.com/a/47675047
type: Comment
has text: get rid of the none maybe
score: 0
type: AnswerComment

http://stackoverflow.com/a/47664376
has comment: http://stackoverflow.com/comment/82314184
has comment: http://stackoverflow.com/comment/82306807
has comment: http://stackoverflow.com/comment/82303163
type: Answer
has comment: http://stackoverflow.com/comment/82408523
accepted answer of: http://stackoverflow.com/q/47577184
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82307389
has body: Have a look here, it seems like the exact answer. Here instead there is my version of the above code fine tuned for text extraction (with masking too). Below there is the original code from the previous article, "ported" to python 3, opencv 3, added mser and bounding boxes. The main difference with my version is how the grouping distance is defined: mine is text-oriented while the one below is a free geometrical distance. import sys import cv2 import numpy as np def find_if_close(cnt1,cnt2): row1,row2 = cnt1.shape[0],cnt2.shape[0] for i in range(row1): for j in range(row2): dist = np.linalg.norm(cnt1[i]-cnt2[j]) if abs(dist) &lt; 25: # &lt;-- threshold return True elif i==row1-1 and j==row2-1: return False img = cv2.imread(sys.argv[1]) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imshow('input', img) ret,thresh = cv2.threshold(gray,127,255,0) mser=False if mser: mser = cv2.MSER_create() regions = mser.detectRegions(thresh) hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]] contours = hulls else: thresh = cv2.bitwise_not(thresh) # wants black bg im2,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,2) cv2.drawContours(img, contours, -1, (0,0,255), 1) cv2.imshow('base contours', img) LENGTH = len(contours) status = np.zeros((LENGTH,1)) print("Elements:", len(contours)) for i,cnt1 in enumerate(contours): x = i if i != LENGTH-1: for j,cnt2 in enumerate(contours[i+1:]): x = x+1 dist = find_if_close(cnt1,cnt2) if dist == True: val = min(status[i],status[x]) status[x] = status[i] = val else: if status[x]==status[i]: status[x] = i+1 unified = [] maximum = int(status.max())+1 for i in range(maximum): pos = np.where(status==i)[0] if pos.size != 0: cont = np.vstack(contours[i] for i in pos) hull = cv2.convexHull(cont) unified.append(hull) cv2.drawContours(img,contours,-1,(0,0,255),1) cv2.drawContours(img,unified,-1,(0,255,0),2) #cv2.drawContours(thresh,unified,-1,255,-1) for c in unified: (x,y,w,h) = cv2.boundingRect(c) cv2.rectangle(img, (x,y), (x+w,…
has comment: http://stackoverflow.com/comment/82360772
downvote count: 0
has comment: http://stackoverflow.com/comment/82309280
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82316433
has comment: http://stackoverflow.com/comment/82311989
answers question: http://stackoverflow.com/q/47577184

http://stackoverflow.com/comment/82117539
comment on: http://stackoverflow.com/a/47580063
has text: @BillKet you can use `decimal.Decimal` objects rather than `float` or `numpy.float64` objects. They can represent decimal numbers exactly, but this will come at a speed/memory cost. You will likely have to implement your own `arange` function as well. Here is the doc: https://docs.python.org/3.6/library/decimal.html
type: Comment
score: 0
type: AnswerComment

mfcc
type: Tag
tags question: http://stackoverflow.com/q/47690706
tag name: mfcc

http://stackoverflow.com/comment/82485878
type: QuestionComment
comment on: http://stackoverflow.com/q/47678013
has text: Hi Marcin, thanks for the comment. Here are the answers: 1. No, I did consider trying with setup.py but havent tried it so far. 2. I don't! Nowhere in the code do I use pytest...I have no idea why this exception is throwing with pytest. What we did observe though is that if we let it be run triggered by our crons then its working...we didn't have any more of this error since we turned our crons on...that means that what happened here remains a mystery for us and just happened when we manually ran the code and just the next day, the few first runs was just ok.
score: 0
type: Comment

http://stackoverflow.com/q/47586089
score: 1
linked to: http://stackoverflow.com/q/47152691
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/47152691
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82129877
type: UnansweredQuestion
tagged with: pivot-table
has body: example data: exdata = {'year':[1 ,2 ,5 ,7 ,2 ,3 ,2 ,4 ,8 ,9], 'price':[120 ,99 ,55 ,23 ,87 ,31 ,149 ,45 ,32 ,55], 'dist':[999 ,3741 ,8893 ,5321 ,1987 ,9299 ,573 ,4732 ,4536 ,4032], 'loca':['a' ,'b' ,'a' ,'c' ,'d' ,'d' ,'a' ,'e' ,'c' ,'a']} Using a pandas.pivot_table() to represent by 'price' pd.pivot_table(df, index=['price'], values=['year','dist'], aggfunc=[np.mean]) I want to represent the 'price' axis as a range in the above table. also want to express the number of each range. In this case, if the option is available in the 'pd.pivot_table()'
has title: Representing index rows as a range of values in 'pivot_table' of 'python pandas'
tagged with: python
tagged with: frequency-distribution
answer count: 0
tagged with: pandas

http://stackoverflow.com/q/47669376
tagged with: web-scraping
has title: How to transfer the text output into dataframe
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/82297541
has answer: http://stackoverflow.com/a/47669669
accepted answer: http://stackoverflow.com/a/47669669
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has body: I have done some web scraping with beautiful soup and here is the output text I got: TCGA-KK-A7B3-01A Male Stage not reported Alive FPKM 5.5 Living days 899 (2.5 years) TCGA-G9-6347-01A Male Stage not reported Alive FPKM 14.2 Living days 2089 (5.7 years) TCGA-KC-A4BL-01A Male Stage not reported Alive FPKM 3.8 Living days 934 (2.6 years) TCGA-KK-A7AQ-01A Male Stage not reported Alive FPKM 2.6 Living days 1610 (4.4 years) TCGA-G9-6373-01A Male Stage not reported Alive FPKM 4.7 Living days 811 (2.2 years) .... How do I save this result into a dataframe? How to save this information into csv files. I will need csv files to do further analysis?
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/47604233
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: django
score: 0
has answer: http://stackoverflow.com/a/47605455
has title: How to store Templates in Django 1.11?
tagged with: python
has body: I have two ways to use templates like this. Which is good in Django 1.11 1st way app1/ templates/ contact.html app2/ templates/ home.html about.html And then in settings TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'app1/templates'), os.path.join(BASE_DIR, 'app2/templates')], ... } 2nd way app1/ ... app2/ ... templates/ home.html about.html contact.html And then in settings TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], ... } Which is better in arranging templates

http://stackoverflow.com/comment/82128076
comment on: http://stackoverflow.com/q/47585046
score: 0
has text: Do you think you could throw this in an answer and I'll accept it?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47616241
has comment: http://stackoverflow.com/comment/95481449
score: 48
upvote count: 49
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47614999
has comment: http://stackoverflow.com/comment/116118635
has body: Use quiet=True: import nltk nltk.download('wordnet', quiet=True)

http://stackoverflow.com/q/47583880
type: Question
tagged with: network-programming
tagged with: sockets
tagged with: python
tagged with: packet-sniffers
accepted answer: http://stackoverflow.com/a/47587086
has comment: http://stackoverflow.com/comment/82126297
has comment: http://stackoverflow.com/comment/82125783
type: AnsweredQuestion
score: 0
tagged with: encoding
has body: The title pretty much describes the question: if I send a packet containing, I don't know, some text inside it, from a python program to an other, if there's a hacker sniffing packets on the network, would they be able to see the content of the packet?
answer count: 1
has title: Are python packets sent over sockets clear text?
has answer: http://stackoverflow.com/a/47587086

http://stackoverflow.com/a/47624817
accepted answer of: http://stackoverflow.com/q/47624629
type: Answer
has body: Your problem is that you are checking UPPER version of calc_again string. So you will have always uppercase letters in calc_again.upper(). To fix your code, just make your list of possible cases upper. if (calc_again.upper()=='Y' or calc_again.upper()=='YES' or calc_again.upper()=='YA'): calc() elif (calc_again=='N' or calc_again=="NO" or calc_again=='NOT'): print('Exit') again() else: print('Type y/n') Also, I think you have to put your if statements in while loop, because it have to be executed always depending on user inputs.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47624629

http://stackoverflow.com/a/47576279
answers question: http://stackoverflow.com/q/47575041
has body: If you want to create these reference strings dynamically this will help: column, row = 66, 1 for v in values: if row == 6: row = 1 column += 1 worksheet['{}{}'.format(chr(column),row)] = value row += 1 This will start with B1 and once it reaches B5 it will move to C1 and so on. Doesn't work after column Z.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
accepted answer of: http://stackoverflow.com/q/47575041
type: Answer

http://stackoverflow.com/a/47617527
has body: Is this what you're looking for? &gt;&gt;&gt; x = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] &gt;&gt;&gt; r = [v*2**(-(i//5)) for i, v in enumerate(x)] &gt;&gt;&gt; r [1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.25] &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/47617486
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47617486
type: Answer
has comment: http://stackoverflow.com/comment/82198638
upvote count: 4

http://stackoverflow.com/comment/82110612
score: 1
comment on: http://stackoverflow.com/q/47576697
has text: Two small comments: 1) Including `open()` in the `with` statement takes care of closing the file for you when you leave the `with` block, so you can remove the `file.close()` calls. 2) Did you maybe overwrite the defined function at another point in your code?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82204985
type: QuestionComment
has text: What is the value of `newTest`?
score: 0
comment on: http://stackoverflow.com/q/47623474
type: Comment

http://stackoverflow.com/q/47662152
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82341002
tagged with: couchbase
has comment: http://stackoverflow.com/comment/82335590
upvote count: 1
tagged with: python
has body: I want to query a couchbasedb bucket from R and store the results in a data frame. I went through this blogpost and tried to replicate the steps in my own cluster using custom query, but got the error message in couchbase logs Invalid post received: {mochiweb_request, [#Port&lt;0.5548256&gt;,'POST',"/query/service/", {1,1}, {6, {"host", {'Host', "[removed]:8091"}, {"accept-encoding", {'Accept-Encoding',"gzip, deflate"}, {"accept", {'Accept', "application/json, text/xml, application/xml, */*"}, nil,nil}, {"content-type", {'Content-Type', "application/x-www-form-urlencoded;charset=UTF-8"}, {"content-length", {'Content-Length',"59"}, nil,nil}, nil}}, {"user-agent", {'User-Agent', "libcurl/7.54.0 r-curl/2.6 httr/1.2.1"}, nil,nil}}}]} Then I tried to use the reticulate package in R to query couchbasedb using the python SDK. Python Code: from couchbase.n1ql import N1QLQuery from couchbase.bucket import Bucket import pandas as pd host = '[host_name]:8091' bucket = 'my-bucket' cb = Bucket('couchbase://' + host + '/' + bucket) query = N1QLQuery('Select * from `my-bucket`') df = pd.DataFrame() for row in cb.n1ql_query(query): df = df.append(row, ignore_index=True) The code above works perfectly fine and appends the pandas data frame df with expected values. Below is my unsuccessful attempt to translate the above python code to R using the reticulate function R Code: library(reticulate) reticulate::use_condaenv("my-env", "/usr/local/anaconda3/bin/conda") Bucket &lt;- reticulate::import("couchbase.bucket")$Bucket N1QLQuery &lt;- reticulate::import("couchbase.n1ql")$N1QLQuery pd &lt;- reticulate::import("pandas", "pd") host &lt;- '[host_name]:8091' bucket &lt;- 'my-bucket' cb &lt;- Bucket(paste0('couchbase://', host, '/', bucket)) query = N1QLQuery('Select * from `my-bucket`') Up to this point everything works fine. Now, how can I translate the for loop in python to R that will append query results into the data frame? for row in cb.n1ql_query(query): df = df.append(row, ignore_…
tagged with: http://stackoverflow.com/tag/r
has title: Query Couchbase bucket from R and return a data frame
has comment: http://stackoverflow.com/comment/82356454
answer count: 0
has comment: http://stackoverflow.com/comment/82330298
downvote count: 0
score: 1
tagged with: sql++
favorite count: 0
has comment: http://stackoverflow.com/comment/82320678
tagged with: reticulate
type: Question
linked to: http://stackoverflow.com/q/5963269

spectrogram
tags question: http://stackoverflow.com/q/47662443
tag name: spectrogram
type: Tag

http://stackoverflow.com/q/47626749
downvote count: 1
favorite count: 0
type: Question
tagged with: datetime
has answer: http://stackoverflow.com/a/47628356
tagged with: python
has body: I have the following pandas.Dataframe: Date-Time Week Month 2017-07-29 16:05:00 30 Jul-17 2017-07-29 23:58:00 30 Jul-17 2017-07-30 04:46:00 31 Jul-17 2017-07-30 10:57:00 31 Jul-17 2017-07-31 09:36:00 31 Jul-17 2017-07-31 10:46:00 31 Jul-17 2017-08-01 09:06:00 31 Aug-17 2017-08-01 09:13:00 31 Aug-17 2017-08-02 16:02:00 31 Aug-17 2017-08-02 16:06:00 31 Aug-17 2017-08-02 16:55:00 31 Aug-17 2017-08-02 18:57:00 31 Aug-17 2017-08-02 21:56:00 31 Aug-17 2017-08-03 08:49:00 31 Aug-17 2017-08-03 14:16:00 31 Aug-17 2017-08-04 09:09:00 31 Aug-17 2017-08-04 10:08:00 31 Aug-17 2017-08-05 11:24:00 31 Aug-17 2017-08-05 12:42:00 31 Aug-17 2017-08-06 03:47:00 32 Aug-17 2017-08-06 03:55:00 32 Aug-17 2017-08-07 08:57:00 32 Aug-17 2017-08-07 11:35:00 32 Aug-17 Is there a way I can normalize the month value for each week to be the value of the month to which the mid-week day (Wednesday) belongs? In the above dataframe, Wednesday of week 31 lies in August, so the month column for week 31 should be as follows: Date-Time Week Month 2017-07-29 16:05:00 30 Jul-17 2017-07-29 23:58:00 30 Jul-17 2017-07-30 04:46:00 31 Aug-17 2017-07-30 10:57:00 31 Aug-17 2017-07-31 09:36:00 31 Aug-17 2017-07-31 10:46:00 31 Aug-17 2017-08-01 09:06:00 31 Aug-17 2017-08-01 09:13:00 31 Aug-17 2017-08-02 16:02:00 31 Aug-17 2017-08-02 16:06:00 31 Aug-17 2017-08-02 16:55:00 31 Aug-17 2017-08-02 18:57:00 31 Aug-17 2017-08-02 21:56:00 31 Aug-17 2017-08-03 08:49:00 31 Aug-17 2017-08-03 14:16:00 31 Aug-17 2017-08-04 09:09:00 31 Aug-17 2017-08-04 10:08:00 31 Aug-17 2017-08-05 11:24:00 31 Aug-17 2017-08-05 12:42:00 31 Aug-17 2017-08-06 03:47:00 32 Aug-17 2017-08-06 03:55:00 32 Aug-17 2017-08-07 08:57:00 32 Aug-17 2017-08-07 11:35:00 32 Aug-17 Please note that, both the Week and Month column of the dataframe are derived from the Date-Time column of the same dataframe.
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47636320
upvote count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47628356
score: 1
has answer: http://stackoverflow.com/a/47636320
has title: Set month value for entire week as mid-week day month value

http://stackoverflow.com/q/47672679
type: Question
has title: Pass required argument to optional
upvote count: 2
tagged with: function
has body: Trying to make a board, which must be a square if there as only one argument (and a rectangle if there are two of them). Code sample: class Game: def __init__(self,h,w=h): # lookie-lookie self.board = [[0 for i in range(w)] for j in range(h)] What I expect: b = Game(2) b.board #should return [[0,0],[0,0]] b = Game(2,1) b.board #should return [[0],[0]] What i got: NameError: name 'h' is not defined How should I fix it?
accepted answer: http://stackoverflow.com/a/47672747
downvote count: 1
has answer: http://stackoverflow.com/a/47672747
type: AnsweredQuestion
tagged with: syntax
score: 1
answer count: 1
tagged with: arguments
tagged with: python
favorite count: 0

http://stackoverflow.com/q/47612612
type: Question
tagged with: mongodb
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Pymongo how to import json file into mongodb
has body: I have a local json file and I need to import the json file into mongodb using Pymongo. Anyone knows how to do this?
score: 1
has comment: http://stackoverflow.com/comment/88350860
tagged with: pymongo
linked to: http://stackoverflow.com/q/43095786
has answer: http://stackoverflow.com/a/47612670
favorite count: 0
duplicate of: http://stackoverflow.com/q/43095786

http://stackoverflow.com/comment/82042555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47542667
has text: I know you've commented it but you should consider putting what you've tried in your question and formatting it like you did with the XML.

http://stackoverflow.com/q/47643285
has body: I'd like to modify specific vectors in a 3D tensor, according to a list of positions (indices): #indices: 1D vector of positions, indices.shape: (k) mask = np.zeros(k, n, m) for i in range(k): mask[i][indices[i]] = 1 This mask will be applied to another 3D tensor (same shape), where I want to preserve specific vectors, and zero out the rest. What's the best way to construct such a mask in TensorFlow? I can do it with a loop using an assign op, but I'd like to find a more elegant solution. Perhaps using tf.scatter_nd? EDIT: example: &gt;&gt;&gt; mask_before array([[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]]) &gt;&gt;&gt; indices array([2, 1, 4]) &gt;&gt;&gt; mask_after array([[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 1., 1., 1., 1.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 1., 1., 1., 1.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 1., 1., 1., 1.]]])
has answer: http://stackoverflow.com/a/47647469
possible better answer: http://stackoverflow.com/a/47647469
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82246243
answer count: 2
accepted answer: http://stackoverflow.com/a/47644484
downvote count: 0
has title: How to mask specific slices for each row in a tensor
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47644484
has comment: http://stackoverflow.com/comment/82245787
tagged with: python

http://stackoverflow.com/a/47643497
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47642570
score: 1
has body: This should be a bit faster (about 6x for 200,000 rows but check for yourself, of course). After import numpy as np: arr = np.select( [df1==1,df2==1], [1,0], default=np.nan ) ser = pd.Series( arr ).ffill() If you aren't familiar with np.select it's pretty similar to np.where but allows multiple conditions. You could also do a nested np.where but this is more readable. Below is arr, and what allows you to do a simple ffill without needing to use replace twice is that you have nan's instead of zeroes. array([ 1., 1., 1., nan, nan, nan, 0., 0., nan, nan, nan, nan, nan, nan, 1., nan, nan, 1., nan, nan, 0., nan, nan, nan, nan, 1., 1., 1., nan, nan, nan, nan, nan, 0., nan, nan, 0., nan, nan, nan, nan, nan, nan, 1., 1., 1., nan, nan, nan, nan]) You might also get a little extra speed by storing df1 &amp; df2 as numpy arrays rather than dataframes/series, but I don't think it would matter too much. If speed is really a concern, you should try to do everything in numpy rather than pandas (when possible), but I'm not sure of a good numpy analog for pandas ffill.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47642570
type: Answer

http://stackoverflow.com/comment/82076655
has text: X = train[indexes] Y = target[indexes]
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47558946
type: Comment

http://stackoverflow.com/q/47557395
has title: Why doesn't a message appear when sending an email? - smtplib - Python
has comment: http://stackoverflow.com/comment/82072715
accepted answer: http://stackoverflow.com/a/48098184
favorite count: 0
type: Question
has body: For some reason when trying to send an email no message appears, when I pass the string msg Here's the code I'm using: import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("my_email", "my_password") msg = "my message" server.sendmail("eggs@eggs.com", "eggs_2@eggs.com", msg) server.quit() Any alternative methods or solutions would be great. Edit: When I send the e-mail(to myself) no message appears just an empty e-mail appears in my inbox. Is there an alternative 'built-in' library that I can use?
has comment: http://stackoverflow.com/comment/82100641
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82072291
has answer: http://stackoverflow.com/a/48098184
tagged with: smtp
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82150151

http://stackoverflow.com/comment/82410668
type: QuestionComment
score: 0
has text: To reproduce, just need to run the Jupyter file which is the link I provided. The problem is that I can't finish cross validation part. When training, it will pop up kernel dead and stop running. However, my friends work fine on windows. So, I don't know...
comment on: http://stackoverflow.com/q/47633153
type: Comment

http://stackoverflow.com/comment/82172677
comment on: http://stackoverflow.com/q/47607115
score: 1
type: Comment
has text: Which python version? You might have python2 and 3 installed. You might have installed it for the other python version
type: QuestionComment

http://stackoverflow.com/q/47576618
tagged with: arrays
has answer: http://stackoverflow.com/a/47576751
possible better answer: http://stackoverflow.com/a/47576751
type: Question
has body: I imported a csv file containing zip codes as a string using the following line: my_data = genfromtext('path\to\file.csv', delimiter = ',', dtype=str, autostrip=True) I am importing as a string in order to keep the leading zeroes some zip codes may contain. Now I need to also loop through the entire numpy array and I wanted to do so like this: for i in np.nditer(my_data): do something with my_data[i] But unfortunately it is returning the following error: Arrays used as indices must be of integer (or boolean) type Any idea how I can loop through each element of this numpy array?
tagged with: python
has answer: http://stackoverflow.com/a/47576726
has title: For loop through a numpy array of strings
accepted answer: http://stackoverflow.com/a/47576726
tagged with: numpy
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/47608398
answers question: http://stackoverflow.com/q/47608312
score: 7
has body: You could try something like this - hostnames = ["router1", "router2"] tunnels = ["Tu1000", "Tu5000"] for hostname, tunnel in zip(hostnames, tunnels): # Do stuff with `hostname` and `tunnel` .... Read about zip function here. Read about tuple unpacking here.
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/82179304
type: Answer
accepted answer of: http://stackoverflow.com/q/47608312

http://stackoverflow.com/a/47687293
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47687203
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47687203
type: Answer
has body: The .replace(oldstr, newstr) method will help you, and it is simple and daisy-chainable. So... MyString = MyString.replace('"', '').replace('-', '') Note that the .replace() method only replaces substrings in one shot. It cannot do individual characters. For that, you could do it with a regular expression, but that's more complicated. That module can be accessed with import re. You could use: MyString = re.sub('["-]', '', MyString) Also, on a sidenote... Quoting can be tricky. But there are FOUR different ways you can quote something: in a pair of single quotes, a pair of double quotes, or a pair of triple single-quotes or triple double-quotes. So, all the below are strings in Python: 'hello' "Don't you think" # string with an apostrophe is easily in double quotes '''that this is a really really..''' """long quote? Hey! this quote is actually more than one line long!"""

http://stackoverflow.com/a/47653730
downvote count: 0
has comment: http://stackoverflow.com/comment/82291177
has body: I think what you look after is np.choose(B,A.T) : In [125]: A Out[125]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) In [126]: B = np.asarray([2,1,2,0,1]) In [127]: np.choose(B,A.T) Out[127]: array([ 2, 4, 8, 9, 13])
answers question: http://stackoverflow.com/q/47653405
has comment: http://stackoverflow.com/comment/82293334
type: Answer
has comment: http://stackoverflow.com/comment/82290835
upvote count: 2
score: 2

http://stackoverflow.com/comment/96067384
type: AnswerComment
comment on: http://stackoverflow.com/a/47602779
has text: Funcionó al primer intento. Gracias.
score: 0
type: Comment

http://stackoverflow.com/comment/82105063
comment on: http://stackoverflow.com/q/47574090
score: 0
type: QuestionComment
type: Comment
has text: Thanks landogardner.You are right.After removing the return statement outside the loop.It is working perfectly.my miss.Thanks

http://stackoverflow.com/comment/82350632
comment on: http://stackoverflow.com/a/47695422
type: AnswerComment
has text: That article by Ned is Required Reading for all Python programmers, IMHO. It's a shame that Ned doesn't post here much these days.
score: 1
type: Comment

http://stackoverflow.com/comment/82236720
has text: What is `e`? Is that the content of the email?
comment on: http://stackoverflow.com/q/47639221
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47679770
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/82318959
type: UnansweredQuestion
has title: How to assign value to a dynamic multidimensional dictionary in python with key from strings?
tagged with: python
has comment: http://stackoverflow.com/comment/82318926
tagged with: dictionary
tagged with: key
score: 0
answer count: 0
tagged with: dynamic
has comment: http://stackoverflow.com/comment/82319243
has body: I want to assign value to "original" dictionary with rule in "mapping". How can I achieve that? Before Mapping original = { "id":0, "address":{ "street_name":"", "street_number":0 } } Mapping Recipe mapping = { "id":123, "address/street_name":"ABC", "address/street_number":124, } After Mapping original = { "id":123, "address":{ "street_name":"ABC", "street_number":123 } }

http://stackoverflow.com/comment/82203728
score: 0
has text: yw, please let me know if you have any question regarding this :) @Archit123
type: AnswerComment
comment on: http://stackoverflow.com/a/47613670
type: Comment

http://stackoverflow.com/a/60242719
upvote count: 1
score: 1
has body: As far as I've seen, and I am using the whole sound processing for the first time, you could use pyaudio to play a wav-file as a stream. pyaudio is not pydub. :) First, convert your anydata-file to a wav-file with pydub/ffmpeg, see below, and then use pyaudio to play it as a stream with logic between. Because, when I play an MP3 with pydub, it waits some seconds and then states that the file has been converted to wav in a /tmp-folder. So, why not convert it just once and save it to your own location? It lasts some seconds both ways, anyway, but the latter converting has just to be done once (assuming you have tons of Gigabytes :) ), and then you can just check if the file already exists. -> converting Python convert mp3 to wav with Pydub -> playing and recording sound with python -> pyaudio (comprehensive guide) https://realpython.com/playing-and-recording-sound-python/#pyaudio As you see in the code, you could put your own logic into the while loop where the stream is played. I will try to use that combination in a project I make. Hope it works. :)
answers question: http://stackoverflow.com/q/47596007
downvote count: 0
type: Answer

http://stackoverflow.com/q/47601770
tagged with: django
tagged with: date-range
favorite count: 0
type: Question
has title: Check if any date in a range is between another range
tagged with: django-views
tagged with: python-datetime
accepted answer: http://stackoverflow.com/a/47601900
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I have the following situation: This is my views.py: def home(request): date = datetime.date.today() start_week = date - datetime.timedelta(date.weekday() + 1) end_week = start_week + datetime.timedelta(6) week_tasks = Task.object.filter(owner=request.user, start_date__range=[start_week, end_week]) context = {} context['week_tasks'] = week_tasks return render(request, 'home.html', context) This view check if the start_date (DateField) is inside the range of the current week. But I have another field on the database, end_date, and I want to check if any value of this range is on the current week. Check the exemple: Let's supose that the current week is the week of the day 17. With my current view, only the All Day Event and Conference belong to the week. I need to show that all these events belong to the week. Obs.: I can't just check if start_date and end_date are in the week, because I have the situation of the Long Event, that starts before the week and ends after. WORKING: views.py: def home(request): date = datetime.date.today() if date.isoweekday() == 7: date = date + datetime.timedelta(1) start_week = date - datetime.timedelta(date.isoweekday()) end_week = start_week + datetime.timedelta(6) week_tasks = Task.object.filter(owner=request.user).exclude(end_date__lt=start_week).exclude(start_date__gt=end_week) context = {} context['week_tasks'] = week_tasks return render(request, 'home.html', context)
downvote count: 0
has answer: http://stackoverflow.com/a/47601900
answer count: 1

http://stackoverflow.com/q/47603665
has comment: http://stackoverflow.com/comment/82166179
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82166230
has comment: http://stackoverflow.com/comment/82166143
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/82166232
has comment: http://stackoverflow.com/comment/82166438
has answer: http://stackoverflow.com/a/60701462
has comment: http://stackoverflow.com/comment/82166219
answer count: 4
has answer: http://stackoverflow.com/a/47603737
linked to: http://stackoverflow.com/q/43662993
has body: Can anyone show me how to create half pyramid using list comprehension ? For example * ** *** I tried but did not succeed. I am trying to convert following code into using dictionary comprehension for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("\r")
has comment: http://stackoverflow.com/comment/82166274
has answer: http://stackoverflow.com/a/47603788
has comment: http://stackoverflow.com/comment/82166156
upvote count: 0
has comment: http://stackoverflow.com/comment/82166241
has comment: http://stackoverflow.com/comment/82166201
downvote count: 3
has comment: http://stackoverflow.com/comment/82166290
has answer: http://stackoverflow.com/a/47605086
has comment: http://stackoverflow.com/comment/82166231
has title: Build pyramid pattern using list comprehension in python?
has comment: http://stackoverflow.com/comment/82166226
has comment: http://stackoverflow.com/comment/82166139

http://stackoverflow.com/q/47561840
answer count: 4
has comment: http://stackoverflow.com/comment/82081494
score: 137
type: UnansweredQuestion
downvote count: 3
tagged with: file
tagged with: decorator
linked to: http://stackoverflow.com/q/1188640
has comment: http://stackoverflow.com/comment/82081502
upvote count: 140
favorite count: 0
has answer: http://stackoverflow.com/a/47562483
has answer: http://stackoverflow.com/a/57562083
type: Question
has answer: http://stackoverflow.com/a/47562412
tagged with: object
has comment: http://stackoverflow.com/comment/82081442
has comment: http://stackoverflow.com/comment/113802802
has answer: http://stackoverflow.com/a/76442175
has body: I have a main class that has a ton of different functions in it. It's getting hard to manage. I'd like to be able to separate those functions into a separate file, but I'm finding it hard to come up with a good way to do so. Here's what I've done so far: File main.py import separate class MainClass(object): self.global_var_1 = ... self.global_var_2 = ... def func_1(self, x, y): ... def func_2(self, z): ... # tons of similar functions, and then the ones I moved out: def long_func_1(self, a, b): return separate.long_func_1(self, a, b) File separate.py def long_func_1(obj, a, b): if obj.global_var_1: ... obj.func_2(z) ... return ... # Lots of other similar functions that use info from MainClass I do this because if I do: obj_1 = MainClass() I want to be able to do: obj_1.long_func_1(a, b) instead of: separate.long_func_1(obj_1, a, b) I know this seems kind of nit-picky, but I want just about all of the code to start with obj_1., so there isn't confusion. Is there a better solution that what I'm currently doing? The only issues that I have with my current setup are: I have to change arguments for both instances of the function It seems needlessly repetitive
has comment: http://stackoverflow.com/comment/82082086
tagged with: python
has comment: http://stackoverflow.com/comment/101586384
has comment: http://stackoverflow.com/comment/82082124
has title: How can I separate the functions of a class into multiple files?

http://stackoverflow.com/comment/82113012
comment on: http://stackoverflow.com/q/47540926
type: Comment
type: QuestionComment
score: 0
has text: It's a bit of a problem because it's an image and I don't know how can I add this kind of a file in the posts here. It's actually an image file which I did segmentation for it, so every pixels with value between 2 values are 1 and all the others are 0.

http://stackoverflow.com/comment/82267156
has text: @deceze So there's nothing wrong in or considered bad practice creating a class the way I did, if I think it makes sense in my case? For example if the return values are getting reused several places?
comment on: http://stackoverflow.com/q/47654018
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82346699
type: QuestionComment
has text: `&#65279` is not a random char sequence but is the unicode for 'ZERO WIDTH NO-BREAK SPACE'. You could get rid of this by replacing this by `''` (emtpy string)
score: 2
comment on: http://stackoverflow.com/q/47693761
type: Comment

http://stackoverflow.com/a/47694291
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47598706
has body: I completed the challenge, I used an excel spreadsheet with functions to get all the little code things from every clock cycle and put them together to make one code every 10 seconds. Sorry if that doesn't make sense I'm not sure how to explain it. Then I pasted this into the end of the "validation link" to replace the &lt; clock pts > at the end of the URL. I had to do this very fast before the clock reset. Very stressful haha. Then eventually I did this in time and it gave me the code. I hope this helps. But you'll have to figure out how to get all the codes together in under 10 seconds by yourself, otherwise this is basically cheating, right?

http://stackoverflow.com/comment/82075393
type: QuestionComment
comment on: http://stackoverflow.com/q/47558827
score: 0
type: Comment
has text: Where is `@app.route('/update/<int:adv_id>', methods=['PUT'])` in your code?

http://stackoverflow.com/a/47674005
answers question: http://stackoverflow.com/q/47673187
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82307229
has comment: http://stackoverflow.com/comment/82307303
type: Answer
accepted answer of: http://stackoverflow.com/q/47673187
has body: This should work: from collections import defaultdict # first aggregate all users merged = defaultdict(set) for u in m: for k,v in m[u].iteritems(): merged[(k,)].update(set(v)) # then merged keys as required as long as possible cont = True while cont: cont = False keys = merged.keys() L = len(keys) for i in range(L): ki = keys[i] for j in range(i+1,L): kj = keys[j] if merged[ki] &amp; merged[kj]: merged[ki+kj] = merged[ki].union(merged[kj]) del merged[ki] del merged[kj] cont = True # finally remove remaining artifacts merged = [k for k,v in merged.iteritems() if v]
score: 0

http://stackoverflow.com/comment/82169510
type: AnswerComment
has text: sorry..thats not helping
comment on: http://stackoverflow.com/a/47605354
score: 0
type: Comment

bokeh
tags question: http://stackoverflow.com/q/47611583
tags question: http://stackoverflow.com/q/47554283
tags question: http://stackoverflow.com/q/47618482
tags question: http://stackoverflow.com/q/47605154
tags question: http://stackoverflow.com/q/47601524
type: Tag
tags question: http://stackoverflow.com/q/47657085
tags question: http://stackoverflow.com/q/47566777
tags question: http://stackoverflow.com/q/47589461
tags question: http://stackoverflow.com/q/47564300
tags question: http://stackoverflow.com/q/47651752
tags question: http://stackoverflow.com/q/47673605
tags question: http://stackoverflow.com/q/47579612
tags question: http://stackoverflow.com/q/47661164
tag name: bokeh

http://stackoverflow.com/comment/82073793
type: Comment
has text: I actually meant the opposite `before reading` and wanted to emphasize that the first expectation when read is, that you can set the password of zip files, rather then applying a password when reading.
comment on: http://stackoverflow.com/a/47548272
score: 0
type: AnswerComment

http://stackoverflow.com/q/47632723
has comment: http://stackoverflow.com/comment/82224491
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/82223316
score: 1
has body: How to get data to show NaN for pandas column AD My data looks like: df1 EW WE DA AA DDA 0 CA DA DFA DAW DAQ 1 CA DA DFA DAW DAQ 2 CA DA DFA DAW DAQ 3 d NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN 5 NaN NaN NaN NaN NaN 6 NaN NaN NaN NaN NaN df2 AA AB AC AD AE 0 HAC aw d 1.0 xa 1 HAC aw aw 1.0 xa 2 HAC aw aw 1.0 xa 3 HAC aw aw 1.0 xa 4 HAC aw aw 1.0 xa 5 HAC aw aw 1.0 xa 6 NaN NaN d NaN NaN I want: AA AB AC AD AE 0 HAC aw d 1.0 xa 1 HAC aw aw NaN xa 2 HAC aw aw NaN xa 3 HAC aw aw NaN xa 4 HAC aw aw NaN xa 5 HAC aw aw NaN xa 6 NaN NaN d 1.0 NaN I am using: df3 = df2[df2.AC.isin(df1.EW)] df3 = df3'AC','AD' print (df3)
has comment: http://stackoverflow.com/comment/82223808
has comment: http://stackoverflow.com/comment/82223854
has comment: http://stackoverflow.com/comment/82224223
has comment: http://stackoverflow.com/comment/82223179
has comment: http://stackoverflow.com/comment/82223207
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82223408
has comment: http://stackoverflow.com/comment/82223383
favorite count: 0
has comment: http://stackoverflow.com/comment/82223500
type: Question
has comment: http://stackoverflow.com/comment/82223960
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82223349
accepted answer: http://stackoverflow.com/a/47632825
has comment: http://stackoverflow.com/comment/82224177
has comment: http://stackoverflow.com/comment/82223936
has answer: http://stackoverflow.com/a/47632825
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82232717
has title: Showing NaN for pandas column AD
has comment: http://stackoverflow.com/comment/82224470
has comment: http://stackoverflow.com/comment/82224518
has comment: http://stackoverflow.com/comment/82223238
has comment: http://stackoverflow.com/comment/82223458
has comment: http://stackoverflow.com/comment/82233252

http://stackoverflow.com/comment/82305743
type: QuestionComment
comment on: http://stackoverflow.com/q/47673391
score: 0
has text: short on curlies, though
type: Comment

http://stackoverflow.com/q/47590105
has answer: http://stackoverflow.com/a/47599428
tagged with: python
score: -1
tagged with: parsing
type: AnsweredQuestion
has body: I am trying to parse conditional command line arguments. Here is my code import argparse def parseArguments(): parser = argparse.ArgumentParser(description="Parses the command line arguments") parser.add_argument('-launchTest', dest='launchTest', action='store_true', help='provide this to run triage process of test suites') parser.add_argument('-getStatus', dest='getStatus', action='store_true', help='provide this to run triage process of test suites') parser.add_argument('-configFile', dest='configFile', required=True, help='provide json config data') parser.add_argument('-user', dest='user', required=True, action='store', help='provide user name for launching tests on GVS') parser.add_argument('-date', dest='date' , help='provide date or CL to run tests, date format: MM_DD_YYYY') parser.add_argument('-cl', dest='cl', help='provide either date or cl to run the tests') parser.add_argument('-outPutDir', dest='outPutDir', default='/compune-nightly/nightly/{}/GVS-Tegra/', help='provide output directory path to store results') subparser = parser.add_subparsers(help='sub-command help') parser_a = subparser.add_parser('testName', help='this to run specific test with testName and test details must be present in argumentConfig.json provide gpu and boardName with this') parser_a.add_argument('-gpu', action='store', help='provide this to run specific test with testName, testType and test details must be present in argumentConfig.json') parser_a.add_argument('-boardName', action='store', help='provide this to run specific test with testName, testType, gpu and test details must be present in argumentConfig.json') arguments = parser.parse_args() return arguments def main(): parseArguments() main() From this code, I want to add option in parser like if testName is given in command then it is compulasary to provide cpu and boradname. But When I am trying to run this code it gives Error: parser.py: error: too few arguments python parser.py -configFile=abcd -user=amanj -testName=xyz…
has title: Nested command line parser gives error: too few arguments
upvote count: 0
linked to: http://stackoverflow.com/q/46963172
answer count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47599428
tagged with: argparse

http://stackoverflow.com/a/47659673
score: 2
has comment: http://stackoverflow.com/comment/82278136
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47659654
has comment: http://stackoverflow.com/comment/82279141
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47659654
has comment: http://stackoverflow.com/comment/82278878
type: Answer
has body: You need to add master.mainloop() at the end of your program, as the last logical line. This forces the program to continually update everything.

http://stackoverflow.com/a/47580796
type: Answer
score: 4
has body: multiprocessing.Pool store worker processes list in Pool._pool attr, send a signal to them is straightforward then: import multiprocessing import os import signal def kill(pool): # stop repopulating new child pool._state = multiprocessing.pool.TERMINATE pool._worker_handler._state = multiprocessing.pool.TERMINATE for p in pool._pool: os.kill(p.pid, signal.SIGKILL) # .is_alive() will reap dead process while any(p.is_alive() for p in pool._pool): pass pool.terminate()
has comment: http://stackoverflow.com/comment/96726655
has comment: http://stackoverflow.com/comment/96719396
downvote count: 0
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47553120
has comment: http://stackoverflow.com/comment/96716374
has comment: http://stackoverflow.com/comment/96736262
has comment: http://stackoverflow.com/comment/96670562
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47553120
has comment: http://stackoverflow.com/comment/96722807

http://stackoverflow.com/comment/82046618
has text: SQLAlchemy, PyODBC, MySQL.Connector are all trivial. This is just to establish connection. The split(";") allows a countless number of select statement to run using the established connection, so long as they are separated by ";"
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47544497
score: 0

http://stackoverflow.com/a/47562644
downvote count: 0
has comment: http://stackoverflow.com/comment/82083367
upvote count: 1
has comment: http://stackoverflow.com/comment/82083446
score: 1
type: Answer
has body: You may match and remove the line parts starting with a combination of a backslash and n, or all punctuation (non-word and non-whitespace) chars using a re.sub: a = re.sub(r'\\n.*|[^\w\s]+', '', a) See the regex demo Details \\n.* - a \, n, and then the rest of the line | - or [^\w\s]+ - 1 or more chars other than word and whitespace chars If you need to make sure there is an uppercase letter after \n, you may add [A-Z] after n in the pattern.
accepted answer of: http://stackoverflow.com/q/47562030
answers question: http://stackoverflow.com/q/47562030
type: AcceptedAnswer

http://stackoverflow.com/comment/82133709
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47587633
has text: Thnik you need to pare your question down to a [mcve]. What is going into your algorithm(`CalTab`) and what do you want out (`CalTab`)? What format, shape, size, etc. Right now all I see are from your code are empty arrays of shape `(0,7)` which doesn't make much sense. Especially important would be the `dtype` of the arrays, as that will drive the how to do the manipulation in `numpy`

http://stackoverflow.com/comment/82313476
type: AnswerComment
comment on: http://stackoverflow.com/a/47588025
type: Comment
has text: Most of my POC on the tool with our .net app is done and it looks pretty good as compared to other open source ones. This is the only pending issue that I currently have and its a important piece of the app. Let me know when its possible. Thnx.
score: 0

http://stackoverflow.com/comment/82122967
type: Comment
comment on: http://stackoverflow.com/a/47578933
type: AnswerComment
has text: No problem @alejandropareja
score: 0

http://stackoverflow.com/comment/82159887
score: 0
type: Comment
has text: Lol nvm I accidentally did lower case c
type: AnswerComment
comment on: http://stackoverflow.com/a/47600399

http://stackoverflow.com/comment/82236029
has text: What color model does the tuple represent? Here is a list of the ones PIL supports: http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47638689

http://stackoverflow.com/comment/82199595
has text: I have already tested with `as_index`, it takes freaking long to execute.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47620501

http://stackoverflow.com/q/47604151
tagged with: python-3.x
linked to: http://stackoverflow.com/q/25447700
has answer: http://stackoverflow.com/a/47606265
has body: I have a bar chart that displays 2 bars one for 2015 and one for 2016. x axis shows drug name y axis shows amount prescribed I would like to display annotation on the bars just to make it more clear the number prescribed. I have tried the following but nothing happens? Does anyone know where I am going wrong? Here is my code for p in ax.patches: ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005)) fig = plt.figure() # Create matplotlib figure ax = fig.add_subplot(111) # Create matplotlib axes width = 0.4 df.Occurance_x.plot(kind='bar', color='purple', ax=ax, width=width, position=1) df.Occurance_y.plot(kind='bar', color='blue', ax=ax, width=width, position=0) ax.set_ylabel('Amount Prescribed in 1 year') x_labels = df.VTM_NM ax.set_xticklabels(x_labels, rotation=30) plt.legend(['2016', '2017'], loc='upper right') ax.set_title('BNF Chapter 1 Top 5 drugs prescribed') plt.show()
has answer: http://stackoverflow.com/a/47604492
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
duplicate of: http://stackoverflow.com/q/25447700
tagged with: jupyter-notebook
score: 0
answer count: 2
tagged with: pandas
has title: Annotating bar chart in pandas
has comment: http://stackoverflow.com/comment/82170805
type: Question

http://stackoverflow.com/q/47581243
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
has body: I got a pandas Series object, which looks like this: (Pdb) PiECoS t sit com com_type 1 South Coal Stock 2.0 1 Mid Solar SupIm 4.0 2 South Coal Stock 1.0 2 Mid Solar SupIm 0.0 ... 10 South Coal Stock 0.0 10 Mid Solar SupIm 0.0 Name: sub_commodity_source, Length: 300, dtype: float64 Expected Output: sum all of the t=1 to 10 and add it to t=10 t sit com com_type 1 South Coal Stock 2.0 1 Mid Solar SupIm 4.0 2 South Coal Stock 1.0 2 Mid Solar SupIm 0.0 ... 10 South Coal Stock 3.0 10 Mid Solar SupIm 4.0 or t sit com com_type 10 South Coal Stock 3.0 10 Mid Solar SupIm 4.0
favorite count: 0
type: Question
tagged with: series
score: -2
tagged with: sum
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82119899
has title: Summing a pandas series
has comment: http://stackoverflow.com/comment/82120124
has answer: http://stackoverflow.com/a/47581573
tagged with: pandas
has comment: http://stackoverflow.com/comment/82120396

http://stackoverflow.com/comment/82308379
has text: Oh, got it. For rows that are next to each other.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47673889
type: QuestionComment

http://stackoverflow.com/comment/82320556
type: AnswerComment
has text: Thank you very much for your reply! You implement it almost right. Actually I do not want to merge my tables. I need to fill in invoiceid (of table 1) in table 2 only if 'propertyid' in df matches with 'propertyReference' in invoices and if 'Mouvements' in df matches with 'invoiceGrossAmount'.
comment on: http://stackoverflow.com/a/47679799
type: Comment
score: 0

http://stackoverflow.com/comment/82205009
type: Comment
has text: Converting a 3-D array into a 2-D poly1d array won't work either, for some reason. Logically, `np.apply_along_axis(np.poly1d, 0, arr)` would change it into a new array, but for some reason it keeps it as the old one.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47623406

http://stackoverflow.com/comment/82058535
comment on: http://stackoverflow.com/q/47550922
score: 0
has text: You could possibly check for the `__module__` property of the function that's passed in, and if it's `_operators` then it's one of the functions from there.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82252823
comment on: http://stackoverflow.com/q/47646969
has text: It resloves my question :) ! I find `backup.sh` in our weblogic server, Operations added it and I don't know about how it works, It's really a stupid mistake :(
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82343056
has text: @ShengbaoShui-MSFT. Apologies for the late response. I was looking for a much faster option that is to parse the results straightaway without having to save the output to a file then parse it at the end of the process. If you think this is the best option, could you care to share me the method to parse the file into JSON then expose it to the localhost:5000/DPM?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47670568

http://stackoverflow.com/q/47571786
answer count: 1
downvote count: 1
has title: flask render opencv image on web without saving file
has body: Basically I followed this tutorial to stream processed video (not just retrieving frames and broadcasting) and it works for me (I'm new to html and flask). But I want to save some computation here: I wonder if it's possible to avoid saving opencv image object to a jpeg file and then reading again? Is it a waste of computation? I think it's even better if flask/html template could render the image by using raw 3 data channels RGB of the image. Any idea? Thanks! P/S: I actually tried this following code: _, encoded_img = cv2.imencode('.jpg', img, [ int( cv2.IMWRITE_JPEG_QUALITY ), 95 ] ) But it gives the following error: Debugging middleware caught exception in streamed response at a point where response headers were already sent. Traceback (most recent call last): File "/home/trungnb/virtual_envs/tf_cpu/lib/python3.5/site-packages/werkzeug/wsgi.py", line 704, in next return self._next() File "/home/trungnb/virtual_envs/tf_cpu/lib/python3.5/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded for item in iterable: File "/home/trungnb/workspace/coding/Mask_RCNN/web.py", line 25, in gen if frame == None: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47571963
tagged with: python
has comment: http://stackoverflow.com/comment/82101806
tagged with: flask
has comment: http://stackoverflow.com/comment/82101464
tagged with: opencv
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47571963
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
linked to: http://stackoverflow.com/q/11017466

http://stackoverflow.com/q/47593729
tagged with: python
duplicate of: http://stackoverflow.com/q/43162506
type: AnsweredQuestion
has body: I have created a simple script to apply a grid search on a random forest classifier and while i have worked with it in the past, it seems to be broken now and i cant find why. from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV rfc = RandomForestClassifier(n_estimators=100, n_jobs=-1).fit(X, y) grid_values = {'criterion':['gini','entropy'], 'max_features':['log2', 5, 10, 15, 20, 25], 'max_depth':[None, 5, 10, 15, 20], 'min_samples_split':[2, 3],'n_jobs':[-1], 'class_weight': [{0 : 1., 1: 30.}, {0 : 1., 1: 50.}, {0 : 1., 1: 100.}]} for eval_metric in ('precision', 'accuracy'): rfc_custom = GridSearchCV(rfc, param_grid=grid_values, scoring=eval_metric) rfc_custom.fit(X_train, y_train) rfc_custom.best_params_ print('Grid best parameter (max. {0}): {1}' .format(eval_metric, rfc_custom.best_params_)) print('Grid best score ({0}): {1}' .format(eval_metric, rfc_custom.best_score_)) When i run this, i get the following warning: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Searching online, i added this code and the warning stops: import warnings import sklearn.exception warnings.filterwarnings("ignore",category=sklearn.exceptions.UndefinedMetricWarning) After running the algorithm i get a precision of 0.0 Is this normal because of the warning im getting? Am i maybe missing something?
score: 1
has comment: http://stackoverflow.com/comment/82145804
has title: GridSearch 'UndefinedMetricWarning' and bad result
downvote count: 0
answer count: 1
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43162506
duplicate of: http://stackoverflow.com/q/54150147
accepted answer: http://stackoverflow.com/a/47594782
has comment: http://stackoverflow.com/comment/82146373
has comment: http://stackoverflow.com/comment/82146964
has answer: http://stackoverflow.com/a/47594782

http://stackoverflow.com/comment/82289730
comment on: http://stackoverflow.com/q/47665182
has text: I guess you're used to the way `#include` works in C. In Python, you're not copy-pasting the module. The interpreter opens it, reads it and interprets it, then creates a 'variable' pointing at the module and its contents.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84085169
has text: Wow! Thanks! I can't believe they have an implementation online and don't even mention it on the text! Also, this is very far from what I was doing, I wonder if they had the same problems as I.
comment on: http://stackoverflow.com/a/48538506
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47563784
has comment: http://stackoverflow.com/comment/82086004
answers question: http://stackoverflow.com/q/47563638
has comment: http://stackoverflow.com/comment/82116745
has comment: http://stackoverflow.com/comment/82121202
has comment: http://stackoverflow.com/comment/82086369
has comment: http://stackoverflow.com/comment/82121141
score: 0
has comment: http://stackoverflow.com/comment/82127812
type: Answer
has body: EDIT 2: pandas.cut is built-in: tt=[[1,'2004-01-02',0.1,25,47], [1,'2004-01-17',0.2,150,8], [2,'2004-01-29',0.2,150,25], [3,'2017-07-15',0.3,55,17], [3,'2016-05-12',0.3,55,47], [4,'2012-02-23',0.2,150,22], [4,'2009-10-10',0.1,25,12], [4,'2014-04-04',0.2,150,2], [5,'2008-07-09',0.2,150,43]] start_date_period = pd.date_range('2004-01-01', '12-01-2017', freq='MS') end_date_period = pd.date_range('2004-01-30', '12-31-2017', freq='M') df = pd.DataFrame(tt,columns=['customer_id','transaction_dt','product','price','units']) df['transaction_dt'] = pd.Series([pd.to_datetime(sub_t[1],format='%Y-%m-%d') for sub_t in tt]) the_cut = pd.cut(df['transaction_dt'],bins=start_date_period,right=True,labels=False,include_lowest=True) df['win_start_test'] = pd.Series([start_date_period[int(x)] if not np.isnan(x) else 0 for x in the_cut]) df['win_end_test'] = pd.Series([end_date_period[int(x)] if not np.isnan(x) else 0 for x in the_cut]) print(df.head()) win_start_test and win_end_test should be equal to their counterparts computed using your function. The ValueError was coming from not casting x to int in the relevant line. I also added a NaN check, though it wasn't needed for this toy example. Note the change to pd.date_range and the use of the start-of-month and end-of-month flags M and MS, as well as converting the date strings into datetime.
has comment: http://stackoverflow.com/comment/82086080

http://stackoverflow.com/comment/82092237
has text: @Satendra just posted it above
comment on: http://stackoverflow.com/q/47567146
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47627934
downvote count: 0
tagged with: array-broadcasting
tagged with: matrix
has body: Is there a way, in numpy, to perform what amounts to an outer addition of subarrays? That is to say, I have 2 arrays of the form 2x2xNxM, which may each be considered a stack of 2x2 matrices N high and M wide. I would like to add each of these matrices to each matrix from the other array, to form a 2x2xNxMxNxM array in which the last four indices correspond to the indices in my initial two arrays so that I can index output[:,:,x1,y1,x2,y2] == a1[:,:,x1,y1] + a2[:,:,x2,y2]. If these were arrays of scalars, it would be trivial, all I'd have to do is: A, B = a.ravel(), b.ravel() four_D = (a[...:np.newaxis] + b).reshape(*a1.shape, *a2.shape) for (x1, y1, x2, y2), added in np.ndenumerate(four_D): assert added == a1[x1,y1] + a2[x2,y2] However, this doesn't work for the case where a and b comprise of matrices. I could, of course, use nested for loops, but my dataset is going to be fairly large, and I'm expecting to run this over multiple datasets. Is there an efficient way to do this?
upvote count: 1
tagged with: arrays
has title: Numpy outer addition of subarrays
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47628064
score: 1
possible better answer: http://stackoverflow.com/a/47628064
tagged with: python
has answer: http://stackoverflow.com/a/47628061
accepted answer: http://stackoverflow.com/a/47628061
tagged with: numpy
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82318284
type: Comment
score: 0
type: AnswerComment
has text: @andrus Glad it helped. You can [accept my answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) if you feel it was useful to you.
comment on: http://stackoverflow.com/a/47658606

http://stackoverflow.com/q/47558611
tagged with: python
has title: Maya Python mass .obj import how to turn off obj import warning?
favorite count: 0
type: Question
answer count: 2
upvote count: 2
downvote count: 0
has body: Hey I am importing a list of files into a maya scene via python. Each time a .obj is imported maya gives me following warning: Warning: Option "Use legacy vertex order" will only take effect when option "Multiple Objects" is enabled. My question: Is it possible to turn off this warning? Or a way to to not show the warning in the first place? edit: The problem is that this warning will show up on each and every file that gets imported from the list. I added a screenshot from maya. I am loading the files like this: cmds.file(filePath, i = True) edit2: Here is my function that loops through files in a directory. def loadFiles(*args): # load References into scene from savefile files = 'c:/testfolder' if os.path.exists(files): filesInFolder = [f for f in listdir(files) if isfile(join(files, f))] for file in filesInFolder: filePath = files + '/' + file #cmds.file(filePath, i = True) mel.eval("catchQuiet(`python(\"cmds.file(filePath, i=True)\")`)") #print filePath Thank you for your time and have a nice day!
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47602888
possible better answer: http://stackoverflow.com/a/47563720
has answer: http://stackoverflow.com/a/47602888
has answer: http://stackoverflow.com/a/47563720
tagged with: maya

http://stackoverflow.com/a/47670308
has body: TL-DR: To decrease noise in the autocorrelation function increase the length of your signal x. Partitioning the data and averaging like in spectral estimation is an interesting idea. I wish it would work... The autocorrelation is defined as Let's say we partition the data into two windows. Their autocorrelations become Note how they are only different in the limits of the sumations. Basically, we split the summation of the autocorrelation into two parts. When we add these back together we are back to the original autocorrelation! So we did not gain anything. The conclusion is, there is no such thing implemented in numpy/scipy because there is no point in doing so. Remarks: I hope it's easy to see that this extends to any number of partitions. to keep it simple I left the normalization out. If you divide Rxx by n and the partial Rxx by n/2 you get Rxx / n == (Rxx1 * 2/n + Rxx2 * 2/n) / 2. I.e. The mean of the normalized partial autocorrelation is equal to the complete normalized autocorrelation. to keep it even simpler I assumed the signal x could be indexed beyond the limits of 0 and n-1. In practice, if the signal is stored in an array this is often not possible. In this case there is a small difference between the full and the partialized autocorrelations that increases with the lag l. Unfortunately, this is merely a loss of precision and does not reduce noise. Code heretic! I don't belive your evil math! Of course we can try things out and see: import matplotlib.pyplot as plt import numpy as np n = 2**16 n_segments = 8 x = np.random.randn(n) # data rx = np.correlate(x, x, mode='same') / n # ACF l1 = np.arange(-n//2, n//2) # Lags segments = x.reshape(n_segments, -1) m = segments.shape[1] rs = [] for y in segments: ry = np.correlate(y, y, mode='same') / m # partial ACF rs.append(ry) l2 = np.arange(-m//2, m//2) # lags of partial ACFs plt.plot(l1, rx, label='full ACF') plt.plot(l2, np.mean(rs, axis=0), label='partial ACF') plt.xlim(-m, m) plt.legend() plt.show() Alth…
type: Answer
has comment: http://stackoverflow.com/comment/82331291
score: 4
answers question: http://stackoverflow.com/q/47661872
upvote count: 4
has comment: http://stackoverflow.com/comment/82339035
has comment: http://stackoverflow.com/comment/82331519
downvote count: 0

http://stackoverflow.com/a/47694086
score: 0
has body: There's not a lot wrong with what you are doing, except that you are printing the wrong thing. Instead of print(data[0]) use print(item[0]) data[0] is the first character of the string you read from file. You split this string into a variable called item so that's what you should print.
type: Answer
answers question: http://stackoverflow.com/q/47664547

http://stackoverflow.com/a/47564727
score: 0
answers question: http://stackoverflow.com/q/47564648
type: Answer
has body: Trying this, from ../target_directory.library import module. ../ means going up in directory depth. I hope it helps.

http://stackoverflow.com/comment/82248416
type: QuestionComment
has text: What does addItemWidget have to do?
type: Comment
comment on: http://stackoverflow.com/q/47644274
score: 0

http://stackoverflow.com/q/47582207
type: UnansweredQuestion
has body: I am trying to get some columns with pandas, then trying to aggregate. Here is my code: mostspent = df.groupby(['Customer ID']) mostspent.agg({"VALUE":sum}).sort_values(by="VALUE", ascending=False) VALUE Customer ID HETX 60332.00 DOWY 17234.50 HEXZ 17070.20 But I also want to get Customer Name column too, But I didn't success.
answer count: 1
score: -1
tagged with: pandas
upvote count: 0
has title: Get specific columns and aggregate with pandas
has answer: http://stackoverflow.com/a/47582348
downvote count: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/47660386
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47660227
has body: Put the duplicated code in a function, call the function multiple times: def ask_question(q): a=input(q) if a == "y": print("something") elif a == "y": print("Something") elif a in ("s", "save") print("save") else: print("not option") # now ask_question("first question") print("A bunch of other code for 100 lines") ask_question("second question") Of course your ask_question() needs to be more sophisticated to be useful - e.g. return a value or call other functions.
answers question: http://stackoverflow.com/q/47660227
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82063083
type: Comment
type: QuestionComment
has text: "used the Json.load" Edit your question and show us how you've used it. At this point, the code snippet you've provided does not show any usage of the `json` library.
comment on: http://stackoverflow.com/q/47553168
score: 0

http://stackoverflow.com/a/70438780
has body: AFAIK, the operations are independent of each other, so running them in parallel could work (pseudocode): import dask @dask.delayed def short_path(graph, pair): return graph.get_shortest_paths(pair[0],pair[1], weights='weight') pairs=np.random.choice(np.arange(0,len(graph.nodes)), [k,2]) results = dask.compute(*[short_path(pair) for pair in pairs])
type: Answer
answers question: http://stackoverflow.com/q/47584126
score: 0

http://stackoverflow.com/comment/82235379
type: QuestionComment
has text: @MosesKoledoye sorry I didn't want to post the broken code, I just posted the one that I got to work, just not 100%.. I had added \b before and after `string_column` in the `re.sub` and it gave an error
comment on: http://stackoverflow.com/q/47638438
type: Comment
score: 1

http://stackoverflow.com/q/47618804
score: 2
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/36954511
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82195800
has answer: http://stackoverflow.com/a/47618976
accepted answer: http://stackoverflow.com/a/47618976
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/13940272
tagged with: firebase
has title: Json library in python StringIO parsing?
tagged with: firebase-realtime-database
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I just want to ask something about json and python. If I'm correct, loading a StringIO to json would result to it having a u'. for example, in the json library: &gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; io = StringIO('["streaming API"]') &gt;&gt;&gt; json.load(io) results to [u'streaming API'] so how do I parse this data? in order for me to sort a data that looks like this? I have this data I want to parse. {u'brix': {u'Nov 29, 2017 11:20:15 PM': {u'Checklist': {u'Coffee tray with 3 coffee sticks, 3 creamer, 3 white sugar, 3 brown sugar, 1 equal or sweetener, 3 lipton tea, 2 mineral water, 3 cocktail napkin ?': u'No', u'Luggage bench fabric top is clean': u'No', u'1 facial tissue in a tissue box': u'No', u'Towel Reminder': u'No', u'1 pringles, 1 cashew nut, 1 cup noodles (placed in the coffee tray on the writing desk)?': u'No', After reading a bit about json I found out that this may be a StringIO instead of a json. It was silly that I tried to do json.loads with it when I it's already loaded. All I want is to sort all of these data so it appears properly on web. How do i properly do this? Do i decode these to json first so it becomes something like { "maps":[ {"id":"blabla","iscategorical":"0"}, {"id":"blabla","iscategorical":"0"} ], "masks": {"id":"valore"}, "om_points":"value", "parameters": {"id":"valore"} } Then get a value from that using this? data["maps"][0]["id"] # will return 'blabla' data["masks"]["id"] # will return 'valore' data["om_points"] # will return 'value' Anyway, I'm confused of what I should do, I tried pretty much everything, these example came from other questions . Here's a bit of my code: result1 = firebase.get('/Rooms/Room1/2017-11-29/Inspection/Scan-in/Inspector/', None) result2 = firebase.get('/Rooms/Room1/2017-11-29/Inspection/Scan-out/Inspector/', None) print result1["brix"] Firebase is supposed to return a json file. lol but it doesn't work on mine. Thankyou very much to those who will clear it out to me.

http://stackoverflow.com/a/47642990
answers question: http://stackoverflow.com/q/47642916
score: 1
type: Answer
has body: You can use np.ravel to get a 1D view of the array if possible; otherwise a copy is returned. See the linked documentation for the definition of 'if possible'. a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.ravel()) # [1 2 3 4 5 6]
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82299379
type: QuestionComment
comment on: http://stackoverflow.com/q/47670310
score: 0
has text: Flagging as duplicate of https://stackoverflow.com/q/2464959/1860929
type: Comment

http://stackoverflow.com/q/47686224
downvote count: 2
has answer: http://stackoverflow.com/a/47686265
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
has title: adding two dictionaries of ints
tagged with: python
has answer: http://stackoverflow.com/a/47686253
answer count: 2
has body: I think I have the right idea of solving this function, but it's not getting the desired result shown in the docstring i test it. Can anyone please help me fix this? def add_dicts(d1, d2): '''(dict, dict) -&gt; dict Parameters d1 and d2 are dicts where each key is an int and each value is an int. Return dict d1 with the contents of d2 added to d1. More concisely, if key k is in d1 and in d2, update d1[k] to be the sum of d1[k] and d2[k]. If d2 has a key that is not in d1, add the key value pair from d2 to d1. &gt;&gt;&gt; d1 = {1:1, 2:1, 3:2} &gt;&gt;&gt; d2 = {1:3, 3:1, 4:1} &gt;&gt;&gt; d = add_dicts(d1, d2) &gt;&gt;&gt; d == {1:4, 2:1, 3:3, 4:1} True ''' for (key, value) in d1.items(): if key in d1 and key in d2: d1[key] = d1[key] + d2[key] if key in d2 and key not in d1: d1[key] = {key: value} return d1
upvote count: 0

http://stackoverflow.com/a/47628064
upvote count: 1
has comment: http://stackoverflow.com/comment/82213714
has comment: http://stackoverflow.com/comment/82213840
has body: Same as for scalars inserting additional axes works for higher dimensional arrays too (this is called broadcasting): import numpy as np a1 = np.random.randn(2, 2, 3, 4) a2 = np.random.randn(2, 2, 3, 4) added = a1[..., np.newaxis, np.newaxis] + a2[..., np.newaxis, np.newaxis, :, :] print(added.shape) # (2, 2, 3, 4, 3, 4)
answers question: http://stackoverflow.com/q/47627934
type: Answer
has comment: http://stackoverflow.com/comment/82213789
has comment: http://stackoverflow.com/comment/82213824
has comment: http://stackoverflow.com/comment/82213766
score: 1
downvote count: 0

http://stackoverflow.com/comment/82324880
comment on: http://stackoverflow.com/q/47682666
score: 0
type: Comment
type: QuestionComment
has text: Run `bash shell.sh `

http://stackoverflow.com/a/47572047
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47566948
answers question: http://stackoverflow.com/q/47566948
has body: You should explicitly flush the output buffer of the print.py script (the child script) running in the subprocess. The default behaviour of print is to send the output to standard out (stdout). As such, you should explicitly call sys.sydout.flush() in the child script, after each print statement, to ensure the content of the print statements from the child script are made available to the parent script in a timely manner.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47666302
tagged with: url
has comment: http://stackoverflow.com/comment/82291958
has comment: http://stackoverflow.com/comment/82292785
type: Question
has title: Django URL using javascript to get client end information
accepted answer: http://stackoverflow.com/a/47666491
tagged with: django
tagged with: javascript
tagged with: python
tagged with: jquery
has body: My problem that I am trying to resolve is that I made an Ajax-autocorrect input feature and "onclick" of a button I get the value inside that input and attempt to make the page redirect to a Django URL. Here is the URL inside my url.py file: url(r'^groups/add-member/(?:/(?P&lt;pk_group&gt;[-\w]+))?/(?:/(?P&lt;pk_member&gt;[-\w]+))?/$', views.add_member, name='add-member') inside the HTML I have this script: &lt;script&gt; function add_member(id){ var input=document.getElementById("myText").value console.log(id) //Correctly gets ID # console.log(input) //Correctly gets the name (string) of member instance url = "{% url 'add-member' 0 zzzz %}".replace('0', id).replace('zzzz',input); } &lt;/script&gt; And the resulting error that I get is: Reverse for 'add-member' with arguments '(0, '')' not found. 1 pattern(s) tried: ['flexfeed/groups/add-member/(?:/(?P&lt;pk_group&gt;[-\\w]+))?/(?:/(?P&lt;pk_member&gt;[-\\w]+))?/$'] I'm having trouble understanding my error. If anyone could suggest how to fix this issue or possibly suggest a difdferent approach to this particular problem I'd really appreciate it! The end goal is that I want my page to redirect to my update view at the correct link!
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47666491
answer count: 1

http://stackoverflow.com/q/47552563
has comment: http://stackoverflow.com/comment/82061956
has comment: http://stackoverflow.com/comment/82062094
tagged with: python
has comment: http://stackoverflow.com/comment/82061923
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/82062141
upvote count: 0
has title: Match internal domain links only using regex
answer count: 2
has answer: http://stackoverflow.com/a/47553133
has comment: http://stackoverflow.com/comment/82061785
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/47553322
has body: I've been working on this regex expression for quite a while without much luck. Basically, I'm hoping to solve the following problems: Match: http://ourwebsite.com/index.html &lt;-- match index.html only ourwebsite.com/index.html &lt;-- match index.html only ourwebsite.com/about.html#something &lt;-- match about.html only index.html &lt;-- match index.html /about.html &lt;-- match about.html (do not match /, only about.html) /index &lt;-- match index /index/ &lt;-- match index/ index/ &lt;-- match index/ /about &lt;-- match about /about/ &lt;-- match about/ about/ &lt;-- match about/ /about/us/ &lt;-- match about/us/ No match: someotherwebsite.com/index.html &lt;-- do not match anything someotherwebsite.com/index &lt;-- do not match anything In other words, only match internal website links, but eliminate the starting /. Here's what I've constructed thus far: ^(?:(?:https?):\/\/|\b)http\:\/\/ourwebsite\.com.*|(^[a-zA-Z0-9]*\.[a-z]{3,}) This regex solves most of what I'm trying to do, however, still matches someotherwebsite.com. I'm guessing my regex isn't completely optimal either.. Is there an easier way to do this? I'm using Python for this by the way. If there's any libraries that could do this, I'm all ears.
has comment: http://stackoverflow.com/comment/82062190
favorite count: 0
has comment: http://stackoverflow.com/comment/82063317
type: Question

http://stackoverflow.com/q/47601064
upvote count: 3
has body: I have a Django Form (ModelForm) which has a number of fields. When the user presses submit these are then saved to a database. What I am struggling to work out is, how do I then output/render these results in some other HTML page. Models.py from django.db import models # Create your models here. class Contract(models.Model): name = models.CharField(max_length=200) doorNo = models.SlugField(max_length=200) Address = models.TextField(blank=True) Forms.py from django import forms from contracts.models import Contract class GenerateContract(forms.ModelForm): class Meta(): model = Contract fields = '__all__' Views.py from django.shortcuts import render from contracts.forms import GenerateContract # Create your views here. def index(request): return render(request, 'contracts/index.html') def contractview(request): form = GenerateContract() if request.method == "POST": form = GenerateContract(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print('ERROR') return render(request,'contracts/contracts.html',{'form':form}) At the moment, I am returning the 'Index' Home page of the app as a placeholder.
has title: Displaying Django Form Results
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47601252
answer count: 2
has answer: http://stackoverflow.com/a/47601156
possible better answer: http://stackoverflow.com/a/47601156
downvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47601252
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/47652210
tagged with: vim
has comment: http://stackoverflow.com/comment/82267355
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67929175
downvote count: 0
has body: I'm using ALE with Pylint and pylint-django, but I'm not able to configure it. It shows a linter warning while browsing any file within a Django project: no-member: User class has no member objects for below code. on code like the following: from django.contrib.auth.models import User user_list = User.objects.all()
has comment: http://stackoverflow.com/comment/82267145
favorite count: 0
score: 9
type: Question
has comment: http://stackoverflow.com/comment/82263561
answer count: 2
upvote count: 9
has answer: http://stackoverflow.com/a/47668643
possible better answer: http://stackoverflow.com/a/67929175
accepted answer: http://stackoverflow.com/a/47668643
tagged with: pylint
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82267443
tagged with: neovim
has title: Configuring ALE plugin with Pylint

http://stackoverflow.com/q/47546225
has title: Why I am not getting proper output in this code?
has answer: http://stackoverflow.com/a/47546934
answer count: 1
accepted answer: http://stackoverflow.com/a/47546934
has comment: http://stackoverflow.com/comment/82049872
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82049300
type: AnsweredQuestion
tagged with: python
score: -1
has body: def kruskals(): matrix = [] total = 0 min = 999 u = 0 v = 0 parent = [None]*8 noOfEdges = 1 for i in range(0,7): parent[i] = 0 for j in range(0,7): with open('input.txt') as file: for line in file: matrix.append([int(val) for val in line.split()]) #print matrix if matrix[i][j]== 0: matrix[i][j] = 999 while (noOfEdges &lt; 7 ): min = 999 for i in range(0,7): for j in range(0,7): if min &gt; matrix[i][j]: min = matrix[i][j] a = u = i b = v = j while (parent[u] != 0): u = parent[u] while (parent[v] != 0): v = parent[v] if(v != u): noOfEdges = noOfEdges + 1 print("edge found :{}-&gt;{}:{}".format(a,b,min)) total = total + min parent[v] = u matrix[u][v] = 999 matrix[v][u] = 999 print("The weight of minimum spanning tree is : {}".format(total)) return f.close() kruskals() I have written kruskals algorithm in python.I am taking inputs from text file named 'input.txt'. The problem is that I am getting proper values till certain point, after that the output is not coming.Why is that so? input: 'input.txt': 0 28 999 999 999 10 999 28 0 16 999 999 999 14 999 16 0 12 999 999 999 999 999 12 0 22 999 18 999 999 999 22 0 25 24 10 999 999 999 25 0 999 999 14 999 18 24 999 999 output :( till it displays properly) edge found :0-&gt;5:10 edge found :2-&gt;3:12 edge found :1-&gt;6:14 edge found :1-&gt;2:16 After this the output is not displaying."
has comment: http://stackoverflow.com/comment/82049730
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82049895

http://stackoverflow.com/comment/82244968
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47642285
has text: Error message is included in the post already. See above.

http://stackoverflow.com/q/47564742
tagged with: python
has comment: http://stackoverflow.com/comment/82088908
has comment: http://stackoverflow.com/comment/82088922
has comment: http://stackoverflow.com/comment/82089401
has body: Suppose I have a DataFrame like so x = pd.DataFrame(index = pd.date_range(start="2017-1-1", end="2017-1-13"), columns="a b c".split()) x.ix[0:2, "a"] = 1 x.ix[5:10, "a"] = 1 x.ix[9:12, "b"] = 1 x.ix[1:3, "c"] = 1 x.ix[5, "c"] = 1 a b c 2017-01-01 1 NaN NaN 2017-01-02 1 NaN 1 2017-01-03 NaN NaN 1 2017-01-04 NaN NaN NaN 2017-01-05 NaN NaN NaN 2017-01-06 1 NaN 1 2017-01-07 1 NaN NaN 2017-01-08 1 NaN NaN 2017-01-09 1 NaN NaN 2017-01-10 1 1 NaN 2017-01-11 NaN 1 NaN 2017-01-12 NaN 1 NaN 2017-01-13 NaN NaN NaN The result should be a b c 2017-01-01 1 NaN NaN 2017-01-02 NaN NaN 1 2017-01-03 NaN NaN NaN 2017-01-04 NaN NaN NaN 2017-01-05 NaN NaN NaN 2017-01-06 1 NaN 1 2017-01-07 NaN NaN NaN 2017-01-08 NaN NaN NaN 2017-01-09 NaN NaN NaN 2017-01-10 NaN 1 NaN 2017-01-11 NaN NaN NaN 2017-01-12 NaN NaN NaN 2017-01-13 NaN NaN NaN The above desired output is generated as follows: y = pd.DataFrame(index = pd.date_range(start="2017-1-1", end="2017-1-13"), columns="a b c".split()) y.ix[0, "a"] = 1 y.ix[5, "a"] = 1 y.ix[9, "b"] = 1 y.ix[1, "c"] = 1 y.ix[5, "c"] = 1 Hope I make myself clear enough by the example.
type: AnsweredQuestion
downvote count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47565341
score: -1
has title: How to get a indicator matrix that indicates the first occurrence within a group
favorite count: 0
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/47565341

http://stackoverflow.com/q/47643409
tagged with: pytz
score: 0
answer count: 2
has body: Hi, I have a script on Python with SQL and I use fecthall() method to extract the elements I want and all great until there, because I want do modify two columns (datetime.date and datetime.time) to another timezone but I read docs and Its seems its not veare easy... For now I have the next piece of code fetching the table and then trying to covert firts the date to another timezone, I know... Its a date but if in Spain now is 12am from 5/12/2017 in Mexico is 5pm from 04/12/2017 soooo... BTW Im using pytz cursor.execute(cadenaSQL + cadenaSQL_dos) su_dict[base+' hagent'] = cursor.fetchall() for row in su_dict[base+' hagent']: row = list(row)[0] print row row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) For now I got this error with that code: Traceback (most recent call last): File "cms_V2_30m.py", line 1535, in main() File "cms_V2_30m.py", line 1444, in main select_hagent() File "cms_V2_30m.py", line 211, in select_hagent row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) TypeError: 'datetime.date' object is unsubscriptable EDIT: I think I´m close, the problem now is with row object, because it is a tuple... so it is inmutble, so I am trying to find a way to change this vale... The New code: for row in su_dict[base + ' hagent']: print row[0] #list(row) #print my_date[0] #print datetime.datetime.combine(my_date[0], hoyUTC.time()) row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) The new error: Traceback (most recent call last): File "cms_V2_30m.py", line 1538, in main() File "cms_V2_30m.py", line 1447, in main select_hagent() File "cms_V2_30m.py", line 214, in select_hagent row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) TypeError: 'tuple' object does not support item assignment
tagged with: mysql
has title: Pyodbc update cursor
has answer: http://stackoverflow.com/a/47643589
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/47643599

http://stackoverflow.com/a/47593882
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47592647
type: Answer
has body: You could use threading to implement this. Below is a very rough example of this. threaded_task.py import threading import time class ThreadedTask(threading.Thread): def __init__(self, progress): threading.Thread.__init__(self) self.progress = progress def run(self): for i in range(100): self.progress.step(1) # Update progress bar time.sleep(1) # Simulate long running process main.py from tkinter import * from tkinter import ttk from threaded_task import ThreadedTask root = Tk() progcomp = ttk.Progressbar(root, orient='horizontal', length=200, mode = 'determinate', maximum=100) progcomp.grid() task = ThreadedTask(progcomp) task.start() root.mainloop()
upvote count: 2

http://stackoverflow.com/comment/82154825
comment on: http://stackoverflow.com/q/47598315
has text: It's unclear what you mean by "invert" but you should work out the algorithm with a pen and paper first I think.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47602118
answers question: http://stackoverflow.com/q/47602046
type: Answer
upvote count: 4
has body: It's just what it says: you cannot sort Person objects. If you want this to work, you have to define at least the __lt__ operator for your class, using whatever sort criterion you had in mind -- perhaps alphabetical by name? Another possibility is to simply write your own function, and call it with person.mentees.obj_sort. Also, I'm not sure why this matters: you never use the return value of this operation. You store it in the local variable a (that's a poor variable name, by the way), and never use it.
downvote count: 0
score: 4

http://stackoverflow.com/a/47542301
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47542212
score: 2
has body: Remove anything that is not a letter Prepend an underscore (_) to uppercase letters that are not at the start of the string Lowercase the result df.columns Index(['FooBar', 'SpamEggs', 'Monty-Python'], dtype='object') df.columns.str.replace('[\W]', '')\ .str.replace('(?&lt;!^)([A-Z])', r'_\1')\ .str.lower() Index(['foo_bar', 'spam_eggs', 'monty_python'], dtype='object') This solution generalises quite nicely. Assign the result back to df.columns.
has comment: http://stackoverflow.com/comment/82081120
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47542212

http://stackoverflow.com/q/47637374
has title: Exceptions: Django 1.8 with MSSQL Server 2017 offline
has comment: http://stackoverflow.com/comment/82320350
tagged with: django-forms
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/82318584
type: UnansweredQuestion
tagged with: database
has comment: http://stackoverflow.com/comment/82233525
tagged with: django
tagged with: python
has body: As I'm new to Django. I have installed Django = 1.8 version. I tried with MSSQL Server 2017 which is locally installed in standalone system. Apart from settings.py file I had not modified anything. It is showing ImproperlyConfigured: Django 1.11 is not supported even though i had used Django 1.8 version. Settings.py DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'HOST': '127.0.0.1', 'NAME': 'demo2016', 'USER': '', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } C:\Users\Vitriv-Desktop\Desktop\sqldjango&gt;python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;fro…
tagged with: sql-server
score: 0

http://stackoverflow.com/a/47585453
score: 20
has comment: http://stackoverflow.com/comment/124196832
type: AcceptedAnswer
downvote count: 0
has body: len() isn't implemented for queue.Queue because it would be an "attractive nuisance": something that only an expert should even consider using, but a "friendly name" would encourage non-experts to use it. Unlike most sequence types (like list and deque), a queue.Queue is specifically intended to be used in multi-threaded contexts (and similarly for the multiprocessing module's queue type). While the number of items in a Queue certainly has a definite value at any particular time, it's impossible for user code to find out what that value is: between the time a call to .qsize() returns and your code can look at the returned value, any number of other threads (or processes, in the multiprocessing case) may have made any number of changes to the queue's contents. So the only true thing that can be said about the value returned by .qsize() is that the Queue had that many values in it at some time in the past. By the time you can use the returned value, it may have arbitrarily more (or fewer) values in it. Of course that's not so if you're only running one thread - but then there's no need to pay for the implementation complexity of a Queue (use a list or a deque instead).
has comment: http://stackoverflow.com/comment/82128783
has comment: http://stackoverflow.com/comment/139739096
has comment: http://stackoverflow.com/comment/117400879
answers question: http://stackoverflow.com/q/47585367
upvote count: 20
type: Answer
accepted answer of: http://stackoverflow.com/q/47585367
has comment: http://stackoverflow.com/comment/82128879

http://stackoverflow.com/a/51261265
answers question: http://stackoverflow.com/q/47658596
has body: If we run lldb with DYLD_PRINT_LIBRARIES=1 set, then we can see that it's loading the Python.framework from /System/Library, but then some other Python libraries from Homebrew: dyld: loaded: /System/Library/Frameworks/Python.framework/Versions/2.7/Python ... dyld: loaded: /usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so But if we tell DYLD to specifically load Python.framework from Homebrew, then it works: DYLD_FRAMEWORK_PATH="$(brew --prefix python@2)/Frameworks/" "$(xcrun -f lldb)" Tested on macOS 10.13.6 with brew'd Python 2.7.15. Update: When System Integrity Protection is enabled, using DYLD_FRAMEWORK_PATH may be prohibited on the Xcode Command Line Tools trampoline executables running from /usr/bin. To work around that, we run xcrun -f lldb to use the real LLDB executable instead.
type: Answer
has comment: http://stackoverflow.com/comment/98586619
score: 8
has comment: http://stackoverflow.com/comment/101984624
has comment: http://stackoverflow.com/comment/101984149
has comment: http://stackoverflow.com/comment/102019552
downvote count: 1
has comment: http://stackoverflow.com/comment/101984720
upvote count: 9
has comment: http://stackoverflow.com/comment/101984505
has comment: http://stackoverflow.com/comment/94887902

http://stackoverflow.com/a/47601376
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82162498
has comment: http://stackoverflow.com/comment/82166184
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47601155
has comment: http://stackoverflow.com/comment/82165612
has body: Sounds Like you need rolling np.where(df['a']==df['a'].rolling(10).max(),'istrue','isnottrue')
has comment: http://stackoverflow.com/comment/82162177
accepted answer of: http://stackoverflow.com/q/47601155
upvote count: 2

http://stackoverflow.com/q/47594932
downvote count: 0
tagged with: scipy
favorite count: 0
has answer: http://stackoverflow.com/a/47595271
type: Question
tagged with: interpolation
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47595271
score: 2
type: AnsweredQuestion
tagged with: pandas
has title: Row-wise Interpolation in dataframe using interp1d
answer count: 1
has body: I have the following dataframe (df) in python: X1 X2 Y1 Y2 X YInt 10 20 0.6 1 17 ??? 5 50 0.4 1 9 ??? I'm trying to add a new column (YInt) to that dataframe, which evaluates the linearly-interpolated Y Value for a given X and the given coordinates X1,Y2, X2,Y2 in a given row. So far I have the following code: df['YInt'] = interp1d(df'X1','X2',df'Y1','Y2',bounds_error=False)(df['X']) However, an error is reported that the Arrays don't equal in length.

http://stackoverflow.com/comment/82341746
type: Comment
type: QuestionComment
has text: LinkedIn may have blocked your IP as well. LinkedIn has lot of scraping protection even for the public non authenticated pages
score: 0
comment on: http://stackoverflow.com/q/47691229

http://stackoverflow.com/q/47563539
has title: Modifying a complex fixed text file?
has answer: http://stackoverflow.com/a/47564074
tagged with: python
has comment: http://stackoverflow.com/comment/82085284
has body: I have a text file like this example: fit c3 start=1455035 step=1 2.000000 2.000000 2.000000 2.000000 2.000000 2.000000 fit c2 start=5195348 step=1 1.000000 1.000000 1.000000 1.000000 1.000000 fit c4 start=6587009 step=1 10.000000 10.000000 10.000000 10.000000 10.000000 each text line(starting with fit) is followed by some number lines. I want to sum all numbers which are below each text line (so they are in the same group) and replace the last number of that group by the sum of number of that specific group and also replace the rest of numbers by 1.000000 - like in this output example: fit c3 start=1455035 step=1 1.000000 1.000000 1.000000 1.000000 1.000000 12.000000 fit c2 start=5195348 step=1 1.000000 1.000000 1.000000 1.000000 5.000000 fit c4 start=6587009 step=1 1.000000 1.000000 1.000000 1.000000 50.000000 and write it into a new file. I tried this code in Python, but actually did not return what I want. infile = open("file.txt", "r") for line in infile: if line startswith"fit": for l in len(line): line[l] = line + line[l+1] Do you know how to do that in python?
has comment: http://stackoverflow.com/comment/82085013
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82086566
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/82085027
has answer: http://stackoverflow.com/a/47564024
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82297664
comment on: http://stackoverflow.com/q/47668802
type: QuestionComment
has text: khahesh mikonam azizam :)
type: Comment
score: 0

http://stackoverflow.com/a/47596267
has comment: http://stackoverflow.com/comment/82159175
has comment: http://stackoverflow.com/comment/90051179
score: 2
accepted answer of: http://stackoverflow.com/q/47596137
has comment: http://stackoverflow.com/comment/90028030
type: Answer
has comment: http://stackoverflow.com/comment/82167946
has body: Your convolution is cutting the tips of the sequence. Use padding='same' in the convolutional layers. The message, though, seems not to fit your model. Your model clearly has 5 output features (because of Dense(5)), but the massage says it expects 1. Maybe this is happening because of "sparse" crossentropy. You should probably, by the format of your data, use a "categorical_crossentropy".
answers question: http://stackoverflow.com/q/47596137
has comment: http://stackoverflow.com/comment/82161401
has comment: http://stackoverflow.com/comment/90049008
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82167943
downvote count: 0
has comment: http://stackoverflow.com/comment/82162893
has comment: http://stackoverflow.com/comment/90028580

http://stackoverflow.com/a/47665408
has comment: http://stackoverflow.com/comment/82290227
type: Answer
answers question: http://stackoverflow.com/q/47665218
score: 2
upvote count: 2
downvote count: 0
has body: Here's a possible way to do it. import numpy as np import scipy.misc images = np.zeros((176,128,128,3)) for i in range(len(images)): scipy.misc.imsave('date_set_' + str(i) + '.jpg', images[i,:,:,:])

http://stackoverflow.com/comment/82253650
type: AnswerComment
has text: @SamiulSalehin great! Consider marking the answer as accepted to show that your problem is resolved.
comment on: http://stackoverflow.com/a/47634859
type: Comment
score: 0

http://stackoverflow.com/a/55378377
answers question: http://stackoverflow.com/q/47563013
type: Answer
score: 0
has body: As error shows that path can not be imported. So here we will use the url instead of path as shown below:- first import the url package then replace the path with url from django.conf.urls import url urlpatterns = [ url('admin/', admin.site.urls), ] for more information you can take the reference of this link.

http://stackoverflow.com/q/47657835
type: Question
has comment: http://stackoverflow.com/comment/82277377
has answer: http://stackoverflow.com/a/47659409
tagged with: python
has comment: http://stackoverflow.com/comment/82275781
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47659409
tagged with: tensor
has title: In Tensorflow, is there a direct way to construct an array tensor from a scalar tensor?
answer count: 1
has body: For example, something similar to: x = 12 y = np.array([[x, x], [0, 0]]) Is there a direct to construct the array tensor y given scalar tensor x in Tensorflow? Without using tf.expand_dims and tf.pad. x = tf.placeholder(tf.int32) y = ? Thank you very much.
tagged with: tensorflow

http://stackoverflow.com/a/62812162
upvote count: 3
has comment: http://stackoverflow.com/comment/119068858
score: 1
downvote count: 2
has body: Delete the history entry from the database will solve the issue. Error: alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810' select * from alembic_version where version_num='e39d16e62810' Option 1: Update the record with your latest revision id update alembic_version set version_num='&lt;your_version_num&gt;' where version_num='e39d16e62810' Option 2: Delete this record: delete from alembic_version where version_num='e39d16e62810'
answers question: http://stackoverflow.com/q/47656071
type: Answer

http://stackoverflow.com/comment/82096337
has text: I have edited the question, thank you. @ddor254
comment on: http://stackoverflow.com/q/47569284
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82227114
type: Comment
score: 0
type: AnswerComment
has text: You don't necessarily need to use the `::` though do you? A single `:` will work, at least it appears so in the post from @RoachLord.
comment on: http://stackoverflow.com/a/47634665

http://stackoverflow.com/a/47615098
upvote count: 4
score: 4
type: AcceptedAnswer
has body: The code you posted is correct and work with both python 2.7 and 3.6 (for 3.6 you have to put parenthesis around the print statement). However, the code as is has a 3 spaces indent which should be fixed to 4 spaces. here how to reproduce your error s = [] str = 'overload str with string' # The str below is a string and not function, hence the error s.append(' '.join(str(x) for x in ['a', 'b', 'c'])) print(s) Traceback (most recent call last): File "python", line 4, in &lt;module&gt; File "python", line 4, in &lt;genexpr&gt; TypeError: 'str' object is not callable There must be somewhere where you redefine str builtin operator as a str value like the example above. Here a shallower example of the same problem a = 'foo' a() Traceback (most recent call last): File "python", line 2, in &lt;module&gt; TypeError: 'str' object is not callable
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47614975
answers question: http://stackoverflow.com/q/47614975
type: Answer

http://stackoverflow.com/comment/82287533
type: Comment
has text: @Alasdair I updated the question with the full traceback.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47664064

http://stackoverflow.com/q/47553951
has comment: http://stackoverflow.com/comment/82065134
linked to: http://stackoverflow.com/q/4881607
has answer: http://stackoverflow.com/a/47559015
has comment: http://stackoverflow.com/comment/82065459
has comment: http://stackoverflow.com/comment/82064702
score: 1
has comment: http://stackoverflow.com/comment/82065037
answer count: 1
has comment: http://stackoverflow.com/comment/82065833
downvote count: 0
has comment: http://stackoverflow.com/comment/82066044
upvote count: 1
has comment: http://stackoverflow.com/comment/82064615
has comment: http://stackoverflow.com/comment/82065126
favorite count: 0
has comment: http://stackoverflow.com/comment/82065258
has comment: http://stackoverflow.com/comment/82070486
type: Question
has comment: http://stackoverflow.com/comment/82065213
has body: I have 2 apps named social and instagram. The structure of models.py file is as follows : In social app : from instagram.models import User as instagramUser class User(models.Model): # some fields class Meta: abstract = True class Foo(models.Model): # Some fields def save(self, *args, **kwargs): # some validation on User models from instagram app (instagramUser) super(Foo, self).save(*args, **kwargs) and in instagram app : from social.models import User as socialUser class User(socialUser): # Some additional fields Conceptually this structure is correct and the model Foo should be located in social app. But as expected when running circular dependency occurs. I want to keep conceptual correctness while resolving the circular dependency. How can I do that?
has comment: http://stackoverflow.com/comment/82066593
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82064579
has comment: http://stackoverflow.com/comment/82075775
tagged with: circular-dependency
has comment: http://stackoverflow.com/comment/82070410
has title: circular dependency in Django models

system
tag name: system
type: Tag
tags question: http://stackoverflow.com/q/47662760

http://stackoverflow.com/q/47687924
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/82335426
favorite count: 0
type: Question
has body: Usually my markdown document uses only one type of code language. For example, python is used to highlight all my code blocks. ```python some code here. ``` ```python another piece of code ``` Since I need to type python for every piece of my code block, I would like to know if there is a way to define a default pre code highlighting language for the whole document. Then if it's defined, for example, cpp, all of the code blocks in the document will be highlighted using cpp syntax. Thank you very much.
has title: Set default pre code language for a whole markdown document
has comment: http://stackoverflow.com/comment/82340146
tagged with: python
tagged with: highlighting
has comment: http://stackoverflow.com/comment/82393361
upvote count: 13
tagged with: markdown
tagged with: c++
has answer: http://stackoverflow.com/a/76851033
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/47545082
tagged with: pyinstaller
score: 0
answer count: 1
has title: Possible to get python source code from pyinstaller app?
type: Question
has answer: http://stackoverflow.com/a/47754980
type: UnansweredQuestion
has body: So I'm working on a web scraping project right now and it's pretty specific; however, I have found a great project on the internet that was made with Pyinstaller. I have tried to reach out to the developer, but I think the code has been dead for a while. However, it would really help me with my project to see the logic in the code. Is there any way to deconstruct a pyinstaller app and view the source code? Some more info: So I have managed to use uncompyle6 and pyinstxtractor.py to look at the files within the initial .exe file. Within that, there was another .exe file with the same name as the app that I decompiled too. However, both of these directories just contained a lot .pyc files that appear to just be external modules. Within the innermost .exe, there is a file with the same name as the app but with no extension. I assume this is the main code, but when I open it in a text editor, it just looks like this, with little bits of readable code: https://i.sstatic.net/Pc5nH.jpg. I have scavenged the internet for this and found nothing, so any little piece of advice is invaluable. Thanks
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/a/47582677
downvote count: 0
has body: If the primary use case is going from keyword to set name (i.e. 'apples' -> fruit), you should probably have a single dict that looks like: {'apples': 'fruit', 'bananas': 'fruit',...} You could use a constant to represent the categories instead but I suspect that string interning will make this not much worse (if at all).
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47582619

http://stackoverflow.com/comment/82050852
has text: You want to open a text file, read the first line until you hit `\n` and close it again?
type: QuestionComment
comment on: http://stackoverflow.com/q/47547169
score: 0
type: Comment

http://stackoverflow.com/comment/82206260
type: QuestionComment
has text: I think you should put only `top.deiconify()` as `login` and then call `top.destroy()` if the user validates. In its current state it keeps, at best, overwriting widget objects and stuff.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47623370

http://stackoverflow.com/comment/82229825
type: QuestionComment
comment on: http://stackoverflow.com/q/47627575
score: 0
has text: as I said in aswer `spritecollide` need group as second argument and `Pong` is not group but single object.
type: Comment

http://stackoverflow.com/q/47650917
has comment: http://stackoverflow.com/comment/82266190
tagged with: python
has comment: http://stackoverflow.com/comment/82265333
has comment: http://stackoverflow.com/comment/82263807
has comment: http://stackoverflow.com/comment/82262026
has comment: http://stackoverflow.com/comment/82262111
answer count: 0
tagged with: weighted
type: UnansweredQuestion
score: 0
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
downvote count: 1
favorite count: 0
tagged with: multiclass-classification
type: Question
has body: Simply put, I have an imbalanced data set and I have to train using partial_fit because of the size. Some of the methods I use can't naturally handle multiclass problems, so I am wrapping them with a OneVsRestClassifier. However, this causes problems adjusting the class_weights. Because I use partial_fit the option of setting class_weight='balanced' or 'auto' is not possible. Is there a simple solution where I can use OneVsRestClassifier and still weight my classes? Example code: model = OneVsRestClassifier(SGDClassifier(loss='log', alpha=1e-4, penalty='elasticnet', class_weight=weights)) model.partial_fit(features, labels_i, classes=np.unique(labels_i)) where weights is a dictionary containing the weights for each class.
has title: Handling imbalanced data with partial_fit and OneVsRestClassifier

http://stackoverflow.com/a/47684881
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82351511
score: 3
has comment: http://stackoverflow.com/comment/82348876
type: Answer
answers question: http://stackoverflow.com/q/47677328
has body: Xpath is not a good way for searching elements in Appium/XCUITest as it is often too slow and might not work as you expect it to work (your case with contains). Instead you should you try XCUITest native locator strategies: iOSNsPredicate or iOSClassChain, e.g. driver.find_element_by_ios_predicate("label contains 'Some text'") You can check more examples here: python client tests, java client tests
accepted answer of: http://stackoverflow.com/q/47677328
upvote count: 3

http://stackoverflow.com/q/47684387
has comment: http://stackoverflow.com/comment/135596077
type: Question
has body: Most documentation simply tells you to add the name of each of your apps to the INSTALLED_APPS array in your Django project's settings. What is the benefit/purpose of this? What different functionality will I get if I create 2 apps, but only include the name of one in my INSTALLED_APPS array?
linked to: http://stackoverflow.com/q/3038459
accepted answer: http://stackoverflow.com/a/47684488
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/125612413
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47684488
answer count: 1
score: 24
upvote count: 24
has title: What is the purpose of adding to INSTALLED_APPS in Django?
favorite count: 0

http://stackoverflow.com/comment/82069549
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47556060
has text: You should try running `pep8` (or better yet, `flake8`) on your code, then you will know! `pip install flake8` and then just run `flake8` where your code lives.
score: 0

http://stackoverflow.com/comment/82166019
type: QuestionComment
comment on: http://stackoverflow.com/q/47603286
has text: How is your `Group` class going to be different from a [`pygame.sprite.Group`](http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group)? Perhaps you could/should just use the predefined `Group` class by creating an instance of one and adding your own `Sprite` instances to it.
score: 0
type: Comment

http://stackoverflow.com/comment/82173465
type: QuestionComment
has text: First of all, variables defined in functions are local to the function, not visible outside. Secondly, as of line 17, none of the functions have been invoked yet. They were defined, but not yet used. They have not been called yet.
score: 2
comment on: http://stackoverflow.com/q/47607515
type: Comment

http://stackoverflow.com/comment/82268747
type: QuestionComment
has text: Take a look to: https://github.com/ottoyiu/django-cors-headers
score: 0
comment on: http://stackoverflow.com/q/47654886
type: Comment

http://stackoverflow.com/comment/82256901
comment on: http://stackoverflow.com/q/47647938
type: QuestionComment
has text: Please excuse the typo @data
type: Comment
score: 0

http://stackoverflow.com/comment/82196730
has text: @A.Keshavarz Ok, are you sure it does not error, because it should stay open for at least 2 seconds if the code is correct. Try running the code in python (not pyinstaller) and tell me if it works.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47611701
type: AnswerComment

http://stackoverflow.com/q/47623638
has comment: http://stackoverflow.com/comment/82205327
has comment: http://stackoverflow.com/comment/82205256
tagged with: python
accepted answer: http://stackoverflow.com/a/47623679
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/82205340
has answer: http://stackoverflow.com/a/47623679
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/183853
answer count: 2
possible better answer: http://stackoverflow.com/a/47623682
has title: multiplying 2 integers of the same value by 300 yields different results
has comment: http://stackoverflow.com/comment/82205204
has answer: http://stackoverflow.com/a/47623682
linked to: http://stackoverflow.com/q/2958684
tagged with: division
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/1267869
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: I am trying to figure out why a difference of 283 happens when I decide to multiply rather than divide. Here is some Python code from my terminal. As you can see both variables are integers, but depending on whether I divide one to get to the other or multiply the other changes the value slightly. &gt;&gt;&gt; type(times), times (&lt;type 'int'&gt;, 1512296383) &gt;&gt;&gt; type(payout), payout (&lt;type 'int'&gt;, 5040987) &gt;&gt;&gt; [times / 300 - payout, times - payout * 300] [0, 283] &gt;&gt;&gt; [times / 300, payout, times, payout * 300] [5040987, 5040987, 1512296383, 1512296100]

http://stackoverflow.com/comment/82141742
comment on: http://stackoverflow.com/q/47590455
type: Comment
has text: @Bharath since it is undirected we only take for eg 1,2 and not 2,1
type: QuestionComment
score: 0

http://stackoverflow.com/a/47561390
downvote count: 0
type: Answer
upvote count: 16
answers question: http://stackoverflow.com/q/47561337
has body: pd.DataFrame({'monkeydict':pd.Series(monkeydict),'pigdict':pd.Series(pigdict)}) Out[879]: monkeydict pigdict 16:41 NaN 3.0 16:43 1.0 NaN 16:44 1.0 2.0 16:49 3.0 NaN 16:51 NaN 3.0 Or (Notice here, you need to rename your columns after create the data frame) pd.DataFrame([monkeydict,pigdict]).T Out[887]: 0 1 16:41 NaN 3.0 16:43 1.0 NaN 16:44 1.0 2.0 16:49 3.0 NaN 16:51 NaN 3.0
score: 16
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47561337

http://stackoverflow.com/q/47679859
upvote count: 1
score: 1
has title: Preprocessing text data with TFRecords files
tagged with: python
tagged with: nlp
favorite count: 0
type: Question
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47896467
has body: I have a .tfrecord dataset of text documents (emails) with corresponding labels '0' or '1' (for spam/non-spam). All of this dataset is already in the form of a .tfrecord file. I'm trying to turn the emails into a bag-of-words representation. I have all the helper methods to do it, but I'm still not familiar with tfrecords. This is what I have so far to read the tf_record file: def read_from_tfrecord(filenames): tfrecord_file_queue = tf.train.string_input_producer([filenames], name='queue') reader = tf.TFRecordReader() _, tfrecord_serialized = reader.read(tfrecord_file_queue) tfrecord_features = tf.parse_single_example(tfrecord_serialized, features={ 'label': tf.FixedLenFeature([], tf.int64), 'text': tf.FixedLenFeature([], tf.string), }, name='features') text = tfrecord_features['text'] label = tfrecord_features['label'] return label, text How should I proceed if I want to use my helper methods to modify the 'texts' ?
answer count: 1
tagged with: tfrecord
tagged with: tensorflow

http://stackoverflow.com/comment/82333455
comment on: http://stackoverflow.com/a/47660586
score: 0
type: Comment
type: AnswerComment
has text: See update. This time the *inner_dict* pre-populates keys by field names to `None` and the loop updates if key shows in XML. Be sure to include the `if item.tag in` which I noticed you above example did not include per my last update.

http://stackoverflow.com/q/47697775
score: 2
accepted answer: http://stackoverflow.com/a/47697839
type: AnsweredQuestion
upvote count: 3
has body: How do I generate all possible pairs permutations from a list in Python? Example: input = [3, 8, 2] output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
has answer: http://stackoverflow.com/a/47697958
has answer: http://stackoverflow.com/a/47697839
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/104420
tagged with: python-3.x
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/47697840
has comment: http://stackoverflow.com/comment/82355645
has answer: http://stackoverflow.com/a/47697890
has answer: http://stackoverflow.com/a/47697840
has title: How to generate all possible pairs with permutations from list in Python?
answer count: 4
linked to: http://stackoverflow.com/q/104420

http://stackoverflow.com/comment/82154838
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47598323
has text: See `str.split` and `str.strip`, `str.split` takes an argument that indicates what it should split on. These two methods make this task relatively easy.

http://stackoverflow.com/a/47657428
answers question: http://stackoverflow.com/q/47656978
has body: I would use merge avg_df = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean().reset_index().rename(columns={'Purchase_Amount': 'Avg'}) trainDf = trainDf.merge(avg_df, on='User_ID')
score: 0
type: Answer

http://stackoverflow.com/comment/82309533
has text: Exactly what I was looking for. Thanks. Can you please also give a small explanation?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47675347
type: Comment

http://stackoverflow.com/q/47683257
has comment: http://stackoverflow.com/comment/82325990
has answer: http://stackoverflow.com/a/47683403
has body: How can I simply calculate the level based on an input experience? I'm making a "pet chance generator" for a game called runescape. The program asks for your current experience and approximates the level based on the experience value input by the user. Below is the only method I could think of to do this but as you can see there is a wall of text basically copy pasted 40 times. Please help! I currently have: def calculate_level(xp): if xp &lt; 368599: level = 62 elif xp &lt; 368599 * 1.101141**2: level = 63 elif xp &lt; 368599 * 1.101141**3: level = 64 elif xp &lt; 368599 * 1.101141**4: level = 65 elif xp &lt; 368599 * 1.101141**5: level = 66 elif xp &lt; 368599 * 1.101141**6: level = 67 elif xp &lt; 368599 * 1.101141**7: level = 68 elif xp &lt; 368599 * 1.101141**8: level = 69 elif xp &lt; 368599 * 1.101141**9: level = 70 elif xp &lt; 368599 * 1.101141**10: level = 71 elif xp &lt; 368599 * 1.101141**11: level = 72 elif xp &lt; 368599 * 1.101141**12: level = 73 elif xp &lt; 368599 * 1.101141**13: level = 74 elif xp &lt; 368599 * 1.101141**14: level = 75 elif xp &lt; 368599 * 1.101141**15: level = 76 elif xp &lt; 368599 * 1.101141**16: level = 77 elif xp &lt; 368599 * 1.101141**17: level = 78 elif xp &lt; 368599 * 1.101141**18: level = 79 elif xp &lt; 368599 * 1.101141**19: level = 80 elif xp &lt; 368599 * 1.101141**20: level = 81 elif xp &lt; 368599 * 1.101141**21: level = 82 elif xp &lt; 368599 * 1.101141**22: level = 83 elif xp &lt; 368599 * 1.101141**23: level = 84 elif xp &lt; 368599 * 1.101141**24: level = 85 elif xp &lt; 368599 * 1.101141**25: level = 86 elif xp &lt; 368599 * 1.101141**26: level = 87 elif xp &lt; 368599 * 1.101141**27: level = 88 elif xp &lt; 368599 * 1.101141**28: level = 89 elif xp &lt; 368599 * 1.101141**29: level = 90 elif xp &lt; 368599 * 1.101141**30: level = 91 elif xp &lt; 368599 * 1.101141**31: level = 92 elif xp &lt; 368599 * 1.101141**32: level = 93 elif xp &lt; 368599 * 1.101141**33: level = 94 elif xp &lt; 368599 * 1.101141**34: l…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47683427
accepted answer: http://stackoverflow.com/a/47683435
has comment: http://stackoverflow.com/comment/82326088
answer count: 3
has answer: http://stackoverflow.com/a/47683435
score: 1
downvote count: 1
favorite count: 0
type: Question
has title: How can I determine level based on experience?
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/47683403
tagged with: python
has comment: http://stackoverflow.com/comment/82326006

http://stackoverflow.com/comment/82101978
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47572467
has text: Thanks for that info about `_flavour.sep`, although I'm wary about using undocumented features: they can disappear without notice. ;)
type: Comment

http://stackoverflow.com/comment/82252997
type: Comment
type: QuestionComment
has text: your content is empty it seems.
comment on: http://stackoverflow.com/q/47647162
score: 0

http://stackoverflow.com/comment/82064480
has text: I just wanted to say thank you. You have helped me out a great deal.
comment on: http://stackoverflow.com/a/47541790
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47571477
has body: Using the AWS Command Line Interface, you would do it like this aws dynamodb scan \ --table-name table_name\ --projection-expression "field1,fields2" \ --filter-expression "filter1 = :filter_value"\ A scan always reads every row in the database. A filter expression simply limits what is returned to you. By default you get all attributes ('columns') back for each item but you can limit that using a projection expression. Queries can be used when you are searching on an indexed attribute. For information checkout the docs on scans and query
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47568483

http://stackoverflow.com/comment/82353220
has text: I tried executing that and again it just did nothing and showed nothing, there is no exception being thrown, its just not executing what it is supposed to execute.
comment on: http://stackoverflow.com/a/47696700
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82088634
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47547675
type: AnswerComment
has text: Otree does have a participant.vars variable and a session.vars variable, so it may be possible to use that.

http://stackoverflow.com/comment/82089753
has text: That is not true. You can open urls other than from your urls.py. Show the original code that you are trying. We cannot guess problem with `href="#"`.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47565913

http://stackoverflow.com/comment/82156875
type: Comment
type: AnswerComment
has text: Thanks @Bharath. Should be fixed now.
score: 0
comment on: http://stackoverflow.com/a/47598549

http://stackoverflow.com/q/47626320
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47626994
has answer: http://stackoverflow.com/a/47626364
has title: Multiple lists input to a file
accepted answer: http://stackoverflow.com/a/47626364
type: AnsweredQuestion
upvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/47626424
has body: I have 4 lists with equal length. like: List1: x1,x2,x3,x4... List2: y1,y2,y3,y4... List3: z1,z2,z3,z4,... list4: a1,a2,a3,a4,.... I want to read them and write to a file as: x1,y1,z1,a1.... for that : with open('do.txt','a+') as writefile: for i in iter(List1): writefile.write(i) how can we write all the in the file at the same time.
downvote count: 1
has comment: http://stackoverflow.com/comment/82210440
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82210400
has answer: http://stackoverflow.com/a/47626424

http://stackoverflow.com/comment/82246788
comment on: http://stackoverflow.com/q/47642369
type: Comment
score: 1
has text: Forgot out.close();?
type: QuestionComment

http://stackoverflow.com/a/47686192
accepted answer of: http://stackoverflow.com/q/47685507
score: 1
answers question: http://stackoverflow.com/q/47685507
has comment: http://stackoverflow.com/comment/82335195
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82335372
has comment: http://stackoverflow.com/comment/82335682
has body: If you need convert to date import datetime df.value.apply(lambda x : datetime.datetime.strptime(x + '-0', "%Y W%W-%w")) Out[133]: 0 2016-04-24 1 2016-05-01 2 2016-05-22 3 2016-05-01 4 2016-05-15 Name: value, dtype: datetime64[ns] without change the date I am going to use reindex with groupby df1=df.groupby('Name')['binary','value'].apply(lambda x : x.set_index('value').\ reindex(['2016 W16','2016 W17','2016 W18','2016 W19','2016 W20'])) df1.loc[df1.groupby(level=0).binary.bfill().dropna().index].fillna(0).reset_index() Out[65]: Name value binary 0 apple 2016 W16 1.0 1 berry 2016 W16 0.0 2 berry 2016 W17 1.0 3 lime 2016 W16 0.0 4 lime 2016 W17 0.0 5 lime 2016 W18 0.0 6 lime 2016 W19 1.0 7 melon 2016 W16 0.0 8 melon 2016 W17 0.0 9 melon 2016 W18 0.0 10 melon 2016 W19 0.0 11 melon 2016 W20 1.0 12 orange 2016 W16 0.0 13 orange 2016 W17 1.0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82358910
has comment: http://stackoverflow.com/comment/82335344
upvote count: 1
has comment: http://stackoverflow.com/comment/82335175
has comment: http://stackoverflow.com/comment/82335305

http://stackoverflow.com/comment/82085170
type: QuestionComment
has text: What's the fourth dimension?
score: 0
comment on: http://stackoverflow.com/q/47563354
type: Comment

http://stackoverflow.com/a/47588043
has comment: http://stackoverflow.com/comment/82445841
score: 1
has body: I believe you can use broadcasting: start_date_period = pd.period_range('2004-01-01', '12-31-2017', freq='30D') end_date_period = pd.period_range('2004-01-30', '12-31-2017', freq='30D') tra = df['transaction_dt'].values[:, None] idx1 = np.argmax(tra &lt; start_date_period.end_time.values, axis=1) idx2 = np.argmin(tra &gt; end_date_period.start_time.values, axis=1) df['window_start_dt'] = start_date_period[idx1] df['window_end_dt'] = end_date_period[idx2] print (df) customer_id transaction_dt product price units window_start_dt \ 0 1 2004-01-02 thing1 25 47 2004-01-01 1 1 2004-01-17 thing2 150 8 2004-01-01 2 2 2004-01-29 thing2 150 25 2004-01-01 3 3 2017-07-15 thing3 55 17 2017-06-21 4 3 2016-05-12 thing3 55 47 2016-04-27 5 4 2012-02-23 thing2 150 22 2012-02-18 6 4 2009-10-10 thing1 25 12 2009-10-01 7 4 2014-04-04 thing2 150 2 2014-03-09 8 5 2008-07-09 thing2 150 43 2008-07-08 window_end_dt 0 2004-01-30 1 2004-01-30 2 2004-01-30 3 2017-07-20 4 2016-05-26 5 2012-03-18 6 2009-10-30 7 2014-04-07 8 2008-08-06
accepted answer of: http://stackoverflow.com/q/47580701
type: Answer
has comment: http://stackoverflow.com/comment/82155728
has comment: http://stackoverflow.com/comment/82485991
has comment: http://stackoverflow.com/comment/82488951
answers question: http://stackoverflow.com/q/47580701
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82409153
upvote count: 1
has comment: http://stackoverflow.com/comment/82481276

http://stackoverflow.com/comment/82149941
score: 0
has text: Please fix your indentation!
type: QuestionComment
comment on: http://stackoverflow.com/q/47596154
type: Comment

http://stackoverflow.com/q/47547221
score: -1
upvote count: 0
linked to: http://stackoverflow.com/q/40278444
downvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47547294
has title: ValueError: too many values to unpack (expected 2) cv2
type: Question
has body: Hi all i having facing the above error while executing the code below. img = cv2.imread('034.jpg',0) ret,thresh = cv2.threshold(img,127,255,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) error as: File "bb.py", line 6, in contours,hierarchy = cv2.findContours(thresh, 1, 2) ValueError: too many values to unpack (expected 2)
duplicate of: http://stackoverflow.com/q/40278444
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47687852
accepted answer: http://stackoverflow.com/a/47687904
upvote count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47687890
favorite count: 0
tagged with: parameters
score: 2
type: AnsweredQuestion
has title: How to get the count of command line parameters in Python regardless of python keyword?
linked to: http://stackoverflow.com/q/29540541
has body: I have a small sample program in Python: import sys print ("This is the name of the script: "+ sys.argv[0]) print ("Number of arguments: " + str(len(sys.argv))) print ("The arguments are: " + str(sys.argv)) I run it in Windows CLI: python args.py -a -b Output: This is the name of the script: args.py Number of arguments: 3 The arguments are: ['args.py', '-a', '-b'] Looks good. Now I call it without specifying "python": args.py -a -b Now the output is totally different: This is the name of the script: C:\args.py Number of arguments: 1 The arguments are: ['C:\\args.py'] Shouldn't I be getting the same result? Why does it show a different argument count, even though python.exe is executing the program in both cases? How do I correct this?
possible better answer: http://stackoverflow.com/a/47687890
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47687904

http://stackoverflow.com/comment/82118007
type: Comment
type: QuestionComment
has text: No, I found this online and was thinking how I could switch it around. (still a noob :p)
comment on: http://stackoverflow.com/q/47580337
score: 0

http://stackoverflow.com/comment/82199273
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47620646
has text: @OmSharma Sorry, missed that. I'm pretty sure this is as fast as it will get. There is no other way to improve efficiency as far as I can see.
type: AnswerComment

http://stackoverflow.com/comment/82213617
has text: Ah ok that's a bit clearer I think.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47623241

http://stackoverflow.com/comment/82121790
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47582095
has text: Do you mean `if char == 'a'` and `elif char == 'b'`?
score: 3

linux
tags question: http://stackoverflow.com/q/47626377
tags question: http://stackoverflow.com/q/47672435
tags question: http://stackoverflow.com/q/47670568
tags question: http://stackoverflow.com/q/47643872
tags question: http://stackoverflow.com/q/47595020
tags question: http://stackoverflow.com/q/47693494
tag name: linux
tags question: http://stackoverflow.com/q/47671547
tags question: http://stackoverflow.com/q/47607115
tags question: http://stackoverflow.com/q/47638180
tags question: http://stackoverflow.com/q/47578577
tags question: http://stackoverflow.com/q/47585704
tags question: http://stackoverflow.com/q/47542260
tags question: http://stackoverflow.com/q/47585674
tags question: http://stackoverflow.com/q/47607652
tags question: http://stackoverflow.com/q/47684246
tags question: http://stackoverflow.com/q/47656211
tags question: http://stackoverflow.com/q/47618036
tags question: http://stackoverflow.com/q/47549851
tags question: http://stackoverflow.com/q/47575303
tags question: http://stackoverflow.com/q/47594274
tags question: http://stackoverflow.com/q/47606317
type: Tag
tags question: http://stackoverflow.com/q/47657965
tags question: http://stackoverflow.com/q/47600569
tags question: http://stackoverflow.com/q/47542282
tags question: http://stackoverflow.com/q/47587333
tags question: http://stackoverflow.com/q/47560798
tags question: http://stackoverflow.com/q/47640229
tags question: http://stackoverflow.com/q/47618710
tags question: http://stackoverflow.com/q/47612712

http://stackoverflow.com/comment/82600253
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47732014
type: Comment
has text: @akim "not supported" doesnt mean "doesnt work". I statically link with asan all the time when I build with GCC: https://gist.github.com/kwk/4171e37f4bcdf7705329

http://stackoverflow.com/comment/82208866
comment on: http://stackoverflow.com/q/47624760
score: 1
type: Comment
has text: This problem is ill-posed as stated. You cannot generalize to MxM for any shape of input array. How would you create 3x3 arrays out of the original example array? [[1 2 3] [4 5 6] [7 8 9]], [[9 10 11] [12 13 14] [15 16 ??]] The example only works because N=M^2. Your 60x60 array with 10x10 blocks for e.g. would not work.
type: QuestionComment

http://stackoverflow.com/q/47544256
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82046673
has answer: http://stackoverflow.com/a/47545113
type: UnansweredQuestion
has title: Can we update docker image
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82045566
tagged with: docker
tagged with: build
tagged with: dockerhub
has comment: http://stackoverflow.com/comment/82045693
has comment: http://stackoverflow.com/comment/82060823
upvote count: 0
has body: So i use docker to build image with command docker build so the image may follows this example : RUN mkdir /somefolder/someapp ADD mycode /somefolder/someapp WORKDIR "/somefolder" So as you can see , i need to add the folder mycode which contain all of my python code to the work directory. And it works all fine to the deployment. Now i need to change some code file in mycode folder. Is there anyway i can automatically update the image , not rebuilding it again using docker build
tagged with: addition

http://stackoverflow.com/a/47578022
type: Answer
has comment: http://stackoverflow.com/comment/82113975
has body: First, you haven't subscribed to your http call, and you can't set asynchronous data in synchronous manner, you need to do it like this: this.weatherstatsservice.getWeatherData().subscribe(data =&gt; this.data = data); Second, you have a typo, .json is a function, call it as such .map((res:Response) =&gt; res.json());
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82113553
answers question: http://stackoverflow.com/q/47577948
has comment: http://stackoverflow.com/comment/82113910
accepted answer of: http://stackoverflow.com/q/47577948
has comment: http://stackoverflow.com/comment/82113458
score: 1

http://stackoverflow.com/q/47670737
tagged with: keras
type: Question
has title: Custom loss in Keras
has comment: http://stackoverflow.com/comment/82301640
has answer: http://stackoverflow.com/a/47692279
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 1
has body: I'd like to implement a custom loss in Keras that takes the last affine layer as an input. This is the SGM loss described in Hariharan et al. 2017 This means that the loss function doesn't get only y_true and y_predict as parameters, but also the last affine layer. How can this be implemented in keras?

http://stackoverflow.com/a/47600652
score: 1
answers question: http://stackoverflow.com/q/47600569
type: Answer
has comment: http://stackoverflow.com/comment/99491985
has comment: http://stackoverflow.com/comment/99492244
has comment: http://stackoverflow.com/comment/99490576
downvote count: 0
upvote count: 1
has body: I guess you can renice the whole server (not aware of any way to renice a particular notebook). If the other notebooks are running on distinct notebook server process, you can do it from a subshell: --------------------------------------------------------------- !for pid in `pgrep -f jupyter`; do { renice -20 $pid; }; done --------------------------------------------------------------- 9721 (process ID) old priority 19, new priority -20 12449 (process ID) old priority 19, new priority -20 25502 (process ID) old priority 19, new priority -20 Or, if you want to do it in Python, first get the list of running servers: &gt;&gt;&gt; from notebook import notebookapp &gt;&gt;&gt; servers = list(notebookapp.list_running_servers()) &gt;&gt;&gt; servers [{'url': 'http://localhost:8888/', 'base_url': '/', 'token': '5ea29b3...7e1fba5331ae', 'secure': False, 'pid': 9721, 'hostname': 'localhost', 'password': False, 'port': 8888, 'notebook_dir': '/home/paulos/work' }] Filter the list for the ones you want if needed. pids = [_['pid'] for _ in servers if meets_condition(_)] Then call setpriority: &gt;&gt;&gt; from ctypes import cdll &gt;&gt;&gt; libc = cdll.LoadLibrary("libc.so.6") &gt;&gt;&gt; pids = [_['pid'] for _ in servers] &gt;&gt;&gt; for pid in pids: print("old priority for PID", pid, "is", libc.getpriority(0, pid)) libc.setpriority(0, pid, 20) print("new priority for PID", pid, "is", libc.getpriority(0, pid)) old priority for PID 9721 is 0 new priority for PID 9721 is 19

http://stackoverflow.com/comment/82253499
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47638297
type: AnswerComment
has text: what i have got from answers from all is if function is average(*a,b) then we need to specify average(1,2,3,b=4) and if we have average(a=5,*b) and we need to call without passing a then average(b=(2,3,4)). thanks

http://stackoverflow.com/a/47615169
answers question: http://stackoverflow.com/q/47615093
has body: I think it's saying that the decorated function is never actually assigned to anything in the namespace before the decorator is applied. When you write a function with a decorator, the function you write is passed to the decorator as an argument, and the object the decorator returns is then treated as the function. Here's a quick example: def dec(func): print('times_two' in globals()) def _inner(*args, **kwargs): print("Decorated") return func(*args, **kwargs) return _inner @dec def times_two(x): return x*2 print('times_two' in globals()) You can see this running here. The print in dec says False, because the name "times_two" isn't bound to anything before the decorator is done "decorating" the function.
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82188793
has comment: http://stackoverflow.com/comment/82188893
downvote count: 0
has comment: http://stackoverflow.com/comment/82188938
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82188960
has comment: http://stackoverflow.com/comment/82188869
has comment: http://stackoverflow.com/comment/82189062
accepted answer of: http://stackoverflow.com/q/47615093
has comment: http://stackoverflow.com/comment/82200175
type: Answer

http://stackoverflow.com/a/47564024
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82086142
upvote count: 3
downvote count: 1
has body: lines = open("file.txt", "r").read().splitlines() _sum = 0. for i, line in enumerate(lines): if not line.startswith('fit') : _sum += float(line) lines[i] = '{:0.6f}'.format(1.) if line.startswith('fit') and i &gt; 0: lines[i-1] = '{:0.6f}'.format(_sum) _sum = 0 elif i+1 &gt;= len(lines): lines[i] = '{:0.6f}'.format(_sum) print '\n'.join(lines) output fit c3 start=1455035 step=1 1.000000 1.000000 1.000000 1.000000 1.000000 12.000000 fit c2 start=5195348 step=1 1.000000 1.000000 1.000000 1.000000 5.000000 fit c4 start=6587009 step=1 1.000000 1.000000 1.000000 1.000000 50.000000
answers question: http://stackoverflow.com/q/47563539

http://stackoverflow.com/q/47585184
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47585287
has answer: http://stackoverflow.com/a/47585276
upvote count: 2
accepted answer: http://stackoverflow.com/a/47586204
has title: How to join values between sublists
has answer: http://stackoverflow.com/a/47586204
tagged with: python
has comment: http://stackoverflow.com/comment/82128093
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82128085
has answer: http://stackoverflow.com/a/47585294
has body: I have a list with sublists, for example: LA=[[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]] If the first element in each sublist is an ID, how do I join the ones with the same ID to get something like this: LR=[[1,11],[2,10],[4,8],[6,5]] I've tried using a for loop, but it's too long and not efficient.
has comment: http://stackoverflow.com/comment/82128083
downvote count: 2
possible better answer: http://stackoverflow.com/a/47585276

http://stackoverflow.com/a/47586255
type: Answer
answers question: http://stackoverflow.com/q/47586186
score: 0
upvote count: 1
downvote count: 1
has body: import pandas as pd import numpy as np import glob import datetime as dt import math principle = 50000 # Amount initially invested rate_of_return = .076 # Return on investment or the interest rate years = 26 # Assuming starting at age 40 and end at age 65 roi_list = [] for i in range(years): roi_list.append(principle) principle = principle*(math.exp(rate_of_return)) yearlist = [] for i in range(years): yearlist.append(i + 40) dates = pd.DataFrame(yearlist) df = pd.DataFrame(roi_list, index = dates) # Creates a dataframe containing the roi_list values print(df) Is this how you want it?

http://stackoverflow.com/comment/82344726
type: QuestionComment
comment on: http://stackoverflow.com/q/47692684
score: 0
has text: @tripleee cool that could work
type: Comment

http://stackoverflow.com/comment/82219931
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47590890
score: 0
has text: @dsgdfg I think I checked, but all my path seems to be correct. I followed the tuto very carefully. It seems that It doesn't find the path to _caffee, very strange...

http://stackoverflow.com/a/48548056
downvote count: 0
has comment: http://stackoverflow.com/comment/84092067
has body: I am not really familiar with how Python requests works, but after reading through some docs and finding a similar issue someone had with sending files to Zendesk (this post), you might want to try using the data (or json) parameter instead of files in your request. Also, maybe attaching a params with filename if that's applicable here as well similar to the post I linked. Another thing to do would be to put a Content-Type header on this request. i.e. requests.put( ..., headers={'Content-Type': 'application/binary'}, data=open(os.path.expanduser(charges_file_path), 'rb').read() )
type: Answer
has comment: http://stackoverflow.com/comment/89031866
answers question: http://stackoverflow.com/q/47541676
score: 2
upvote count: 2

http://stackoverflow.com/q/47636152
has comment: http://stackoverflow.com/comment/82231144
has comment: http://stackoverflow.com/comment/82230808
has answer: http://stackoverflow.com/a/47637460
linked to: http://stackoverflow.com/q/18547885
tagged with: authentication
type: Question
has body: I am extremely new to Tkinter and must use this for my programming coursework, i am looking for help to understand how to I destroy/hide the LoginWindow when the SuccessfulLogin window is opened. Bear in mind that i am new to tkinter. Thank you. import tkinter from tkinter import ttk ----------------------------------------------------------------------------------------------------------------------- class loginWindow(): def __init__(self, master): #constructor self.master = master self.master.title("Main Menu") #window title self.master.geometry("400x400") #window size self.master.configure(background = "#fff1d0") #window colour, hexadecimal codes #self.photo = PhotoImage(file = "filename.png") #sets up image #self.photoLabel = Label(self.master, image = self.photo, bg = "red") #puts image on label #self.photoLabel.place(x=350 y=600) #places onto the screen with specified coordinates self.enterLabel = tkinter.Label(self.master, text = "Launcher", font = ("Helvetica", 16), bg = "#fff1d0") self.enterLabel.pack(pady = 10) self.emptySpace = tkinter.Label(self.master, text = " ", bg = "#fff1d0") self.emptySpace.pack(pady = 10) self.username = tkinter.Label(self.master, text = "Username:", bg = "#fff1d0") #Label widget and properties self.username.pack() self.enterUser = tkinter.ttk.Entry(self.master, width = 40) #Creates text entry widget self.enterUser.pack() self.password = tkinter.Label(self.master, text = "Password:", bg = "#fff1d0") #Label widget and properties self.password.pack() self.enterPass = tkinter.ttk.Entry(self.master, width = 40, show = "*") #Creates text entry widget self.enterPass.pack() self.loginButton = tkinter.ttk.Button(self.master, width = 40, text = "Login", command = self.loginAccess) self.loginButton.pack(pady = 10) def loginAccess(self): username = "Aaron" #Needs to become a dictionary or database or something with all usernames and passwords password = "Password" global userUsername userUsername = self.enterUser.get() userPassword = self.en…
tagged with: tkinter
type: UnansweredQuestion
tagged with: window
answer count: 1
tagged with: ttk
tagged with: python
has comment: http://stackoverflow.com/comment/82230329
score: 0
has title: Tkinter - How to close one window whilst opening another window in Tkinter - Python 3

http://stackoverflow.com/q/47689082
type: Question
has body: I put together a simple script to encode movies, now while the script works just fine I am having difficulties on changing the window title on script start instead on when its terminated. since is kind of useless to mark each window after it finished. can I use subprocess to perform such task? so change the title while the script runs? I am using this in a bash script to change the title: PS1="\e]2;$1\a\[$1 \W]\$"
tagged with: python
type: UnansweredQuestion
answer count: 1
has title: change window title with python on script start
tagged with: python-2.7
tagged with: subprocess
score: 0
has answer: http://stackoverflow.com/a/47690207

http://stackoverflow.com/q/47659966
has comment: http://stackoverflow.com/comment/82284691
has comment: http://stackoverflow.com/comment/82284729
has body: I did not write this code, nor do I really work with Python, so please bear with me. The code below is supposed to run an update on one of our databases &amp; create a few new files. When I try to run it, however, I get the error above. I think it works up to a certain point: import arcpy import os import csv import pandas as pd import xlwt import glob ##set workspaces os.chdir("//dotatufs04/crm/Public/temp/DDahms/Python/Update_MRS") In_shp = "DraftHistoricProjectFootprints.gdb/DraftHistoricProjectFootprints" ##delete columns on Production_dot_project os.system(r"\\dotatufs04\crm\Public\temp\DDahms\Python\Update_MRS\Scripts\run_macro_delete_columns.vbs") ##make joined shapefile and update status try: # Set environment settings arcpy.env.workspace = "//dotatufs04/crm/Public/temp/DDahms/Python/Update_MRS" arcpy.env.qualifiedFieldNames = False # Set local variables layerName = "shapefile2" joinTable = "PRODUCTION_DOTPF_PROJECT.xls/Sheet3$" layerName2 = "tableview" joinField1 = "AKSAS_Num_Txt" joinField2 = "AKSAS_NUMBER" join_tview = "test_tview" output_shp = "DraftHistoricProjectFootprints.gdb/joined" # Create a feature layer from the vegtype featureclass arcpy.MakeFeatureLayer_management(In_shp, layerName) # Make Table view from .xls arcpy.MakeTableView_management(joinTable, join_tview) # Join the feature layer to a table arcpy.AddJoin_management(layerName, joinField1, join_tview, joinField2) arcpy.CopyFeatures_management(layerName, output_shp) except Exception as err: print(err.args[0]) #add "update" field lstFields = arcpy.ListFields(output_shp) x = False for field in lstFields: if field.name == "update": x = True if x &lt;&gt; "True": arcpy.AddField_management(output_shp, "updated", "STRING") #calculate field infield = "updated" expression = 'myfunct(!AKSAS_Num_Txt!,!AKSAS_NUMBER!)' codeblock = '''def myfunct(val1,val2): if (val1 &lt;&gt; val2 or val1 == 'N/A' or val1 == '' or val2 == '' or val2 == 'N/A' or val1== None or val2 == None): return "Not Updated" else: r…
type: Question
has title: Error: UNC paths are not supported. Default to Windows Directory
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0

http://stackoverflow.com/q/47569284
score: 1
tagged with: function
answer count: 1
downvote count: 0
upvote count: 1
has title: Global DataFrame not updated python
tagged with: global-variables
accepted answer: http://stackoverflow.com/a/47569606
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82096205
tagged with: dataframe
tagged with: python
has body: I have this code: latitude = pd.DataFrame() longitude = pd.DataFrame() datasets = [] datasets.append(latitude) datasets.append(longitude) def fun(key, job): global latitude global longitude if(key == 'LAT'): latitude = job.copy() elif(key == 'LON'): longitude = job.copy() for d in datasets: print(d.shape) Following this: Why does assigning to my global variables not work in Python? I have used the global keyword to ensure that the variables are correctly referenced. However, the values are not updated. Any advice? I have already verified that the if statements are correct as I am able to print something in them. OUTPUT: (0, 0) (0, 0) Moreover, I am using spyder and I can see that the list contains empty dataframe and also the global variable are empty.
linked to: http://stackoverflow.com/q/929777
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47569606
has comment: http://stackoverflow.com/comment/82096337
tagged with: pandas

http://stackoverflow.com/q/47673571
tagged with: flickr
favorite count: 0
type: Question
has body: I have tried to extract public images using flickr API and python. my snippet is as follows. import flickrapi import json api_key="xxxxxxxxxxxxxxx" api_secret="xxxxxxxxxxxx" flickr = flickrapi.FlickrAPI(api_key,api_secret,format='parsed-json') photos = flickr.photos.search(text="whale", has_geo=1, per_page=500, content_type=1, extras='geo, date_taken', place_id="Gdm6XV1TUb52hMbKtA") this has resulted total 455 photos over two pages. 1st page contains only 250 and rest in the 2nd page. I don't know why it can't be put into single page (455&lt;500). As per flickr documentation maximum photos that can be placed on one page is 500. I have tried this in flickr search explorer and it showed all the results within one page. Any help is appreciated.
type: UnansweredQuestion
has title: Flickr api search, can't get maximum number of results (=500) per page
tagged with: python
upvote count: 2
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/82317527
score: 1
type: Comment
type: QuestionComment
has text: I've being using save and load models since I lost couple hours of work due to a power outage. Saving the last epoch for a model and resuming to it is like gold to me.
comment on: http://stackoverflow.com/q/47676466

http://stackoverflow.com/comment/82068851
type: Comment
type: QuestionComment
has text: When you say "for some reason I can not access the SprintBacklogID from the Select command", do you mean you get back zero records from the `SELECT`? Is there an error? What is the behavior?
score: 0
comment on: http://stackoverflow.com/q/47555711

http://stackoverflow.com/q/47623155
tagged with: django-rest-framework
score: 0
tagged with: oop
has comment: http://stackoverflow.com/comment/82215660
type: Question
has title: Django REST Framework: AttributeError: 'PhotoView' object has no attribute 'encoding'
answer count: 0
has comment: http://stackoverflow.com/comment/82280907
type: UnansweredQuestion
has body: I have this code: class UploadedPhotoView(GenericViewSet, ListModelMixin): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (IsAuthenticated, ) def get_queryset(self): return self.queryset.filter(owner=self.request.user) class PhotoView(GenericViewSet, CreateModelMixin, ListModelMixin): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (IsAuthenticated, ) uploaded_view = UploadedPhotoView.as_view({'get': 'list'}) def perform_create(self, serializer): try: serializer.save(owner=self.request.user) except IntegrityError: raise SuspiciousOperation @list_route(methods=('GET', )) def uploaded(self, request, *args, **kwargs): return self.uploaded_view( request, *args, **kwargs ) After running the tests I got next: File "/Users/denny/project/picme/api2/venv/lib/python3.6/site-packages/rest_framework/views.py", line 376, in initialize_request parser_context=parser_context File "/Users/denny/project/picme/api2/venv/lib/python3.6/site-packages/rest_framework/request.py", line 151, in __init__ self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET AttributeError: 'PhotoView' object has no attribute 'encoding' So I find it like bug, but I think the problem is in the magic of rest framework. If I rewrite the function uploaded like below then it works. @list_route(methods=('GET', )) def uploaded(self, request, *args, **kwargs): return UploadedPhotoView.as_view({'get': 'list'})( request, *args, **kwargs )
tagged with: django
tagged with: python

http://stackoverflow.com/q/47577783
has answer: http://stackoverflow.com/a/47580269
tagged with: numpy
tagged with: structured-array
accepted answer: http://stackoverflow.com/a/47580269
has comment: http://stackoverflow.com/comment/82115190
has title: How to write to single field in structured array without getting warning
has comment: http://stackoverflow.com/comment/82114158
tagged with: python
has body: I am trying to normalize all data contained in different fields of my structured array if the field contains floats. However, even though I am looping through each field one-by-one I am receiving a warning. for idt, dt in enumerate(data.dtype.names): if "float32" in data.dtype[idt].name: stds = np.std(data[dt]) means = np.mean(data[dt]) data[dt] = (data[dt] - means) / stds After executing the last line this pops up: FutureWarning: Numpy has detected that you (may be) writing to an array returned by numpy.diagonal or by selecting multiple fields in a structured array. This code will likely break in a future numpy release -- see numpy.diagonal or arrays.indexing reference docs for details. The quick fix is to make an explicit copy (e.g., do arr.diagonal().copy() or arr'f0','f1'.copy()). data[dt] = (data[dt] - means) / stds I can run it line by line in a debugger to make sure everything is as expected, e.g.: In[]: data.dtype Out[]: dtype([('a', '&lt;f4'), ('b', '&lt;f4'), ('c', '&lt;f4'), ('d', '&lt;i4')]) In[]: dt Out[]: 'a' In[]: data[dt].shape Out[]: (2000, 8) Following the suggestion in the warning message, copying the array works: data2 = data.copy() for idt, dt in enumerate(data2.dtype.names): if "float32" in data2.dtype[idt].name: stds = np.std(data2[dt]) means = np.mean(data2[dt]) data2[dt] = (data2[dt] - means) / stds data = data2 What would be a more elegant way to get rid of the warning? And what did the copy change in this case?
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82113715
type: Question

http://stackoverflow.com/a/47628409
type: Answer
answers question: http://stackoverflow.com/q/47628325
score: 1
upvote count: 1
has body: You could use the map function: df['DWY'] = list(map(lambda x: dt.strptime(x,'%w-%U-%Y'), df['DWY'])) I personally like the way list comprehension work better: df['DWY'] = [dt.strptime(entry, '%w-%U-%Y') for entry in df['DWY']]
downvote count: 0

http://stackoverflow.com/comment/82311369
has text: Ok I see. Here's how I managed to do it: `images_array = da.concatenate([da.from_delayed(delayed(item[0]), shape=(nr_boxes_per_img, 200, 200, 3), dtype=np.uint8) for item in splitted_imgs_bag], axis=0)`. As I find it way too complex and still based on a list comprehension loop I'll select @r-zu question as the best one. Thanks a lot for your help.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47554003
type: AnswerComment

http://stackoverflow.com/comment/82070664
has text: You're trying to install it with python 3 somehow. You can see that theres a line that references `File "/usr/lib/python3.4/importlib/__init__.py"`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47556635
score: 0

http://stackoverflow.com/comment/124969854
type: AnswerComment
comment on: http://stackoverflow.com/a/65745699
has text: This worked for me. I am running Andronix modded Debian
type: Comment
score: 0

http://stackoverflow.com/a/47645661
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47645562
upvote count: 2
has body: You need to check is the substring is present in any of the elements of the array: a = [['4', 'red crayon'], ['2', 'purple people eater'], ['6', 'red hammer'], ['12', 'green screwdriver']] [True if any(['red' in elt for elt in sub]) else False for sub in a] output: [True, False, True, False]
downvote count: 0

http://stackoverflow.com/comment/82455366
has text: @erocoar Does `numpy` has something to pandas' `describe()` function?
type: Comment
comment on: http://stackoverflow.com/q/47658342
type: QuestionComment
score: 0

http://stackoverflow.com/q/47573623
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47573666
answer count: 1
has title: How to remove set of characters when a string comprise of "\" and Special characters in python
type: Question
has body: a = "\Virtual Disks\DG2_ASM04\ACTIVE" From the above string I would like to get the part "DG2_ASM04" alone. I cannot split or strip as it has the special characters "\", "\D" and "\A" in it. Have tried the below and can't get the desired output. a.lstrip("\Virtual Disks\\").rstrip("\ACTIVE") the output I have got is: 'G2_ASM04' instead of "DG2_ASM04"
has comment: http://stackoverflow.com/comment/82104024

http://stackoverflow.com/comment/82060222
has text: Works beautifully for the cases I've tested so far thanks.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47550953

http://stackoverflow.com/q/47686971
answer count: 1
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
has title: Proper way to share temporary data between two users
has body: Here is my case in django,i need to create a match between two users, users take turn, after one of them has finished, i need to send user1 score to user2 and vise versa. How can i create a match between two players? How do i store their data(scores) in a way that can be accessed for both users. Here is what i've tried : user1 sends GET request to get a user2 as a opponent by getting user2 id (i can say i made a match there), then after user1 finished he make another GET request with his id and score to django. and here is where i stuck : I don't know how to send user1 score to user2. I don't know how to store the data so both users can access each other score. I'm quite new to django, so i did all that based on my basic knowledge of the framework, please correct me if i'm wrong and possibly suggest a better approach.
has comment: http://stackoverflow.com/comment/82341877
has comment: http://stackoverflow.com/comment/82335173
tagged with: algorithm
has answer: http://stackoverflow.com/a/47688189
accepted answer: http://stackoverflow.com/a/47688189
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82272569
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47650360
has text: Thank you for your help, the code works the only issue I encountered is that I get the code in this order :
score: 0

http://stackoverflow.com/a/47654314
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47653321
upvote count: 2
has body: One way to do it would be using pandas.DataFrame.apply() and pandas.Series.map() like this: df.apply(lambda ds: ds.map(lambda x: x if x != None else (None, None)))
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47653321

http://stackoverflow.com/q/47664945
has answer: http://stackoverflow.com/a/47665267
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/60609791
has answer: http://stackoverflow.com/a/60609791
has title: Django API list with pagination - Page is not JSON serializable
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47665267
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
tagged with: pagination
favorite count: 0
has body: I am trying to create a Django API for a list with pagination but have this error TypeError: Object of type 'Page' is not JSON serializable The following is my API code: @api_view(['POST']) def employee_get_list_by_page(request): # ----- YAML below for Swagger ----- """ description: employee_get_list_by_page parameters: - name: token type: string required: true location: form - name: page type: string required: true location: form - name: page_limit type: string required: true location: form """ token = request.POST['token'] try: auth_employee = AuthEmployeeSessionToken.objects.get(token=token) except AuthEmployeeSessionToken.DoesNotExist: return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE) employee_list = Employee.objects.filter(company = auth_employee.employee.company.id) page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(employees,status=status.HTTP_200_OK) &lt;-- passing employees probably cause this error that employees as Page is not JSON serializable. This is my model https://gist.github.com/axilaris/89b2ac6a7762f428ad715f4916f43967. as_dict notice I have this .as_dict() to create my json for response. I use it for single request but for list Im not sure how it is done. How do an API query for this list with pagination support ? Side issue which I want the JSON to list just the fields that I want.
type: Question
tagged with: serialization
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/82287941
type: QuestionComment
comment on: http://stackoverflow.com/q/47664319
has text: You probably simply want an optional parameter, e.g. `def __init__(self,left,right=None):` then `self.right = right if right is not None else left`
score: 1
type: Comment

http://stackoverflow.com/comment/82057530
score: 1
has text: What total data size are you talking about here?
comment on: http://stackoverflow.com/q/47549965
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47635397
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47637717
answer count: 3
tagged with: pandas
downvote count: 1
possible better answer: http://stackoverflow.com/a/47635557
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47635557
has comment: http://stackoverflow.com/comment/82228756
has body: data1 = { 'node1': [2,2,3,6], 'node2': [6,7,7,28], 'weight': [1,2,1,1], } df1 = pd.DataFrame(data1, columns = ['node1','node2','weight']) I want to rename the node1 and node 2 in the data1 according in increasing order. Nodes are 2 3 6 7 28 so they become 1 2 3 4 5 respectively. So the dataframe becomes- data1 = { 'node1': [1,1,2,3], 'node2': [3,4,4,5], 'weight': [1,2,1,1], } df1 = pd.DataFrame(data1, columns = ['node1','node2','weight']) The data looked like this before but now looks like this
score: 5
has comment: http://stackoverflow.com/comment/82228632
accepted answer: http://stackoverflow.com/a/47635500
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82302019
upvote count: 6
has answer: http://stackoverflow.com/a/47635500
has title: Reordering nodes in increasing order in pandas dataframe

http://stackoverflow.com/q/47652495
answer count: 2
linked to: http://stackoverflow.com/q/1612177
tagged with: cookies
downvote count: 0
tagged with: web
has comment: http://stackoverflow.com/comment/82263260
has answer: http://stackoverflow.com/a/47820625
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Browser not sending cookie in subsequent request
tagged with: sanic
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/47715663
has body: Working with a project, where using cookie for user identification. When user arrives, it calls the service (which is running in localhost) and the service sending cookie with the response header looks like below: curl 'http://127.0.0.1:8000/api/v1.0/tracking' -X OPTIONS -H 'Access-Control-Request-Method: POST' -H 'Origin: http://local.com:8080' -H 'Access-Control-Request-Headers: content-type,x-forwarded-for' --compressed The response header looks like below: HTTP/1.1 200 OK Connection: keep-alive Keep-Alive: 60 Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, x-forwarded-for Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, PATCH, GET Content-Length: 0 Content-Type: text/plain; charset=utf-8 Set-Cookie: id=random_id_123_123; expires=Wed, 06-Dec-2017 10:57:36 GMT; Domain=.local.com; Path=/ And then after a specific user action, the app is sending following API request: curl 'http://127.0.0.1:8000/api/v1.0/tracking?event=video_added&amp;user_id=123123123' -H 'Origin: http://local.com:8080' -H 'Accept: */*' -H 'Referer: http://local.com:8080/' -H 'Connection: keep-alive' --compressed The request header for the above request looks like below: GET api/v1.0/tracking?event=video_added&amp;user_id=123123123 HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Accept: */* Origin: http://local.com:8080 User-Agent: My user agent Referer: http://local.com:8080/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 I was expecting the cookie (random_id_123_123) to be received with the first request as response header would be the request header for the second request. The website is running on: http://local.com:8080 (which actually running on local machine and my vhost config pointing 127.0.0.1 local.com) and its being served by python SimpleHTTPServer. The backend service which is setting the cookie is running on port 8000 in localhost also. Seems I have missed something during the implementation. Whats that? Edit: Here i…
upvote count: 11
has comment: http://stackoverflow.com/comment/82263873

http://stackoverflow.com/comment/82115138
type: Comment
has text: Can you specify the shape of your placeholders?
type: QuestionComment
comment on: http://stackoverflow.com/q/47550498
score: 0

http://stackoverflow.com/comment/82361438
comment on: http://stackoverflow.com/a/47697551
type: Comment
has text: Let me edit the sample code here and remove the stop() method. I'm not sure why it would be needed. Didn't you just want the worker to stop the processing? In that case it'd be done simply by calling loop.quit() from the worker.
type: AnswerComment
score: 0

http://stackoverflow.com/a/47656847
has body: You should add encoding to your read_csv code: df = pd.read_csv("C:\\python_files\\data.csv", dtype={'EMP_ID': object}, encoding='utf8')
score: 0
has comment: http://stackoverflow.com/comment/82322175
has comment: http://stackoverflow.com/comment/82321895
has comment: http://stackoverflow.com/comment/82276697
answers question: http://stackoverflow.com/q/47656695
type: Answer
has comment: http://stackoverflow.com/comment/82295948
has comment: http://stackoverflow.com/comment/82272474

http://stackoverflow.com/a/47575965
answers question: http://stackoverflow.com/q/47575560
score: 3
type: Answer
upvote count: 3
downvote count: 0
has body: I don't have enough points to comment, or I would do that. Depending on your DB of choice, you could just have an auto increment column that is set at the time of adding your other columns. You also could set that column to unique and use try/except on your statement to catch the error and increment your position.

http://stackoverflow.com/comment/82307557
score: 0
has text: What do you mean by some rows don't have a value? Do you mean there is no value in the gross column for a given year, or that there are rows where both the title_year and gross columns are blank?
type: Comment
comment on: http://stackoverflow.com/a/47672528
type: AnswerComment

http://stackoverflow.com/comment/82329089
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47684652
has text: Which values of visualize_x and visualize_y correspond to each of the 7 features? You would like to see a scatter plot with 7 colors, one for each feature, right? A preliminary problem is then to get the x and y values associated with a given color
type: Comment

http://stackoverflow.com/q/47687203
has comment: http://stackoverflow.com/comment/82333930
has answer: http://stackoverflow.com/a/47687276
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82333916
type: Question
has answer: http://stackoverflow.com/a/47687384
has comment: http://stackoverflow.com/comment/82333996
has title: Python - Remove quotes and double minus using replace
has body: Given a string such as --"I like salami. "-I want to walk to the shops" How can I return the string such as I like salami. I want to walk to the shops. I can alter each individually but when I use '-"' it fails. Quotes b = '"' for char in b: solution = MyString.replace(char,"") #output --I like salami. -I want to walk to the shops Minus b = '-' for char in b: solution = MyString.replace(char,"") #output "I like salami. "I want to walk to the shops" Together MyString = '--"I like salami. "-I want to walk to the shops"' b = '"-' for char in b: print(MyString.replace(char,"")) #output "I like salami. "I want to walk to the shops"
accepted answer: http://stackoverflow.com/a/47687293
has answer: http://stackoverflow.com/a/47687556
has answer: http://stackoverflow.com/a/47687293
tagged with: python
answer count: 6
possible better answer: http://stackoverflow.com/a/47687268
has answer: http://stackoverflow.com/a/47687596
has answer: http://stackoverflow.com/a/47687268

http://stackoverflow.com/a/47566471
has body: You can use [::-1] for reverse.Slice notation is easy to reverse string s = "reverse" s = s[::-1] print(s) output esrever
score: 0
answers question: http://stackoverflow.com/q/47566434
type: Answer

http://stackoverflow.com/comment/82080428
score: 1
comment on: http://stackoverflow.com/a/47561385
type: Comment
has text: if `a % 4 < 2:` is probably even better.
type: AnswerComment

http://stackoverflow.com/q/47643804
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82320375
tagged with: odbc
has body: I am trying to populate Pandas Dataframe into empty MS Access 2016 table via pyodbc. I get the following error message when I try to insert Dataframes into Access: pyodbc.dataerror: ('22008', [ODBC Microsoft Access Driver]Datetime field overflow. Research showed that MS Access Date/Time datatypes correspond to ODBC SQL_TIMESTAMP datatypes. I tried the following to convert datetime64[ns] to SQL_TIMESTAMP: import datetime cursor.execute("INSERT sql statement...VALUES(?)", datetime.datetime(order_date)) However, I get this error: TypeError: an integer is required (got type Timestamp). What do I need to do in order to successfully populate Pandas/Numpy's datetime64[ns] values into Access tables? Do I need to convert them into SQL_TIMESTAMP and how? EDIT: I tried running Gord Thompson's solution below and I am running into this error: import datetime dt = dt64_to_datetime(dt_ns) &gt;&gt; AttributeError:'datetime' has no attribute 'utcfromtimestamp' What is the reason behind this error? (Tested on pyodbc 4.0.17, Python 3.6.2, MS Access 2016)
type: Question
has answer: http://stackoverflow.com/a/47678989
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/82324753
has comment: http://stackoverflow.com/comment/82319675
has title: How to convert Pandas DataFrame column from Pandas datetime64[ns] to Pyodbc SQL_Timestamp
linked to: http://stackoverflow.com/q/13703720
score: 0
tagged with: ms-access-2016
answer count: 1

http://stackoverflow.com/comment/82226743
comment on: http://stackoverflow.com/a/47633515
type: Comment
has text: So this means that, left un-intercepted, the call will go through and the program will exit, right?
type: AnswerComment
score: 0

http://stackoverflow.com/a/69343042
answers question: http://stackoverflow.com/q/47642747
upvote count: 0
downvote count: 1
has body: I solved the problem. The error pop up as a result of package dependencies that have been installed on your default virtual environment but not in the tox environment. Make sure that all the packages required to run tox is added in your requirements.txt including unittest and pytest
type: Answer
score: -1

http://stackoverflow.com/a/47613345
has comment: http://stackoverflow.com/comment/82185159
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47613323
has body: You can use itertools.chain: import itertools s = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370])) final_s = [list(itertools.chain.from_iterable(i)) for i in s] Output: [[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]] or using reduce in Python2: s = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370])) new_s = [reduce(lambda x, y:list(x)+list(y), i) for i in s] Output: [[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]]

http://stackoverflow.com/comment/82301490
type: AnswerComment
has text: @RujunGuan Have you got any answer ? In case of any error just ask in comment
type: Comment
comment on: http://stackoverflow.com/a/47669669
score: 0

http://stackoverflow.com/comment/82105897
score: 0
type: Comment
type: AnswerComment
has text: virtural enviroment can be any where, to run project just you have to run from that virtualenv
comment on: http://stackoverflow.com/a/47574443

http://stackoverflow.com/comment/82189028
type: Comment
has text: provide more code and shapes of the image and ndarrays. i guess reshaping the numpy array should help. a good resource for broadcasting is in [numpy documentation](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html).
score: 0
comment on: http://stackoverflow.com/q/47615309
type: QuestionComment

http://stackoverflow.com/comment/82114679
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47578774
has text: * It is important to point out that the number of rows I search the value below depends on the value "DaysToReception" has

http://stackoverflow.com/a/47631136
has body: You need stack with rename_axis for columns names and last reset_index: df = df.stack().rename_axis(('uid','iid')).reset_index(name='rat') print (df.head()) uid iid rat 0 4 1 4.332076 1 4 2 4.340775 2 4 3 4.311200 3 4 4 4.341143 4 5 1 4.000000
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47631087
answers question: http://stackoverflow.com/q/47631087
type: Answer
score: 1

http://stackoverflow.com/comment/82242926
comment on: http://stackoverflow.com/a/47621952
has text: Do you even try yourself what you're suggesting?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47632173
tagged with: python
linked to: http://stackoverflow.com/q/15667189
upvote count: 1
score: 1
has body: In C python, does id() return the memory location of the variable all the time.Also can we do anything useful with the memory location apart from printing it
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15667189
type: Question
has title: Get Memory location and access
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82040652
type: Comment
type: AnswerComment
has text: Where @Randyr says "Handle rest of request here..." one would usually redirect to the same view (so the `get` request is processed): `return redirect(reverse('url_pattern_name'))`
comment on: http://stackoverflow.com/a/47541678
score: 0

http://stackoverflow.com/a/47565597
has comment: http://stackoverflow.com/comment/82089163
accepted answer of: http://stackoverflow.com/q/47565110
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Let's try with ascending as list: df.sort_index(level=[0,1], ascending=[True,True]) A B Gain/Expsr% -10.0 2.104 1.194 -2.0 1.389 0.892 Gain/MaxDD -10.0 0.024 0.064 -2.0 0.020 0.058 and df.sort_index(level=[0,1], ascending=[True, False]) A B Gain/Expsr% -2.0 1.389 0.892 -10.0 2.104 1.194 Gain/MaxDD -2.0 0.020 0.058 -10.0 0.024 0.064
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47565110
has comment: http://stackoverflow.com/comment/82089159

http://stackoverflow.com/comment/82079638
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47560837
type: QuestionComment
has text: I corrected typo. Thanks @Jean-FrançoisFabre

http://stackoverflow.com/comment/82040263
score: 0
type: AnswerComment
has text: I have made an update in the initial post, the `U0.00` updates in every line and is not the same in every line. I apologize for the typo
comment on: http://stackoverflow.com/a/47541390
type: Comment

http://stackoverflow.com/comment/82164091
has text: Are you sure that `_norm` is present inside `rnn_cell` module? Please run `dir(rnn_cell)` to see what it contains or check source code of tensorflow inside your site-pacakges install location: `site-packages/tensorflow/contrib/rnn/python/ops/rnn_cell.py`
score: 0
comment on: http://stackoverflow.com/q/47602302
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47682407
has body: I understand that you want to insert a 3x5 matrix to an empty array. Then np.append can do that. Just specify the right axis. import numpy as np mat = np.empty((0,3,5)) mat3x5 = np.matrix('1,1,1,1,2;3,1,2,3,1;2,3,1,2,3') mat3x5 = np.expand_dims(mat3x5, 0) result = np.append(mat, mat3x5, axis=0)
type: Answer
answers question: http://stackoverflow.com/q/47682218
score: 0

http://stackoverflow.com/a/47562326
has body: You could use list comprehension: your_list = [('deployment appears', 4.0), ...] filtered = [tuple(some_number) for _, some_number in your_list]
type: Answer
answers question: http://stackoverflow.com/q/47562280
score: 0

http://stackoverflow.com/q/47576217
linked to: http://stackoverflow.com/q/9202224
has body: I'm working on a project which signs into your email account for you using python 3. I can't install getpass.getpass() and I couldn't find a good site that would have a solution. I'm trying to hide the user input on the password input so nobody could see it. Ex. username = input("Enter your username/n") password = input("Enter your password:/n") # I can't figure out how to hide the input on this line.
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82109292
duplicate of: http://stackoverflow.com/q/9202224
type: Question
tagged with: python
type: UnansweredQuestion
has title: Password input (python3)
has comment: http://stackoverflow.com/comment/82109380
has comment: http://stackoverflow.com/comment/82109381
has comment: http://stackoverflow.com/comment/82118422

http://stackoverflow.com/q/47590485
has comment: http://stackoverflow.com/comment/82138119
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: bytecode
has comment: http://stackoverflow.com/comment/82138030
upvote count: 1
tagged with: python
downvote count: 1
tagged with: optimization
has comment: http://stackoverflow.com/comment/82138034
score: 0
has title: In python, for a class variable supposed to be constant, is using literals faster than constructing it?
has body: I had big problem trying to explain it so i'll put the example. Suppose I have a big tuple of data that's supposed to act like a constant. For this project, I was making a card-deck class so to make the tuple will all the base cards, but I was wondering about it too for larger data sets and how Python (standard C implementation) handles these optimizations. I have two options: deckCards = [] for value in range(1,14): for suit in range(4): deckCards.append(Card(value,suit)) deckCards=tuple(deckCards) Or: deckCards = (Card(1,0), Card(1,1), Card(1,2),..) The seconds maintenability is disastrous, and the first loop will result in the second expression in the end with extra operations between... The critical thing I want to know is: once Python has interpreted it and converted to bitcode the deckCards tuple, will it stay as that data for the durantion of the program (or import from another module) or will it recalculate it (AKA reinstantiate it) EVERY time that i access the variable? I know that Java and C# will optimize most const or static readonly vars and convert them to a single memory allocation to avoid recalculating, but I don't know how this works in Python. Thanks for the answers in advance.
has comment: http://stackoverflow.com/comment/82142077

http://stackoverflow.com/q/47603276
tagged with: python
has answer: http://stackoverflow.com/a/47638893
has title: logits doesn't have the proper shape in vgg16 model for x-ray classification
score: 0
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/43051201
tagged with: tensorflow
type: Question
has body: I got the same error as here. I have two classes, so the rank of labels should be one -- which is correct-- and rank of logits should be two -- [bachsize, #classes]-- which is 4 here-- [? 3,3,2]. In that link mentioned using flatten() on convolutional layer(s). Which layers do you apply flatten() on? all the convolutions? or only the last one in the network -- I mean fc8 --. Here's what I have in vgg.py: with variable_scope.variable_scope(scope, 'vgg_16', [inputs]) as sc: end_points_collection = sc.original_name_scope + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with arg_scope( [layers.conv2d, layers_lib.fully_connected, layers_lib.max_pool2d], outputs_collections=end_points_collection): net = layers_lib.repeat( inputs, 2, layers.conv2d, 64, [3, 3], scope='conv1') net = layers_lib.max_pool2d(net, [2, 2], scope='pool1') net = layers_lib.repeat(net, 2, layers.conv2d, 128, [3, 3], scope='conv2') net = layers_lib.max_pool2d(net, [2, 2], scope='pool2') net = layers_lib.repeat(net, 3, layers.conv2d, 256, [3, 3], scope='conv3') net = layers_lib.max_pool2d(net, [2, 2], scope='pool3') net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv4') net = layers_lib.max_pool2d(net, [2, 2], scope='pool4') net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv5') net = layers_lib.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. net = layers.conv2d(net, 4096, [7, 7], padding='VALID', scope='fc6') net = layers_lib.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = layers.conv2d(net, 4096, [1, 1], scope='fc7') net = layers_lib.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = layers.conv2d( net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc8') # Convert end_points_collection into a end_point dict. end_points = utils.convert_collection_to_dict(end_points_collection) if spatial_squeeze: net = array_o…

http://stackoverflow.com/comment/82216344
comment on: http://stackoverflow.com/q/47629124
score: 0
has text: @VinodBhavnani -- there is nothing wrong in using `GET` here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82217589
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47629449
type: Comment
has text: @Jean-FrançoisFabre updated test cases, btw its complexity is o(n)3 we have to reduce the time complexity

http://stackoverflow.com/comment/82279233
score: 0
comment on: http://stackoverflow.com/q/47660136
type: QuestionComment
type: Comment
has text: Then you must use a UPS, or a backup battery, through a current sensor check if this happens and then use the battery or the UPS. This problem is more electrical than programming so it must be closed for me.

http://stackoverflow.com/a/47658601
has body: One way of doing it is to reverse your for loop. Instead of iterating through your keys, you can iterate through your text segments. I don't think you need to use regular expressions since you have a very specific case. import re text = "foo 123 doo 342 ghh 568 loo 243" s = re.split(r'(\d+)', text) textDict = {"2":"fg" , "3":"gh", "8":"hj"} for i in range(len(s) - 1): s[i] = s[i][:-1] + textDict[s[i][-1]] if str(s[i][-1]) in textDict else s[i] u = "".join(s) u = str(u) print u This gives the following output : &gt; foo 12gh doo 34fg ghh 56hj loo 24gh I believe this is also more efficient since instead of having two nested loops (which gives us a complexity in the order of O(n*m)), you iterate through one list, which gives us O(n).
answers question: http://stackoverflow.com/q/47658377
downvote count: 0
has comment: http://stackoverflow.com/comment/82284476
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/47664754
type: AnsweredQuestion
has title: Reduce ticks & format axis labels in Matplotlib - scaling
answer count: 2
has body: I have an array of subplots, but whenever I try to reduce the tick density or even change the format, the values seem to change. Is there a distinction here between the 'tick' and its value? How would I match the correct value to the tick if so? Here's a stand-alone plot that's right: France Here's the (EDITED) code I'm trying: import matplotlib as mpl from matplotlib.ticker import FormatStrFormatter f, axarr = plt.subplots(5,6,figsize=(30,30)) for i in range(0,6): for j in range(0,5): # there are only 26 entries in ser if (4*i+j) &lt; 26: x = pp_gdp.loc[pp_gdp.index == ser.index[4*i+j],:].round(1) y = ser.loc[ser.index == ser.index[4*i+j],:].round(1) axarr[j,i].scatter(x,y) axarr[j,i].set_title(ser.index[4*i+j]) xt = axarr[j,i].get_xticks() #axarr[j,i].set_xscale('linear') axarr[j,i].set_xticks([axarr[j,i].get_xticks()[0],int(len(axarr[j,i].get_xticks())/2), axarr[j,i].get_xticks()[-1]]) axarr[j,i].set_xticklabels([x.values.min(),sorted(x.values)[0][int(len(xt)/2)],x.values.max()]) yt = axarr[j,i].get_yticks() #axarr[j,i].set_yscale('linear') axarr[j,i].set_yticks([axarr[j,i].get_yticks()[0],int(len(axarr[j,i].get_yticks())/2), axarr[j,i].get_yticks()[-1]]) axarr[j,i].set_yticklabels([y.values.min(),sorted(y.values)[0][int(len(yt)/2)],y.values.max()]); Here's what I get if I comment out all the tick code, i.e. the default subplots: Default plot As you can see, it's far too dense to read. Here's what happens when I try nbins: axarr[j,i].locator_params(tight=True, axis='y', nbins=10) axarr[j,i].locator_params(tight=True, axis='x', nbins=5) France nbins wrong Again, the values are wrong on both axes. Using the get_xticks and set_xticks as in the big code sample sort of works, but ruins the intuition of the plot. Also the scale is all wrong because of the way it keeps the 0. Very linear plots stay linear, but the slope is exaggerated. Plots a little more complicated lose their shape altogether, as in: China now wrong The chart on the rightis much harder to understand, …
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/82311731
possible better answer: http://stackoverflow.com/a/47664946
downvote count: 0
has comment: http://stackoverflow.com/comment/82312003
accepted answer: http://stackoverflow.com/a/47686282
upvote count: 1
has comment: http://stackoverflow.com/comment/82330842
has answer: http://stackoverflow.com/a/47686282
favorite count: 0
has comment: http://stackoverflow.com/comment/82308292
type: Question
has comment: http://stackoverflow.com/comment/82331172
has comment: http://stackoverflow.com/comment/82311784
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/47664946
has comment: http://stackoverflow.com/comment/82312238
tagged with: plot
linked to: http://stackoverflow.com/q/6682784

http://stackoverflow.com/q/47647833
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47648273
score: 0
answer count: 1
tagged with: selenium
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I've written some code in python in combination with selenium to select few options from three different dropdown boxes to reach the destination page. First off the browser is needed to click on a link in the first page to reach the page where dropdown item options are located. My script can click on the first page link but when it comes to choose the item from dropdown options then it fails to do that. Site address URL The link titled Search by Selecting a Plan or Network available in the first page (when clicked) leads to the second page where dropdown options can be found. Options I wanna choose from three different dropdowns (from second page): Medical Arizona All plans/networks Here is what I've tried so far: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() wait = WebDriverWait(driver, 20) driver.get("use_above_link") wait.until(EC.presence_of_element_located((By.ID, "lnkGuestPlanSearch"))).click() Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanC')).select_by_visible_text('Medical') Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlState')).select_by_visible_text('Arizona') Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanN')).select_by_visible_text('All plans/networks') driver.quit() Elements within which dropdown options are embedded: &lt;/select&gt;&lt;div class="chosen-container chosen-container-single pf-field-320-30" style="width: 0px;" title="" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanC_chosen"&gt;&lt;a class="chosen-single"&gt;&lt;span tabindex="0"&gt;Enter or select type of care&lt;/span&gt;&lt;div&gt;&lt;b&gt;&lt;/b&gt;&lt;/div&gt;&lt…
has answer: http://stackoverflow.com/a/47648273
has comment: http://stackoverflow.com/comment/82254597
tagged with: web-scraping
has title: Trouble choosing names from dropdown options
tagged with: python

http://stackoverflow.com/comment/82347384
has text: can you update your question with how you would like the output to be in this case?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47657863

http://stackoverflow.com/q/47692182
type: Question
has answer: http://stackoverflow.com/a/47692412
type: AnsweredQuestion
score: 3
answer count: 5
has title: Sum values grouped by key in list of dict
tagged with: python
possible better answer: http://stackoverflow.com/a/47692398
has answer: http://stackoverflow.com/a/47692634
accepted answer: http://stackoverflow.com/a/47692475
has answer: http://stackoverflow.com/a/47692615
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47692398
has answer: http://stackoverflow.com/a/47692475
has body: I have a list of dicts and now I am trying to find the total jobs for each remote identifier. In this case I am expecting for the id 64 -&gt; 11 jobs and 68 -&gt; 0 jobs [{ 'jobs': { 'count': 4 }, 'remote_identifier': { 'id': '64' } }, { 'jobs': { 'count': 0 }, 'remote_identifier': { 'id': '68' } }, { 'jobs': { 'count': 7 }, 'remote_identifier': { 'id': '64' } }] I already tried something like this, but I don't know how to adapt it to my needs, since that only counts the number of occurrences. from collections import Counter print Counter(item['remote_identifier']['id'] for item in items )
upvote count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82174983
has text: If you're using Python 3 you can use [*extended tuple unpacking*](https://www.python.org/dev/peps/pep-3132/): Replace `for first, second in d` by `for first, second, *rest in d`. Then `rest` will be a list containing all remaining entries in the tuple (empty if the tuple has length 2).
comment on: http://stackoverflow.com/a/47608106
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82351078
comment on: http://stackoverflow.com/a/47695761
has text: This works for this case, but is there a possibility to implement clicking on the element that as an a element with "title" attribute next to it ? As shown below this doesn't work when there are multiple anchors. [screenshot](http://prntscr.com/hkbc2q)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47577060
tagged with: python
has body: So I have a custom layer, that does not have any weights. In a fist step, I tried to implement the functions manipulating the input tensors in Kers. But I did not succeed because of many reasons. My second approach was to implement the functions with numpy operations, since the custom layer I am implementing does not have any weights, from my understanding, I would say, that I could use numpy operarations, as I don't need backpropagation, since there are no weights, right? And then, I would just convert the output of my layer to a tensor with: Keras.backend.variable(value = output) So the main idea is to implement a custom layer, that takes tensors, convert them to numpy arrays, operate on them with numpy operations, then convert the output to a tensor. The problem is that I seem not to be able to use .eval() in order to convert the input tensors of my layer into numpy arrays, so that they could be manipulated with numpy operations. Can anybody tell, how I can get around this problem ?
tagged with: numpy
type: AnsweredQuestion
tagged with: tensor
score: 1
accepted answer: http://stackoverflow.com/a/47581730
has comment: http://stackoverflow.com/comment/82117243
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47581730
upvote count: 1
tagged with: keras
favorite count: 0
has title: How to Switch from Keras Tensortype to numpy array for a custom layer?
type: Question
tagged with: theano

http://stackoverflow.com/comment/106261198
comment on: http://stackoverflow.com/a/58068662
type: Comment
has text: Sure. If you visit this page : [sampleIframe](https://www.dyn-web.com/tutorials/iframes/basics/demo.php) , you will see iframe where you will also see scroll bar. I tried lot of codes but still no code is able to take full screenshot of iframe by scrolling it. All codes take screenshot like this : [screenshot](https://i.sstatic.net/IkodE.png)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82314261
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47677298
has text: @M.irfan, all answers posted here provide you your desired result set (starting from index `0`) ;)
type: Comment

http://stackoverflow.com/a/47672747
accepted answer of: http://stackoverflow.com/q/47672679
type: AcceptedAnswer
downvote count: 0
has body: At function definition, the value passed to optional arguments is evaluated, however, in that instant, h is not defined. You can instead use a sentinel value as a placeholder for the optional argument: class Game(object): def __init__(self,h,w=None): if w is None: w = h If you're on Python 2, remember to subclass object.
has comment: http://stackoverflow.com/comment/82304457
type: Answer
answers question: http://stackoverflow.com/q/47672679
score: 3
upvote count: 3

http://stackoverflow.com/a/47692696
accepted answer of: http://stackoverflow.com/q/47692556
type: Answer
has body: Yes when t1.start() happens it executes the method which is specified in target(i.e run). Once its completed it exits automatically. You can check this by checking the running process eg in linux use below command, "ps -aux |grep python" or "ps -aux |grep "program_name.py" when your target is running count will be more. To wait until a process has completed its work and exited, use the join() method. But in your case its not required more example are here : https://pymotw.com/2/multiprocessing/basics.html
answers question: http://stackoverflow.com/q/47692556
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/82306169
score: 0
has text: no init is fine since BoxLayout has an init.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47670361

http://stackoverflow.com/comment/82215576
has text: with 25.0 i resolved, thanks!
score: 0
comment on: http://stackoverflow.com/a/47628805
type: Comment
type: AnswerComment

scons
tag name: scons
type: Tag
tags question: http://stackoverflow.com/q/47675177

http://stackoverflow.com/a/47682967
has body: Just append them as a list/tuple to your original list: items = [] for i in response['Contents']: # assuming response['Contents'] is a list items.append([ 's3://' + response['Name'] + '/' + i['Key'], i['Key'].rsplit('/', 1)[-1], i['Size'] ])
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47682920

http://stackoverflow.com/a/47721134
upvote count: 3
has body: I have found a solution to my problem. It seems like after installing High Sierra some header files in the /usr/local/include are messed up, and causing the brew installation to malfunction. Uninstall and reinstalling brew solved the problem. rm -rf /usr/local/Cellar /usr/local/.git &amp;&amp; brew cleanup ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47635408
accepted answer of: http://stackoverflow.com/q/47635408
score: 3
type: Answer

http://stackoverflow.com/a/47613833
has comment: http://stackoverflow.com/comment/82203693
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/47611399
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47611399
upvote count: 8
has body: For arguments why setting the width of a text box to a defined width is hard see this question which is about setting the title text box width. In principle the answer over there could be used here as well - making this rather complicated. A relatively easy solution would be to specify the x-position of the text in data coordinates and its y position in axes coordinates. This allows to create a rectangle as background for the text with the same coordinates such that it looks like a bounding box of the text. import matplotlib.pyplot as plt import numpy as np ind = [1,2,4,5] data = [4,5,6,4] perc = np.array(data)/float(np.array(data).sum()) width=0.7 pad = 3 # points fig, ax = plt.subplots() bar = ax.bar(ind, data, width=width) fig.canvas.draw() for label, x in zip(perc, ind): text = ax.text( x, 1.00, '{:4.0%}'.format(label), ha="center", va="center" , transform=ax.get_xaxis_transform(), zorder=4) bb= ax.get_window_extent() h = bb.height/fig.dpi height = ((text.get_size()+2*pad)/72.)/h rect = plt.Rectangle((x-width/2.,1.00-height/2.), width=width, height=height, transform=ax.get_xaxis_transform(), zorder=3, fill=True, facecolor="lightblue", clip_on=False) ax.add_patch(rect) plt.show()

http://stackoverflow.com/comment/82323628
type: QuestionComment
has text: I have a feeling you're going to need to use [selenium](http://selenium-python.readthedocs.io/)
comment on: http://stackoverflow.com/q/47682159
score: 0
type: Comment

http://stackoverflow.com/comment/82145000
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47591408
has text: @JytinJalmon Sure, but first you need to have access to the original file for reading, is it the case?
score: 0

music21
type: Tag
tags question: http://stackoverflow.com/q/47556847
tag name: music21

http://stackoverflow.com/comment/82258097
comment on: http://stackoverflow.com/q/47649830
has text: use {{ }} try this `connStr = 'DRIVER={{ODBC Driver 13 for SQL Server}};SERVER={s};PORT=1443;DATABASE={d};UID={u};PWD={p}'.format(s = server, d = database, u = username, p = password)`
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/47575302
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82107798
has body: Add your app name or your custom domain in ALLOWED_HOSTS in settings.py ALLOWED_HOSTS = ['myapp.herokuapp.com'] and then run heroku run python manage.py migrate
has comment: http://stackoverflow.com/comment/106249271
answers question: http://stackoverflow.com/q/47574730
type: Answer
has comment: http://stackoverflow.com/comment/82107885
has comment: http://stackoverflow.com/comment/82107675
has comment: http://stackoverflow.com/comment/82107745
downvote count: 0

http://stackoverflow.com/comment/82226379
comment on: http://stackoverflow.com/q/47633374
type: Comment
has text: Both the negated or the inverse mean squared error should work. If the maximum distance is bounded you can use the negated value, if it is not the inverse would have a low bound of zero anyway.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82181303
type: Comment
score: 0
has text: Does it run locally, i.e. without multiprocessing? Otherwise, does it run for much smaller inputs - say 100 records? I suspect the problem is that your inputs are too big to pickle, or perhaps unpickle. As an aside - you might want to use multiprocessing.Pool instead.
type: QuestionComment
comment on: http://stackoverflow.com/q/47611442

http://stackoverflow.com/q/47585686
has title: Python os.makedirs and shutil.copyfile - Error 13 - Permission denied
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47585811
score: 0
has answer: http://stackoverflow.com/a/47585811
tagged with: windows
has comment: http://stackoverflow.com/comment/82129073
tagged with: python
tagged with: shutil
tagged with: permissions
has comment: http://stackoverflow.com/comment/82129320
type: Question
tagged with: file-copying
answer count: 1
has body: In my code, I create a directory like so: try: os.makedirs(playlist_name) except OSError as e: if e.errno != errno.EEXIST: raise Which creates a directory in the place where I run my python script. Then I wish to copy three files from the original directory where the folder is located into the newly created directory, like so # Copy FFMPEG files into that folder so youtube dl can download the videos as audio tracks # Tried using os.getcwd() to get full path, same error shutil.copyfile(os.getcwd() + '\\ffmpeg.exe', os.getcwd() + "\\" + playlist_name) shutil.copyfile('ffplay.exe', "/" + playlist_name + "/") shutil.copyfile('ffprobe.exe', "/" + playlist_name + "/") However, trying to copy those files throws this error: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\ME\\Documents\\python\\DIRECTORY\\PLAYLIST_NAME_HERE' I have tried various shutil copy methods with the same error. EDIT: This is running on windows

http://stackoverflow.com/q/47593493
has comment: http://stackoverflow.com/comment/82144638
tagged with: keras
has comment: http://stackoverflow.com/comment/82144409
has answer: http://stackoverflow.com/a/47593736
type: Question
possible better answer: http://stackoverflow.com/a/47593736
has comment: http://stackoverflow.com/comment/82144439
has body: following is my code (x_train, y_train), (x_test, y_test) = cifar10.load_data() # Convert and pre-processing y_train = np_utils.to_categorical(y_train, num_classes) y_test = np_utils.to_categorical(y_test, num_classes) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 model = Sequential() model.add(Dense(10, input_shape=x_train.shape[1:], activation='relu')) model.add(Dense(10, input_shape=x_train.shape[1:],activation='softmax')) sgd = SGD(lr = 0.001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer='nadam',metrics=['accuracy']) model.summary() earlyStopping=EarlyStopping(monitor='val_loss', patience=0, verbose=2, mode='auto') checkpoint = ModelCheckpoint("filepath", monitor='val_acc', verbose=1, save_best_only=True, mode='max') history = History() print("Training...") model.fit(x_train, y_train, batch_size=32, nb_epoch=1000, verbose=2,validation_split=0.2,callbacks=[history,earlyStopping,checkpoint]) But it gives an error. Here is the traceback ValueError Traceback (most recent call last) &lt;ipython-input-18-9ea5b53744c6&gt; in &lt;module&gt;() 1 model = Sequential() ----&gt; 2 model.add(Dense(10, input_shape=x_train.shape[1:], activation='relu')) 3 model.add(Dense(10, input_shape=x_train.shape[1:],activation='softmax')) 4 5 /home/fatima/anaconda2/lib/python2.7/site-packages/keras/models.pyc in add(self, layer) 440 # and create the node connecting the current layer 441 # to the input layer we just created. --&gt; 442 layer(x) 443 444 if len(layer.inbound_nodes) != 1: /home/fatima/anaconda2/lib/python2.7/site-packages/keras/engine/topology.pyc in __call__(self, inputs, **kwargs) 601 602 # Actually call the layer, collecting output(s), mask(s), and shape(s). --&gt; 603 output = self.call(inputs, **kwargs) 604 output_mask = self.compute_mask(inputs, previous_mask) 605 /home/fatima/anaconda2/lib/python2.7/site-packages/keras/layers/core.pyc in call(self, inputs) 843 outpu…
has comment: http://stackoverflow.com/comment/82144564
has comment: http://stackoverflow.com/comment/82144526
has answer: http://stackoverflow.com/a/47594135
tagged with: python
accepted answer: http://stackoverflow.com/a/47594135
type: AnsweredQuestion
score: 0
answer count: 2
has title: How to reshape input for training on CIFAR dataset?

http://stackoverflow.com/a/47618794
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47617930
has comment: http://stackoverflow.com/comment/82279055
has body: You're very probably using the setting data_format='channels_first' in the pooling layer. I see you added 'channels_last' to the convolutional layer, but you probably didn't add it to the pooling layer. If you want to change the default setting for keras, find the &lt;user&gt;/.keras/keras.json file and change it there.
type: Answer
accepted answer of: http://stackoverflow.com/q/47617930

http://stackoverflow.com/comment/82313959
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47663599
has text: @MarkRansom - `Time` is used instead of `datetime` because `datetime` is missing many astronomy-critical features. E.g., dynamic range of a nanosecond over Gigayear spans, conversion to/from standard astronomy forms like JD or MJD, an understanding of the UT1 to UTC conversion, numpy support, etc.

http://stackoverflow.com/comment/82226606
comment on: http://stackoverflow.com/a/47632586
has text: Thanks, but the number of each variable would be 500 not just 7. I would like to load the variable from my csv file.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47548242
has title: Can I close the CMD window that opened with subprocess.Popen in Python?
has answer: http://stackoverflow.com/a/47553564
possible better answer: http://stackoverflow.com/a/47553564
has comment: http://stackoverflow.com/comment/82053214
type: Question
has comment: http://stackoverflow.com/comment/82055132
has answer: http://stackoverflow.com/a/47549778
accepted answer: http://stackoverflow.com/a/47549778
answer count: 2
tagged with: subprocess
has comment: http://stackoverflow.com/comment/82053166
score: 6
has comment: http://stackoverflow.com/comment/82053070
upvote count: 6
tagged with: python
favorite count: 0
type: AnsweredQuestion
downvote count: 0
has body: I have a program that need to run small tasks in new CMDs. For example: def main() some code ... proc = subprocess.Popen("start.bat") some code... proc.kill() subprocess,Popen opens a new cmd window and runs "start.bat" in it. proc.kill() kills the process but doesn't close the cmd window. Is there a way to close this cmd window? I thought about naming the opened cmd window so i can kill it with the command: /taskkill /f /im cmdName.exe Is it possible ?if no, What do you suggest ? Edit, Added Minimal, Complete, and Verifiable example: a.py: import subprocess,time proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE) time.sleep(5) proc.kill() b.py while True: print("IN") c.bat python b.py
has comment: http://stackoverflow.com/comment/82053170
has comment: http://stackoverflow.com/comment/82053853
tagged with: cmd

json-api
tags question: http://stackoverflow.com/q/47623021
type: Tag
tag name: json-api

http://stackoverflow.com/a/47551635
downvote count: 0
has comment: http://stackoverflow.com/comment/82061726
has comment: http://stackoverflow.com/comment/82060324
has comment: http://stackoverflow.com/comment/82060199
type: Answer
has comment: http://stackoverflow.com/comment/82060812
score: 4
has body: I use regexp to do this. &gt;&gt;&gt; import re &gt;&gt;&gt; line = 'hi. hello! how are you? fine! me too, haha. haha.' &gt;&gt;&gt; re.sub(r"(?:^|(?:[.!?]\s+))(.)",lambda m: m.group(0).upper(), line) 'Hi. Hello! How are you? Fine! Me too, haha. Haha.'
upvote count: 4
answers question: http://stackoverflow.com/q/47551275

javascript
tags question: http://stackoverflow.com/q/47639238
tags question: http://stackoverflow.com/q/47614874
tags question: http://stackoverflow.com/q/47561251
tags question: http://stackoverflow.com/q/47670349
tags question: http://stackoverflow.com/q/47665289
tags question: http://stackoverflow.com/q/47671284
tags question: http://stackoverflow.com/q/47570493
tags question: http://stackoverflow.com/q/47627927
tags question: http://stackoverflow.com/q/47666302
tags question: http://stackoverflow.com/q/47591401
tags question: http://stackoverflow.com/q/47606765
tags question: http://stackoverflow.com/q/47605073
tags question: http://stackoverflow.com/q/47588196
tags question: http://stackoverflow.com/q/47548638
tags question: http://stackoverflow.com/q/47684885
tags question: http://stackoverflow.com/q/47648276
tags question: http://stackoverflow.com/q/47620498
tags question: http://stackoverflow.com/q/47619568
tags question: http://stackoverflow.com/q/47622102
tag name: javascript
tags question: http://stackoverflow.com/q/47549699
tags question: http://stackoverflow.com/q/47676919
tags question: http://stackoverflow.com/q/47607892
tags question: http://stackoverflow.com/q/47602356
tags question: http://stackoverflow.com/q/47647938
tags question: http://stackoverflow.com/q/47644570
tags question: http://stackoverflow.com/q/47597560
tags question: http://stackoverflow.com/q/47567325
tags question: http://stackoverflow.com/q/47685090
tags question: http://stackoverflow.com/q/47601879
tags question: http://stackoverflow.com/q/47647162
tags question: http://stackoverflow.com/q/47662604
tags question: http://stackoverflow.com/q/47659675
tags question: http://stackoverflow.com/q/47610505
tags question: http://stackoverflow.com/q/47591223
tags question: http://stackoverflow.com/q/47668709
tags question: http://stackoverflow.com/q/47611583
tags question: http://stackoverflow.com/q/47548490
tags question: http://stackoverflow.com/q/47621716
tags question: http://stackoverflow.com/q/47668906
tags question: http://stackoverflow.com/q/47680153
tags question: http://stackoverflow.com/q/47652769
tags question: http://stackoverflow.com/q/47602205
tags question: http://stackoverflow.com/q/47636968
tags question: http://stackoverflow.com/q/47566489
tags question: http://stackoverflow.com/q/47661591
tags question: http://stackoverflow.com/q/47651016
tags question: http://stackoverflow.com/q/47629124
tags question: http://stackoverflow.com/q/47621547
type: Tag
tags question: http://stackoverflow.com/q/47643683
tags question: http://stackoverflow.com/q/47672609

sitemap
type: Tag
tags question: http://stackoverflow.com/q/47686487
tag name: sitemap
tags question: http://stackoverflow.com/q/47628667

http://stackoverflow.com/comment/82350520
score: 0
type: Comment
has text: https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Did%2Cname%2Cemail%2Cfirst_name%2Clast_name&version=v2.11 ... just supply your own access token (make a debug output somewhere in your app), or choose your own app id from the dropdown (then it should automatically populate the token field with one that includes all the permissions you granted to your app.)
type: QuestionComment
comment on: http://stackoverflow.com/q/47694931

http://stackoverflow.com/q/47683498
tagged with: function
accepted answer: http://stackoverflow.com/a/47683641
tagged with: iterable-unpacking
tagged with: python
possible better answer: http://stackoverflow.com/a/47683542
answer count: 4
has title: Python Function Returning List Objects Out of Order
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I'm relatively new to the Python language. I'm aware of most of the basic functionality &amp; theory, all the different classes of object and their behavior/properties etc. Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively. One in particular has left me vexed! Can anyone share any insight into why this result is not as expected? Here is the code I ran: test_list = [2, 4, 6] def test_func(k): global x, y, z for n in k: k[k.index(n)] = n * 2 x, y, z = k return k test_func(test_list) print(test_list) print(x) print(y) print(z) I would have expected the result to be: [4, 8, 12] 4 8 12 However, the actual result is as follows: [8, 4, 12] 8 4 12 It seems that the first two items of the list have been swapped. I can't see what could be causing this? If anyone can see what's happening here, please share the insight! Thanks, Oscar South
tagged with: list
downvote count: 0
has answer: http://stackoverflow.com/a/47683641
has answer: http://stackoverflow.com/a/47683552
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47683542
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47683580

http://stackoverflow.com/a/54540842
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/47608506
downvote count: 0
has body: While I trust the previous answers better understand EnsureDispatch, if you came here because you have this problem but cannot amend your code, or do not want to, I was able to fix this problem by renaming a folder. Running these lines raised the same error: from win32com.client.gencache import EnsureDispatch import sys xl = EnsureDispatch("Excel.Application") # Error here print(sys.modules[xl.__module__].__file__) Now, unfortunately, if you get the error it's hard to know where that file is. For me it was this folder: C:\Users\&lt;username&gt;\AppData\Local\Temp\gen_py\. Appending an underscore to that folder name (or deleting it) should cause the folder to be re-created when the code is re-run. hat tips to https://www.pyxll.com/_forum/index.php?topic=436.0 https://gist.github.com/rdapaz/63590adb94a46039ca4a10994dff9dbe The pyxll link has another block of code to call for potentially another folder location. I didn't use it so i'm not posting the code here. The fix above worked for me, but just in case you can go further down the rabbit hole.

http://stackoverflow.com/q/47648632
has comment: http://stackoverflow.com/comment/82260520
downvote count: 0
has title: Django forms.VaildationError not showing on a class based view
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47649432
has comment: http://stackoverflow.com/comment/82257765
has comment: http://stackoverflow.com/comment/82255827
has comment: http://stackoverflow.com/comment/82256606
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82261589
has body: My forms.validationerror is not showing. Below is my form that I am using. The if statement works and it detects the issue, and prints out the content successfully. As a lot the existing errors on stackoverflow suggest, the content is not None as shown in the print statement. class PollItemMessageAddForm(forms.ModelForm): class Meta: model = Message fields = [ "content" ] labels = { 'content': 'Add your comment', } widgets = { 'content': Textarea(attrs={'cols': 10, 'rows': 5}), } def __init__(self, *args, **kwargs): # this line should be before a super call self.request = kwargs.pop('request', None) super(PollItemMessageAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success')) def clean_content(self): content = self.cleaned_data.get("content") if len(content) &gt; 50: print content raise forms.ValidationError("Please limit your message to less the 50 characters") return content Below is my views.py post statement in my class based view, which skips the form.isvalid to be redirected to the same url where the error message should appear. I am using a detailview and formmixin in my class based view if it helps. I cant see where the issue is coming from in the absence of a traceback. Any help would be appreciated. def post(self, request, *args, **kwargs): url = "/polls/" + str(self.get_object().id) form = self.get_form() if request.method == "POST": if form.is_valid(): print "works" return self.form_valid(form) return HttpResponseRedirect(url)
has comment: http://stackoverflow.com/comment/82255969
has answer: http://stackoverflow.com/a/47649432
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82255862
has comment: http://stackoverflow.com/comment/82255632
has comment: http://stackoverflow.com/comment/82260462
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82255989

http://stackoverflow.com/a/47549240
answers question: http://stackoverflow.com/q/47548953
downvote count: 1
has comment: http://stackoverflow.com/comment/82152166
type: Answer
has comment: http://stackoverflow.com/comment/82055856
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/82055102
has body: Having never used the heapq module, I prefer this module-free approach: sorted( fruitsCount.items(), key=lambda pair: pair[1], reverse=True )[:3] Smaller, but less clear: sorted( fruitsCount.items(), key=lambda pair: -pair[1] )[:3]

http://stackoverflow.com/comment/82099828
comment on: http://stackoverflow.com/q/47571061
has text: `for line in login_info:` is a bit misleading. It's confusing to re-use `line` like that. That loop iterates over the list of words in the line you just read, but it only looks at the first word, since you `return` after checking that first word. You don't need a loop: you should just be checking the second word on the line.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47620697
linked to: http://stackoverflow.com/q/370357
tagged with: function
has answer: http://stackoverflow.com/a/47621153
downvote count: 0
favorite count: 0
type: Question
has body: I don't quite understand why the code def f(): print(s) s = "foo" f() runs perfectly fine but def f(): print(s) s = "bar" s = "foo" f() gives me UnboundLocalError. I know that I can fix this by declaring s as a global variable inside the function or by simply passing s an an argument into the function. Still I don't understand how python seemingly knows whether or not s is referenced inside the function before the line has been executed? Does python make some sort of list of all local variable references when the function is read into the global frame?
duplicate of: http://stackoverflow.com/q/370357
has comment: http://stackoverflow.com/comment/82199663
has title: Local and global references with UnboundLocalError
tagged with: python
tagged with: global
possible better answer: http://stackoverflow.com/a/47621107
has answer: http://stackoverflow.com/a/47621107
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: local
accepted answer: http://stackoverflow.com/a/47621153
upvote count: 2

c++
tags question: http://stackoverflow.com/q/47643901
tags question: http://stackoverflow.com/q/47618622
tags question: http://stackoverflow.com/q/47665824
tags question: http://stackoverflow.com/q/47587858
tags question: http://stackoverflow.com/q/47674658
tags question: http://stackoverflow.com/q/47556726
tags question: http://stackoverflow.com/q/47603920
tags question: http://stackoverflow.com/q/47599162
tags question: http://stackoverflow.com/q/47678568
tags question: http://stackoverflow.com/q/47571924
tags question: http://stackoverflow.com/q/47658521
tags question: http://stackoverflow.com/q/47617024
tags question: http://stackoverflow.com/q/47633863
type: Tag
tags question: http://stackoverflow.com/q/47642009
tags question: http://stackoverflow.com/q/47653159
tags question: http://stackoverflow.com/q/47616809
tags question: http://stackoverflow.com/q/47564437
tags question: http://stackoverflow.com/q/47687912
tags question: http://stackoverflow.com/q/47575449
tags question: http://stackoverflow.com/q/47553964
tags question: http://stackoverflow.com/q/47580725
tags question: http://stackoverflow.com/q/47678246
tags question: http://stackoverflow.com/q/47619097
tag name: c++
tags question: http://stackoverflow.com/q/47687924

http://stackoverflow.com/a/59207908
score: 27
answers question: http://stackoverflow.com/q/47629570
downvote count: 1
has body: After read the topic, It works for me: Uninstall aws $ sudo rm -rf /usr/local/aws $ sudo rm /usr/local/bin/aws Reinstall it again $ brew reinstall awscli
has comment: http://stackoverflow.com/comment/111716040
upvote count: 28
type: Answer

http://stackoverflow.com/comment/82283736
comment on: http://stackoverflow.com/q/47662156
score: 0
type: Comment
type: QuestionComment
has text: @JeremyDouglass right, that solution is *perfectly* Pythonic. It is very readable, the logic is straight-forward and expressed in typical python idioms, e.g. "append to the last sublist" => `lspl[-1].append(i)`. It is also *performant*.

http://stackoverflow.com/a/47604697
has body: There can only be one QApplication within the PyQt application, so if you already created it, do not do it again. Another problem is that the variables exist only within the context, in your case mainWindow, so at the end of the function StartInterface will eliminate this variable and the window, the solution is to make the mainWindow member of the class, so the context will be the class and no longer the function, so it will stay correctly. def IniciarInterfaz(self): self.hide() self.ex = mainWindow() self.ex.setStyleSheet("background-color: #fff") self.ex.show()
answers question: http://stackoverflow.com/q/47604561
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47604561
score: 3

http://stackoverflow.com/comment/82137790
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47590099
has text: have you tried something like `soup.findAll(text = re.compile('your regex here'))`?
score: 0

http://stackoverflow.com/comment/82112552
score: 0
type: AnswerComment
has text: @Gemini try the vectorized solution which is a thousand times faster than using lambda
comment on: http://stackoverflow.com/a/47577370
type: Comment

http://stackoverflow.com/q/47670660
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/47630440
accepted answer: http://stackoverflow.com/a/47691524
has comment: http://stackoverflow.com/comment/82300185
has body: as a continue to this import pyodbc not working in eclipse can any one please explain to me how the pyodbc import should look like ? when i do pip install pyodbc or python -m pip install pyodbc-4.0.21-cp36-cp36m-win_amd64.whl all i get is a folder pyodbc-4.0.21.dist-info which does not have any python files in it ...this is the content of the lib lib content is this is the right content? or there should be python files that need to be created some how my problem is that eclipse does not recognize the import pyodbc (getting Unresolved import: pyodbc ) UPDATE when i open the consule from eclipse and writing import pyodbc i am not getting any errors just when doing import from the .py file (in the eclipse) i am getting the error pleeeeeeeeese help
tagged with: python
tagged with: eclipse
has comment: http://stackoverflow.com/comment/82300121
has comment: http://stackoverflow.com/comment/82300810
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47691524
has title: import pyodbc not working in eclipse -python

http://stackoverflow.com/a/47546335
answers question: http://stackoverflow.com/q/47545511
type: Answer
has body: Solution to my code, this fixed it. add quotes around {} - > '{}' as well as add self.db_connec.commit() class Database(object): def __init__(self,ip_address,datetime_now, ): self.db_connec = mysql.connector.connect(user = DATABASE_USER, password = DATABASE_PASS, host = DATABASE_HOST, database = DATABASE) self.ip = ip_address self.datetime_now = datetime_now def run_query(self, query): if self.db_connec == None: raise mysql.connector.DatabaseError return None def log_threat(self): self.cursor = self.db_connec.cursor() print("Logging Threat... ") self.cursor.execute("INSERT INTO unauthorized_clients (ip_address, time) VALUES ('{}', '{}')".format(self.ip, self.datetime_now)) self.db_connec.commit() if __name__ == "__main__": client_connect()
score: 0
has comment: http://stackoverflow.com/comment/82053908

http://stackoverflow.com/comment/82228632
score: 1
has text: How should the resulting dataframe look like?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47635397

http://stackoverflow.com/comment/82250445
comment on: http://stackoverflow.com/q/47645828
score: 0
type: Comment
type: QuestionComment
has text: There's [jmsepath](https://pypi.python.org/pypi/jmespath). And [objectpath](http://objectpath.org/).

http://stackoverflow.com/comment/100229226
type: Comment
comment on: http://stackoverflow.com/q/47667045
score: 0
type: QuestionComment
has text: From my experience so far the _default_ behaviour for pandas in api-gateway is that the data frame has to be 'modified' via `to_json`, but then _also_ has to be passed through `json.dumps()`. I _do not_ understand why though as this _appears_ to double encode the json , but only for dataframes. So if someone could shed some light on that I'd be greatful.

http://stackoverflow.com/comment/82327879
comment on: http://stackoverflow.com/q/47683896
score: 0
type: Comment
has text: @bkarj `self` isn't the same instance or class then. If so, maybe use a global boolean (urgh!!) to communicate.
type: QuestionComment

http://stackoverflow.com/q/47563013
has answer: http://stackoverflow.com/a/55378377
has answer: http://stackoverflow.com/a/48847331
possible better answer: http://stackoverflow.com/a/48847331
has answer: http://stackoverflow.com/a/54321896
score: 56
has answer: http://stackoverflow.com/a/56190589
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/75982531
answer count: 16
has answer: http://stackoverflow.com/a/74772242
has answer: http://stackoverflow.com/a/50494608
has answer: http://stackoverflow.com/a/70426875
has answer: http://stackoverflow.com/a/52990056
has answer: http://stackoverflow.com/a/47563055
accepted answer: http://stackoverflow.com/a/47563055
upvote count: 57
has answer: http://stackoverflow.com/a/55685061
has body: Tried to run command: from django.urls import path Getting error: Traceback (most recent call last): File "&lt; stdin >", line 1, in ImportError: cannot import name 'path' I am using django version 1.11
type: AnsweredQuestion
has title: Unable to import path from django.urls
tagged with: django-views
has answer: http://stackoverflow.com/a/57159188
has answer: http://stackoverflow.com/a/49126869
has answer: http://stackoverflow.com/a/59676286
downvote count: 1
tagged with: django-urls
has answer: http://stackoverflow.com/a/71635109
favorite count: 0
has answer: http://stackoverflow.com/a/63765075
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82348187
score: 0
type: AnswerComment
type: Comment
has text: You can easily compile that program into an executable file as i did and then you can create a symlink with your own icon to make it user-friendly. I suggest you to use PyInstaller as it is easy to use and it`s tested on my repo aswell.
comment on: http://stackoverflow.com/a/47692514

http://stackoverflow.com/a/47613007
accepted answer of: http://stackoverflow.com/q/47612878
type: AcceptedAnswer
has body: By the time you get to the elif count == 4 line, count will always be 4. That's why. I got a hunch it could work if you changed the order: ... if count == 4: end() break elif count &gt;= 0 and count &lt;=3: ... However, it would be even nicer if you could write it without global variables. Instead of global variables you have local ones that are passed over to the next function as arguments. Like this: import random def end(cards): print("Your card is: ", cards[10]) def choice(count,pile_1,pile_2,pile_3): while True: user = input("Think of a card. Now to which pile does your card belong to?: ") if user == "1": cards = (pile_2 + pile_1 + pile_3) print(cards) split(count+1, cards) break elif user == "2": cards = (pile_1 + pile_2 + pile_3) print(cards) split(count+1, cards) break elif user == "3": cards = (pile_1 + pile_3 + pile_2) print(cards) split(count+1, cards) break else: print("Invalid input") def split(count,cards): if count == 4: end(cards) return pile_1 = [] pile_2 = [] pile_3 = [] for i in range(0,21,3): pile_1.append(cards[i]) pile_2.append(cards[i+1]) pile_3.append(cards[i+2]) print() print("first pile: ", pile_1) print("second pile: ", pile_2) print("third pile: ", pile_3) choice(count,pile_1,pile_2,pile_3) def main(): cards = [] file = open('cards.txt.', 'r') for line in file: cards.append(line.strip()) file.close random.shuffle(cards) print(cards) split(0, cards) main()
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/93209308
has comment: http://stackoverflow.com/comment/93209489
has comment: http://stackoverflow.com/comment/82186858
answers question: http://stackoverflow.com/q/47612878
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82184494

http://stackoverflow.com/a/47570690
accepted answer of: http://stackoverflow.com/q/47570493
type: Answer
has comment: http://stackoverflow.com/comment/82098777
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47570493
has body: One neat way to do this is to use a snippet html for product detail and send the product detail html snippet using render_to_string and just replace that html snippet in the modal. rendered = render_to_string('product_detail_snippet.html', context, context_instance=RequestContext(request)) return JsonResponse({'product_snippet': rendered}) And in the ajax success: $('#product-quick-view-modal').find('.modal-body').html(data.product_snippet);

http://stackoverflow.com/comment/82410400
type: QuestionComment
comment on: http://stackoverflow.com/q/47675177
has text: Are the source files in the same directory as the SConstruct? Or as it sounds like from above, they are located in a subdirectory which maps to a git submodule?
score: 0
type: Comment

http://stackoverflow.com/q/47598315
has body: So basically I have to make a code that inverts every odd letter of a string. I got a fair way, but couldn't figure out how to put the string back together properly. So the output should be 'hlleo', but instead i get 'hloe'. How do i fix this? Input is hello Expected output is hlleo Output is hloe word = 'hello' output = '' value = -1 word1 = word[0::2] word2 = word[1::2] word2 = word2[::-1] print(word2) print(word1) for letter in word2: value += 2 output = word1[:value] + letter + word1[value:] print(output) print('Correct output should be "hlleo"')
has comment: http://stackoverflow.com/comment/82154832
type: Question
has comment: http://stackoverflow.com/comment/82154788
has comment: http://stackoverflow.com/comment/82154855
answer count: 5
accepted answer: http://stackoverflow.com/a/47598454
tagged with: python
has comment: http://stackoverflow.com/comment/82155020
has title: How do i invert every odd letter in a string?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82154825
has answer: http://stackoverflow.com/a/47598593
has answer: http://stackoverflow.com/a/47598438
has answer: http://stackoverflow.com/a/47598459
possible better answer: http://stackoverflow.com/a/47598438
has answer: http://stackoverflow.com/a/47598454
has answer: http://stackoverflow.com/a/47598456
has comment: http://stackoverflow.com/comment/82155879

http://stackoverflow.com/a/50335238
has body: Also, what its worth, PyTorch has a good and faster implementation of Glove these days.
answers question: http://stackoverflow.com/q/47666699
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/82320696
comment on: http://stackoverflow.com/a/47680082
has text: If I understand correctly, this syntax supports fitting for a problem of of type `y = a.x_1 + b.x_2 + c`. Then, the first parameter is a list of n-dimensional vectors. Also, like you said in the last line, it doesn't make sense for me to use 2d vectors as input then. In fact, it should give the wrong answer.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82241358
comment on: http://stackoverflow.com/q/47636985
type: Comment
type: QuestionComment
score: 0
has text: I'm not altogether sure what you want to accomplish. However, I would suggest looking at the code in the wxPython demo for 'FourWaySplitter' under 'Advanced Generic Widgets.'

http://stackoverflow.com/comment/82330255
type: AnswerComment
has text: class as in 0 or 1 ? You have 7 groups and two classes per group?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47685021

http://stackoverflow.com/comment/82175773
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47608532
has text: Is there any specific thing you want to check this for? Maybe solving that would be easier...

http://stackoverflow.com/a/47659591
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47659354
has body: On Windows 10, using Python 3.6, I could successfully open the file and read the first line: with open('09nested.mod') as f: print(f.readlines()[0]) // File: 09nested.mod &gt;&gt;&gt;
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82278138
answers question: http://stackoverflow.com/q/47659354
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82221777
has text: `from django.apps import apps` ```app.config_from_object(settings)``` `app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])`
comment on: http://stackoverflow.com/q/47630459
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47676138
tagged with: machine-learning
has body: I want to freeze the layers except the first three layers in the Inception v3 model with TensorFlow in Python 3 also modify the weights of these three layers to be able to re-initialize and re-train only the three first layers of the network. If this can't be done within the inception model, is there any other network (in TensorFlow) with which this could be done?
tagged with: python
tagged with: data-science
tagged with: deep-learning
upvote count: 3
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47697061
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 2
has title: Freezing part of layers in Inception V3 in TensorFlow with Python 3

http://stackoverflow.com/comment/82087814
has text: I'm confused at why you'd have a list formatted like that. Why not have a list in a transposed form to what you have, i.e. have the arrays of the same size in the same sublist?
type: Comment
comment on: http://stackoverflow.com/q/47564821
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82102327
has text: Yes, for `NearestCentroid` it is not possible to compute a score. This is simply a limitation of the model. It assigns a class to each sample, but not a probability of that class. I guess if you need to use Nearest Centroid and you want a probability, you can use some ensemble method. Train a bunch of models of subsets of your training data, and average their predictions on your test set. That could give you a score. See http://scikit-learn.org/stable/modules/ensemble.html#bagging
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47572573

stdout
tags question: http://stackoverflow.com/q/47659188
tags question: http://stackoverflow.com/q/47584399
type: Tag
tag name: stdout
tags question: http://stackoverflow.com/q/47634922
tags question: http://stackoverflow.com/q/47671655
tags question: http://stackoverflow.com/q/47623800

http://stackoverflow.com/q/47670349
has comment: http://stackoverflow.com/comment/111891212
tagged with: python
has comment: http://stackoverflow.com/comment/130413359
tagged with: image
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82312484
downvote count: 0
tagged with: javascript
has body: Possibly a silly problem but i couldn't solve it alone. I am running a Flask application and one of the functions allows to take a picture from a camera on a remote raspberry pi zero, then display it on the web page with JavaScript. All I am getting seems to be the EXIF data of the picture, e.g. (from Chrome's dev console 'Elements'): Here is the Flask route: @app.route('/_getShot', methods=['GET']) def takePicture(): os.system('ssh pi@192.168.3.40 python3 singleShot.py &') sleep(6) #with open("static/shot.jpg", 'rb') as shot: # return flask.send_file(shot.read(), as_attachment=True, attachment_filename='shot.jpg', mimetype='image/jpeg') # return flask.Response(shot.read(), mimetype="image/jpeg") shot = 'static/shot.jpg' return flask.send_file(shot, mimetype='image/jpeg') I've left a couple other methods I've tried, commented out (same result). For now, the singleShot.py script (on the remote RPI zero) takes a picture then scp's it on the main RPI in my_app/static/, until I can properly return the image in Python without needing to physically write it on disk. And the html/javascript: Shot I've tested multiple methods and syntax , but unless I set the image source as 'static/shot.jpg', I'm only getting that EXIF data. I'm not sure whether the issue is in the Python or JavaScript code. Anyone can help?
tagged with: flask
favorite count: 0
type: Question
has title: Python Flask + Javascript : return image and display in web page
score: 3
has comment: http://stackoverflow.com/comment/130413321

http://stackoverflow.com/q/47673734
has answer: http://stackoverflow.com/a/47673861
possible better answer: http://stackoverflow.com/a/47673861
favorite count: 0
has body: I'm trying to open a excel so it is displayed visibly. I am using: import subprocess subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx']) https://ibb.co/eOhY4b Sorry if this is obvious but I keep getting this error message. AS far as I can tell the file is located there. FileNotFoundError: [WinError 2] The system cannot find the file specified
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82306307
score: 1
has title: open excel file python so it is visible
downvote count: 1
has answer: http://stackoverflow.com/a/47674006
accepted answer: http://stackoverflow.com/a/47674006
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
tagged with: subprocess
has comment: http://stackoverflow.com/comment/82306399
linked to: http://stackoverflow.com/q/2422798
tagged with: python

http://stackoverflow.com/q/47648821
tagged with: static-methods
type: AnsweredQuestion
score: 0
has body: I want to read the logging.config file only once and enable/disable the logger only once for the all the modules in my python project. I tried the following ways: 1. Using @staticmethod 2. Using Singelton pattern. Which is the better way to initialize or setup the logging only once for the entire python project? #Log.py import logging.config class Monitor(object): fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") logging.config.fileConfig(fileName) logger = logging.getLogger('root') logger.disabled = True/False #set from some other config file @staticmethod def Log(logMessage): Monitor.logger.info(logMessage) #Log1.py class Monitor(object): # Here will be the instance stored. __instance = None def __init__(self): if Monitor.__instance != None: raise Exception("This class is a singleton!") else: Monitor.__instance = self self.fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") logging.config.fileConfig(self.fileName) logger = logging.getLogger('root') logger.disabled = True/False #set via some config file @staticmethod def Log(logMessage): if Monitor.__instance == None: Monitor.__instance = Monitor() Monitor.logger.info(logMessage) else: Monitor.logger.info(logMessage)
accepted answer: http://stackoverflow.com/a/47869747
answer count: 1
has answer: http://stackoverflow.com/a/47869747
type: Question
tagged with: python-3.x
has title: Python Setup logging configuration only once
tagged with: python
tagged with: design-patterns
tagged with: logging

http://stackoverflow.com/comment/82320975
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47676106
type: QuestionComment
has text: could you explain me better

http://stackoverflow.com/comment/82198893
comment on: http://stackoverflow.com/q/47620444
score: 0
has text: what is your desired output?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47569811
has comment: http://stackoverflow.com/comment/82097586
has answer: http://stackoverflow.com/a/47570584
tagged with: python
linked to: http://stackoverflow.com/q/111155
has body: I'm having some issues when running my code inside Spyder3 IPython console. Now I did some digging on this and come to the conclusion that either I have graphical issues regarding drivers or X11 forwarding or whatsoever. Or I simply have an issue of not properly cleaning up my code which is why the second execution always becomes troublesome, requiring a kernel restart which as well might cause errors due to BadWindows etc. I do hope cleaning up properly will suffice, because dealing with any of these XCB errors or GTK warnings is too complicated My question is: How do I properly cleanup tkinter window objects, pygame surfaces and multithreads? Expectation: Delete everything after the window is closed because it certainly is not required anymore at that point or will simply cause errors if it persists. I've read about the python Deconstructor del but before I go into this I would prefer to know what kind of things even require deletion. Here's an example of error message I get on second execution of my program (first execution works properly) An error ocurred while starting the kernel [xcb] Unknown sequence number while processing queue [xcb] Most likely this is a multi‑threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python3: ../../src/xcb_io.c:259: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed. X Error of failed request: BadWindow (invalid Window parameter) Major opcode of failed request: 2 (X_ChangeWindowAttributes) Resource id in failed request: 0xe00008 Serial number of failed request: 75 Current serial number in output stream: 76 X Error of failed request: BadWindow (invalid Window parameter) Major opcode of failed request: 2 (X_ChangeWindowAttributes) Resource id in failed request: 0xe00008 Serial number of failed request: 75 Current serial number in output stream: 76 X Error of failed request: BadWindow (invalid Window parameter) Major opcode of failed request: 2 (X_ChangeWindowAttributes) Resource i…
has comment: http://stackoverflow.com/comment/82097795
has comment: http://stackoverflow.com/comment/82098464
has comment: http://stackoverflow.com/comment/82097269
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82097704
has comment: http://stackoverflow.com/comment/82097177
has comment: http://stackoverflow.com/comment/82097837
tagged with: pygame-surface
type: Question
has title: How to clean up python tkinter windows / pygame windows?
tagged with: tkinter
type: UnansweredQuestion
tagged with: python-multithreading

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/47574255
tags question: http://stackoverflow.com/q/47643379
tags question: http://stackoverflow.com/q/47550789
tag name: google-oauth

http://stackoverflow.com/comment/82122530
score: 0
type: Comment
has text: When you say it will "add it to an arrayy/list [sic]", which array are you talking about? You explicitly create one called `search`, and then you append to what we can only assume is a list named `Search`. Please create a [mcve], there's not enough detail in what you provided.
type: QuestionComment
comment on: http://stackoverflow.com/q/47582344

angularjs
tags question: http://stackoverflow.com/q/47591223
type: Tag
tags question: http://stackoverflow.com/q/47645276
tags question: http://stackoverflow.com/q/47542091
tags question: http://stackoverflow.com/q/47629215
tag name: angularjs

http://stackoverflow.com/comment/82313019
comment on: http://stackoverflow.com/a/47676991
score: 0
type: Comment
type: AnswerComment
has text: Guess what pandas plotting is from matplotlib, if you see here https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html they say `Make plots of DataFrame using matplotlib / pylab.`

http://stackoverflow.com/q/47650892
has comment: http://stackoverflow.com/comment/82260321
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82260150
has comment: http://stackoverflow.com/comment/82260075
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82262189
tagged with: python
has answer: http://stackoverflow.com/a/47651778
has body: consider the following python function: def prandom(): t = time.time() s = t - int(t) s = str('{0:.16f}'.format(s)) print s s = int(s[5]) print(s) return s the naive intention is to get a pseudorandom digit. However: how do you explain that, no matter how many times I run the function (on a Windows 10 machine) I get either a 0 or a 9? Is there something I am missing?
score: 0
has title: strange behavior of python function time.time()

http://stackoverflow.com/a/47646347
score: 0
answers question: http://stackoverflow.com/q/47640949
has body: The error says it all as follows : selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home You need to override any other existing paths and pass the absolute path of the chromedriver binary as an argument while initializing the webdriver instance as follows : from selenium import webdriver driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
type: Answer

http://stackoverflow.com/comment/82301765
comment on: http://stackoverflow.com/a/47669669
score: 0
type: AnswerComment
has text: Just done. It has been solved now. Thanks a lot for your help.
type: Comment

http://stackoverflow.com/q/47583121
linked to: http://stackoverflow.com/q/42186757
favorite count: 0
type: Question
upvote count: 2
tagged with: google-app-engine
has title: WooCommerce API gives 401 in Google App Engine but works (200 OK) in local env
tagged with: python
has body: I’m writing an app that allows users to integrate their WooCommerce stores with my site. I’m using the Python wrapper for the WooCommerce REST API and my app is hosted on Google App Engine. Here’s my code to call the Woocommerce API. (I’m using https to connect to all the WooCommerce stores) def request_woo_api(self, user, request_url): wcapi = API( url=user.woo_url, consumer_key=user.woo_consumer_key, consumer_secret=user.woo_consumer_secret, wp_api=True, version="wc/v2", query_string_auth=True ) resp = wcapi.get(request_url).json() return resp I get a 200 OK response when I test my code on my dev machine. But when I deploy my code to Google App Engine I get a 401 response for some WooCommerce stores. {u'message': u'Sorry, you cannot list resources.', u'code': u'woocommerce_rest_cannot_view', u'data': {u'status': 401}} I read here in this documentation that Google App Engine appends a value (AppEngine-Google; (http://code.google.com/appengine; appid: &lt;application_id&gt;)) to the user-agent header for all outbound requests. And I think this is the problem because I tried calling a woocommerce api from my local machine and it worked, but when I appended this value to my header the same endpoint gave the 401 error. &gt;&gt;&gt; headers = {'User-Agent': 'WooCommerce API Client-Python/1.2.1'} &gt;&gt;&gt; result = requests.get(url, headers=headers) &gt;&gt;&gt; print result.json() [{u'date_completed_gmt': None, u'date_modified_gmt': u'2017-11-30T18:13:59', u'payment_method': u'....... &gt;&gt;&gt; headers = {'User-Agent': 'WooCommerce API Client-Python/1.2.1; AppEngine-Google; (http://code.google.com/appengine; appid: 123)'} &gt;&gt;&gt; result = requests.get(url, headers=headers) &gt;&gt;&gt; print result.json() {u'message': u'Sorry, you cannot list resources.', u'code': u'woocommerce_rest_cannot_view', u'data': {u'status': 401}} The fact that this happens only for a couple of WooCommerce sites and not the others makes me think that these users might have a WooComme…
answer count: 1
tagged with: woocommerce-rest-api
tagged with: woocommerce
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47763919
downvote count: 0
has answer: http://stackoverflow.com/a/47763919

http://stackoverflow.com/comment/82334846
type: AnswerComment
comment on: http://stackoverflow.com/a/47687688
score: 0
has text: @Ervan You didn't add the `encoding` keyword to `open`. See my comment in the code above.
type: Comment

http://stackoverflow.com/a/47810847
upvote count: 17
answers question: http://stackoverflow.com/q/47649902
has comment: http://stackoverflow.com/comment/88002598
type: Answer
has body: Like @hoefling already mentioned, it's a privilege issue. Login via SSH ssh user@synology and enter user password. Get admin privileges sudo su and enter sudo password. Get installation file wget https://bootstrap.pypa.io/get-pip.py and execute installation file. python get-pip.py Let me know if it worked for you.
score: 17
has comment: http://stackoverflow.com/comment/88002995
has comment: http://stackoverflow.com/comment/82620833
downvote count: 0
has comment: http://stackoverflow.com/comment/82618834
has comment: http://stackoverflow.com/comment/123886509

http://stackoverflow.com/q/47640324
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/82241347
has comment: http://stackoverflow.com/comment/82239382
has body: Trying to auth to Duo Security admin API but stuck in their way of authenticating. Reference: https://duo.com/docs/adminapi#authentication They have a function that says it would be used to construct the “Authorization” and “Date” headers. Does anyone know how to go about getting this started? import base64, email, hmac, hashlib, urllib def sign(method, host, path, params, skey, ikey): """ Return HTTP Basic Authentication ("Authorization" and "Date") headers. method, host, path: strings from request params: dict of request parameters skey: secret key ikey: integration key """ # create canonical string now = email.Utils.formatdate() canon = [now, method.upper(), host.lower(), path] args = [] for key in sorted(params.keys()): val = params[key] if isinstance(val, unicode): val = val.encode("utf-8") args.append( '%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~'))) canon.append('&amp;'.join(args)) canon = '\n'.join(canon) # sign canonical string sig = hmac.new(skey, canon, hashlib.sha1) auth = '%s:%s' % (ikey, sig.hexdigest()) # return headers return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}
tagged with: hmac
type: Question
has comment: http://stackoverflow.com/comment/82239107
answer count: 0
tagged with: api
type: UnansweredQuestion
has title: Duo Security Auth
tagged with: python
tagged with: python-requests

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/47544450
tags question: http://stackoverflow.com/q/47668497
tags question: http://stackoverflow.com/q/47620588
tags question: http://stackoverflow.com/q/47618804
tags question: http://stackoverflow.com/q/47658694
tags question: http://stackoverflow.com/q/47580110
tags question: http://stackoverflow.com/q/47655909
tags question: http://stackoverflow.com/q/47553168
tags question: http://stackoverflow.com/q/47577301
tags question: http://stackoverflow.com/q/47681617
tags question: http://stackoverflow.com/q/47568356
tags question: http://stackoverflow.com/q/47693070
tags question: http://stackoverflow.com/q/47647491
tags question: http://stackoverflow.com/q/47586741
tags question: http://stackoverflow.com/q/47579348
tags question: http://stackoverflow.com/q/47630287
tags question: http://stackoverflow.com/q/47685300
tags question: http://stackoverflow.com/q/47665788
tags question: http://stackoverflow.com/q/47601389
tags question: http://stackoverflow.com/q/47615589
tags question: http://stackoverflow.com/q/47687411
tags question: http://stackoverflow.com/q/47624036
tags question: http://stackoverflow.com/q/47574857
tags question: http://stackoverflow.com/q/47648886
tag name: json
tags question: http://stackoverflow.com/q/47659782
tags question: http://stackoverflow.com/q/47563095
tags question: http://stackoverflow.com/q/47588402
tags question: http://stackoverflow.com/q/47564015
tags question: http://stackoverflow.com/q/47671985
tags question: http://stackoverflow.com/q/47544955
tags question: http://stackoverflow.com/q/47553615
tags question: http://stackoverflow.com/q/47652443
tags question: http://stackoverflow.com/q/47662955
tags question: http://stackoverflow.com/q/47619568
tags question: http://stackoverflow.com/q/47628924
tags question: http://stackoverflow.com/q/47643805
tags question: http://stackoverflow.com/q/47590051
tags question: http://stackoverflow.com/q/47558828
tags question: http://stackoverflow.com/q/47560489
tags question: http://stackoverflow.com/q/47574255
tags question: http://stackoverflow.com/q/47602020
tags question: http://stackoverflow.com/q/47679770
tags question: http://stackoverflow.com/q/47565445
tags question: http://stackoverflow.com/q/47687648
tags question: http://stackoverflow.com/q/47583800
tags question: http://stackoverflow.com/q/47568211
tags question: http://stackoverflow.com/q/47674398
tags question: http://stackoverflow.com/q/47585554
tags question: http://stackoverflow.com/q/47679678
tags question: http://stackoverflow.com/q/47647162
tags question: http://stackoverflow.com/q/47620829
tags question: http://stackoverflow.com/q/47546035
tags question: http://stackoverflow.com/q/47587713
tags question: http://stackoverflow.com/q/47657424
tags question: http://stackoverflow.com/q/47577948
tags question: http://stackoverflow.com/q/47577927
tags question: http://stackoverflow.com/q/47594898
tags question: http://stackoverflow.com/q/47621716
tags question: http://stackoverflow.com/q/47679834
tags question: http://stackoverflow.com/q/47675367
tags question: http://stackoverflow.com/q/47597476
tags question: http://stackoverflow.com/q/47593974
tags question: http://stackoverflow.com/q/47651708
tags question: http://stackoverflow.com/q/47681401
type: Tag
tags question: http://stackoverflow.com/q/47686304
tags question: http://stackoverflow.com/q/47645484
tags question: http://stackoverflow.com/q/47644448
tags question: http://stackoverflow.com/q/47591727
tags question: http://stackoverflow.com/q/47545841
tags question: http://stackoverflow.com/q/47650531
tags question: http://stackoverflow.com/q/47585856
tags question: http://stackoverflow.com/q/47632855
tags question: http://stackoverflow.com/q/47565541
tags question: http://stackoverflow.com/q/47586719
tags question: http://stackoverflow.com/q/47653948
tags question: http://stackoverflow.com/q/47603392
tags question: http://stackoverflow.com/q/47694878
tags question: http://stackoverflow.com/q/47585381

http://stackoverflow.com/q/47651327
possible better answer: http://stackoverflow.com/a/47651785
downvote count: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/47651785
has comment: http://stackoverflow.com/comment/82260912
favorite count: 0
type: Question
has body: I'm making a mysql request with python, when I'm printing the result it gives me the results but it adds some characters extra for me xD What I need is: Asia TAG Australia TAG ... What I get is: ('Asia TAG',) ('Australia TAG',) ... Those ('...',) how does this get in my results? current = con_mysql.cursor() current_query = "SELECT name FROM event_categories WHERE visible=1" current.execute(current_query) for name in current: print(name)
tagged with: python
has answer: http://stackoverflow.com/a/47651433
accepted answer: http://stackoverflow.com/a/47651433
has comment: http://stackoverflow.com/comment/82261010
has title: Python MySQLQuery result returns extra characters
type: AnsweredQuestion
score: 0
answer count: 2
upvote count: 1

http://stackoverflow.com/q/47598343
has comment: http://stackoverflow.com/comment/82156326
type: AnsweredQuestion
score: 0
has body: I have a dataframe with multiple pairs of columns that have to be merged. The columns contain mutually exclusive data. That is, if there is a value in Column A, the value for that row in Column B will be empty. df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', '', 'A2', ''], 'B': ['', 'B1', '', 'B3'], 'C': ['C1','C2','',''], 'D': ['','','D3','D4']}) So I have something like this: A B C D key 0 A0 C1 K0 1 B1 C2 K1 2 A2 D3 K2 3 B3 D4 K3 I'd like to merge columns A and B so all values end up in column A. I also want to do this form C and D, while keeping the index and any other columns such as Key untouched. I'm fine doing this in multiple steps. I don't need to do A-B merge and the C-D merge at the same time. Ideally, I would end up with: A C key 0 A0 C1 K0 1 B1 C2 K1 2 A2 D3 K2 3 B3 D4 K3 I've tried df = df.A.combine_first(df.B) but that gets me nowhere.
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47598732
has title: Merge two columns in the same pandas dataframe
tagged with: dataframe
tagged with: python
tagged with: merge
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47598732
possible better answer: http://stackoverflow.com/a/47598549
has answer: http://stackoverflow.com/a/47598549

http://stackoverflow.com/q/47619920
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47623843
has comment: http://stackoverflow.com/comment/82198251
tagged with: dataframe
tagged with: python
tagged with: merge
tagged with: web-crawler
has body: I am working on my Naver Crawler (its a Korea Google :P). I have working on this code for a week now, and I have one last task to solve! So my code below shows Data Crawling through Naver API and receiving data to "js" in each loop. All I need to do is combine each dataframe (dfdfdf) and combine at the bottom. But my result always shows the last looped data. Bottom line is that I want to add DataFrame for each loop that I am taking. I tried merge, join but it seems to be not working. Please let me know and if my code below does not make sense (or too dirty) let me know! import os import sys import urllib.request import pandas as pd import json import numpy as np from datetime import datetime, timedelta import time ex = pd.ExcelFile('mat_hierarchy.xlsx').parse('Sheet1') DNA1 = [] #adding list to DNA DNA1.extend(ex.iloc[:,3]) DNA1.extend(ex.iloc[:,2]) seen = set() DNA = [] for item in DNA1: if item not in seen: seen.add(item) DNA.append(item) # len(DNA) #Setting Date weekly or daily #dd = pd.date_range('2016-01-01',datetime.now().date() - timedelta(2)) dd = pd.date_range(start = '2016-01-01',end = datetime.now().date() - timedelta(2), freq = 'W-MON') setendDate = datetime.now().date() - timedelta(1) endDate = setendDate.strftime('%Y-%m-%d') #Setting DataFrame &amp; List Data = pd.DataFrame(index=dd) #Naver API Connection client_id = "ID" client_secret = "PW" url = "https://openapi.naver.com/v1/datalab/search"; #Setting requests body_intro = "{\"startDate\":\"2016-01-01\",\"endDate\":\"" body_endDate = "\",\"timeUnit\":\"date\",\"keywordGroups\":[{\"groupName\":\"" body_keywords = "\",\"keywords\":[\"" body_groupName = "\"]},{\"groupName\":\"" body_last = "\"]}],\"ages\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\"]}" df_list=[] for i in range(2270,len(DNA),5): if((len(DNA)%5==0) or (i &lt; (len(DNA)-(len(DNA)%5)))): body = body_intro + endDate + body_endDate + DNA[i] + body_keywords + DNA[i] + body_groupName + DNA[i+1] + body_keywords + DNA[i+1…
score: 0
has comment: http://stackoverflow.com/comment/82207095
has title: Naver Crawler: Combining DataFrame per each loop Python
tagged with: join
accepted answer: http://stackoverflow.com/a/47623843
answer count: 1

http://stackoverflow.com/comment/82214290
type: Comment
comment on: http://stackoverflow.com/a/47628168
type: AnswerComment
score: 0
has text: @V.Khakhil it's more than that, you should read docs for [`prefetch_related`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related) that i've already attached to answer.

http://stackoverflow.com/a/47642402
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47642194
answers question: http://stackoverflow.com/q/47642194
type: Answer
has comment: http://stackoverflow.com/comment/82245377
has body: Ok. I've found the solution: os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs') returns an str, while: p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/') returns a PosixPath I ended up casting the latter as a string by using str(), although this looks ugly to me. I'm keeping the question open for better answers.
score: 0

http://stackoverflow.com/comment/82292930
type: AnswerComment
has text: Did it work? I am not sure if .txt.txt will work. I have worked on *nix systems, not much on windows though, but I think the problem could be in the writing the path, where '\' should be '\\' in (e.g. "C:\\Users\\Desktop\\file.txt" ), because of special characters thing. Also, look this [link](https://automatetheboringstuff.com/chapter8/). Here you can find detailed explanation for working with files and directories, they also have examples for both windows and *nix systems.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47648236

http://stackoverflow.com/q/47620582
has title: sanic event loop and autobahn
has answer: http://stackoverflow.com/a/50784503
downvote count: 0
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: autobahn
tagged with: sanic
tagged with: python
score: 4
upvote count: 4
has body: I have a project written with Sanic application = Sanic(__name__) ... application.run(host=application.config.HOST, port=application.config.PORT, debug=application.config.DEBUG, log_config=application.config.LOG) and my site has a section for realtime operations for realtime section i want to use autobahn with sanic loop and i have custom chat protocol class ChatServerProtocol(WebSocketServerProtocol): .... and chat factory: class ChatFactory(WebSocketServerFactory): ... and i get sanic event loop and set factory to ChatFactory async def after_server_start(app, loop): factory = ChatFactory(u"ws://127.0.0.1:9000") factory.protocol = ChatServerProtocol loop.set_task_factory(factory) The above code fails: Error: Bad Request Traceback (most recent call last): File "httptools/parser/parser.pyx", line 296, in httptools.parser.parser.cb_on_message_complete (httptools/parser/parser.c:4868) File "/Users/XXX/Documents/Projects/sanic_env/lib/python3.6/site-packages/sanic/server.py", line 227, in on_message_complete self.execute_request_handler() File "/Users/XXX/Documents/Projects/sanic_env/lib/python3.6/site-packages/sanic/server.py", line 234, in execute_request_handler self.stream_response)) File "uvloop/loop.pyx", line 1146, in uvloop.loop.Loop.create_task (uvloop/loop.c:24809) TypeError: __call__() takes 1 positional argument but 3 were given and Questions: A: can I use sanic event loop for autobahn? ‌B: If yes, how should it be done?

http://stackoverflow.com/a/47646325
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47645911
type: AcceptedAnswer
has body: One way would be to use np.identity to create a complete set of one-hot vectors and select the appropriate ones using advanced indexing: import numpy as np x = np.random.random((10,321,321)) y = np.random.rand(10,21,321,321) z = np.random.randint(0,21,size=(10,321,321)) yc = y.copy() yct= yc.transpose(0, 2, 3, 1) yct[x &lt;= 0.5] = np.identity(21, dtype=yc.dtype)[z[x &lt;= 0.5]] for i in range(10): for j in range(321): for k in range(321): if x[i][j][k] &lt;= 0.5: for l in range(21): if l == z[i][j][k]: y[i][l][j][k] = 1 else: y[i][l][j][k] = 0 print(np.all(yc == y)) # True
score: 4
answers question: http://stackoverflow.com/q/47645911
type: Answer

http://stackoverflow.com/comment/82173438
has text: Isn't result defined within each function ie result = a+b etc? I expected that line 17 would print the answer to the equation from whichever function is called.
comment on: http://stackoverflow.com/q/47607515
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47686697
has comment: http://stackoverflow.com/comment/82333449
has body: for the unique and non-unique cases, a dictionary of IDs in linked_to for each ID could be obtained via: def linked_ids(df): #set up the dictionary dict = {} #iterate through the rows for row in df.index: #separate the semi-colon delimited linked to field linked_to = df.ix[row,'Linked_to'].split(";") if df.ix[row,'ID'] not in dict.keys(): dict[df.ix[row,'ID']] = [] for linked_id in linked_to: if linked_id not in dict[df.ix[row,'ID']]: dict[df.ix[row,'ID']].append(linked_id) else: for linked_id in linked_to: if linked_id not in dict[df.ix[row,'ID']]: dict[df.ix[row,'ID']].append(linked_id) return dict
upvote count: 2
answers question: http://stackoverflow.com/q/47686559
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47686559
score: 2

http://stackoverflow.com/q/47612366
score: 3
has title: Merge dataframe/panel to allow for export to *ONE* excel sheet, not multiple
has answer: http://stackoverflow.com/a/49236405
tagged with: dataframe
tagged with: python
tagged with: merge
tagged with: pandas
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
has body: When running the following code: import datetime as dt from datetime import datetime import pandas as pd import pandas_datareader.data as web from pandas import ExcelWriter import xlrd import xlwt start = dt.datetime.strptime("8/11/2017", "%m/%d/%Y") end = dt.datetime.today() book = xlrd.open_workbook('Example.xlsx') sheet = book.sheet_by_name('Okay') data = sheet.col_values(0, 1) ##print(data) df = web.DataReader(data, 'yahoo', start, end) print(df) resultingdf = pd.concat([data], axis=1) I get the following error: TypeError: cannot concatenate object of type "&lt;class 'list'&gt;"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid However, when I cease from concat-ing, and just print the dataframe, it shows as this: &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 6 (items) x 79 (major_axis) x 4 (minor_axis) Items axis: Adj Close to Volume Major_axis axis: 2017-12-01 00:00:00 to 2017-08-11 00:00:00 Minor_axis axis: AAPL to UCTT I'm obviously missing something, but it appears the code doesn't want to run properly because it doesn't want to concat a list... but the output the line prior classifies it not as a list, but as a panel, which can be concat'd. Hmmm My end goal is to be able to allow for writing of the entire dataframe to ONE excel sheet, ideally with the open, close, high, low, volume of one stock being listed before moving on to the open, close, etc. of another; that's more of a secondary objective however. As it stands, if I were to write this to an excel sheet it would write the 'open prices' for each stock on one tab, the 'close prices' on another, and so on and so forth, leaving me with 5+ tabs. Any help would be great. Thanks in advance.
type: Question
accepted answer: http://stackoverflow.com/a/49236405

http://stackoverflow.com/a/47687982
accepted answer of: http://stackoverflow.com/q/47687912
type: Answer
answers question: http://stackoverflow.com/q/47687912
score: 2
has body: In Python it is unnecessary to create a getter method (especially if the getter simply returns the attribute value with no checks or modifications). You can implement meaningful get and set methods but they should actually do something. The preferred approach is to use property decorators as described here: How does the @property decorator work? class Building(object): def __init__(self): self._height = 100 @property def height(self): return self._height @height.setter def height(self, value): if 0 &lt; value &lt; 1000: self._height = value else: raise ValueError('Attribute: height must be between 0 and 1000.') Then the property methods are used when reading from or assigning to the attribute: b = Building() print(b.height) 100 b.height = 90 print(b.height) 90 b.height = 2000 print(b.height) 90 By convention, reserved attributes are preceded by a single underscore and private attributes by a double underscore. However, this is more to alert users of the class that the attributes should be handled with care and nothing prevents them from accessing the attributes.
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82335611
downvote count: 0

http://stackoverflow.com/comment/82243346
type: QuestionComment
has text: Nah, the text sent to the console from `GridSearchCV(pipe_1, params, verbose = 2, scoring='roc_auc', cv=cv)`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47640889

http://stackoverflow.com/q/47618885
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82292693
answer count: 3
has body: I have a flask application with many route endpoints. In each of those routes, I need to do some common operations like Authentication check, validation logic for permission, XSS validation and few more common validation logic. I have read few posts which says of using login_required decorator in every methods for the Authentication verification. Now my question is should I create a decorator for each of the validation type and use them in every method. Please let me know how to handle such cases in Flask application. @Login_required() @Xss_validate() @permission_check() def subsribe_service(cs_dict, data_dict): Logic to subscribe.... @Login_required() @Xss_validate() @permission_check() def unsubsribe_service(cs_dict, data_dict): Logic to unsubscribe.... @Login_required() @Xss_validate() @permission_check() def delete_service(cs_dict, data_dict): Logic to delete.... @Login_required() @Xss_validate() @permission_check() def edit_service(cs_dict, data_dict): Logic to edit.... As you can see I have common logic as a decorator in all the action methods. I have such decorators in all the applications since every action require those 3 logic.
tagged with: flask
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47675848
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82195815
has answer: http://stackoverflow.com/a/47620775
has title: where to put common logic in Flask routes
has answer: http://stackoverflow.com/a/70112097
upvote count: 2

http://stackoverflow.com/q/47645584
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82249869
has body: I am developing my skills in Python and now try to add some logging to my files. I run into formatting issue and cannot find any information or I ask the wrong question. So to it: Some snippets of my code. import logging logging.basicConfig(filename='/var/log/larmlog/getandsendlogger.log',level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S ') I am fetching two variables from MySQL cursor.execute("""SELECT omr,county FROM rico where pocnr = '%s'""" % (pocin)) records = cursor.fetchall() nystad = [record[0] for record in records] county = [record[1] for record in records] logging.debug("chkomr returns nystad {} and county {}.".format(nystad,county)) and when I use the variables in the log it looks like this 2017-12-05 02:46:02 - root - DEBUG - chkomr returns nystad [None] and county [u'J\xf6nk\xf6pings l\xe4n']. Why and how can I correct it? Should be strings with Swedish. The log should say Jönköpings län. My code should be set to utf-8. I have not asked so many questions here and probably messed up the question with codeblocks and so. Just ask if you need more code or explanation.
answer count: 1
has comment: http://stackoverflow.com/comment/82292843
has comment: http://stackoverflow.com/comment/82249991
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/47667775
type: UnansweredQuestion
has title: Need some formatting help in the logging function in Python 2.7
tagged with: python
tagged with: logging

http://stackoverflow.com/a/47647597
answers question: http://stackoverflow.com/q/47647410
has comment: http://stackoverflow.com/comment/82253806
has body: DF.assign(_PCT_=DF.X.pct_change(-1)) Y X PCT _PCT_ 0 1 100 NaN -0.047619 1 2 105 0.050000 -0.086957 2 3 115 0.095238 0.210526 3 4 95 -0.173913 0.055556 4 5 90 -0.052632 0.022727 5 6 88 -0.022222 -0.200000 6 7 110 0.250000 0.100000 7 8 100 -0.090909 inf 8 9 0 -1.000000 NaN Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs) periods : int, default 1 Periods to shift for forming percent change https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html
has comment: http://stackoverflow.com/comment/82253434
score: 6
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47647410
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82071156
type: QuestionComment
has text: I may be totally wrong here, but if you only specify the axes to contract then it's not clear which order the remaining axes should appear in. In the numpy example you completely specify this by the first argument. Maybe Eigen keeps them in the order first tensor's surviving axes first, then second tensor's surviving axes?
comment on: http://stackoverflow.com/q/47556726
score: 1
type: Comment

http://stackoverflow.com/q/47659071
has comment: http://stackoverflow.com/comment/82276851
accepted answer: http://stackoverflow.com/a/47659564
upvote count: 0
has answer: http://stackoverflow.com/a/47659564
has comment: http://stackoverflow.com/comment/82277275
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/82277546
has comment: http://stackoverflow.com/comment/82277498
has comment: http://stackoverflow.com/comment/82277583
has comment: http://stackoverflow.com/comment/82277288
has comment: http://stackoverflow.com/comment/82276819
type: Question
has comment: http://stackoverflow.com/comment/82277383
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82276905
has title: Can somebody explain and solve my Value Error when reading in from a text file
has comment: http://stackoverflow.com/comment/82276928
has comment: http://stackoverflow.com/comment/82276952
has body: For some reason my code(following) has brought up a Value Error which I cannot understand. Please evaluate my code too. You can find the project I am trying to do at http://www.ocr.org.uk/Images/226767-unit-j276-03-programming-project-task-1-sample-non-exam-assessment.pdf fileid = "details for nea.txt" ID = [] surname = [] forename = [] dob = [] addr = [] addrT = [] addrTh = [] addrF = [] addrFi = [] homNum = [] gend = [] tutor = [] schoolEm = [] def Read(): file = open(fileid, "r") Record = file.readline() for line in Record: line = line.strip() A,B,C,D,E,F,G,H,I,J,K,L,M = line.split(',') ID.append(A) surname.append(B) forename.append(C) dob.append(D) addr.append(E) addrT.append(F) addrTh.append(G) addrF.append(H) addrFi.append(I) homNum.append(J) gend.append(K) tutor.append(L) schoolEm.append(M) file.close() def Save(): Record = [] file = open(fileid,"w") for i in range(len(ID)): Record.append(ID[i] +","+surname[i]+","+forename[i]+","+dob[i]+","+addr[i]+","+addrT[i]+","+addrTh[i]+","+addrF[i]+","+addrFi[i]+","+homNum[i]+","+gend[i]+","+tutor[i]+","+schoolEm[i]+"\n") file.writelines(Record) file.close() Read() print(ID) print(surname) The Text File I used goes as following: 01,abe,fat,01/02/02,5,Stoney Lane,Stur,Dorset,DR101LM,0123,M,C,email@sc. The lists titled addr, addrT represent the different lines of address.
downvote count: 1
has comment: http://stackoverflow.com/comment/82276852
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/82277102
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82276998

http://stackoverflow.com/a/47664694
has comment: http://stackoverflow.com/comment/82293452
upvote count: 2
downvote count: 2
has body: What u have is a JSON formatted string which u want to convert to python dictionary. Using the JSON library : import json with open("your file", "r") as f: dictionary = json.loads(f.read()); Now dictionary contains the data structure which ur looking for.
type: Answer
has comment: http://stackoverflow.com/comment/82310808
answers question: http://stackoverflow.com/q/47663809
score: 0

http://stackoverflow.com/comment/82299354
comment on: http://stackoverflow.com/q/47668971
type: QuestionComment
type: Comment
score: 0
has text: Thanks for the link but is it possible to make dummy twin axis beacuse I need to do other plottings w.r.t. original y-axis values. Now the problem is if I am trying to plot points on the line graph by taking y-axis values but it is taking twin y-axis values 0 to 1.

http://stackoverflow.com/a/47678536
has comment: http://stackoverflow.com/comment/82343221
accepted answer of: http://stackoverflow.com/q/47678252
answers question: http://stackoverflow.com/q/47678252
type: AcceptedAnswer
downvote count: 0
score: 20
upvote count: 20
type: Answer
has body: Method #1 Using broadcasting, we can use comparison against the max values, while keeping dims to facilitate broadcasting - a.max(axis=1,keepdims=1) == a Sample run - In [83]: a Out[83]: array([[0, 1], [2, 1], [4, 8]]) In [84]: a.max(axis=1,keepdims=1) == a Out[84]: array([[False, True], [ True, False], [False, True]], dtype=bool) Method #2 Alternatively with argmax indices for one more case of broadcasted-comparison against the range of indices along the columns - In [92]: a.argmax(axis=1)[:,None] == range(a.shape[1]) Out[92]: array([[False, True], [ True, False], [False, True]], dtype=bool) Method #3 To finish off the set, and if we are looking for performance, use intialization and then advanced-indexing - out = np.zeros(a.shape, dtype=bool) out[np.arange(len(a)), a.argmax(axis=1)] = 1
has comment: http://stackoverflow.com/comment/82316719

http://stackoverflow.com/q/47691542
tagged with: gobject
has title: Calling GMainLoop.quit() for mainloop running in child process, from parent process
accepted answer: http://stackoverflow.com/a/47730586
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/200469
has answer: http://stackoverflow.com/a/47730586
has answer: http://stackoverflow.com/a/47697551
score: 1
linked to: http://stackoverflow.com/q/3044580
upvote count: 1
favorite count: 0
type: Question
tagged with: python-multiprocessing
possible better answer: http://stackoverflow.com/a/47697551
tagged with: gstreamer
has body: I need to run a gstreamer pipeline to perform video streaming. The GStreamer pipeline requires a GObject.MainLoop object which has a run() method that does not terminate until quit() is called. For this I create a process (P2) from my main application process (P1), which runs the GObject.MainLoop instance in its main thread. The problem is that loop goes on indefinitly within the process P2 and I'm unable to exit/quit it from the main application process (P1). Following is the section of code that might help understanding the scenario. ''' start() spawns a new process P2 that runs Mainloop within its main thread. stop() is called from P1, but does not quit the Mainloop. This is probably because processes do not have shared memory ''' from multiprocessing import Process import gi from gi.repository import GObject class Main: def __init__(self): self.process = None self.loop = GObject.MainLoop() def worker(self): self.loop.run() def start(self): self.process=Process(target=self.worker, args=()) self.process.start() def stop(self): self.loop.quit() Next, I tried using a multiprocessing Queue for sharing the 'loop' variable between the processes, but am still unable to quit the mainloop. ''' start() spawns a new process and puts the loop object in a multiprocessing Queue stop() calls get() from the loop and calls the quit() method, though it still does not quit the mainloop. ''' from multiprocessing import Process, Queue import gi from gi.repository import GObject class Main: def __init__(self): self.p=None self.loop = GObject.MainLoop() self.queue = Queue() def worker(self): self.queue.put(self.loop) self.loop.run() def start(self): self.p=Process(target=self.worker, args=()) self.p.start() def stop(self): # receive loop instance shared by Child Process loop=self.queue.get() loop.quit() How do I call the quit method for the MainLoop object which is only accessible within the child Process P2?
answer count: 2
downvote count: 0
tagged with: glib
tagged with: python

http://stackoverflow.com/comment/82272993
type: Comment
comment on: http://stackoverflow.com/a/47645623
type: AnswerComment
score: 0
has text: Hi do you have a tip for installing the wunderweather module? Im running 3.6 32 bit version IDLE. I went to https://python.org/pypi/WunderWeather and downloaded/extract/installed the WunderWeather-0.2.9.tar.gz (md5) with Windows powershell but I am getting the module not found error.. Any tips?

http://stackoverflow.com/comment/82325070
type: QuestionComment
has text: It looks like you've almost got it, except that you reset `key_pressed` back to an empty list at the top of your loop. Try moving that statement outside of the loop.
score: 2
comment on: http://stackoverflow.com/q/47682842
type: Comment

http://stackoverflow.com/comment/82199882
has text: since you have used only part of the example in the docs, you should get similar graphs as in the answer if you use the complete example, where indeed there are more points when plotting the result of the interpolation.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47620826

http://stackoverflow.com/q/47597567
answer count: 1
accepted answer: http://stackoverflow.com/a/47597699
type: Question
has answer: http://stackoverflow.com/a/47597699
tagged with: keylogger
has body: I am currently in the process of developing a project where I use a python keylogger I have made. But I want to execute the keylogger via a voice command to Alexa. Is this possible at the moment to do in an Alexa skill?
tagged with: python
has title: Remotely execute programs via Amazon Alexa
type: AnsweredQuestion
tagged with: alexa-skills-kit
score: 0

http://stackoverflow.com/comment/82190424
comment on: http://stackoverflow.com/q/47616073
score: 0
type: Comment
type: QuestionComment
has text: You are calling the main function recursively at line number 39 , is it intentional??

http://stackoverflow.com/comment/82159176
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47597693
has text: get all values from user instance (ie. position, energy, image_name, class name, etc) and create dictionary which you can convert to JSON string. When user returns you can convert JSON to dictionary and recreate instance `if class ="hero": Hero(position, energy, ....)`. Or you can try to "serialize" object using modules like `pickle`, `shelf`
score: 2

http://stackoverflow.com/q/47661161
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I have .csv file which looks like this: id,product 1,car 1,phone 2,tv I want to get all rows which match the certain condition e.g: If the id==1, and product value contains letter "a", print all matched rows (e.g '1,car' will be printed). I know this would be better to work with database but I need to work with csv file. I tried with pandas: import pandas as pd df = pd.read_csv('products.csv') for value_i in df.id: for value_p in df.product: if (value_i==2 and "a" in value_p): print(value_i, value_p) But I don't get a good result. If someone can give me a hint how to access values of a columns I would be thankful.
tagged with: python
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: How to get column values of csv file in pandas or other methods in python
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47661201
accepted answer: http://stackoverflow.com/a/47661201

http://stackoverflow.com/comment/82202458
score: 0
type: QuestionComment
type: Comment
has text: I don't think there are any built in functions to do this in Oracle or MySql. You can write a user defined function to do it though. Is that what you are looking for?
comment on: http://stackoverflow.com/q/47619682

http://stackoverflow.com/comment/82107588
has text: Are you importing selenium web driver too?
comment on: http://stackoverflow.com/q/47575226
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47583942
has answer: http://stackoverflow.com/a/47584080
favorite count: 0
has body: I have a list which contains some items. I want to rearrange them as follows: product_name should be the first element items starting with image should be the last (also, they should be sorted) the rest of the items should come in between, in no particular order. Misc: There's only one (and always a) product_name in my list and the items inside are arranged in no particular order (that said, the order of the items is random - I just gave an example). Also, the list contains unique items. The below does its job, but it seems a bit verbose and inefficient. I'm sure there's a way to do this in a single for loop but I kinda have a brainfart now. Is there an easier way to achieve the following? def rearrange(header): final = ['product_name'] images = sorted([item for item in header if item.startswith('image')]) for item in header: if item != 'product_name' and not item.startswith('image'): final.append(item) final += images return final header = [ 'word2', 'image_4', 'word1', 'product_name', 'image_3', 'image_1', 'image_5', 'word3', 'image_6', 'image_2', ] print(rearrange(header)) Result: ['product_name', 'word2', 'word1', 'word3', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'image_6']
type: Question
tagged with: python-3.x
has title: Rearranging elements in a list
tagged with: python
possible better answer: http://stackoverflow.com/a/47584053
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47584053
answer count: 3
score: 1
accepted answer: http://stackoverflow.com/a/47584080
downvote count: 0
has answer: http://stackoverflow.com/a/47584079
upvote count: 1

http://stackoverflow.com/comment/82106931
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47575041
has text: Can you expand on your explanation a bit? I'm not sure what "making it dynamic" means.

http://stackoverflow.com/comment/96842059
comment on: http://stackoverflow.com/q/47610316
score: 0
type: Comment
type: QuestionComment
has text: I can't find PyQt4 in my computer.....

http://stackoverflow.com/comment/82063679
type: Comment
comment on: http://stackoverflow.com/a/47553196
type: AnswerComment
has text: x_ contains images loaded above, but why aren't they tensor but list?
score: 0

matplotlib
tags question: http://stackoverflow.com/q/47572366
tags question: http://stackoverflow.com/q/47648453
tags question: http://stackoverflow.com/q/47577754
tags question: http://stackoverflow.com/q/47560074
tags question: http://stackoverflow.com/q/47611399
tags question: http://stackoverflow.com/q/47594537
tags question: http://stackoverflow.com/q/47590957
tags question: http://stackoverflow.com/q/47638161
tags question: http://stackoverflow.com/q/47644479
tags question: http://stackoverflow.com/q/47664874
tags question: http://stackoverflow.com/q/47679618
tags question: http://stackoverflow.com/q/47553142
tags question: http://stackoverflow.com/q/47670727
tags question: http://stackoverflow.com/q/47626773
tags question: http://stackoverflow.com/q/47676638
tags question: http://stackoverflow.com/q/47553958
tags question: http://stackoverflow.com/q/47633005
tags question: http://stackoverflow.com/q/47610614
tags question: http://stackoverflow.com/q/47564932
tags question: http://stackoverflow.com/q/47644966
tags question: http://stackoverflow.com/q/47622542
tags question: http://stackoverflow.com/q/47546626
tags question: http://stackoverflow.com/q/47571689
tags question: http://stackoverflow.com/q/47571924
tags question: http://stackoverflow.com/q/47637046
tags question: http://stackoverflow.com/q/47632343
tags question: http://stackoverflow.com/q/47605702
tags question: http://stackoverflow.com/q/47645613
tags question: http://stackoverflow.com/q/47612684
tags question: http://stackoverflow.com/q/47697797
tags question: http://stackoverflow.com/q/47544242
tags question: http://stackoverflow.com/q/47579249
tags question: http://stackoverflow.com/q/47552392
tags question: http://stackoverflow.com/q/47662443
tags question: http://stackoverflow.com/q/47696390
tags question: http://stackoverflow.com/q/47609537
tags question: http://stackoverflow.com/q/47598536
tags question: http://stackoverflow.com/q/47677813
tags question: http://stackoverflow.com/q/47660537
tags question: http://stackoverflow.com/q/47563373
tags question: http://stackoverflow.com/q/47643925
tags question: http://stackoverflow.com/q/47541367
tags question: http://stackoverflow.com/q/47596266
tags question: http://stackoverflow.com/q/47682380
tags question: http://stackoverflow.com/q/47541127
tags question: http://stackoverflow.com/q/47697782
tag name: matplotlib
tags question: http://stackoverflow.com/q/47637989
tags question: http://stackoverflow.com/q/47676776
tags question: http://stackoverflow.com/q/47563831
tags question: http://stackoverflow.com/q/47569054
tags question: http://stackoverflow.com/q/47579442
tags question: http://stackoverflow.com/q/47651288
tags question: http://stackoverflow.com/q/47562040
tags question: http://stackoverflow.com/q/47686623
tags question: http://stackoverflow.com/q/47687414
tags question: http://stackoverflow.com/q/47685350
tags question: http://stackoverflow.com/q/47649694
tags question: http://stackoverflow.com/q/47608583
tags question: http://stackoverflow.com/q/47682951
tags question: http://stackoverflow.com/q/47546143
tags question: http://stackoverflow.com/q/47580878
tags question: http://stackoverflow.com/q/47542104
tags question: http://stackoverflow.com/q/47677434
tags question: http://stackoverflow.com/q/47633009
tags question: http://stackoverflow.com/q/47658467
tags question: http://stackoverflow.com/q/47680573
tags question: http://stackoverflow.com/q/47652027
tags question: http://stackoverflow.com/q/47571895
tags question: http://stackoverflow.com/q/47572067
tags question: http://stackoverflow.com/q/47603465
tags question: http://stackoverflow.com/q/47597534
tags question: http://stackoverflow.com/q/47576599
tags question: http://stackoverflow.com/q/47658456
tags question: http://stackoverflow.com/q/47597577
tags question: http://stackoverflow.com/q/47558392
tags question: http://stackoverflow.com/q/47577536
tags question: http://stackoverflow.com/q/47615938
tags question: http://stackoverflow.com/q/47639967
tags question: http://stackoverflow.com/q/47668802

http://stackoverflow.com/q/47585503
accepted answer: http://stackoverflow.com/a/47586108
tagged with: while-loop
tagged with: if-statement
has answer: http://stackoverflow.com/a/47585782
possible better answer: http://stackoverflow.com/a/47585782
tagged with: python
has comment: http://stackoverflow.com/comment/82128731
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: function
has title: Programming a thermostat in Python with “if statement” logic for time scheduling
has body: I am working on a thermostat that can be programmed to be off according to the time of day. This is my thermostat function: def thermostat(ac_on, acPower, temp_inside, Temp_desired): if temp_inside &gt; Temp_desired: ac_on = True if temp_inside &lt; Temp_desired: ac_on = False ac_heatflow = acPower if ac_on == True else 0 return ac_heatflow, ac_on Temp_desired is a set integer value, and temp_inside is the changing indoor temperature value that gets compared to Temp_desired (right now every couple of seconds) to see if the air conditioner (A/C) will be “on,” or “off.” ac_heatflow is the power usage when the A/C is on, and acPower is the A/C power value assigned outside of the function. My issue now is that I want to now add a time component to my thermostat, where the the A/C can be programmed to be off. For example, the A/C will work normally throughout the day, but from 8:00am to 10:00am it must be off, and from 3:00pm to 5:45pm it must be off, so during these intervals ac_on = False, but outside these intervals the thermostat will revert back to the original method where it determines if the air conditioner is on/off based on the room temperature. The aforementioned time intervals will be in seconds when used in the function, so 8:00am would be 28800, 10:00am --> 36000, 3:00pm --> 54000, 5:45pm --> 63900. This is what I have been trying: def thermostat(ac_on, acPower, temp_inside, Temp_desired, start, end, t): while t &gt;= start or t &lt;= end: ac_on = False else: if temp_inside &gt; Temp_desired + 2: ac_on = True if temp_inside &lt; Temp_desired: ac_on = False ac_heatflow = 400 if ac_on == True else 0 return ac_heatflow, ac_on start is a start time of the interval, end is the interval end time and t right now is in seconds. There is a calculation of temperature every couple of seconds over a 24 hour period, a full day is 86400 seconds, so start and end can be any value between 0 and 86400, for example, start = 1000 and end = 3000. The issue with the above code …
type: Question
has answer: http://stackoverflow.com/a/47586108

http://stackoverflow.com/comment/82277618
has text: Also, what do you do with unhashable values?
score: 0
comment on: http://stackoverflow.com/q/47659197
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82286181
type: AnswerComment
score: 1
has text: @fragmentedreality thanks, I didn't bother to check for duplicates. Will make sure I do that
comment on: http://stackoverflow.com/a/47663443
type: Comment

http://stackoverflow.com/comment/82295893
type: AnswerComment
has text: Thanks Ned. I tried this option. But I am facing one issue. in --source option we can give the directory or package name. We have a particular package "abcd". for which the path to package is "python2.6/site-packages/abcd-0.1-py2.6.egg/abcd/", but this is exactly not a directory, because "egg" file is a compressed one and this path is not taken as a directory by coverage. And when I use package name "abcd" with --source option, it is not giving me the files which are not hit. Does using "package name" means that the files, which import this package, are covered by coverage?
type: Comment
comment on: http://stackoverflow.com/a/47665763
score: 0

http://stackoverflow.com/a/47568191
downvote count: 0
type: Answer
has body: Based on np.triu_indices, in case you really want to do this with pure NumPy: s = feature_mat.shape[0] i, j = np.triu_indices(s, 1) # All possible combinations of indices dist_mat = np.empty((s, s)) # Don't waste time filling with zeros np.einsum('ii-&gt;i', dist_mat)[:] = 0 # When you can just fill the diagonal dist_mat[i, j] = dist_mat[j, i] = np.linalg.norm(feature_mat[i] - feature_mat[j], axis=-1) # Vectorized version of your original process The benefit of this method over broadcasting is that you can do it in chunks: n = 10000000 # Based on your RAM available for k in range (0, i.size, n): i_ = i[k: k + n] j_ = j[k: k + n] dist_mat[i_, j_] = dist_mat[j_, i_] = \ np.linalg.norm(feature_mat[i_] - feature_mat[j_], axis = -1)
upvote count: 2
answers question: http://stackoverflow.com/q/47566072
score: 2

http://stackoverflow.com/a/47600079
accepted answer of: http://stackoverflow.com/q/47599745
type: Answer
has body: This should work. (x - y) * z sample: &gt;&gt;&gt; x.shape,y.shape, z.shape ((10L, 5L), (5L,), (5L,)) &gt;&gt;&gt; x array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39], [40, 41, 42, 43, 44], [45, 46, 47, 48, 49]]) &gt;&gt;&gt; y array([0, 1, 2, 3, 4]) &gt;&gt;&gt; z array([1, 2, 3, 4, 5]) &gt;&gt;&gt; (x-y)*z array([[ 0, 0, 0, 0, 0], [ 5, 10, 15, 20, 25], [ 10, 20, 30, 40, 50], [ 15, 30, 45, 60, 75], [ 20, 40, 60, 80, 100], [ 25, 50, 75, 100, 125], [ 30, 60, 90, 120, 150], [ 35, 70, 105, 140, 175], [ 40, 80, 120, 160, 200], [ 45, 90, 135, 180, 225]])
score: 1
answers question: http://stackoverflow.com/q/47599745
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82246235
comment on: http://stackoverflow.com/q/47642424
type: Comment
type: QuestionComment
has text: Hey, @Asher! It's there. In the example. bahia.others and vicetoria.others are the DictFields
score: 0

http://stackoverflow.com/q/47561543
type: Question
has comment: http://stackoverflow.com/comment/82082842
has comment: http://stackoverflow.com/comment/82081754
tagged with: variable-assignment
tagged with: python
has answer: http://stackoverflow.com/a/47565399
tagged with: tkinter
has title: How to use radio buttons to assign a value to a variable in Python?
tagged with: radio-button
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82081842
answer count: 1
has body: I am trying to assign a value to a variable using a radio button in python with the following code: def print_me(): global payment global membership if studentMemString == "PY_VAR0": membership = "STUDENT" payment = studentMem elif adultMemString == "PY_VAR10": membership = "ADULT" payment = adultMem elif childMemString == "PY_VAR0": membership = "CHILD" payment = childMem else: pass print(membership) print(payment) root = tk.Tk() studentMem = tk.StringVar() studentMemString = str(studentMem) adultMem = tk.StringVar() adultMemString = str(adultMem) childMem = tk.StringVar() childMemString = str(childMem) studentRadBtn = tk.Radiobutton(root, text="Student - £19.99", variable=studentMem, value= 19.99) studentRadBtn.pack() adultRadBtn = tk.Radiobutton(root, text="Adult - £34.99", variable=adultMem, value= 34.99) adultRadBtn.pack() childRadBtn = tk.Radiobutton(root, text="Child - £5.99", variable=childMem, value=5.99) childRadBtn.pack() button = tk.Button(root, text="click", command=print_me) button.pack() root.mainloop() (update) Okay So now the issue is that when i start the program all the radio buttons are active and regardless of which one I try to click on the only one that is called is the first one. Why are they all selected?
has comment: http://stackoverflow.com/comment/82081763
tagged with: tkinter-layout
has comment: http://stackoverflow.com/comment/82081018

http://stackoverflow.com/comment/82170176
has text: Yeah i tried with pip and it says `Requirement already satisfied: pytesseract in ./anaconda3/lib/python3.6/site-packages`
comment on: http://stackoverflow.com/a/47605715
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82302550
score: 0
type: Comment
has text: could you please tell me your pillow version, i have Pillow (4.3.0) and it's work fine.
type: QuestionComment
comment on: http://stackoverflow.com/q/47671664

http://stackoverflow.com/a/47581218
has body: sample2 is not a reference to sample, but a reference to the value that sample had. When you do sample = {}, the old value still exists, and sample2 still references it, but sample1 now references {} instead.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47581188

http://stackoverflow.com/comment/82449227
type: QuestionComment
score: 0
has text: @ekhumoro I was not known about busy indicator, So I was trying it in a different way. Now I could implement busy indicator. And using QThread I tried executing FORTRAN code separately. Currently I face a weird small problem. please read my description and can you give me some hints now.
comment on: http://stackoverflow.com/q/47618622
type: Comment

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/47590623

http://stackoverflow.com/comment/82201246
score: 0
has text: when you have a gui-app, that app is blocking and needs to be blocking (how could it otherwise read keystrokes, mouse movements etc), it of course has event handling, signal/slot in Qt. As said I can't help much apart from pointing out what way I believe you need to go. It's probably not a good idea to use the built-in python subprocess framework, you should use the PyQt built-in framework to make your subprocess with, and you also need to make it as an independent process outside of the gui-loop. There are examples around for `QtRunnable/QtThreadPool` which will do what you want to achieve.
type: QuestionComment
comment on: http://stackoverflow.com/q/47609793
type: Comment

http://stackoverflow.com/comment/82328763
comment on: http://stackoverflow.com/a/47683673
has text: @MilánJanosov Sure, you can try catch these and output some value as proxy. But this needs somewhat to play with smoothness assumption. but it's worth a try.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47656211
has comment: http://stackoverflow.com/comment/82278420
tagged with: opencv
tagged with: linux
has comment: http://stackoverflow.com/comment/82277559
has comment: http://stackoverflow.com/comment/82270569
has comment: http://stackoverflow.com/comment/82277251
has body: I read nearly all of the questions about this subject but I didn't solve it. I am working on Linux/Mint. I installed OpenCV in the virtual environment a lot of times when trying to solve this problem. Problem is that: "cv2.videoCapture() return always false". I built the OpenCV with -D WITH_FFMPEG=ON option and it would finish successfully and the result that about FFmpeg was like that: It seemed to be OK. Also, when I run "make -j8" command, it finished with no problem. So I thought everything will be OK. When I tried to check FFmpeg support with this command: python -c "import cv2; print(cv2.getBuildInformation())" | grep -i FFmpeg it gave me NO result. I installed OpenCV with following these steps. I also tried to find if FFMPEG supports codec for decoding AVC encoded files. ffmpeg -codecs | grep -i avc and, the output is : DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_cuvid ) (encoders: h264_nvenc nvenc nvenc_h264 ) D.A.L. avc On2 Audio for Video Codec (decoders: on2avc ) I didn't understand why FFmpeg has seemed "YES" when I have building OpenCV at that time has given "NO" result with cv2.getBuildInformation(). (cv_env)➜ cv_env pkg-config --modversion opencv 3.2.0 (cv_env)➜ cv_env python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 &gt;&gt;&gt; cv2.__version__ '3.3.0' (cv_env)➜ cv_env python -c "import cv2; print(cv2.getBuildInformation())" | grep -i ffmpeg FFMPEG: NO (cv_env)➜ cv_env python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 &gt;&gt;&gt; cv2.__file__ '/opt/cv_env/local/lib/python2.7/site-packages/cv2/cv2.so' (cv_env)➜ cv_env python3 Python 3.4.3 (default, Nov 28 2017, 16:41:13) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv…
tagged with: python
has comment: http://stackoverflow.com/comment/82273080
has comment: http://stackoverflow.com/comment/82279569
has comment: http://stackoverflow.com/comment/82302797
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/82279164
answer count: 0
has comment: http://stackoverflow.com/comment/82278103
tagged with: ffmpeg
tagged with: video-capture
type: UnansweredQuestion
downvote count: 0
has title: build opencv with ffmpeg support
has comment: http://stackoverflow.com/comment/82278776
score: 4
has comment: http://stackoverflow.com/comment/82276227

http://stackoverflow.com/q/47669389
favorite count: 0
has title: Python array index slicing with [[ ]]
type: Question
downvote count: 5
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82297744
score: -3
tagged with: numpy
has comment: http://stackoverflow.com/comment/82297723
has body: centers = np.array([[1,2,3],[4,5,6]]) print(centers[[0,0,0,0,0,1,1]]) output: [[1 2 3] [1 2 3] [1 2 3] [1 2 3] [1 2 3] [4 5 6] [4 5 6]] What is this feature? I'm not sure what is this called.
upvote count: 2
has comment: http://stackoverflow.com/comment/82297679
has answer: http://stackoverflow.com/a/47669449
has comment: http://stackoverflow.com/comment/82297525
answer count: 1

http://stackoverflow.com/comment/82209450
type: AnswerComment
score: 0
has text: Did you check ks[5]? That seems to be the only other place I can think of that would cause problems. My next tip is to add print statements between every line to see where it is breaking. So that way it is easier to know where the bug is
comment on: http://stackoverflow.com/a/47586477
type: Comment

http://stackoverflow.com/comment/82197083
type: Comment
score: 0
has text: Thanks for this advice, but I am still getting the same error. How can I print the stack trace in heroku?
comment on: http://stackoverflow.com/q/47619436
type: QuestionComment

http://stackoverflow.com/q/47680233
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47680265
answer count: 3
score: 2
has answer: http://stackoverflow.com/a/47680265
has body: I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of - def funtion1(mylists,x): row=1 for elm in mylists: ws.write(row,x,elm) row+=1 x += 1 col=0 function1(mylist1,col) function1(mylist2,col) function1(mylist3,col) etc I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?
downvote count: 0
has comment: http://stackoverflow.com/comment/82319764
has answer: http://stackoverflow.com/a/47680352
has comment: http://stackoverflow.com/comment/82320155
favorite count: 0
type: Question
has title: increment value outside of function for every use in python
upvote count: 2
tagged with: function
possible better answer: http://stackoverflow.com/a/47680849
tagged with: python
has answer: http://stackoverflow.com/a/47680849
has comment: http://stackoverflow.com/comment/82319738

awk
tags question: http://stackoverflow.com/q/47577556
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/47629877
tags question: http://stackoverflow.com/q/47640229

http://stackoverflow.com/q/47548957
accepted answer: http://stackoverflow.com/a/47549987
has comment: http://stackoverflow.com/comment/82055388
has comment: http://stackoverflow.com/comment/82055277
has comment: http://stackoverflow.com/comment/102805064
has comment: http://stackoverflow.com/comment/82054512
has answer: http://stackoverflow.com/a/47549987
tagged with: arrays
linked to: http://stackoverflow.com/q/31468117
has comment: http://stackoverflow.com/comment/82054845
has body: I have a case where I need to write a very large 2D array to a file(pkl,npy,npz... ). My logic is to get the array part by part and save it to the file sequentially. Also, I want to read the same array, from this file, sequentially. Since the array is too big I cannot do any of this in one go. So my question is, how can I achieve this? Is there an inbuilt or external package that can help me do this? The environment I'm using is python. This is the part of the code that causes a Memory Error. def generate_arrays(): model=loadGloveModel('glove.6B.100d.txt') clf=pickle.load(open('cluster.pkl','rb')) tags=pickle.load(open('tags.pkl','rb')) cursor=db.cursor() sql="SELECT * FROM tag_data" try: cursor.execute(sql) db.commit() except Exception as e: print "Error",e db.rollback() ingre=[] keyw=[] for i in cursor.fetchall(): tag=np.zeros(len(tags)) ing=np.zeros(len(set(clf.labels_))) ii=word_tokenize(i[1]) tt=word_tokenize(i[2]) for j in ii: try: vec=model[j] except: continue pos=clf.predict([vec]) ing[pos] +=1 for j in tt: if j in tags: tag[tags.index(j)] +=1 ingre.append(ing) keyw.append(tag) return [ingre,keyw] arr = generate_arrays() pickle.dump(arr,open('input.pkl','wb')) I think the problem is due to the low RAM of the machine. Can we open a file stream and write arrays as batches. Similarly, can I read arrays as batches of n rows? Any help would be appreciated.
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82055236
has title: How to read and write numpy arrays which is larger than main memory?
score: 1
upvote count: 3
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82055624
has comment: http://stackoverflow.com/comment/82054778
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/102801728

http://stackoverflow.com/q/47687333
score: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47690673
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82337957
has body: I am hoping someone can give me an idea or a solution to the problem I have below. I have been trying to figure out how I can find the percentage a player played with another based off start time, end time, and period(or any other stat I did not mention). I can sum the duration of each player in a pivot table to see the full ice time of a player But for the life of me I cannot seem to figure out the other. Whether it needs to be in R, Excel, or a python script I have exhausted my ideas. I know this is not a straight forward scripting question but I can't think of a better spot to pose the question. I can clearly see in example 1 Suter and Dumba played together twice in the small snippet of data i provided. But to plot that on a graph or just find the percentage is where I am asking for any ideas. Below are 2 examples of how i can access OnIce data. Example 1. At the end of the period/game I can get the prior Line Shift data. LastName of player will appear multiple times throughout the df. LastName StartTime EndTime Duration ShiftNumber Period Foligno 0:00 0:40 0:40 1 1 Suter 0:00 0:40 0:40 1 1 Staal 0:00 0:40 0:40 1 1 Niederreiter 0:00 0:40 0:40 1 1 Dubnyk 0:00 20:00 20:00 1 1 Dumba 0:00 0:40 0:40 1 1 Zucker 0:40 1:26 0:46 1 1 Koivu 0:40 1:34 0:54 1 1 Murphy 0:40 1:26 0:46 1 1 Brodin 0:40 1:26 0:46 1 1 Granlund 0:40 1:39 0:59 1 1 Reilly 1:26 2:09 0:43 1 1 Winnik 1:26 2:18 0:52 1 1 Coyle 1:34 2:16 0:42 1 1 Stewart 1:39 2:13 0:34 1 1 Dumba 2:09 2:39 0:30 2 1 Suter 2:09 2:39 0:30 2 1 Example 2. I can run a script every couple seconds and save to a csv what player id's are OnIce at the same time. HomePlayerId HomeDuration 8475744 94 8471702 74 8477944 69 8475163 74 8474651 623 8477043 74 HomePlayerId HomeDuration 8475744 111 8471702 91 8477944 86 8475163 91 8474651 640 8477043 91
answer count: 1
tagged with: python
has title: Plot the Percent of time played together
tagged with: http://stackoverflow.com/tag/r
accepted answer: http://stackoverflow.com/a/47690673
type: AnsweredQuestion

http://stackoverflow.com/comment/82221448
score: 0
type: QuestionComment
has text: how about this ?.encode("utf-8", "ignore").decode('utf-8', "ignore")
type: Comment
comment on: http://stackoverflow.com/q/47631594

http://stackoverflow.com/q/47638438
has comment: http://stackoverflow.com/comment/82235262
downvote count: 1
has title: re.sub with variables, whole string by itself only
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47638517
tagged with: substitution
has answer: http://stackoverflow.com/a/47638517
has comment: http://stackoverflow.com/comment/82235259
linked to: http://stackoverflow.com/q/1751301
tagged with: python
tagged with: regex
has body: Column 1 in my csv has the target_string (to be replaced) and column 2 is the context (text_column). I can't get it to only remove the string when it is stand alone. I have tried adding \b, but that doesn't work. Text : "Foo, FOOBAR FOO FOOBAR FOO FOO FOOBAR." string_column = col [1] text_column = col [2] string_replacement = "BAR" text_column = re.sub(string_column, string_replacement, text_column, flags=re.IGNORECASE) What I get is : "BARBAR BAR BARBAR BAR BAR BARBAR." What I need is: "FOOBAR BAR FOOBAR BAR BAR FOOBAR." EDIT I don't think this is a duplicate of the linked question. Those responses wouldn't have helped me, and are far more complicated than the simple solution provided here.
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82235379
has comment: http://stackoverflow.com/comment/82235685
duplicate of: http://stackoverflow.com/q/1751301
has comment: http://stackoverflow.com/comment/82235420
has comment: http://stackoverflow.com/comment/82235565
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/82358387

http://stackoverflow.com/a/47689819
type: Answer
has body: To catch all of your examples, I think you could use: ^\w+(?:\w+\-?|\-\w+)+$ Beginning of the string ^ Match a word character one or more times \w+ Start a non capturing group (?: Match a word character one or more times with an optional hyphen \w+\-? Or | A hyphen with one or more word characters \-\w+ Close the non capturing group ) End of the string $
score: 0
answers question: http://stackoverflow.com/q/47688358

parsing
tags question: http://stackoverflow.com/q/47599575
tags question: http://stackoverflow.com/q/47546923
tag name: parsing
tags question: http://stackoverflow.com/q/47606877
tags question: http://stackoverflow.com/q/47548324
tags question: http://stackoverflow.com/q/47586719
tags question: http://stackoverflow.com/q/47553615
tags question: http://stackoverflow.com/q/47579743
tags question: http://stackoverflow.com/q/47625950
tags question: http://stackoverflow.com/q/47662955
tags question: http://stackoverflow.com/q/47659423
tags question: http://stackoverflow.com/q/47590105
tags question: http://stackoverflow.com/q/47623869
tags question: http://stackoverflow.com/q/47583800
tags question: http://stackoverflow.com/q/47540852
tags question: http://stackoverflow.com/q/47605357
type: Tag

http://stackoverflow.com/q/47587680
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: datareader
tagged with: python
has body: I have been successfully using a script like this for months using google as the data provider. A few days ago it stopped working. Here is the input: import numpy as np import pandas as pd import pandas_datareader.data as wb from datetime import date, datetime, time, timedelta from pandas.tseries.offsets import BDay data_provider = 'google' # 'google', 'quandl', or 'yahoo' today = date.today() four_days_ago = today - BDay (4) tickers = [{'ACET':1},{'HBAN':2},{'HPQ':3},{'IPG':4},{'AOSL':5},{'HBI':6},{'NRG':7},{'IBM':8},{'MMM':9}] enter_list = [] rank_list = [] for x in tickers: for ticker, rank in x.items(): try: df = wb.DataReader (ticker, data_provider, four_days_ago, today) print ('reading data for ' + ticker + ' from ' + data_provider) except: print ('\ncan not read data for ' + ticker + ' from ' + data_provider) if df.iloc[1]['Low'] &lt; df.iloc[0]['Low']: enter_list.append (ticker) rank_list.append (rank) df2 = pd.DataFrame({'ticker' : enter_list, 'rank' : rank_list}, columns = ['ticker', 'rank']) if len(df2) == 0: print ('\nthere are no qualifying stocks') else: print ('\nlower stocks\n') print (df2) Here is the output: reading data for ACET from google Traceback (most recent call last): File "C:\Users\dvdad\Anaconda3.4.2.0.64.bit\lib\site-packages\pandas\core\indexes\base.py", line 2483, in get_value return libts.get_value_box(s, key) File "pandas\_libs\tslib.pyx", line 923, in pandas._libs.tslib.get_value_box (pandas\_libs\tslib.c:18843) File "pandas\_libs\tslib.pyx", line 932, in pandas._libs.tslib.get_value_box (pandas\_libs\tslib.c:18477) TypeError: 'str' object cannot be interpreted as an integer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\stocks\question 8 for stack overflow.py", line 25, in &lt;module&gt; if df.iloc[1]['Low'] &lt; df.iloc[0]['Low']: File "C:\Users\dvdad\Anaconda3.4.2.0.64.bit\lib\site-packages\pandas\core\series.py", line 601, in __getitem__ result = self.index.get_val…
tagged with: yahoo
has title: Pandas datareader errors
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/comment/82180826
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47609561
has text: So are you still eager to help with last part of code which is Hamming Window? Please see the description.

http://stackoverflow.com/comment/82389303
has text: Here is my Openshift 3 python pyramid stater app. It has the bare minimum configuration. http://github.com/fatfantasma/Openshift_3_Pyramid_Starter?files=1.
comment on: http://stackoverflow.com/q/47690610
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82376044
score: 1
type: Comment
type: QuestionComment
has text: BTW, Python has several different array-like data structures: tuple, list, and [array.array](https://docs.python.org/3/library/array.html). And then there are Numpy arrays. So to avoid confusion it's a good idea to use the correct names. However, `.join` is _not_ a list method, it's a string method which accepts an iterable of strings as its argument.
comment on: http://stackoverflow.com/q/47693461

http://stackoverflow.com/comment/82062224
type: Comment
comment on: http://stackoverflow.com/a/47552748
score: 0
type: AnswerComment
has text: I'm correcting the misconception that `SchoolForm` is receiving multiple arguments. I don't know enough Django to know what argument (or arguments) would make sense to `SchoolForm`.

http://stackoverflow.com/q/47676248
linked to: http://stackoverflow.com/q/47079111
tagged with: metrics
has answer: http://stackoverflow.com/a/55151505
has answer: http://stackoverflow.com/a/51051401
has title: Accessing validation data within a custom callback
has answer: http://stackoverflow.com/a/54897630
tagged with: python
has comment: http://stackoverflow.com/comment/83240054
has comment: http://stackoverflow.com/comment/105550142
answer count: 4
score: 30
has comment: http://stackoverflow.com/comment/115647303
has comment: http://stackoverflow.com/comment/100455188
linked to: http://stackoverflow.com/q/54590826
has body: I'm fitting a train_generator and by means of a custom callback I want to compute custom metrics on my validation_generator. How can I access params validation_steps and validation_data within a custom callback? It’s not in self.params, can’t find it in self.model either. Here's what I'd like to do. Any different approach'd be welcomed. model.fit_generator(generator=train_generator, steps_per_epoch=steps_per_epoch, epochs=epochs, validation_data=validation_generator, validation_steps=validation_steps, callbacks=[CustomMetrics()]) class CustomMetrics(keras.callbacks.Callback): def on_epoch_end(self, batch, logs={}): for i in validation_steps: # features, labels = next(validation_data) # compute custom metric: f(features, labels) return keras: 2.1.1 Update I managed to pass my validation data to a custom callback's constructor. However, this results in an annoying "The kernel appears to have died. It will restart automatically." message. I doubt if this is the right way to do it. Any suggestion? class CustomMetrics(keras.callbacks.Callback): def __init__(self, validation_generator, validation_steps): self.validation_generator = validation_generator self.validation_steps = validation_steps def on_epoch_end(self, batch, logs={}): self.scores = { 'recall_score': [], 'precision_score': [], 'f1_score': [] } for batch_index in range(self.validation_steps): features, y_true = next(self.validation_generator) y_pred = np.asarray(self.model.predict(features)) y_pred = y_pred.round().astype(int) self.scores['recall_score'].append(recall_score(y_true[:,0], y_pred[:,0])) self.scores['precision_score'].append(precision_score(y_true[:,0], y_pred[:,0])) self.scores['f1_score'].append(f1_score(y_true[:,0], y_pred[:,0])) return metrics = CustomMetrics(validation_generator, validation_steps) model.fit_generator(generator=train_generator, steps_per_epoch=steps_per_epoch, epochs=epochs, validation_data=validation_generator, validation_steps=validation_steps, shuffle=True, callbacks=[metri…
downvote count: 0
has answer: http://stackoverflow.com/a/64018936
has comment: http://stackoverflow.com/comment/105550161
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89066402
tagged with: keras
upvote count: 30
favorite count: 0
type: Question

http://stackoverflow.com/q/47683816
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82327343
has comment: http://stackoverflow.com/comment/82327258
has comment: http://stackoverflow.com/comment/82327603
has answer: http://stackoverflow.com/a/47683851
accepted answer: http://stackoverflow.com/a/47683851
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82327237
has body: def gDiceRoll(): gDiceOptions.destroy() global gDiceRoll gDiceRoll = Tk() gDiceRoll.title("Green Dice Roll") gDiceRoll.config(background="#32cd32") lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32") play() while True: outcomeG = random.randint(1, 100) lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32") if outcomeG &lt;= 25: lbloutcome.config(text="G1", font=(25)) gDiceRoll.update() f = open("Logs.txt", "a") ts = time.time() sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ') f.write(sttime + "G1 \n") f.close() photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G1.gif") lblop = Label(gDiceRoll, image=photo) lblop.pack() lbloutcome.pack() gDiceRoll.mainloop() gDiceRoll.after(1) os.execl(sys.executable, sys.executable, *sys.argv) break elif outcomeG &lt;= 22: lbloutcome.config(text="G2", font=(25)) gDiceRoll.update() f = open("Logs.txt", "a") ts = time.time() sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ') f.write(sttime + "G2 \n") f.close() photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G2.gif") lblop = Label(gDiceRoll, image=photo) lblop.pack() lbloutcome.pack() gDiceRoll.mainloop() gDiceRoll.after(1) os.execl(sys.executable, sys.executable, *sys.argv) break #etc Every time I run the program ir ALWAYS comes out with G1. I have tried to fix it many ways but they just create other problems. The elif G1 &lt;= 25 means it has a 25% chance of doing G1 but it always does G1. How can I fix this? Any help will be greatly appreciated
has comment: http://stackoverflow.com/comment/82327489
type: AnsweredQuestion
tagged with: tkinter
tagged with: random
downvote count: 0
upvote count: 1
answer count: 1
has title: Same result every time with random numbers (python)
favorite count: 0
has comment: http://stackoverflow.com/comment/82327211
type: Question

http://stackoverflow.com/comment/82202898
has text: Er, yes. Why did you post that comment?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47622247

http://stackoverflow.com/a/47690171
answers question: http://stackoverflow.com/q/47689968
type: Answer
has body: Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above: ```{r setup, include=FALSE} library(knitr) library(reticulate) knitr::knit_engines$set(python = reticulate::eng_python) ``` ```{python} import numpy as np import matplotlib.pyplot as plt import numpy.random as rng import matplotlib.cm as cm from matplotlib.animation import FuncAnimation radii=(rng.random(int(1e3))+1)**2 iota=2*np.pi*rng.random(int(1e3)) x_posit=np.sqrt(radii)*np.cos(iota) y_posit=np.sqrt(radii)*np.sin(iota) plt.plot(x_posit, y_posit, 'go') plt.show() ``` Note the plt.show() command. This will produce your expected output!
downvote count: 0
score: 7
upvote count: 7

http://stackoverflow.com/q/47625436
has title: Google Trend Crawler: CSV writing issues
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: python
tagged with: web-crawler
has body: Below code is Google Trend Crawler that uses unofficical API from "https://github.com/GeneralMills/pytrends". My code runs fine but one problem is that no one knows the limit to Google Trend Crawler. So if I run my Crawler with List of 2000 or more "DNA", then I have error saying I have exceeded the request limit. If I have gone over the limit, all of my crawled data before the limit will be lost since I am writing to csv at the end of the code. Is there a way to write my data to csv for every loop, so even though I pass the limit, at least I have the data before the limit was reached? Thanks from pytrends.request import TrendReq from datetime import datetime import pandas as pd import time import xlsxwriter pytrends = TrendReq(hl='en-US,tz=360') Data = pd.DataFrame() #for loop check writer path path = "C:/Users/aijhshin/Workk/GoogleTrendCounter.txt" #file = open(path,"a") #setting index using 'apple' keyword kw_list = ['apple'] pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='') Googledate = pd.DataFrame(pytrends.interest_over_time()) Data['Date'] = Googledate.index #Google Trend Crawler limit = 1600 request per day for i in range(len(DNA)): kw_list = [DNA[i]] pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='') #results df = pd.DataFrame(pytrends.interest_over_time()) if(df.empty == True): Data[DNA[i]] = "" else: df.index.name = 'Date' df.reset_index(inplace=True) Data[DNA[i]] = df.loc[:, DNA[i]] #test for loop process file = open(path,"a") file.write(str(i) + " " + str(datetime.now()) + " ") file.write(DNA[i] +'\n') file.close() #run one per nine second (optional) #time.sleep(9) #writing csv file (overwrite each time) Data.to_csv('Google Trend.csv') print("Crawling Done")
has comment: http://stackoverflow.com/comment/82208782
has comment: http://stackoverflow.com/comment/82208953
tagged with: google-crawlers
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47625698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47625698

postgresql-bigsql
type: Tag
tag name: postgresql-bigsql
tags question: http://stackoverflow.com/q/47564957

http://stackoverflow.com/comment/82206634
type: QuestionComment
comment on: http://stackoverflow.com/q/47615802
type: Comment
has text: You are getting an `InvalidSchema` exception. That means that `requests` thinks that the schema part of the URL is invalid, e.g. "blah://blah.com/session". You have obscured it in your question, but what is the full exception message? I would guess that the problem is related to the use of environment variables - perhaps Lambda modifies them in some way. Please print out exactly what your code is getting for `api_base`.
score: 0

http://stackoverflow.com/q/47666070
has comment: http://stackoverflow.com/comment/82295795
tagged with: selenium
tagged with: web-scraping
has title: Scraped CSV pandas dataframe I get: ValueError('Length of values does not match length of ' 'index')
has comment: http://stackoverflow.com/comment/82291366
possible better answer: http://stackoverflow.com/a/47667056
accepted answer: http://stackoverflow.com/a/47669506
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47667056
has answer: http://stackoverflow.com/a/47669506
has comment: http://stackoverflow.com/comment/82295624
has comment: http://stackoverflow.com/comment/82295035
has comment: http://stackoverflow.com/comment/82295433
has comment: http://stackoverflow.com/comment/82294534
tagged with: python
has comment: http://stackoverflow.com/comment/82295119
has comment: http://stackoverflow.com/comment/82291382
has comment: http://stackoverflow.com/comment/82295755
has body: I run below code and get: raise ValueError('Length of values does not match length of ' 'index') ValueError: Length of values does not match length of index for: print(df3) zz = df1.WE=np.where(df1.EW.isin(df3.AL),df1.WE,np.nan) df3['O2'] = zz #Error Line I have got this to work for data in a csv that has identical column structure save for this is scraped data where as the other csv was created manually. df1 EW WE \ 0 can v can 1.900 1 Lanus U20 v Argentinos Jrs U20 2.100 DA 0 https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F... 1 https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F... df2 AA AB AC AD \ 0 Today 19:00 Indonesia U23 Kyrgyzstan U23 650.00 1 Today 23:00 Brunei Darussalam U23 Mongolia U23 3.30 2 Today 19:30 can can 110.00 AE 0 https://www.betfair.com.au/exchange/plus/footb... 1 https://www.betfair.com.au/exchange/plus/footb... 2 https://www.betfair.com.au/exchange/plus/footb... df3 df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL']) Desired: df3: DAT G \ 0 Today 19:00 can v can TN O1 \ 0 can v can 1.900 L1 \ 0 https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F... TN2 O2 \ 0 can v can 110.00 L2 D 0 https://www.betfair.com.au/exchange/plus/footb... 108.1 Code: import pandas as pd import time import numpy as np import pandas as pd print('####CURRIES###') df1 = pd.read_csv('C:\\O\\df1.csv', index_col=False, usecols=[0,1,2], names=["EW", "WE", "DA"], header=None) print(df1) print('####Mangoes###') df2 = pd.read_csv('C:\\O\\df2.csv', index_col=False, usecols=[0,1,2, 3, 4], names=["AA", "AB", "AC", "AD", "AE"], header=None) print(df2) df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL']) df3['DAT'] = df2['AA'] df3['G'] = df2['AB'] + ' v ' + df2['AC'] df3['AK'] = df2['AB'] + ' v ' + df2['AC'] df3['AL'] = df2['AB'] + ' v ' + df2['AC'] print(df3) #TN print('Vlookup') aa = df3.AK=np.where(df3.AK.isin(df1.EW),df3.AK,np.nan) print(aa) df3['TN'] = aa print('Vlookup output') print(df3) …
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82295103
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/47681337
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82337877
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47677065
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47677065
has body: sp.vstack concatenates the matrices vertically, just as np.vstack does (except it works with the coo attributes of the componenets). In [93]: dx = spnabla_x(10,10) In [94]: dy = spnabla_y(10,10) In [95]: dx Out[95]: &lt;100x100 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 180 stored elements in Compressed Sparse Row format&gt; In [96]: dy Out[96]: &lt;100x100 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 180 stored elements in Compressed Sparse Row format&gt; In [97]: dx.A Out[97]: array([[-1., 1., 0., ..., 0., 0., 0.], [ 0., -1., 1., ..., 0., 0., 0.], [ 0., 0., -1., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., -1., 1., 0.], [ 0., 0., 0., ..., 0., -1., 1.], [ 0., 0., 0., ..., 0., 0., 0.]]) In [98]: dy.A Out[98]: array([[-1., 0., 0., ..., 0., 0., 0.], [ 0., -1., 0., ..., 0., 0., 0.], [ 0., 0., -1., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]) In [99]: dxy = sp.vstack((dx,dy)) In [100]: dxy Out[100]: &lt;200x100 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 360 stored elements in Compressed Sparse Row format&gt; In [101]: dxy Out[101]: &lt;200x100 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 360 stored elements in Compressed Sparse Row format&gt; In [102]: np.allclose(dxy[:100,:].A,dx.A) So the first N rows of dxy are the same as the dx, etc. I should warn that indexing of sparse matrices is much slower than for regular numpy arrays. And it does not create a view; it's a new matrix with its own data. Unless you need to do some calculation with the whole dxy, there isn't much point in stacking dx and dy.

http://stackoverflow.com/comment/82064025
type: QuestionComment
type: Comment
has text: if I relist the environments afterwards, it is not there
comment on: http://stackoverflow.com/q/47549969
score: 0

http://stackoverflow.com/comment/82296461
type: Comment
has text: https://www.w3schools.com/html/html5_audio.asp and you need to include put absolute path to your file, that is reachable in browser.
score: 0
comment on: http://stackoverflow.com/q/47668766
type: QuestionComment

http://stackoverflow.com/q/47561787
has comment: http://stackoverflow.com/comment/82081354
has title: making a new modified version of a list without modifying the original list in python
tagged with: list
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47562370
answer count: 2
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47561935
has comment: http://stackoverflow.com/comment/82081491
has answer: http://stackoverflow.com/a/47561935
has body: i need to modify the contents of my og list into a different list w/out actually changing my og list. def createList(numbers): my_List= [0] * numbers for q in range(0, len(my_List)): myList[q]= randint (1, 21) q=q+1 return my_List def modifyList(newList): for i in range(0, len(newList)): if i % 2 == 0: newList[i]= newList[i] / 2 else: newList[i]= newList[i] * 2 return newList def main(): my_List= createList(10) print my_List newList= modifyList(my_List) print my_List print newList
has comment: http://stackoverflow.com/comment/82081578
type: Question
has answer: http://stackoverflow.com/a/47562370
tagged with: python
has comment: http://stackoverflow.com/comment/82081352

dynamic
tags question: http://stackoverflow.com/q/47679770
tag name: dynamic
type: Tag
tags question: http://stackoverflow.com/q/47638300

http://stackoverflow.com/comment/82087227
has text: Hello Noctis, that function worked great. It currently displays all the results. I'd like to know how to make it sum the RRC connections. Example if I enter 25.806 that it will sum all the record.rrc. I've tried various methods of sum to it and nothing works. Any final assistance is greatly appreciated.
type: Comment
comment on: http://stackoverflow.com/a/47561472
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82280204
type: QuestionComment
has text: you didn't have any borders when creating the buttons. You should submit az wxBORDER_SIMPLE style when they are created
type: Comment
comment on: http://stackoverflow.com/q/47660325
score: 1

http://stackoverflow.com/a/47657853
has body: I managed to circumvent the problem by downloading python3.4.4 and installing OpenCV version 3.1.0.5. No idea why later versions are problematic!
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47638580

http://stackoverflow.com/comment/82289651
score: 0
type: Comment
has text: I see y is always getting only empty lines\
type: AnswerComment
comment on: http://stackoverflow.com/a/47664145

http://stackoverflow.com/q/47671514
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82304027
has comment: http://stackoverflow.com/comment/87134017
has comment: http://stackoverflow.com/comment/82305469
has title: Fabric: How to edit file across machines?
score: 0
answer count: 1
tagged with: fabric
has comment: http://stackoverflow.com/comment/82306121
tagged with: devops
tagged with: python
has answer: http://stackoverflow.com/a/47674181
has comment: http://stackoverflow.com/comment/82302054
type: Question
has body: Is there a way to use Fabric to open editor and set text? I have to set new keys on 50+ servers and not willing to do it manually.
has comment: http://stackoverflow.com/comment/82303611

http://stackoverflow.com/q/47581938
has answer: http://stackoverflow.com/a/47581970
tagged with: input
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/82121565
downvote count: 4
upvote count: 0
score: -4
answer count: 1
tagged with: output
has comment: http://stackoverflow.com/comment/82121460
has title: Python: How can I get input between 1 and 10?
favorite count: 0
type: Question
tagged with: if-statement
has body: while True: print ("wanna exit? type a number that not between(1-11)range") side1 = input("Type 1st side: ") side2 = input("Type 2st side: ") side3 = input("Type 3rd side: ") a= [1,11] if (side1 not in a) : print("You exit,goodbye! ") break else: a = int(side1) b = int(side2) c= int(side3) perimeter = (a + b +c ) print ("The perimeter of triangle is :", perimeter ) i input a number between 1 and 10 , however it outputed "you exit...." again and again
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82121553

http://stackoverflow.com/comment/82483576
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47757771
has text: Thank you for your input! Well, my data is not in csv format but multiple hdf5 files from which I only read parts. I do not want to duplicate the data into csv files, because different parameters in my SceneGenerator would force me to write again all the data to a new set of csv files. My question is therefore precisely, how I can use a python generator for creating the input. I bet there is a more direct way than first writing all the training (and test) data into csv files.
type: Comment

http://stackoverflow.com/comment/82164404
comment on: http://stackoverflow.com/a/47585424
has text: yeah that is exactly what I wrote?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47678396
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47676225
has comment: http://stackoverflow.com/comment/82321712
has comment: http://stackoverflow.com/comment/82336226
upvote count: 1
has body: You can use Popen and shell=True to run the command From subprocess import Popen output='spice://127.0.0.1:5903' Command='remote-viewer'+' '+output #Proc=Popen(Command,shell=True) Proc=Popen(Command)

http://stackoverflow.com/q/47620089
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82198252
has title: Pycharm: ImportError: No module named 'src'
has body: I'm developping a chat app using Pycharm IDE. I have multiple directories in my project folder, and I want to perform import from some of dirs but I can't, I got this error . Note that I could do the import before, but now I can't. I don't know what happen. ImportError: No module named 'src' This is a picture of the error and the hierarchy of files.
tagged with: pycharm
has comment: http://stackoverflow.com/comment/82198165
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47620197

http://stackoverflow.com/comment/82196321
type: AnswerComment
comment on: http://stackoverflow.com/a/47618244
score: 1
type: Comment
has text: Don't you also need to change `variable = self.matinee_price` to `variable = self.matinee_price_var`?

http://stackoverflow.com/q/47619154
tagged with: pip
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82196655
duplicate of: http://stackoverflow.com/q/45917541
linked to: http://stackoverflow.com/q/20994716
has comment: http://stackoverflow.com/comment/82196651
type: UnansweredQuestion
tagged with: intel
tagged with: python
tagged with: conda
has body: Recently I installed intel-python distribution on my windows machine. I found that it supports conda and pip installs right off the start. I tried using both and they seemed to work fine. They both installed packages to the same python distribution, so I dont have much problem using any of them. But I was wondering if one was better than other in certain situations or in general?
answer count: 0
has title: Use conda or pip in intel-python?
upvote count: 2
score: 1
linked to: http://stackoverflow.com/q/45917541

datetimeindex
tags question: http://stackoverflow.com/q/47543572
tag name: datetimeindex
tags question: http://stackoverflow.com/q/47691724
tags question: http://stackoverflow.com/q/47620882
type: Tag

http://stackoverflow.com/a/47987890
type: Answer
has comment: http://stackoverflow.com/comment/83276728
score: 1
has body: I'm not sure I'm able to give a good answer to all your questions, but I found it interesting and took a look and here is my result. In general, import mod.sub or from mod import sub assumes that sub is a sub-module in a mod package. However, it could also mean that sub is a field/variable declared in a mod module. The presence of an __init.py__-file will denote that a folder is a package: The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package (...). I believe that, from werkzeug import security and import werkzeug.security both imports a module security, thus security.generate_password_hash is a known and valid attribute. Basically, from werkzeug.security import generate_password_hash imports that very attribute directly via the valid import statement. In the Werkzeug Quickstart docs, I found the following: Make sure to import all objects from the places the documentation suggests. It is theoretically possible in some situations to import objects from different locations but this is not supported. Further, Werkzeug transition to 1.0 states: Werkzeug originally had a magical import system hook that enabled everything to be imported from one module and still loading the actual implementations lazily as necessary. Unfortunately this turned out to be slow and also unreliable on alternative Python implementations and Google’s App Engine. Starting with 0.7 we recommend against the short imports and strongly encourage starting importing from the actual implementation module. Werkzeug 1.0 will disable the magical import hook completely. It appears that Werkzeug modifies how modules are loaded. (I speculate that this is not uncommon in big packages with contri…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47688957
has comment: http://stackoverflow.com/comment/83272013
has comment: http://stackoverflow.com/comment/83040932
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83034536
answers question: http://stackoverflow.com/q/47688957

http://stackoverflow.com/comment/82160919
comment on: http://stackoverflow.com/a/47601068
type: AnswerComment
has text: Thank you for your solution and time. Although with recursion you are not allowed to use while. The function itself should loop until: " n == 1" and then give back the list "syracuse_sequence".
score: 1
type: Comment

http://stackoverflow.com/comment/82151579
type: QuestionComment
score: 2
has text: Can you give more details on what `condition1` and `condition2` are?
type: Comment
comment on: http://stackoverflow.com/q/47596837

http://stackoverflow.com/comment/82128444
has text: @Prune .Sorry about that. Fixed it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47585163
score: 0

http://stackoverflow.com/comment/82154371
type: AnswerComment
score: 0
type: Comment
has text: I read what is in the link and I understand what you mean, but I do not know how to write the code with ajax for my dropdown..
comment on: http://stackoverflow.com/a/47597310

http://stackoverflow.com/comment/82243951
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47642667
type: AnswerComment
has text: RuntimeError: dictionary changed size during iteration

http://stackoverflow.com/comment/82079685
comment on: http://stackoverflow.com/q/47560842
has text: pip install ptpython, then use it in place of 'python' to enter the REPL. It handles indents and lots of other things more elegantly.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47548490
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django-debug-toolbar
favorite count: 0
type: Question
has body: I'm working on djangoproject.com website with Django Debug Toolbar configured in this dev settings. I founded an issue with django-debug-toolbar that I reported in the issue #796 of djanoproject.com but after some test I think it's only a configuration problem and we need help to solve it. All the below sentence are related with the code on branch master used locally. Django Debug Toolbar works well for www , for example, if I open http://www.djangoproject.dev:8000/ I can show the toolbar and open the SQL panel. If I try to open for example http://docs.djangoproject.dev:8000/en/1.11/ I can see the toolbar but I got 0: error if I try to open SQL panel This is the message I saw on browser console: Failed to load http://www.djangoproject.dev:8000/debug/render_panel/?store_id=212b2bb5adc54a3a81b97b6da5547d4c&amp;panel_id=SQLPanel: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://docs.djangoproject.dev:8000' is therefore not allowed access. I can see all the data if I open directly the url: http://www.djangoproject.dev:8000/debug/render_panel/?store_id=212b2bb5adc54a3a81b97b6da5547d4c&amp;panel_id=SQLPanel I think the problem is that the toolbar is trying to open a www. for the panel instead of a docs. url but I don't know how to update the settings to fix this. Can you suggest to us the code to fix this bug and to use django-debug-toolbar panels with in different third-level domains as for docs.djangoproject.com ?
has title: Broken django-debug-toolbar panels with sub domains configuration
accepted answer: http://stackoverflow.com/a/48129126
tagged with: django
tagged with: javascript
has answer: http://stackoverflow.com/a/48129126
tagged with: python
type: AnsweredQuestion
tagged with: cors
score: 1

http://stackoverflow.com/comment/82288852
has text: I haven't used fromfile, but I might try the example in the documentation yo u linked and see how similar the file it generates when using it save data is to what you have. I might expect it to store some metadata along with the data, meaning either "no", or you'd have to edit your file.
type: Comment
comment on: http://stackoverflow.com/q/47664026
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82070072
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47545329
has text: Ok, I managed to use this concept for the same record, now I need to copy it to the selected journal, I'll think on how to do that or open a new question for it

http://stackoverflow.com/comment/82135411
score: 0
has text: show your code and error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47588379

http://stackoverflow.com/a/47690655
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47672076
has body: I changed the program to: import multiprocessing import threading import time def consumer(l): counter = 0 while counter &lt; 20: time.sleep(5) del l[0 : len(l)/2+1] print("consumer l address {}".format(hex(id(l)))) print "consumer l: {}".format(l) counter += 5 def producer(l): for i in range(10): time.sleep(i) print("producer l address {}".format(hex(id(l)))) l.append(i) print "producer l: {}".format(l) if __name__=="__main__": mgr = multiprocessing.Manager() l = mgr.list() print("list address {}".format(hex(id(l)))) p = multiprocessing.Process(target=producer, args=(l,)) c = multiprocessing.Process(target=consumer, args=(l,)) p.start() c.start() p.join() c.join() print "done" Notice that I have used del instead of creating a new list and assigning it to the old one. I have also added address printing statements in the above code. If you run it as it is, you should see that the address of the list remains same everywhere as we are not recreating the list. If you change line number 9 back to l = l[len(l)/2:] and run the program, you should notice that the address of the lists for the consumer and producer changes after the first operation.
type: Answer
downvote count: 0

http://stackoverflow.com/a/47589259
score: 11
downvote count: 0
has comment: http://stackoverflow.com/comment/82233501
type: Answer
has comment: http://stackoverflow.com/comment/82232380
upvote count: 11
has comment: http://stackoverflow.com/comment/82150223
has comment: http://stackoverflow.com/comment/90170383
answers question: http://stackoverflow.com/q/47582274
has comment: http://stackoverflow.com/comment/82157010
has comment: http://stackoverflow.com/comment/90549220
has body: If the worksheet has only around 100,000 cells then you shouldn't have any memory problems. You should probably investigate this further. iter_cols() is not available in read-only mode because it requires constant and very inefficient reparsing of the underlying XML file. It is however, relatively easy to convert rows into columns from iter_rows() using zip. def _iter_cols(self, min_col=None, max_col=None, min_row=None, max_row=None, values_only=False): yield from zip(*self.iter_rows( min_row=min_row, max_row=max_row, min_col=min_col, max_col=max_col, values_only=values_only)) import types for sheet in workbook: sheet.iter_cols = types.MethodType(_iter_cols, sheet)

http://stackoverflow.com/q/47558824
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82076910
tagged with: python
has comment: http://stackoverflow.com/comment/82075469
tagged with: python-3.6
has title: Write in new column in a CSV python?
has body: I am trying to allow the user to input their score next to the name of the person on a CSV file. So far, I have got the following which enables me to input names on a new line on the CSV but I cannot find how to create a new column. I am using Python 3.6.3 import csv file = open ("test results.csv" , 'a') name = input('enter your name: ') file.write(name + "\n") file.close()
upvote count: 2
score: 2
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/11070527
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82075380
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82075431

http://stackoverflow.com/a/47689258
type: Answer
answers question: http://stackoverflow.com/q/47689007
upvote count: 1
downvote count: 1
has body: According to documentation: face_recognition.api.load_image_file(file, mode='RGB')[source] Loads an image file (.jpg, .png, etc) into a numpy array Parameters: file – image file name or file object to load mode – format to convert the image to. Only ‘RGB’ (8-bit RGB, 3 channels) and ‘L’ (black and white) are supported. Returns: image contents as numpy array https://face-recognition.readthedocs.io/en/latest/face_recognition.html#face_recognition.api.load_image_file So you need to pas image path or object. "{}" sims incomplete code to me.
score: 0

http://stackoverflow.com/q/47679719
has body: Using Cloudera Data Science Workbench, python 2 session i am calling a .sql file : Changing tables names for security: DROP TABLE IF EXISTS database1.table1 ; CREATE TABLE IF NOT EXISTS database1.table1 ; AS Select tb.column1 FROM database2.table2 as tb lIMIT 10 The queries execute fine in HUE but i get the following error when I call them from pyhive Pyhs2Exception: "Error while compiling statement: FAILED: ParseException line 1:84 missing EOF at ';' My guess is i have have to execute two separate statements when using pyhive, is there a way to combine sql statements when executing one cursor? here is the cursor part from python, it works fine calling each of the statements if i run them alone" the drop or create statements": cursor = conn.cursor() cursor.execute((open("sandbox/test2_table_create.sql").read()))
tagged with: hql
has comment: http://stackoverflow.com/comment/82320281
type: Question
has comment: http://stackoverflow.com/comment/82320356
has comment: http://stackoverflow.com/comment/82319902
has answer: http://stackoverflow.com/a/47820660
tagged with: python
has comment: http://stackoverflow.com/comment/82318984
has comment: http://stackoverflow.com/comment/82320154
type: AnsweredQuestion
score: 0
has title: Error while compiling statement: FAILED: ParseException line 1:84 missing EOF at
accepted answer: http://stackoverflow.com/a/47820660
tagged with: pyhive
answer count: 1

http://stackoverflow.com/comment/82159654
score: 0
has text: what have you tried so far? what results are you getting? what do you expect as the final result?
type: QuestionComment
comment on: http://stackoverflow.com/q/47600529
type: Comment

http://stackoverflow.com/q/47570285
score: 0
tagged with: authentication
tagged with: scrapy
has title: Python Scrapy Login to website then scrape data, Can't add new url to scrapte
has comment: http://stackoverflow.com/comment/82135478
type: Question
tagged with: python
tagged with: request
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82098229
has body: I want to scrape some data from my own website,I have already finish login def start_requests(self): return [Request("http://localhost:8080/website/admin.php?s=/Public/login.html", cookies={'PHPSESSID': '4titclg3ihgdprp5308vnp4gj6', 'onethink_admin___forward__': '%2Fwebsite%2Fadmin.php%3Fs%3D%2FMenu%2Findex%2Fpid%2F16.html'}, callback=self.post_login)] but when I scrape data from the other pages, I try to use: yield scrapy.Request(url,callback) to add a new request to downloader,the method wasn't started def post_login(self, response): if response.url != "http://localhost:8080/website/admin.php?s=/Public/login.html": self.go_main(response) else: return [FormRequest.from_response(response, method='POST', headers=self.headers, formdata={ 'username': 'admin', 'password': '123456' }, callback=self.after_login, dont_filter=True )] def after_login(self, response): log.info(response.body) json_array = json.loads(str(response.body, encoding="utf-8")) if json_array['status'] == 1: create_excel_file() self.make_url_to_join(response) else: log.info("error code:" + str(json_array['status'])) def go_main(self, response): self.make_url_to_join(response) def make_url_to_join(self, response): for con in self.config: register_url = "http://localhost:8080/website/admin.php?s=/Platform/promote_statistics&amp;timestart=" + str( yesterday) + "&amp;timeend=" + str(yesterday) + "&amp;promote_id=" + con['id'] spend_url = "http://localhost:8080/website/admin.php?s=/Platform/promotepay_statistics&amp;timestart=" + str( yesterday) + "&amp;timeend=" + str(yesterday) + "&amp;promote_id=" + con['id'] log.debug(register_url) yield scrapy.Request(register_url, callback=self.parse_register_item) yield scrapy.Request(spend_url, callback=self.parse_spend_item) def parse_register_item(self, response): log.info("register_data_url：" + response.url) def parse_spend_item(self, response): log.info("spend_data_url：" + response.url) every time I scrape data,the make_url_to_join can't run and I can't add new …
has comment: http://stackoverflow.com/comment/82128469
answer count: 0

http://stackoverflow.com/comment/82221701
type: Comment
type: AnswerComment
score: 0
has text: I did put txindex=1 in the bitcoin.conf file for my second blockchain. However I started making request once only 1000 block or so had loaded. I will try with txindex in argument and give a shot to this getblock tonight
comment on: http://stackoverflow.com/a/47630839

http://stackoverflow.com/comment/82068250
comment on: http://stackoverflow.com/q/47555614
type: Comment
type: QuestionComment
score: 0
has text: Pygame doc: [music](http://pygame.org/docs/ref/music.html): "Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead."

http://stackoverflow.com/comment/82059483
comment on: http://stackoverflow.com/q/47551406
score: 0
has text: @pushpendrachauhan I also try with text file but return's same output
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47620588
tagged with: http://stackoverflow.com/tag/json
tagged with: difflib
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82199688
has comment: http://stackoverflow.com/comment/82200064
answer count: 0
has comment: http://stackoverflow.com/comment/82199186
has comment: http://stackoverflow.com/comment/82199185
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I am developing a program which searches the meaning of words(word dictionary) and if I input a wrong spelling of the word, it corrects and suggests the correct word. However the program crashes after doing a similarity check. data.json is the python dictionary file containing words as keys and their definitions as values. Below is my code: import json from difflib import get_close_matches data = json.load(open("data.json")) def func(key): key= key.lower() if key in data: print(data[key]) elif len(get_close_matches(key,data.keys())) &gt; 0: ans = input("Did you mean %s instead?" % get_close_matches(key, data.keys())[0]) if ans == "yes": print([data(get_close_matches(key, data.keys()))[0]]) else: print("This word does not exist") else: print("This word does not exist") key = input("Enter key:") func(key) Below is the output when I run the code: Enter key:precipitattion Did you mean precipitation instead?yes Traceback (most recent call last): File "C:/Users/DELL-7450/PycharmProjects/Plural bo Minalowich/Test.py", line 24, in &lt;module&gt; func(key) File "C:/Users/DELL-7450/PycharmProjects/Plural bo Minalowich/Test.py", line 15, in func print([data(get_close_matches(key, data.keys()))[0]]) TypeError: 'dict' object is not callable Process finished with exit code 1 However, below is a similar code which works, not sure what Im missing: import json from difflib import get_close_matches data = json.load(open("data.json")) def translate(w): w = w.lower() if w in data: return data[w] elif len(get_close_matches(w, data.keys())) > 0: yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0]) if yn == "Y": return data[get_close_matches(w, data.keys())[0]] elif yn == "N": return "The word doesn't exist. Please double check it." else: return "We didn't understand your entry." else: return "The word doesn't exist. Please double check it." word = input("Enter word: ") translate(word) I am not sure what I am missing here. Any help wou…
has title: Getting TypeError when the program tries to print get_close_matches
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/47611647
linked to: http://stackoverflow.com/q/39368516
tagged with: emr
tagged with: apache-spark
score: 0
has title: How to set number of splits and reducers in pyspark
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47613472
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47612233
has body: I'm trying to run pyspark on amazon EMR instances to read data from dynamodb and would like to know how to set the number of splits and workers in my code? I followed the instructions from the following two documentations to come with the code below which currently connects to a dynamoDB and reads the data. connecting to dynamoDB from pyspark and Pyspark documentation from pyspark.context import SparkContext sc = SparkContext.getOrCreate() conf = {"dynamodb.servicename": "dynamodb", "dynamodb.input.tableName": "Table1", "dynamodb.endpoint": "https://dynamodb.us-east- 1.amazonaws.com", "dynamodb.regionid":"us-east-1", "mapred.input.format.class": "org.apache.hadoop.dynamodb.read.DynamoDBInputFormat", "mapred.output.format.class": "org.apache.hadoop.dynamodb.write.DynamoDBOutputFormat" orders = sc.hadoopRDD(inputFormatClass="org.apache.hadoop.dynamodb.read.DynamoDBInputFormat", keyClass="org.apache.hadoop.io.Text", valueClass="org.apache.hadoop.dynamodb.DynamoDBItemWritable", conf=conf) I was trying to change the values of instances and parallelism of SparkConf class but not sure how that will affect the SparkContext variable SparkConf().set('spark.executor.instances','4') SparkConf().set('spark.default.parallelism', '128') to set the splits and reducers, but it doesn't seem to change it.
linked to: http://stackoverflow.com/q/34467573
has comment: http://stackoverflow.com/comment/127218280

http://stackoverflow.com/comment/82276719
has text: @BrandonDube We were just needed to swap the positions of inputs there. Edited.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47646944
score: 0

http://stackoverflow.com/comment/82176675
type: QuestionComment
has text: Can you please post the FULL traceback as an edit to your question?
score: 0
comment on: http://stackoverflow.com/q/47608865
type: Comment

http://stackoverflow.com/comment/82352426
has text: I'm just starting work now, so I can't write out a full answer. A few things I'll say though: instead of using the underscore naming ("df_square"), I'd just call the dictionary itself "squared_df" or something. Then you'd do `squared_df[your_key]`. Giving every key a "_square" suffix just make it harder to use, since then you have to concatenate the key together every time you want to access a value. That convention may make sense in SuperMongo, but that's likely since their dynamic variables create globals, and having a underscore suffix prevents name collisions.
comment on: http://stackoverflow.com/q/47675185
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82258922
score: 0
has text: Oauth DB tables should be present in your resource server, only the records are created in AUTH server .. because you have INTROSPECTION details in settings
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47587486

http://stackoverflow.com/q/47562434
favorite count: 0
has answer: http://stackoverflow.com/a/47562571
has body: I have a list of strings like this: l = ['car58=C:/Files/SB.car58- 094.38.JPG', 'bike53=C:/Files/SB.bike53- 006.33.JPG', 'car46=C:/Files/SB.car46- 88.22.JPG', 'bike12=C:/Files/SB.bike12- 006.33.JPG', 'acc9=C:/Files/SB.acc9- 006.33.JPG'] I'm trying to sort the list using the start (position 0) of each string up to the "=" character ignoring all characters after it, so that the outcome is: s = ['acc9=C:/Files/SB.acc9- 116.95.JPG', 'bike12=C:/Files/SB.bike12- 006.33.JPG', 'bike53=C:/Files/SB.bike53- 002.12.JPG', 'car46=C:/Files/SB.car46- 88.22.JPG', 'car58=C:/Files/SB.car58- 094.38.JPG'] Edit: The answer provided by Ajax1234 solved my issue: s = sorted(l, key=lambda x:x[:x.index('=')])
type: Question
has title: Sort list of strings
tagged with: python
possible better answer: http://stackoverflow.com/a/47562571
tagged with: list
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47562470
upvote count: 1
score: 1
tagged with: sorting
has answer: http://stackoverflow.com/a/47562470

http://stackoverflow.com/comment/82252915
comment on: http://stackoverflow.com/a/47646944
has text: Thank you -- this answer is excellent. It's interesting that tensordot beats regular dot with transpose here, speed-wise.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47689875
has comment: http://stackoverflow.com/comment/82341297
has comment: http://stackoverflow.com/comment/82341095
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82341237
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: django
tagged with: multi-select
has comment: http://stackoverflow.com/comment/82340474
favorite count: 0
has answer: http://stackoverflow.com/a/47706531
has title: Django 2.0 multiselect issue
tagged with: django-crispy-forms
tagged with: python
has body: I am testing 2.0 and have encountered the same error in two different places. It has to do with multi-select. I get the following error. Exception Value: not enough values to unpack (expected 2, got 0) here is the code from crispy-forms-foundation {% if not field|is_checkbox and not field|is_checkboxselectmultiple %} {% crispy_field field %} {% endif %} the other package error was from: localflavor.us.models import USStateField, PhoneNumberField, USZipCodeField What do I need to change to get these to work properly in 2.0? Cheers
score: -1

http://stackoverflow.com/q/47624723
answer count: 1
type: Question
has title: value not added to dict using int boolean decision mysteriously - python
tagged with: python
tagged with: dictionary
tagged with: boolean
has body: I am trying to increment values to 4 dictionaries here (the dictionary is di_A1, di_A2, di_B1, di_B2). I am checking lines in a file at positions 3-9 in for the first name of the parent, then position 11 for the sex, and 12-14 for the age. Position 11 will always be 1 or 2. 1 - male, 2 - female. Position 12-14 will contain a number from 001 > 150 for age. The first of those characters determines if the "parent" should be saved to an A or B dictionary. The remaining 3 values determine the age of the parent, which are grouped into values of over or under 50 years of age. dictionaries: di_A1 stores dad names, under 50; di_A2 stores dad names, over 50; di_B1 stores mom names, under 50; di_B2 stores mom names, over 50; Later I print these to a .csv file in these 5 columns: first name count of dads 50 or under count of dads 50 or over count of moms 50 or under count of moms 50 or over The very first piece where I save them to the dictionary is not working. I think it's when I check the age value that is broken. def main(): import re # I use this later, but maybe I should be using it here? # find all files to check filelist = glob.glob("FOLDER/subfolder/names*/*.TXT") di_A1 = {} di_A2 = {} di_B1 = {} di_B2 = {} for file in filelist: infile = open(file,"r") for line in infile: sex_age = int(line[10:14]) #11 stores sex, 12-14 store age firstname = line[2:9] # 3-9 store first name if (sex_age &lt; 1051) : #if male 50 or under di_A1[firstname] = di_A1.get(firstname,0) + 1 elif (sex_age &lt; 1150) : #if male 50 or over di_A2[firstname] = di_A2.get(firstname,0) + 1 elif (sex_age &lt; 2051) : #if female 50 or under di_B1[firstname] = di_B1.get(firstname,0) + 1 elif (sex_age &lt; 2150) : #if female 50 or over di_B2[firstname] = bi_B2.get(firstname,0) + 1 infile.close() more after this, but I'm pretty sure that stuff is working Right now, nothing is saved in any of the dictionaries. What am I doing wrong? I should note that I was thinking of breaking this down further to more age g…
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47625443

join
type: Tag
tags question: http://stackoverflow.com/q/47561694
tag name: join
tags question: http://stackoverflow.com/q/47643952
tags question: http://stackoverflow.com/q/47619920
tags question: http://stackoverflow.com/q/47598556
tags question: http://stackoverflow.com/q/47695075
tags question: http://stackoverflow.com/q/47542543
tags question: http://stackoverflow.com/q/47645899
tags question: http://stackoverflow.com/q/47560231

http://stackoverflow.com/a/47629699
accepted answer of: http://stackoverflow.com/q/47629640
type: Answer
answers question: http://stackoverflow.com/q/47629640
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You can iterate through the keys and values of a dict using items(). for i, js in info.items(): for j in js: # Make query with j (In Python 2 you might prefer to use iteritems() instead of items().) If you don't need to make use of the keys at all, you could just use values (or itervalues for Python 2). for js in info.values(): for j in js: # Make query with j Maybe a list comprehension would work for you; it is impossible to tell without knowing what "Make query with j" entails.

http://stackoverflow.com/comment/82294929
has text: While I disagree with 'unclear' vote, you should provide your own attempt.
type: Comment
comment on: http://stackoverflow.com/q/47667980
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82317760
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47679332
has text: `proceed << proceed2` is not doing what you think it is doing
score: 7

http://stackoverflow.com/q/47692572
has comment: http://stackoverflow.com/comment/87418406
linked to: http://stackoverflow.com/q/50200946
tagged with: heroku
answer count: 0
score: 3
upvote count: 3
favorite count: 0
type: Question
has body: I have developed VK bot on language python and deploy to Heroku after the command heroku ps:scale web=1, the script runs and works few seconds and after few seconds script stops proccess with log Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch on Python Process exited with status 137 That is my Procfile: web: python bot.py I changed the Procfile to: web: python bot.py -p $PORT, but It did not help
type: UnansweredQuestion
downvote count: 0
has title: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch on Python
tagged with: python

http://stackoverflow.com/a/47659955
answers question: http://stackoverflow.com/q/47659914
has body: Your path indicates that you are searching a relative path (starts with .) and also an absolute path (starts with C:). You can't do both simultaneously. Try: for filename in glob.glob('C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'):
has comment: http://stackoverflow.com/comment/82278707
type: Answer
score: 0

http://stackoverflow.com/q/47671372
has comment: http://stackoverflow.com/comment/82302115
tagged with: python
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47675045
tagged with: pandas
upvote count: 3
downvote count: 0
has title: stuck in pandas if loop all() any()?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47671846
possible better answer: http://stackoverflow.com/a/47671846
score: 3
accepted answer: http://stackoverflow.com/a/47675045
has body: I try to write some basic functions and found me know completely stuck in a quite simple problem regarding the use of if elif else on python pandas dataframe. Here is an example: dummy data: d = {'x': [1, 2, 0, -2, -2], 'y': [3, 4, 5, 4, -4]} df = pd.DataFrame(data=d) my function: def cart2sph(data): #ceval indicates using numerical expressions newDF = pd.DataFrame() x = data['x'].astype(float) y = data['y'].astype(float) if (x == 0).all(): newDF['angle'] = sign(y)* pi / 2 else: newDF['angle'] = arctan(y/x) if (x &lt; 0 and y &gt;= 0).all(): newDF['angle'] += pi elif (x &lt; 0 and y &lt; 0).all(): newDF['angle'] -= pi return newDF I always get the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 11, in cart2sph File "C:\Users\tpotrusil\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). ...and can´t see the problem!?! Very thankful for any help!

http://stackoverflow.com/a/47647175
has body: You are trying to do matrix multiplication. So you should make use of tf.matmul. The operation of tf.multiply does elementwise multiplication for which both the tensor's shapes must be same.
downvote count: 0
answers question: http://stackoverflow.com/q/47646183
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/47545838
has body: Per the docs, build_fn should be returning a model. It should not be a model. build_fn should construct, compile and return a Keras model, which will then be used to fit/predict. One of the following three values could be passed to build_fn Model instances do not return themselves or new models when you invoke __call__. I believe your intention is to do this: def get_model(): model = Model(sequence_input, preds) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc']) print("model fitting - Bidirectional LSTM") model.summary() return model #estimate the accuracy estimator = KerasClassifier(build_fn=get_model, epochs=50, batch_size=64, verbose=2)
downvote count: 0
has comment: http://stackoverflow.com/comment/82050908
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47545540
answers question: http://stackoverflow.com/q/47545540
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/47635766
has body: I'm working on web scraping using selenium and phantomJs, everything is going as I want. But now I'm stuck in a problem which is about clicking on a button that downloads a file and get that file to my system folders. While searching I found the wget library that can do such a thing but I had a problem of the dowload url cause it's not an http link but a javascript link, here is my code : s1 = BeautifulSoup(self.driver.page_source, "html.parser") s2=s1.find('a', {"id":"ctl0_CONTENU_PAGE_EntrepriseDownloadDce_completeDownload"}) f=s2.get('href') #x=self.driver.find_element_by_name("ctl0_CONTENU_PAGE_EntrepriseDownloadDce_completeDownload") wget.download(f,out="C://Users/users MGE/Téléchargements") and this is the error I'm getting: raise URLError('unknown url type: %s' % type) urllib.error.URLError: Can anyone help me solve this problem of wget, or find another solution to get the downloaded file when clicking on the dowload button?
has title: Python: get my dowloaded file to my file systems using phantomjs and selenium
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: file
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/82235963
has comment: http://stackoverflow.com/comment/82230598
tagged with: phantomjs
score: 0
has comment: http://stackoverflow.com/comment/82270382

http://stackoverflow.com/a/47676417
upvote count: 2
has comment: http://stackoverflow.com/comment/82311744
downvote count: 0
answers question: http://stackoverflow.com/q/47676270
has body: You could use re.sub() with a lookahead assertion: &gt;&gt;&gt; import re &gt;&gt;&gt; s = '(X_xy09 and X_foobar or (X_abc123 and X_something))' &gt;&gt;&gt; re.sub(r'\b[A-Z]_(?=[a-zA-Z0-9])', '', s) '(xy09 and foobar or (abc123 and something))' from the docs: (?=...) Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
type: Answer
score: 2

payment-gateway
tags question: http://stackoverflow.com/q/47593342
type: Tag
tag name: payment-gateway

http://stackoverflow.com/q/47680917
tagged with: python
has body: I'm making a basketball stats database, and have a table in SQL with the player's totals from all of their games combined. I'm having trouble adding to it, however. I use a temporary table for each game, and then I need to add all of the temporary values to the player's total table. How would I do this? I have tried many methods, each of which throw an error. Here are a few: (live_players is the temporary table, and here I'm only trying to join the points column.) db.execute("UPDATE players JOIN live_players AS t1 ON players.player_id = t1.player_id SET points = points + t1.points") db.execute("MERGE INTO players USING live_players ON players.player_id = live_players.player_id WHEN MATCHED THEN UPDATE SET points = points + live_players.points")
linked to: http://stackoverflow.com/q/1293330
type: UnansweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47681516
tagged with: mysql
has comment: http://stackoverflow.com/comment/82322901
type: Question
has answer: http://stackoverflow.com/a/47681376
linked to: http://stackoverflow.com/q/982919
has title: SQL Add to Existing Table from Temp Table

http://stackoverflow.com/q/47663110
has comment: http://stackoverflow.com/comment/82285878
tagged with: python
has comment: http://stackoverflow.com/comment/82286525
has body: I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list: for string in tr[30].strings: if string == 'X': print(string) print(string.next()) Getting error: TypeError: 'NavigableString' object is not callable
has answer: http://stackoverflow.com/a/47663158
has comment: http://stackoverflow.com/comment/82294877
has answer: http://stackoverflow.com/a/47663375
answer count: 2
upvote count: 2
type: UnansweredQuestion
score: 1
has title: Getting the next item in a python for loop
has comment: http://stackoverflow.com/comment/82285575
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1011938
has comment: http://stackoverflow.com/comment/82285492

http://stackoverflow.com/a/65931424
has comment: http://stackoverflow.com/comment/130618098
has comment: http://stackoverflow.com/comment/130618612
has comment: http://stackoverflow.com/comment/119934963
upvote count: 38
type: Answer
has comment: http://stackoverflow.com/comment/135453557
score: 33
has comment: http://stackoverflow.com/comment/135508084
has body: A bit late to the party with a couple of single-line suggestions that don't require writing a custom function nor the use of a loop and work on Linux: pathlib.Path.glob() takes interleaved symbols in brackets. For the case of ".txt" and ".xls" suffixes, one could write files = pathlib.Path('temp_dir').glob('*.[tx][xl][ts]') If you need to search for ".xlsx" as well, just append the wildcard "*" after the last closing bracket. files = pathlib.Path('temp_dir').glob('*.[tx][xl][ts]*') A thing to keep in mind is that the wildcard at the end will be catching not only the "x", but any trailing characters after the last "t" or "s". Prepending the search pattern with "**/" will do the recursive search as discussed in previous answers.
has comment: http://stackoverflow.com/comment/135453638
has comment: http://stackoverflow.com/comment/135546006
downvote count: 5
answers question: http://stackoverflow.com/q/47655205
has comment: http://stackoverflow.com/comment/127516075

http://stackoverflow.com/q/47654846
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82268767
has comment: http://stackoverflow.com/comment/82269890
has body: I've been trying to be able to feed my own images in some tensorflow code to look how the code would react to my own images instead of the MNIST set. I've been able to import images(i think) into tensorflow but I have two placeholders that should get my image data and label data. I tried to use feed_dict(which still seems right to me) to be able to use my data in the rest of my code but it won't accept any data I feed it. I know I can't feed it a Tensor and apparently not a batch but the only way I can think of to make this work is to feed it a list. I saw feed_dict is able to use numpy arrays but im not sure how i should approach converting data to a numpy array. I'm new to TensorFlow and python so please forgive any mistakes I made, I'm still learning how everything works. with tf.name_scope('Image_Data_Input'): def read_labeled_image_list(image_list_file): print('read_labeled_image_list function opened') f = open(image_list_file, 'r') print('image_list_file opened') filenames = [] labels = [] print('Arrays formed') for line in f: filename, label = line[:-1].split(' ') filenames.append(filename) labels.append(label) print('Lines deconstructed') return filenames, labels def read_image(input_queue): label = input_queue[1] file_contents = tf.read_file(input_queue[0]) decoded_image = tf.image.decode_jpeg(file_contents, channels=3) print('Image decoded to JPEG') decoded_image.set_shape([2560, 1440, 3]) decoded_image = tf.image.resize_images(decoded_image, [128, 128]) return decoded_image, label image_list, label_list = read_labeled_image_list(image_list_file) images = tf.convert_to_tensor(image_list, dtype=tf.string) labels = tf.convert_to_tensor(label_list, dtype=tf.string) input_queue = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True) image, label = read_image(input_queue) The indentation behaved a little weird when i pasted my code so I'm not sure everything is properly placed. Well now I have these placeholder: with tf.name_scope('inpu…
tagged with: python
has comment: http://stackoverflow.com/comment/82269789
has comment: http://stackoverflow.com/comment/82268555
has title: Feed_dict doesnt accept my data
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/47660844
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47660844

http://stackoverflow.com/a/47660220
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: You need to save a reference to the window or it will be garbage collected when on_click() finishes executing. The easiest way is to store it in App through the use of self @pyqtSlot() def on_click(self): self.ex1 = App1()
has comment: http://stackoverflow.com/comment/82308364
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47660050
has comment: http://stackoverflow.com/comment/82308040
answers question: http://stackoverflow.com/q/47660050

http://stackoverflow.com/q/47571018
has comment: http://stackoverflow.com/comment/82104119
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82099320
has comment: http://stackoverflow.com/comment/82103632
has comment: http://stackoverflow.com/comment/82105974
has comment: http://stackoverflow.com/comment/82103113
tagged with: tensorflow
type: Question
tagged with: one-hot-encoding
has comment: http://stackoverflow.com/comment/82109237
accepted answer: http://stackoverflow.com/a/47576804
has title: Does Tensorflow use only one hot encoding to store labels?
has body: I have just started working with Tensorflow, with Caffe it was super practical reading in the data in an efficient manner but with Tensorflow I see that I have to write data loading process myself, creating TFRecords, the batching, the multiple threats, handling those threads etc. So I started with an example, inception v3, as they handle the part to read in the data. I am new to Tensorflow and relatively new to Python, so I feel like I don't understand what is going on with this part exactly (I mean yes it extends the size of the labels to label_index * no of files -but- why? Is it creating one hot encoding for labels? Do we have to? Why doesn't it just extend as much for the length or files as each file have a label? Thx. labels.extend([label_index] * len(filenames)) texts.extend([text] * len(filenames)) filenames.extend(filenames) The whole code is here: https://github.com/tensorflow/models/tree/master/research/inception The part mentioned is under data/build_image_data.py and builds image dataset from an existing dataset as images stored under folders (where foldername is the label): https://github.com/tensorflow/models/blob/master/research/inception/inception/data/build_image_data.py
answer count: 1
has answer: http://stackoverflow.com/a/47576804
tagged with: python
tagged with: tensorflow-datasets

http://stackoverflow.com/comment/82095641
type: Comment
type: QuestionComment
score: 2
has text: *tie-braker* policy?
comment on: http://stackoverflow.com/q/47569108

http://stackoverflow.com/comment/82237656
comment on: http://stackoverflow.com/q/47639244
has text: thats odd because when I print it prints 15 and even if i put it as "for col in range(15):" it still does not work
score: 0
type: Comment
type: QuestionComment

databricks
tag name: databricks
tags question: http://stackoverflow.com/q/47620564
type: Tag

http://stackoverflow.com/a/52630964
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47564740
has body: Consider using: import tkinter as tk and then, prefix all your calls like: root = tk.Tk() or, variableName.pack(side = tk.LEFT) and so on...
score: 5
downvote count: 0

http://stackoverflow.com/a/47666778
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47663553
has body: Stock Python has a convenience class, itemgetter: In [27]: from operator import itemgetter In [28]: L = [0,1,2,3,4,5,6,7,8,9] In [29]: nArr=np.array([0,-1,2,6]) In [30]: itemgetter(*nArr) Out[30]: operator.itemgetter(0, -1, 2, 6) In [31]: itemgetter(*nArr)(L) Out[31]: (0, 9, 2, 6) Internally it does something equivalent to the list comprehension: In [33]: [L[x] for x in nArr] Out[33]: [0, 9, 2, 6] So it isn't a fast operation like the array indexing (look at its code). It may be most useful as a way of doing sort or other operations where you'd like to define a key function that fetches multiple values. https://stackoverflow.com/a/47585659/901925 Make a random nested list: In [54]: arr = np.random.randint(0,10,(4,4)) In [55]: L = arr.tolist() In [56]: L Out[56]: [[9, 5, 8, 4], [1, 5, 5, 8], [8, 0, 5, 8], [1, 4, 5, 1]] lexical sort by 'column': In [57]: sorted(L) Out[57]: [[1, 4, 5, 1], [1, 5, 5, 8], [8, 0, 5, 8], [9, 5, 8, 4]] lexical sort by 'columns' 2 and 1 (in that order): In [59]: sorted(L, key=itemgetter(2,1)) Out[59]: [[8, 0, 5, 8], [1, 4, 5, 1], [1, 5, 5, 8], [9, 5, 8, 4]]
accepted answer of: http://stackoverflow.com/q/47663553
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/82334581
type: Comment
type: AnswerComment
has text: @user6456568 - Sorry, but I'm not the best person to help with decode issues. My apologies...
score: 0
comment on: http://stackoverflow.com/a/47686920

http://stackoverflow.com/a/47689033
upvote count: 0
has comment: http://stackoverflow.com/comment/82337283
has comment: http://stackoverflow.com/comment/82337357
answers question: http://stackoverflow.com/q/47688824
downvote count: 1
has body: Using the np.subtract(X,Y) almost halves the execution time. It is faster than X-Y but the speed is till lower than the dot product. Might help
type: Answer
score: -1

http://stackoverflow.com/comment/82298961
comment on: http://stackoverflow.com/q/47656295
type: QuestionComment
has text: And another comment... You realize that with your line ```return sklearn.model_selection.train_test_split(X, y, test_size = 1 - train_ratio, random_state=0``` you may well end up with a training set containing only zero labelled observation right? That may also be the source why your model labels everything as zero. **EDIT**: I checked and you actually get 4 of your observations that are labelled as 1. Still a very unbalanced dataset.
score: 0
type: Comment

http://stackoverflow.com/a/47623682
score: 1
has body: Your issue is that in Python 2.x, integer division does not return an exact floating point result. Casting one value to a float shows that the division does not exactly equal 300: &gt;&gt;&gt; float(1512296383)/5040987 300.0000561397996 Therefore when you do 1512296383/5040987, you'll get the integer 300, which will introduce a small error.
answers question: http://stackoverflow.com/q/47623638
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82205212
has comment: http://stackoverflow.com/comment/82205263

http://stackoverflow.com/a/47594135
has body: I don't have the inclination to go and download the entire CIFAR dataset onto this laptop, so I'll illustrate with manually constructed data. y_train = np.random.randint(0,10,100) #100 samples with values 0-9 x_train = np.random.randint(0,255,32*32*3*100).reshape(100,-1) #100 samples with quite a lot of features. Thought CIFAR images were 32*32*3.. num_classes = y_train.max()+1 #10 y_train = np_utils.to_categorical(y_train, num_classes) x_train = x_train.astype('float32') x_train /= 255 model = Sequential() model.add(Dense(10, input_shape=x_train.shape[1:], activation='relu')) model.add(Dense(10,activation='softmax')) sgd = optimizers.SGD(lr = 0.001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer='nadam',metrics=['accuracy']) model.summary() earlyStopping=EarlyStopping(monitor='val_loss', patience=10, verbose=2, mode='auto') print("Training...") model.fit(x_train, y_train, batch_size=32, nb_epoch=1000, verbose=2,validation_split=0.2,callbacks=[earlyStopping]) Proceeds without a hitch. Key here was the reshape on the x_train data.
answers question: http://stackoverflow.com/q/47593493
type: Answer
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82146042
has comment: http://stackoverflow.com/comment/82145695
has comment: http://stackoverflow.com/comment/82145829
accepted answer of: http://stackoverflow.com/q/47593493

http://stackoverflow.com/a/47982055
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82939452
has body: Here is my solution: from collections import defaultdict string = "103264685134845354863" d = defaultdict(int) for elt in range(len(string)-2): d[string[elt:elt+3]] += 1 d = {key: d[key] for key in d.keys() if d[key] &gt; 1} With a bit of creativity in for loop(and additional lookup list with True/False/None for example) you should be able to get rid of last line, as you only want to create keys in dict that we visited once up to that point. Hope it helps :)
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47581326

http://stackoverflow.com/q/47597689
tagged with: sortedcontainers
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47601177
has answer: http://stackoverflow.com/a/47601177
downvote count: 1
answer count: 1
favorite count: 0
tagged with: numpy
has body: I have a numpy array with the shape n×2, a bunch of tuples of length 2, that I would like to transfer to SortedList. So the goal is to create a SortedList with integer tuples of length 2. The problem is that the constructor of SortedList checks the truth value of each entry. This works fine for one-dimensional arrays: In [1]: import numpy as np In [2]: from sortedcontainers import SortedList In [3]: a = np.array([1,2,3,4]) In [4]: SortedList(a) Out[4]: SortedList([1, 2, 3, 4], load=1000) But for two dimensions, when each entry is an array, there is no clear truth value and SortedList is uncooperative: In [5]: a.resize(2,2) In [6]: a Out[6]: array([[1, 2], [3, 4]]) In [7]: SortedList(a) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-7-7a4b2693bb52&gt; in &lt;module&gt;() ----&gt; 1 SortedList(a) /home/me/miniconda3/envs/env/lib/python3.6/site-packages/sortedcontainers/sortedlist.py in __init__(self, iterable, load) 81 82 if iterable is not None: ---&gt; 83 self._update(iterable) 84 85 def __new__(cls, iterable=None, key=None, load=1000): /home/me/miniconda3/envs/env/lib/python3.6/site-packages/sortedcontainers/sortedlist.py in update(self, iterable) 176 _lists = self._lists 177 _maxes = self._maxes --&gt; 178 values = sorted(iterable) 179 180 if _maxes: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() My current workaround is to convert each line to a tuple manually: sl = SortedList() for t in np_array: x, y = t sl.add((x,y)) However, this solution offers some room for improvement. Does anyone have an idea how to solve this problem without explicitly unpacking all the arrays into tuples?
type: Question
tagged with: python
score: -1
has title: Populating a SortedLIst from an n×2 numpy array

http://stackoverflow.com/comment/82358908
type: AnswerComment
score: 0
has text: Thanks!This worked as well. I changed it slightly to: df.set_index('ID')['LINKED_TO'].str.split(';').to_dict()
type: Comment
comment on: http://stackoverflow.com/a/47687031

http://stackoverflow.com/q/47642570
downvote count: 0
accepted answer: http://stackoverflow.com/a/47643497
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82243970
tagged with: arrays
tagged with: python
has title: Replace 0 by the last value seen in the array (similar to the fillna method with NaN values) in pandas dataframes
has body: I've been trying to create a new boolean array from two initial boolean arrays (df1 and df2) , following this rule: -If the last True value was seen in df1, the value in df3 is True -If the last True value was seen in df2, the value in df3 is False I found a way to do this by substracting the two arrays, then remplacing the 0 values by NaN values, using the .fillnamethod to fill the NaN values, and finally remplacing the -1 values by 0. The code looks like this (with random arrays given as examples): import pandas as pd import matplotlib.pyplot as plt import numpy as np df1 = pd.Series((1,1,1,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,1,0,0, 0,0,0,0,0,1,1,1,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,1,1,1,0,0,0,0)) df2 = pd.Series((0,0,0,0,0,0,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,1,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,0)) df3 = df1-df2 df3 = df3.replace(0,np.nan).fillna(method='ffill') df3 = df3.replace(-1,0) It does the trick and returns me the array I want, however it seems not optimized to remplace values several times like this, and working around thefillna method to do what I want. Would anyone know a way to do this more 'properly', and if there is a method similar to the fillna one, but on other values than NaN? Optimization is really important on this problem, as I'll go through this process a lot of time.
has answer: http://stackoverflow.com/a/47643497
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pandas
answer count: 1

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/47576775

http://stackoverflow.com/q/47588243
has comment: http://stackoverflow.com/comment/82134356
tagged with: python
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/47588937
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47588297
possible better answer: http://stackoverflow.com/a/47588297
has body: Here is my code to print the reverse of DNA sequence, only if the string contain character ["A","T","G","C"] dna=input("Enter DNA sequnce") [print(dna[::-1]) for x in dna if x in["A","T","G","C"]] input: ATGC the output: CGTA CGTA CGTA CGTA How do I prevent the code from looping the number of characters present in the string. Can I get the output once and break the loop?
has answer: http://stackoverflow.com/a/47588335
downvote count: 0
answer count: 3
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82133777
has title: How to break out of python comprehensive list after printing the output once
has comment: http://stackoverflow.com/comment/82133847
favorite count: 0
has answer: http://stackoverflow.com/a/47588937
type: Question

pact
tags question: http://stackoverflow.com/q/47595272
type: Tag
tags question: http://stackoverflow.com/q/47635547
tag name: pact

http://stackoverflow.com/q/47599745
tagged with: arrays
has comment: http://stackoverflow.com/comment/82158131
tagged with: python
has answer: http://stackoverflow.com/a/47600079
has comment: http://stackoverflow.com/comment/82158524
accepted answer: http://stackoverflow.com/a/47600079
has comment: http://stackoverflow.com/comment/82158500
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82158032
has title: how to multiply and divide a numpy array's each sub numpy array with two numpy arrays
answer count: 1
has comment: http://stackoverflow.com/comment/82157996
type: Question
tagged with: numpy
has body: I was trying to multiply and divide a numpy array's each sub numpy array with two numpy arrays. I have a numpy array x with shape [100, 5], two numpy arrays y and y both with shape (5,). I am trying to change the value of the tensor: For each sub numpy array w along with axis=0 in x, it should have shape [1, 5], I want to do (w - y)*z. My thought was to for-loop over x and pick each sub array inside it to do this and then reconstruct the original array. However, this may be not efficient.

http://stackoverflow.com/comment/82089492
has text: @Wen I no sure, but his expect data different with the image!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47565741

http://stackoverflow.com/a/47695132
type: Answer
has body: If you return a tuple as a key it will first sort by the first element and then by the second. Since you want to sort by first last name then first name your key should return (last name, first name). l = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')] def get_key1(x): return (x[1], x[0]) print(sorted(l, key=get_key1))
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47694476
has comment: http://stackoverflow.com/comment/82353571

http://stackoverflow.com/q/47541349
has body: I am woarking with python 3.6, I want to use the new API from : ib_insync. I have installed this library and followed the instructions from the help page : Python version 3.6 or higher; The Interactive Brokers Python API version 9.73.03 or higher; A running TWS or IB gateway application (version 967 or higher). Make sure the API port is enabled and 'Download open orders on connection' is checked. Hoever, when I run the sample code on Spyder I have the following error message : IB API from http://interactivebrokers.github.io is required An exception has occurred, use %tb to see the full traceback. I have checked that the labrary ib_insync is in the kernel. Is there is something I could do more ? Thanks
has title: First installation of ib_insync and error messages
tagged with: interactive-brokers
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82040123
has comment: http://stackoverflow.com/comment/82044930
has answer: http://stackoverflow.com/a/52221962
tagged with: python
score: 0

http://stackoverflow.com/comment/82355645
has text: Welcome to SO. This is not a free code-writing service, hence your question is supposed to present your own attempts. Moreover, this question is a duplicate.
type: Comment
comment on: http://stackoverflow.com/q/47697775
score: 0
type: QuestionComment

http://stackoverflow.com/a/47632086
answers question: http://stackoverflow.com/q/47631594
has comment: http://stackoverflow.com/comment/82221954
type: Answer
score: -1
has body: When you are writing the tweet data to a file use .decode('utf-8') And when you try to read data from that file use .encode('utf-8') Here I am posting an example: # -*- coding: utf-8 -*- string1 = "آکاش کمار" string2 = string1.decode('utf-8') string3 = string2.encode('utf-8') print(string3)
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/47554778
tagged with: python
score: -1
upvote count: 0
tagged with: list
tagged with: constructor
has comment: http://stackoverflow.com/comment/82066495
type: UnansweredQuestion
has title: generator imbedded in list
has comment: http://stackoverflow.com/comment/82066512
has answer: http://stackoverflow.com/a/47554936
downvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: My code yValues = [3, 6, 12] retVal = [] for num in range(2): retVal.append((num),(Y for Y in range( math.ceil(yValues[num]-yVaules[num-1]) )) ) what I'd like this to return is the list retVal[(0, 3), (0, 4), (0, 5), (0, 6), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12)] I haven't worked with constructors in a while, cause right now I'm just getting retVal[(0, constructorFunction at ...), (1, constructorFunction at ...)]

http://stackoverflow.com/q/47582680
has title: Reformatting a date-frame into a new output format
has answer: http://stackoverflow.com/a/47582815
favorite count: 0
type: Question
has body: I have a the output from a pivot table in dataframe (df) which is that looks like: Year Month sum 2005 10 -1.596817e+05 11 -2.521054e+05 12 5.981900e+05 2006 1 8.686413e+05 2 1.673673e+06 3 1.218341e+06 4 4.131970e+05 5 1.090499e+05 6 1.495985e+06 7 1.736795e+06 8 1.155071e+05 ... 9 7.847369e+05 10 -5.564139e+04 11 -7.435682e+05 12 1.073361e+05 2017 1 3.427652e+05 2 3.574432e+05 3 5.026018e+04 Is there a way to reformat the dataframe so the output to console would look like: Month 1 2 3 4 5 6 7 8 9 10 11 12 Year 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 All the values would be populated in the new table as well.
possible better answer: http://stackoverflow.com/a/47582850
has answer: http://stackoverflow.com/a/47582850
tagged with: python
accepted answer: http://stackoverflow.com/a/47582815
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/comment/82074806
comment on: http://stackoverflow.com/q/47549799
type: Comment
type: QuestionComment
has text: This seems to work, thank you
score: 0

http://stackoverflow.com/comment/82121211
type: Comment
has text: If you add "abc" to the list twice and then try to delete it, `lb_items.get("active")` will return "abc (2)". "abc (2)" is not an element of your dictionary. "abc" is an element of your dictionary, but that's different from "abc (2)".
type: QuestionComment
comment on: http://stackoverflow.com/q/47581791
score: 0

http://stackoverflow.com/q/47602422
upvote count: 1
tagged with: floating-point
tagged with: string
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82163665
accepted answer: http://stackoverflow.com/a/47602541
has title: String will not convert to float
has answer: http://stackoverflow.com/a/47602541
type: Question
has body: I'm trying to find the class average for a select group of data. However, my 'score' will not change from a string to a float. Please help! #1. Helping Mr. Couch calculate his class average inFile=open("Mr.Couch.py", 'r') outFile=open("sol.txt.py", 'w') name=inFile.readline() score=inFile.readline() summ=0.0 count=0 while (score!=" "): count=count+1 summ=summ+float(score) name=inFile.readline() score=inFile.readline() average=summ/count inFile.close() outFile.write("Class average=", average) outFile.close() The result should give the average of all the class scores. However, I continue to end up with the error "could not convert string into float". Please help!
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/82163661
has comment: http://stackoverflow.com/comment/82163682
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82163736
downvote count: 3

http://stackoverflow.com/comment/82215892
comment on: http://stackoverflow.com/q/47628953
score: 0
has text: actually the above code can be used to **append to an existing xml file** . The only problem is that the sub elements gets written twice.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47579741
answers question: http://stackoverflow.com/q/47578974
has comment: http://stackoverflow.com/comment/82116773
downvote count: 0
upvote count: 1
has body: You could use Radiobutton to select only one option meters or feet You use one IntVar with two Radiobutton which have different value self.option = tk.IntVar(value=1) c = tk.Radiobutton(self, text="Meters", value=1, variable=self.option) c = tk.Radiobutton(self, text="Feet", value=2, variable=self.option) And in OnButtonClick you can get selected element (value 1 or `2) with selected = self.option.get() if selected == 1: print('meters') else: print('feet') BTW: you should use try/except because sometimes log() has wrong argument and give error. BTW: we use CamelCaseNames for classes like Label or Entry. For other elements we use lower_case_names - for example on_button_click Full code: import Tkinter as tk import math Lreq = 105 Dref = 1 class CompintAppTk(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title('Wattage Calculator') self.initialize() self.mainloop() def initialize(self): self.grid() self["bg"] = "grey" ## Title &amp; subtitle labels --------------------------------------- titlelbl = tk.Label(self, text="Wattage Calculator", anchor="center", fg="black", bg="darkorange2") titlelbl.grid(column=0, row=0, columnspan=4, sticky='EW') ## Input Labels -------------------------------------------------- sensitivitylbl = tk.Label(self, text="Loudspeaker sensitivity?", anchor="w", fg="white", bg="SlateGray4") sensitivitylbl.grid(column=0,row=2,columnspan=3,sticky='EW') distancelbl = tk.Label(self, text="Distance from speaker to listening position?", anchor="w", fg="white", bg="SlateGray4") distancelbl.grid(column=0, row=3, columnspan=3, sticky='EW') headroomlbl = tk.Label(self, text="How much headroom for amplifier?", anchor="w", fg="white", bg="SlateGray4") headroomlbl.grid(column=0,row=4, columnspan=3, sticky='EW') wattagelbl = tk.Label(self, text="Total Wattage :", anchor="w", fg="white", bg="SlateGray4") wattagelbl.grid(column=0, row=7, columnspan=3, sticky='EW') ## end of input labels ------------------------------------------------ ## Input Boxes -----…
score: 1
type: Answer

machine-learning
tags question: http://stackoverflow.com/q/47666699
type: Tag
tags question: http://stackoverflow.com/q/47692054
tags question: http://stackoverflow.com/q/47652467
tags question: http://stackoverflow.com/q/47599436
tags question: http://stackoverflow.com/q/47659998
tags question: http://stackoverflow.com/q/47587448
tags question: http://stackoverflow.com/q/47569394
tags question: http://stackoverflow.com/q/47561012
tags question: http://stackoverflow.com/q/47607443
tags question: http://stackoverflow.com/q/47665606
tags question: http://stackoverflow.com/q/47639811
tags question: http://stackoverflow.com/q/47603105
tags question: http://stackoverflow.com/q/47696236
tags question: http://stackoverflow.com/q/47578414
tags question: http://stackoverflow.com/q/47554554
tags question: http://stackoverflow.com/q/47558518
tags question: http://stackoverflow.com/q/47614963
tags question: http://stackoverflow.com/q/47543316
tags question: http://stackoverflow.com/q/47644306
tags question: http://stackoverflow.com/q/47692738
tags question: http://stackoverflow.com/q/47574478
tags question: http://stackoverflow.com/q/47574815
tags question: http://stackoverflow.com/q/47609537
tags question: http://stackoverflow.com/q/47676138
tags question: http://stackoverflow.com/q/47617512
tags question: http://stackoverflow.com/q/47629377
tags question: http://stackoverflow.com/q/47657533
tags question: http://stackoverflow.com/q/47564504
tags question: http://stackoverflow.com/q/47551850
tags question: http://stackoverflow.com/q/47568966
tags question: http://stackoverflow.com/q/47545540
tags question: http://stackoverflow.com/q/47622828
tags question: http://stackoverflow.com/q/47560074
tags question: http://stackoverflow.com/q/47568428
tags question: http://stackoverflow.com/q/47598627
tag name: machine-learning
tags question: http://stackoverflow.com/q/47577168
tags question: http://stackoverflow.com/q/47687872
tags question: http://stackoverflow.com/q/47604717
tags question: http://stackoverflow.com/q/47550754
tags question: http://stackoverflow.com/q/47593225
tags question: http://stackoverflow.com/q/47625868
tags question: http://stackoverflow.com/q/47632684
tags question: http://stackoverflow.com/q/47571896
tags question: http://stackoverflow.com/q/47658039
tags question: http://stackoverflow.com/q/47628131
tags question: http://stackoverflow.com/q/47656295
tags question: http://stackoverflow.com/q/47610529
tags question: http://stackoverflow.com/q/47624798
tags question: http://stackoverflow.com/q/47675520
tags question: http://stackoverflow.com/q/47650917
tags question: http://stackoverflow.com/q/47565963
tags question: http://stackoverflow.com/q/47618414
tags question: http://stackoverflow.com/q/47663694
tags question: http://stackoverflow.com/q/47553103
tags question: http://stackoverflow.com/q/47686227
tags question: http://stackoverflow.com/q/47683090

http://stackoverflow.com/q/47669582
tagged with: alphabetical
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82299024
tagged with: listdir
has body: I'm trying to sort files and directories in specific way (for me it is usuall way but ok). So I have JPG files, then some txt files or wav and I have some directories I want it sorted like first sort by name all files then sort directories but when I'm trying to do something like : path = "/my_path" arr = os.listdir(path) arr.sort(key=lambda x: (os.path.isdir(x), x)) print(arr) Code gives me output : ['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'HRYS', 'WAVS', 'k.txt', 's.wav'] but it should be : ['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'k.txt', 's.wav', 'HRYS', 'WAVS'] How to do it in proper way ?
has comment: http://stackoverflow.com/comment/82298954
accepted answer: http://stackoverflow.com/a/47669667
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/82298818
has answer: http://stackoverflow.com/a/47669667
has comment: http://stackoverflow.com/comment/82298710
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82298587
upvote count: 2
has comment: http://stackoverflow.com/comment/82298733
downvote count: 0
answer count: 1
has title: Sort files then directories os.listdir PYTHON
has comment: http://stackoverflow.com/comment/82298874
tagged with: directory

http://stackoverflow.com/comment/82204796
type: QuestionComment
has text: Write a function for it?
score: 0
comment on: http://stackoverflow.com/q/47623434
type: Comment

http://stackoverflow.com/a/47659174
type: AcceptedAnswer
has body: You could adjust the ini in your PHP code with ini_set ini_set('xdebug.max_nesting_level', 200);
accepted answer of: http://stackoverflow.com/q/47658565
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47658565

http://stackoverflow.com/q/47568428
has comment: http://stackoverflow.com/comment/82095989
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82095431
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26962159
tagged with: machine-learning
tagged with: python
has title: svm predict ValueError: X.shape[1] = 2 should be equal to 211, the number of samples at training time
tagged with: svm
has comment: http://stackoverflow.com/comment/82094472
has body: I am confused as what's wrong and how to approach fixing it: def plot_boundary(my_svm, xmin, xmax, ymin, ymax): """ Function to plot the decision boundary for a trained SVM It works by making a grid of x1 ("xvals") and x2 ("yvals") points, And for each, compute whether the SVM classifies that point as True or False. Then, a contour is drawn with a built-in pyplot function. """ # Hint: Use the following method built into the svm module # my_svm.predict(np.array([x1[i],x2[j]])) #np.array([xvals[x]), np.array(yvals[y]]) h = 0.02 #xx = np.linspace(xmin, xmax, 0.02) #yy = np.linspace(ymin, ymax, 0.02) xx, yy = np.meshgrid(np.arange(xmin, xmax, h), np.arange(ymin, ymax, h)) #xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j] Z = my_svm.predict(np.c_[xx.ravel(), yy.ravel()]) #Z = my_svm.predict(np.array(Xval[xx]), np.array(yvals[yy])) #Z = my_svm.predict(Xval, yval) #Z = my_svm.decision_function(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) #plt.contour(xx, yy, Z) color_map = plt.cm.RdBu #ax.contourf(xx, yy, Z, cmap=color_map, alpha=.8) plt.contour(xx, yy, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], levels=[-.5, 0, .5]) plt.show(block=False) #my_svm.predict(np.array([Xvals[x],yvals[y]])) #contour = plt.contour(x1,x2, mtrx , levels=[0] ) #contour = plt.contour( ) plt.title("Decision Boundary") and then I call it with: plot_data() plot_boundary(clf,-.5,.3,-.8,.6) In which svm is: from sklearn import svm def gauss_kernel(x1, x2, gamma): x1 = x1.flatten() x2 = x2.flatten() sigma = math.sqrt(gamma) return np.exp(-np.sum((x1-x2)**2)/(2*sigma**2)) # from @lejlot http://stackoverflow.com/a/26962861/583834 def gaussianKernelGramMatrix(X1, X2, K_function=gauss_kernel, gamma=0.1): """(Pre)calculates Gram Matrix K""" gram_matrix = np.zeros((X1.shape[0], X2.shape[0])) for i, x1 in enumerate(X1): for j, x2 in enumerate(X2): gram_matrix[i, j] = K_function(x1, x2, gamma) return gram_matrix gamma=0.1 y = y.flatten() clf = svm.SVC(kern…
has comment: http://stackoverflow.com/comment/82094660
has comment: http://stackoverflow.com/comment/82094580
has comment: http://stackoverflow.com/comment/82094857
answer count: 0
has comment: http://stackoverflow.com/comment/82095885
score: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82095113
downvote count: 1
has comment: http://stackoverflow.com/comment/82094496
favorite count: 0

http://stackoverflow.com/q/47660392
has body: I'm trying to learn how to webscrape with beautifulsoup + python, and I want to grab the name of the cinematographer from https://letterboxd.com/film/donnie-darko/ but I can't figure out how to isolate the text. The html for what I want is written as below, what I want to output is "Steven Poster": Cinematography Steven Poster within my code I've done soup.find(text="Cinematography"), and a mixture of different thigns like trying to find item or get_text from within the a and p tags, but ...
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47682545
possible better answer: http://stackoverflow.com/a/47682545
score: 0
has answer: http://stackoverflow.com/a/47660516
answer count: 3
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/47660516
has answer: http://stackoverflow.com/a/47660562
has title: Can't get item with python beautifulsoup
tagged with: python

http://stackoverflow.com/q/47652001
tagged with: tkinter
has body: image for that I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again. from tkinter import * from tkinter import messagebox def top(): if entry1.get() == "333": log.destroy() root.deiconify() else: messagebox.showerror("error", "try again") root = Tk() root.geometry("300x300") log = Toplevel(root) log.geometry("200x200") label1 = Label(log, text="password") entry1 = Entry(log) button1 = Button(log, text="login", command=top) label1.pack() entry1.pack() button1.pack(side="bottom") lab = Label(root, text="welcome bro").pack() root.withdraw() root.mainloop()
upvote count: 2
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/47652722
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47652722
has comment: http://stackoverflow.com/comment/82262187
has comment: http://stackoverflow.com/comment/82265401
accepted answer: http://stackoverflow.com/a/47654220
favorite count: 0
has title: How to compulsory close message box for Toplevel window
has answer: http://stackoverflow.com/a/47654220
type: Question
tagged with: toplevel
tagged with: python
linked to: http://stackoverflow.com/q/16803686
has comment: http://stackoverflow.com/comment/82265662
has comment: http://stackoverflow.com/comment/82262752

http://stackoverflow.com/q/47638142
has answer: http://stackoverflow.com/a/47638191
type: AnsweredQuestion
answer count: 2
has title: Passing # character in url with python
possible better answer: http://stackoverflow.com/a/47638313
score: 0
tagged with: url
has answer: http://stackoverflow.com/a/47638313
has body: I have the following code: @app.route('/famcall/Audio/AudioMng_PlayDTMF/&lt;string:output_stream&gt;/&lt;string:dtmf&gt;/&lt;string:duration&gt;/&lt;string:gap&gt;', methods=['GET']) def fam_audio_play_dtmf(output_stream, dtmf, duration, gap): params = [self.mapAudioOutputStream.business_to_tech(output_stream), dtmf, duration, gap] return self.call_fam_function_and_wait_response("AudioMng_PlayDTMF", params) and I want to use the character # in my url because it´s a value that can be used for dtmf. Is there an encode function in python which can help me in this? Or should I forget this scenario?
type: Question
accepted answer: http://stackoverflow.com/a/47638191
tagged with: python

http://stackoverflow.com/q/47576843
has title: Removing rows where all but one column match in MySQL
accepted answer: http://stackoverflow.com/a/47576996
answer count: 2
has answer: http://stackoverflow.com/a/47577353
upvote count: 0
has answer: http://stackoverflow.com/a/47576996
has comment: http://stackoverflow.com/comment/82110866
tagged with: database
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82110832
type: AnsweredQuestion
has body: I have the following table: id | name | time | action | entered ---+-------+-----------+--------+-------- 1 | james | today | x | 1 | james | today | x | yes 1 | james | today | y | 1 | james | today | y | yes 2 | carl | today | x | 2 | carl | today | y | 3 | casey | yesterday | x | 3 | casey | yesterday | x | yes 3 | casey | yesterday | y | 3 | casey | yesterday | y | yes 4 | john | today | x | yes I want to remove the rows where the value of entered is "yes", and there is another row with the same values at all other columns except in entered. In the example above - rows 2,4,8,10 should be deleted. There is a primary key on all five columns. How can I achieve this? Solutions in MySQL or in Python will be accepted.
tagged with: mysql
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47577353

http://stackoverflow.com/q/47593366
tagged with: parameter-passing
has title: Python: typed method arguments
has body: In Python3 it's possible to add the type to the arguments of a function: def foo(bar: str = "default") -&gt; str: """ @param bar: a textual value """ return "test" Now I got two questions. First, how can you do that for a callback function? Meaning, how to define the signature of that callback in the function header? def foo(callback) -&gt; str: """ @param callback: function(value: str) -&gt; str """ # calculate some intermediate stuff my_var = ... return callback(my_var) Second, how to do that for tuples. This would include the defining that the value is of type tuple and should have two values (no triple etc.). def foo(value) -&gt; str: """ @param value: tuple of strings """ v1, v2 = value return v1 + v2 Thanks for your comments and answers.
upvote count: 4
type: AnsweredQuestion
score: 4
has comment: http://stackoverflow.com/comment/82144015
has answer: http://stackoverflow.com/a/47593635
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82143896
tagged with: callback
has comment: http://stackoverflow.com/comment/82144203
favorite count: 0
has comment: http://stackoverflow.com/comment/82143942
has comment: http://stackoverflow.com/comment/82143918
type: Question
accepted answer: http://stackoverflow.com/a/47593635
tagged with: user-defined-functions
tagged with: python

http://stackoverflow.com/q/47580110
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47580658
accepted answer: http://stackoverflow.com/a/47580658
has body: I have a Django REST API with an Angular Front-end. I am getting no errors on the front-end, but no json data is logging to the console. I have a service like so: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) =&gt; res.json()); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata =&gt; { console.log(weatherdata) }) } } feeding a component like so: import { Component, OnInit } from '@angular/core'; import { WeatherstatsService } from '../weatherstats.service'; @Component({ selector: 'weather-stats', templateUrl: './weather-stats.component.html', styleUrls: ['./weather-stats.component.css'] }) export class WeatherStatsComponent implements OnInit { data: any; constructor(private weatherstatsservice: WeatherstatsService) { } ngOnInit() { console.log(this.weatherstatsservice.getWeatherData().subscribe(data =&gt; this.data = data)); } } I am new to both Django and Angular, when I test the API in the browser I get the data I want. What could be happening that means I can't see my json data? (With apologies to people who tried to help on similar issue just now - My brain is exploding with all this new stuff!) Console: Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …} closed : false destination : SafeSubscriber {closed: false, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …} isStopped : false syncErrorThrowable : false syncErrorThrown : false syncErrorValue : null _parent : null _parents : null _subscriptions : Array(1) 0 : MapSubscriber {closed: tr…
has comment: http://stackoverflow.com/comment/82118136
type: AnsweredQuestion
score: 3
tagged with: angular
upvote count: 3
has comment: http://stackoverflow.com/comment/82118274
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82118426
has comment: http://stackoverflow.com/comment/82117558
has comment: http://stackoverflow.com/comment/82118483
has comment: http://stackoverflow.com/comment/82117483
favorite count: 0
type: Question
has title: JSON data not coming through from Django REST API
linked to: http://stackoverflow.com/q/43055706
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82118207

action
tags question: http://stackoverflow.com/q/47641847
tag name: action
type: Tag

http://stackoverflow.com/q/47660439
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47757281
has comment: http://stackoverflow.com/comment/82463567
tagged with: opencv
has comment: http://stackoverflow.com/comment/82474463
has title: Detecting moving object in moving camera(monitoring one area mounted on a drone)
tagged with: python
has comment: http://stackoverflow.com/comment/82472736
possible better answer: http://stackoverflow.com/a/73827805
has answer: http://stackoverflow.com/a/73827805
has comment: http://stackoverflow.com/comment/82471321
score: 2
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82474849
has comment: http://stackoverflow.com/comment/82474641
has comment: http://stackoverflow.com/comment/82473158
upvote count: 2
has comment: http://stackoverflow.com/comment/82471204
has comment: http://stackoverflow.com/comment/82470310
downvote count: 0
has body: def run(self): while True: _ret, frame = self.cam.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) vis = frame.copy() if len(self.tracks) &gt; 0: img0, img1 = self.prev_gray, frame_gray p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2) p1, _st, _err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params) p0r, _st, _err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params) d = abs(p0-p0r).reshape(-1, 2).max(-1) good = d &lt; 1 new_tracks = [] for i in range(len(p1)): A.append(math.sqrt((p1[i][0][0])**2 + (p1[i][0][1])**2)) counts,bins,bars = plt.hist(A) for tr, (x, y), good_flag in zip(self.tracks, p1.reshape(-1, 2), good): if not good_flag: continue tr.append((x, y)) if len(tr) &gt; self.track_len: del tr[0] new_tracks.append(tr) cv2.circle(vis, (x, y), 2, (0, 255, 0), -1) self.tracks = new_tracks cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0)) draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks)) if self.frame_idx % self.detect_interval == 0: mask = np.zeros_like(frame_gray) mask[:] = 255 for x, y in [np.int32(tr[-1]) for tr in self.tracks]: cv2.circle(mask, (x, y), 5, 0, -1) p = cv2.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params) if p is not None: for x, y in np.float32(p).reshape(-1, 2): self.tracks.append([(x, y)]) self.frame_idx += 1 self.prev_gray = frame_gray cv2.imshow('lk_track', vis) ch = cv2.waitKey(1) if ch == 27: break i am using lk_track.py from opencv samples to try and detect a moving object. I am trying to find the camera motion using the histogram of magnitude of optical flow vectors and then calculate the average for similar values which should be directly proportional to the camera motion. I have calculated the magnitude of the vectors and saved it in a list A. Can some suggest on how to find highest similar values from it and calculate the average for only those values?
has comment: http://stackoverflow.com/comment/82280034
accepted answer: http://stackoverflow.com/a/47757281

http://stackoverflow.com/comment/82292041
type: Comment
type: QuestionComment
has text: @MarkRansom Wher is the errors? I copied and pasted the code
score: 0
comment on: http://stackoverflow.com/q/47666279

http://stackoverflow.com/comment/82268830
type: QuestionComment
has text: `add.join(); see.join()` as the last line.
score: 0
comment on: http://stackoverflow.com/q/47655075
type: Comment

http://stackoverflow.com/q/47619946
has answer: http://stackoverflow.com/a/47620341
has answer: http://stackoverflow.com/a/47619999
has answer: http://stackoverflow.com/a/47620381
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1156087
has answer: http://stackoverflow.com/a/47620233
has answer: http://stackoverflow.com/a/47620043
downvote count: 2
has comment: http://stackoverflow.com/comment/82197817
has answer: http://stackoverflow.com/a/47620093
has answer: http://stackoverflow.com/a/47620283
favorite count: 0
has answer: http://stackoverflow.com/a/65821097
has body: I'm trying to check if a word is in a list that is a value of a dictionary. For example i want to check if 'noodles' is in: {1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']} I tried with: element = 'noodles' element in myDict.values() But i get: False
tagged with: list
has comment: http://stackoverflow.com/comment/129523941
type: Question
has answer: http://stackoverflow.com/a/47619982
score: 3
answer count: 9
upvote count: 5
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
has title: Check if a word is in a list that is a value of a dictionary

http://stackoverflow.com/comment/82186218
has text: What do you see then, any error etc. Is your action path working?
type: QuestionComment
comment on: http://stackoverflow.com/q/47611721
score: 0
type: Comment

http://stackoverflow.com/a/75829748
has comment: http://stackoverflow.com/comment/133762464
upvote count: 1
has body: import ast json_dat = json.dumps(ast.literal_eval(row['prod_cat'])) dict_dat = json.loads(json_dat)
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/47659782
type: Answer

http://stackoverflow.com/q/47543929
has title: python-redis:ConnectionError: Error 32 while writing to socket. Broken pipe?
has body: I want to test the value of redis can support up to 512MB language:python import redis conn = redis.Redis() temp_dict={} for i in range(1000000): temp_dict.update({str(i):str(i)}) conn.hmset('hash-key',temp_dict) errors: --------------------------------------------------------------------------- ConnectionError Traceback (most recent call last) in () ----> 1 conn.hmset('hash-key',temp_dict) /usr/local/lib/python2.7/dist-packages/redis/client.pyc in hmset(self, name, mapping) 2009 for pair in iteritems(mapping): 2010 items.extend(pair) -&gt; 2011 return self.execute_command('HMSET', name, *items) 2012 2013 def hmget(self, name, keys, *args): /usr/local/lib/python2.7/dist-packages/redis/client.pyc in execute_command(self, *args, **options) 671 if not connection.retry_on_timeout and isinstance(e, TimeoutError): 672 raise --&gt; 673 connection.send_command(*args) 674 return self.parse_response(connection, command_name, **options) 675 finally: /usr/local/lib/python2.7/dist-packages/redis/connection.pyc in send_command(self, *args) 608 def send_command(self, *args): 609 "Pack and send a command to the Redis server" --&gt; 610 self.send_packed_command(self.pack_command(*args)) 611 612 def can_read(self, timeout=0): /usr/local/lib/python2.7/dist-packages/redis/connection.pyc in send_packed_command(self, command) 601 errmsg = e.args[1] 602 raise ConnectionError("Error %s while writing to socket. %s." % --&gt; 603 (errno, errmsg)) 604 except: 605 self.disconnect() ConnectionError: Error 104 while writing to socket. Connection reset by peer.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82045756
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/64095130
favorite count: 0
type: Question
tagged with: redis
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82044972

http://stackoverflow.com/comment/82056245
type: QuestionComment
comment on: http://stackoverflow.com/q/47549652
score: 0
has text: Thank You, that helped already. Is this a good way to select a batch from a Dataframe or can you maybe refer to a better one?
type: Comment

http://stackoverflow.com/comment/82061021
type: Comment
type: QuestionComment
has text: perhaps using the `locals()` dict. It is not very explicit though. What if those key words are not set?
comment on: http://stackoverflow.com/q/47552107
score: 0

http://stackoverflow.com/comment/82062179
has text: You will need to add some sample data to the question to make it clearer, e.g. example Excel rows and your expected CSV output.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47546210

http://stackoverflow.com/q/47583146
answer count: 1
has comment: http://stackoverflow.com/comment/82125124
has body: OutPut Image / Expected Image I am generating images for cursive scripts through font and its unicode but in output image characters are separate not joined. i need joined characters same as expected image. Please ask if question is not clear. Images are linked above. unicode_text = u"\u0627\u0628\u062A\u062B" list_of_letters = list (unicode_text) folder = 1 n=3 for i in range(1,n+1): for word in itertools.permutations( list_of_letters,i): char = ''.join(word) verdana_font = ImageFont.truetype("Nafees Naskh v2.01.ttf", 30, encoding="unic") text_width, text_height = verdana_font.getsize(''.join(word)) canvas = Image.new('RGBA', (100, 100), (255, 255, 255),) draw = ImageDraw.Draw(canvas) canvas.save(path + '\\' + char[::-1]+'.png', "PNG") folder += 1
has answer: http://stackoverflow.com/a/47583422
type: Question
tagged with: numpy
tagged with: python-imaging-library
tagged with: python-itertools
has title: Cursive Words not connecting in image
type: UnansweredQuestion
tagged with: python-unicode
tagged with: python
has comment: http://stackoverflow.com/comment/82124411
score: 0
has comment: http://stackoverflow.com/comment/82124788

http://stackoverflow.com/comment/82137787
has text: check once i edited the question @MikeScotty
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47589268
score: 0

http://stackoverflow.com/q/47604817
has comment: http://stackoverflow.com/comment/82168915
has comment: http://stackoverflow.com/comment/82177389
score: 0
answer count: 0
has title: replace string in router config. using python
has body: i try to run python script in securecrt for juniper routers such i show configuration on it then make change/replace for strings in it, i want to take output of show configuration then put it to list then make changes then change it to string then apply it. example as below: @router> ...tch ARI|display set #set policy-options policy-statement STM64-L1 term ARI from route-filter 1.1.1.1/32 exact #set policy-options policy-statement STM64-L1 term ARI then accept #set policy-options policy-statement STM64-L1 term rej then reject in it i want to replace string STM64-L1 with 10G-L100 then apply configuration to router again as string my code as below: crt.Screen.Synchronous = True JGR= crt.Dialog.Prompt("enter term name that will applied: ") rep= crt.Dialog.Prompt("enter term name that will removed ") pol= crt.Dialog.Prompt("enter policy that will remove term from it ") npt= crt.Dialog.Prompt("enter policy that will add term to it ") crt.Screen.Send("show configuration | display set | match " +JGR+ "\n") crt.Screen.WaitForString("/n") x=crt.Screen.ReadString("exact") x.split(",") term_name=x term_name=list() for word in term_name: h=term_name.index(pol) term_name.pop(h) term_name.insert(h,npt) yyy= ' '.join(term_name) crt.Screen.Send("edit private "+ "\n") crt.Screen.WaitForString("router#") crt.Screen.Send(yyy+ "\n") crt.Screen.WaitForString("router#") crt.Screen.Send("show | compare " + "\n") crt.Screen.Synchronous = False main() but i face problem that script run without errors but no configuration applied like that value of yyy is just space ? Thanks
type: Question
has comment: http://stackoverflow.com/comment/82168309
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/82193374
score: 2
comment on: http://stackoverflow.com/q/47617506
type: QuestionComment
has text: @Lix: I didn't say I didn't change the indentation. I just said that it didn't change the semantics of the program. In this program you can't change the indentation of the for-loop, which is changing the semantics without producing an error because every block contains just a single statement.
type: Comment

http://stackoverflow.com/q/47640057
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82240649
tagged with: django-rest-framework
answer count: 1
tagged with: serialization
has comment: http://stackoverflow.com/comment/82239210
type: Question
has comment: http://stackoverflow.com/comment/82240152
has comment: http://stackoverflow.com/comment/82238883
has comment: http://stackoverflow.com/comment/82239678
accepted answer: http://stackoverflow.com/a/47641245
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47641245
has body: I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model: class Vote(models.Model): created = models.DateTimeField(auto_now_add=True) voter = models.ForeignKey(User, on_delete=models.CASCADE) snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE) class Meta: ordering = ('created',) After posting and validating a user vote to a snippet, I now want to update the number of votes received by the snippet (I added to the Snippet model a number_of_votes field). I'm doing it in the create method of my VoteSerializer like that: class VoteSerializer(serializers.HyperlinkedModelSerializer): voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=VoteUp.objects.all(), message=already_voted)]) snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all()) def validate(self, data): # ... my validation function def create(self, validated_data): obj = Vote.objects.create(**validated_data) obj.snippet.number_of_votes += 1 obj.snippet.save() return obj It works well but I'm not sure if it's the good way or not to do it. Is there a better way?
has title: In Django Rest Framework how to update FK in serializer

http://stackoverflow.com/comment/82173567
score: 0
type: Comment
has text: Glad it helped.
type: AnswerComment
comment on: http://stackoverflow.com/a/47607543

http://stackoverflow.com/comment/82175663
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47582321
type: Comment
has text: I think the pure Python version you used is pretty much the same histogram implementation that the even higher voted answers used, but if different ways of writing it in Python affect the speed much.

http://stackoverflow.com/q/47596256
tagged with: python
type: AnsweredQuestion
has body: If I am using Keras with theano, what is the difference between A and B in this case ? from keras import backend as K import theano A = theano.tensor.matrix() B = K.zeros(shape = (d1, d2, d3, d4)) where d1-d4 are dimensions for example (1,4,14,14)
tagged with: tensor
upvote count: 1
answer count: 1
downvote count: 0
tagged with: keras
has title: How to understand a theano tensor as a matrix and a keras.backend variable?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47596373
accepted answer: http://stackoverflow.com/a/47596373
tagged with: theano
score: 1

http://stackoverflow.com/comment/82242853
type: QuestionComment
has text: I haven't down-voted, but please note, "It doesn't work" is not an adequate problem specification. Please read [“It’s not working” is not helpful](http://idownvotedbecau.se/itsnotworking/)
comment on: http://stackoverflow.com/q/47642201
score: 2
type: Comment

http://stackoverflow.com/q/47676319
answer count: 2
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/47676724
tagged with: error-handling
has title: How to create a tkinter error message box
favorite count: 0
type: Question
upvote count: 5
tagged with: pyinstaller
duplicate of: http://stackoverflow.com/q/1052420
has answer: http://stackoverflow.com/a/47676461
tagged with: python
has body: I am wanting to create a simple message box in Tkinter that appears and displays the exact error message. Could anyone direct me to how this might be achieved in tkinter, I have not been able to find much on this topic. E.g: traceback.format_exc().replace(':', '-') ctypes.windll.user32.MessageBoxW(0, "Error", "Have you checked your fridge?"d, 1) ^ #'SyntaxError: invalid syntax' I am wanting to add this with pyinstaller. I suppose pyinstaller creates a text file and you can see in cmd before it closes, but it would be nice if a message box appear with exact traceerror.
score: 4
linked to: http://stackoverflow.com/q/1052420
tagged with: python-3.x
tagged with: tkinter

http://stackoverflow.com/q/47599127
type: Question
tagged with: many-to-many
tagged with: model-associations
has title: Using SQLAlchemy, How to filter by association object attribute and Regex?
tagged with: python
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/47600435
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47600435
has body: Using the any() method I'm able to filter queries like such: session.query(Result).filter(Result.related_images.any(url='result1_1512149119.jpg')) This is filtering for images related to a Result class which has a relationship with an Image object that is defined by an association object ResultImages, such that session.query(Result.related_images).all() would return all images that have been specified as related to Result entries. When making first query from above, I get the following output: result1_1512149091.jpg result1_1512149094.jpg result1_1512149097.jpg result1_1512149100.jpg result1_1512149103.jpg result1_1512149105.jpg result1_1512149109.jpg result1_1512149111.jpg result1_1512149113.jpg result1_1512149117.jpg result1_1512149119.jpg result1_1512149122.jpg result1_1512149125.jpg result1_1512149128.jpg In my database, there are many images for many results, such that the following query: session.query(Result).filter(Result.related_images.any(url='result2_1512149119.jpg')) would return the following data: result2_1512149091.jpg result2_1512149094.jpg result2_1512149097.jpg result2_1512149100.jpg result2_1512149103.jpg result2_1512149105.jpg result2_1512149109.jpg result2_1512149111.jpg result2_1512149113.jpg result2_1512149117.jpg result2_1512149119.jpg result2_1512149122.jpg result2_1512149125.jpg result2_1512149128.jpg I've read the documentation related to the any() function, but am still unclear as to how to leverage it for a more nuanced approach (or if it's even possible). For example, for the types of queries I'm making I'll only ever have beforehand knowledge of the result1 substring of the filename. I don't understand why a query, filtered by result1_1512149091.jpg substring, would also return result1_1512149094.jpg. For my particular use, this is ideal but I don't understand why it works in this way. For example, I'd expect filtering by .any('result1') would also return the full list of result1 images, but it returns nothing. What I'd ultimately like…
answer count: 1

http://stackoverflow.com/comment/82276514
type: QuestionComment
has text: maybe you need rather one window with many "pages" which you can replace in window. And then you would need only one button to go back to "home" page.
score: 0
comment on: http://stackoverflow.com/q/47651794
type: Comment

http://stackoverflow.com/comment/82287515
type: QuestionComment
comment on: http://stackoverflow.com/q/47664082
type: Comment
score: 0
has text: Right now all you need to do seems to be moving `master.withdraw()` into `show_entry_fields`. But I believe your question is unclear.

http://stackoverflow.com/comment/82324969
score: 1
type: QuestionComment
has text: @codeforester `-rw-r--r-- 1 pi pi 792 Nov 8 20:52 /home/pi/.profile`
type: Comment
comment on: http://stackoverflow.com/q/47682666

http://stackoverflow.com/comment/82128909
score: 0
type: QuestionComment
has text: Well you could post the answer.
comment on: http://stackoverflow.com/q/47585497
type: Comment

http://stackoverflow.com/comment/82343508
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47691540
has text: So `pip` can install the package fro ma git repo *without* the dist folder created by `sdist`?

http://stackoverflow.com/comment/82171980
comment on: http://stackoverflow.com/a/47590965
has text: Now it's returning another error for the uploaded file name, See this question, please! https://stackoverflow.com/q/47605818/7644562
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/111716040
has text: Same problem, all I did was `brew reinstall awscli` and it was fixed. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/59207908
score: 7
type: Comment

http://stackoverflow.com/q/47613093
favorite count: 0
type: Question
has body: I am trying to stop RDS instance using AWS Lambda function written in Python 2.7. However I cannot get the instances using the tag filters. import boto3 import logging rds = boto3.client('rds') def lambda_handler(event, context): filters = [{ 'Name': 'tag:Application', 'Values': ['appname'] }, { 'Name': 'instance-state-name', 'Values': ['running'] } ] instances = rds.get_all_dbinstances.filter(Filters=filters) instances.status Get all instances with the specified tags This is the error I get: { "stackTrace": [ [ "/var/task/lambda_function.py", 18, "lambda_handler", "instances = rds.get_all_dbinstances(Filters=filters)" ], [ "/var/runtime/botocore/client.py", 553, "__getattr__", "self.__class__.__name__, item)" ] ], "errorType": "AttributeError", "errorMessage": "'RDS' object has no attribute 'get_all_dbinstances'" }
has answer: http://stackoverflow.com/a/47619514
accepted answer: http://stackoverflow.com/a/47619514
tagged with: aws-sdk
tagged with: python
tagged with: boto3
type: AnsweredQuestion
score: 0
has title: Lambda function to stop RDS instance using tag filters
tagged with: amazon-rds
answer count: 1
upvote count: 1
downvote count: 1
tagged with: aws-lambda

http://stackoverflow.com/a/47678815
upvote count: 13
has comment: http://stackoverflow.com/comment/82319401
accepted answer of: http://stackoverflow.com/q/47678682
has comment: http://stackoverflow.com/comment/82318965
has comment: http://stackoverflow.com/comment/82317637
type: AcceptedAnswer
downvote count: 0
score: 13
answers question: http://stackoverflow.com/q/47678682
has comment: http://stackoverflow.com/comment/82319153
has comment: http://stackoverflow.com/comment/82317712
has comment: http://stackoverflow.com/comment/82319061
has comment: http://stackoverflow.com/comment/82319259
has comment: http://stackoverflow.com/comment/94290875
type: Answer
has body: You can use assign to temporarily assign new dtype to the x column: pd.merge(df1.assign(x=df1.x.astype(str)), df2.assign(x=df2.x.astype(str)), how='left', on='x') Output: x y z 0 1 2 2.0 1 3 4 4.0 2 5 6 NaN 3 t 4 7.0 4 m 4 NaN 5 u 8 NaN You may use astype('string') instead using StringDtype with difference noted here.

http://stackoverflow.com/a/47571783
type: Answer
answers question: http://stackoverflow.com/q/47570682
score: 0
has body: One method is to put buttons in one line (as before) but in random order. You have to create list with all words (with many "Doe"), shuffle list and then use this list to create Buttons num_of_doe = level * 2 # we use CamelCaseNames for class names # create list with words all_words = ["Doe"]*num_of_doe + ["Deer"] # shuffle list ("in-place") random.shuffle(all_words) # create buttons using words for word in all_words: b = tk.Button(root, text=word, command=lambda txt=word:shot(txt)) b.pack() BTW: if in lambda you use word from for then you have to use lambda txt=word:shot(txt). If you use lambda:shot(word) then it assign the same value - last value from list - because it put reference to variable word, not value from this variable. If you need more random places then instead pack() you can use place() or grid() to put buttons in random places or cells (in grid) b.place(x=random.randint(0, 200), y=random.randint(0, 100)) or b.grid(row=random.randint(0, 10), column=random.randint(0, 10)) but it makes problem because you can put two buttons in the same place. You need to generate all values first. It needs to keep values on list, then get new random value, compare with values on list and generate new one if it is already on list. It is work for you ;)

http://stackoverflow.com/a/47668588
score: 1
accepted answer of: http://stackoverflow.com/q/47668206
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47668206
has body: As i understand it right, Pelican uses Jinja template engine. So this will do: &lt;meta name="keywords" content=""/&gt; Documentation for this build-in filter: join()
type: Answer
downvote count: 0
upvote count: 1

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/47631200
type: Tag

http://stackoverflow.com/a/47850231
score: 0
answers question: http://stackoverflow.com/q/47697465
has body: Such a token can be retrieved via a previous service call to the ABAP server. For this, first on a none-changing call (GET, HEAD, OPTIONS), the client has to get this token by setting the HTTP header X-CSRF-Token to the value Fetch. A CSRF token is returned by the ABAP server in the same header and can be used for subsequent, server state changing calls using header X-CSRF-Token. (as described in the SAP Online Help) https://help.sap.com/saphelp_nw74/helpdata/de/55/74ed6c93654ee4999b4d07cdda532c/frameset.htm Best Regards, Andre
type: Answer

http://stackoverflow.com/comment/82222757
has text: As the documentation clearly states there must be exactly one call to `task_done()` for each call to `get()`. So you should place it somewhere after `out_que.get()` or you don't use `join()` at all.
comment on: http://stackoverflow.com/q/47624674
score: 0
type: Comment
type: QuestionComment

iterable-unpacking
type: Tag
tags question: http://stackoverflow.com/q/47683498
tags question: http://stackoverflow.com/q/47642568
tag name: iterable-unpacking

http://stackoverflow.com/comment/82201498
type: Comment
type: QuestionComment
has text: happy to do the work, just need a steer in the right direction (as a newbie) -
comment on: http://stackoverflow.com/q/47621547
score: 0

http://stackoverflow.com/q/47624555
downvote count: 0
has answer: http://stackoverflow.com/a/47624834
tagged with: mergesort
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/14733119
has body: I have implemented a mergesort function which works correctly, However, I'm having a hard time modifying it to count the number of inversions in the original array before it is sorted. An inversion is a pair where i &lt; j but a[i] &gt; a[j] an example, a = [5,2,1] has 3 inversions: (5,2),(5,1),(2,1) def mergeSort(a): mid = len(a)//2 if len(a) &lt; 2: return l = a[:mid] r = a[mid:] mergeSort(l) mergeSort(r) return merge(l,r,a) def merge(l,r,a): i = 0 j = 0 k = 0 inv = 0 while(i &lt; len(l) and j &lt; len(r)): if(l[i] &lt; r[j]): a[k] = l[i] i = i + 1 else: a[k] = r[j] inv = inv + 1 j = j + 1 k = k + 1 while i &lt; len(l): a[k] = l[i] i = i + 1 k = k + 1 while j &lt; len(r): a[k] = r[j] j = j + 1 k = k + 1 inv = inv + 1 return [a,inv] a = [6,5,4,3,2,1] print(mergeSort(a)) The above example should return 15 as the count of inversions as n(n-1)/2 is the number of inversions for descending order array. can someone explain how to count it?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82207841
type: Question
accepted answer: http://stackoverflow.com/a/47624834
tagged with: algorithm
tagged with: python
has title: counting inversions of mergesort
type: AnsweredQuestion

http://stackoverflow.com/comment/96742402
type: Comment
type: QuestionComment
has text: @JamesLin did you find a solution?
score: 0
comment on: http://stackoverflow.com/q/47586055

http://stackoverflow.com/q/47630946
tagged with: standard-deviation
tagged with: numpy
type: AnsweredQuestion
has body: I checked the numpy library and found the following definition for the standard deviation in numpy: std = sqrt(mean(abs(x - x.mean())**2)) Why is the abs() function used? - Because mathematically the square of a number will be positive per definition. So I thought: abs(x - x.mean())**2 == (x - x.mean())**2
upvote count: 3
has answer: http://stackoverflow.com/a/47631016
answer count: 1
downvote count: 0
has title: Why does numpy.std() use abs()?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82219782
score: 3
accepted answer: http://stackoverflow.com/a/47631016
has comment: http://stackoverflow.com/comment/82220058
has comment: http://stackoverflow.com/comment/82219714
has comment: http://stackoverflow.com/comment/82219844
tagged with: python

http://stackoverflow.com/a/47647043
answers question: http://stackoverflow.com/q/47646954
has body: You can do this string = "some ' string" final = string.replace('\'','') print(final) output some string
type: Answer
score: 0

http://stackoverflow.com/comment/82292695
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47666452
type: AnswerComment
has text: `change_increasing` would have one lesser element. So, how is `changes[change_increasing]` possible?

http://stackoverflow.com/a/47692039
score: 4
upvote count: 4
has body: As I said in the comment to the question, just replace (re-assign) the values in the dataframe with the data returned from the Imputer. Lets say this is your dataframe: import numpy as np import pandas as pd df = pd.DataFrame(data=[[1,2,3], [3,4,4], [3,5,np.nan], [6,7,8], [3,np.nan,1]], columns=['A', 'B', 'C']) Current df: A B C 0 1 2.0 3.0 1 3 4.0 4.0 2 3 5.0 NaN 3 6 7.0 8.0 4 3 NaN 1.0 If you are sending whole the df to Imputer, just use this: df[df.columns] = Imputer().fit_transform(df) If you are sending only some columns, then use those columns only to assign the results: columns_to_impute = ['B', 'C'] df[columns_to_impute] = Imputer().fit_transform(df[columns_to_impute]) Output: A B C 0 1.0 2.0 3.0 1 3.0 4.0 4.0 2 3.0 5.0 4.0 3 6.0 7.0 8.0 4 3.0 4.5 1.0
downvote count: 0
answers question: http://stackoverflow.com/q/47689825
type: Answer

http://stackoverflow.com/comment/82121554
has text: *"However this does not overlap so I enter AXX and it only gives me AAC"*: for what string? Please give a clear example and the expected output.
comment on: http://stackoverflow.com/q/47581914
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47651979
type: AcceptedAnswer
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47649284
has body: You don't need to use latex rendering. Normal MathText is sufficient. It still has most basic latex capabities, e.g. a small space as \, available. import matplotlib.pyplot as plt plt.plot([1,2], label='$100\,$s') plt.plot([1,3], label='$100$ s') plt.legend() plt.show()
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/47649284

http://stackoverflow.com/a/47624107
answers question: http://stackoverflow.com/q/47623063
type: Answer
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47623063
type: AcceptedAnswer
has body: The problem has the following causes: QModelIndex should not be used to differentiate between items of a model, According to the docs: Note: Model indexes should be used immediately and then discarded. You should not rely on indexes to remain valid after calling model functions that change the structure of the model or delete items. If you need to keep a model index over time use a QPersistentModelIndex. A file has several associated columns in QFileSystemModel, it is appropriate to save the index of the first column. Considering both things the code should be the following: all_entries = list() class MyFileSystemModel(QtWidgets.QFileSystemModel): def data(self, index, role): if index.column() == 0: if QPersistentModelIndex(index) not in all_entries: all_entries.append(QPersistentModelIndex(index)) return super().data(index, role) [...] def print_entries(self): print('*'*80) for index in all_entries: ix = QModelIndex(index) # get QModelIndex from QPersistentModelIndex print(index, os.path.relpath(self.model.filePath(ix),os.path.abspath('.')))

http://stackoverflow.com/q/47662143
has answer: http://stackoverflow.com/a/47662958
has body: I am having troubles understanding the meaning and usages for Tensorflow Tensors and Sparse Tensors. According to the documentation Tensor Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of floating point numbers with dimensions [batch, height, width, channels]. Sparse Tensor TensorFlow represents a sparse tensor as three separate dense tensors: indices, values, and shape. In Python, the three tensors are collected into a SparseTensor class for ease of use. If you have separate indices, values, and shape tensors, wrap them in a SparseTensor object before passing to the ops below. My understandings are Tensors are used for operations, input and output. And Sparse Tensor is just another representation of a Tensor(dense?). Hope someone can further explain the differences, and the use cases for them.
tagged with: python
has answer: http://stackoverflow.com/a/58825601
has title: What is the difference between tensors and sparse tensors?
possible better answer: http://stackoverflow.com/a/58825601
upvote count: 27
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47662958
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
score: 26

http://stackoverflow.com/a/47594371
type: Answer
has body: Using list comprehension [[0 if i&gt;=len(l)/2 else j for i,j in enumerate(l)] for l in A] Output: [[1, 2, 4, 0, 0, 0], [3, 5, 4, 0, 0, 0], [4, 6, 0, 0, 0, 0], [0, -3, -4, 0, 0, 0]]
score: 0
answers question: http://stackoverflow.com/q/47593815

http://stackoverflow.com/q/47644680
has comment: http://stackoverflow.com/comment/82248214
type: Question
has answer: http://stackoverflow.com/a/47644805
has comment: http://stackoverflow.com/comment/82248185
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47644805
has comment: http://stackoverflow.com/comment/82248086
has body: everyone! I'm new to Django and actually making a study project. I'm getting a NoReverseMatch exception and can't understand why. It seems not to have namespace conflicts, the other list views are made in the same way as for the StoredItem model, but only this one throws an exception: models.py: from django.db import models from django.urls import reverse # Create your models here. class LegalEntity(models.Model): name = models.CharField(max_length=100, help_text="Name") rif = models.CharField(max_length=10, help_text="RIF") address = models.TextField(help_text="Address") phone_num = models.CharField(max_length=15, help_text="Phone number") def __str__(self): pass class Contract(models.Model): name = models.CharField(max_length=100, help_text="Name") number = models.CharField(max_length=50, help_text="Contract number") description = models.TextField(help_text="Contract description") start_date = models.DateField(null=False, blank=False, help_text="Start date") expiry_date = models.DateField(null=True, blank=True, help_text="Expiry date") def __str__(self): return "number: {0}, " \ "name: \"{1}\", " \ "starts: {2}, " \ "expires: {3}."\ .format(self.number, self.name, self.start_date, self.expiry_date) def get_absolute_url(self): return reverse('contract-detail', args=[str(self.id)]) class Provider(LegalEntity): contract = models.ForeignKey(Contract) def __str__(self): return "name: \"{0}\", " \ "RIF: {1}, " \ "phone: {2}."\ .format(self.name, self.rif, self.phone_num) def get_absolute_url(self): return reverse('provider-detail', args=[str(self.id)]) class Item(models.Model): name = models.CharField(max_length=100, help_text="Name") serial = models.CharField(max_length=50, help_text="Serial No.") manufacturer = models.CharField(max_length=50, help_text="Manufacturer") provider = models.ForeignKey(Provider) def __str__(self): return "name: \"{0}\", " \ "serial: {1}, " \ "manufacturer: {2}," \ "provider: {3}."\ .format(self.name, self.serial, self.manufacturer, self.pro…
has title: Django : NoReverseMatch error
answer count: 1

http://stackoverflow.com/a/47553635
downvote count: 0
has body: False in _compare is already a boolean so return False not in _compare is the best way to do it. but looking wider: _==inp[0] for _ in inp should be return all(x==inp[0] for x in inp) so it returns False if one value is False This solution works even if the items aren't hashable.
has comment: http://stackoverflow.com/comment/82063969
answers question: http://stackoverflow.com/q/47553596
has comment: http://stackoverflow.com/comment/82063796
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82064111

http://stackoverflow.com/comment/82266141
type: Comment
type: QuestionComment
has text: You need to think of it in terms of *state of the object*. Should a method *modify the object's state* or merely return a value based on the current state of the object?
score: 5
comment on: http://stackoverflow.com/q/47654018

http://stackoverflow.com/comment/127218280
comment on: http://stackoverflow.com/q/47611647
type: QuestionComment
has text: were you able to get its answer? like how to automatically detect things?
score: 0
type: Comment

http://stackoverflow.com/a/47584312
score: 1
answers question: http://stackoverflow.com/q/47575008
has body: So the question is: Given a data set in the form 1,2 1,3 1,4 3,1 6,5 5,7 Identify the chains 1 -&gt; 2 -&gt; 3 -&gt; 4 and 5 -&gt; 6 -&gt; 7 And output them as 1,2 1,3 1,4 5,6 5,7 Here is a working solution in python. (Happy Holidays) To run it use python thisfile.py yourdata.csv &gt; output.csv You, of course, will need to have python3 installed. There are plenty of comments in the code. I gave no thought at all to efficiency, so put the kettle on - it will take about 15 mins or so to complete. If you want it to be faster, its the list.append() calls that take the time. Using numpy would probably speed things up but I didn't want to add extra dependencies. Let me know if you have any questions. Output from your example data is: 3856 , 18216 3856 , 59888 12513 , 12812 12513 , 19922 12513 , 52188 import csv import sys def flatten(l): return list(set([item for subl in l for item in subl])) def main(): # read the csv raw_data = [] with open(sys.argv[1], 'r') as so_data: lst = csv.reader(so_data) for row in lst: raw_data.append(row) data = [] for i in raw_data: data.append([int(i[0].strip()), int(i[1].strip())]) #set keys to uniq elements from col1 and col2 keys1 = list(set([i[0] for i in data])) keys2 = list(set([i[1] for i in data])) keys = list(set(keys1 + keys2)) # find the subchains for each key subchains = {} for key in keys: found = [k for k in data if key in k] found = flatten(found) subchains[key] = found # This is the tricky bit # we need to follow each element of the subchains looking # for new links - we are done for a key when the list doesn't grow chain, links = [], [] chain_dict = {} for key in keys: links.append(subchains[key]) links = flatten(links) done = False size = len(links) while not done: for i in links: # find subchain for i for e in subchains[i]: chain.append(e) chain = list(set(chain)) chain.sort() if len(chain) &gt; size: done = False size = len(chain) else: done = True chain_dict[key] = chain chain, links = [], [] # shorter chains will now b…
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47575008

arrays
tags question: http://stackoverflow.com/q/47621997
tags question: http://stackoverflow.com/q/47675520
tag name: arrays
tags question: http://stackoverflow.com/q/47652962
tags question: http://stackoverflow.com/q/47558240
tags question: http://stackoverflow.com/q/47552154
tags question: http://stackoverflow.com/q/47592755
tags question: http://stackoverflow.com/q/47624656
tags question: http://stackoverflow.com/q/47644890
tags question: http://stackoverflow.com/q/47642570
type: Tag
tags question: http://stackoverflow.com/q/47686897
tags question: http://stackoverflow.com/q/47611823
tags question: http://stackoverflow.com/q/47590148
tags question: http://stackoverflow.com/q/47638689
tags question: http://stackoverflow.com/q/47669791
tags question: http://stackoverflow.com/q/47613772
tags question: http://stackoverflow.com/q/47544101
tags question: http://stackoverflow.com/q/47613323
tags question: http://stackoverflow.com/q/47564583
tags question: http://stackoverflow.com/q/47682662
tags question: http://stackoverflow.com/q/47681799
tags question: http://stackoverflow.com/q/47586128
tags question: http://stackoverflow.com/q/47561752
tags question: http://stackoverflow.com/q/47572037
tags question: http://stackoverflow.com/q/47588714
tags question: http://stackoverflow.com/q/47680897
tags question: http://stackoverflow.com/q/47546035
tags question: http://stackoverflow.com/q/47681110
tags question: http://stackoverflow.com/q/47600071
tags question: http://stackoverflow.com/q/47576618
tags question: http://stackoverflow.com/q/47639347
tags question: http://stackoverflow.com/q/47604046
tags question: http://stackoverflow.com/q/47683415
tags question: http://stackoverflow.com/q/47561443
tags question: http://stackoverflow.com/q/47582014
tags question: http://stackoverflow.com/q/47624760
tags question: http://stackoverflow.com/q/47649686
tags question: http://stackoverflow.com/q/47651591
tags question: http://stackoverflow.com/q/47670890
tags question: http://stackoverflow.com/q/47613121
tags question: http://stackoverflow.com/q/47589268
tags question: http://stackoverflow.com/q/47596270
tags question: http://stackoverflow.com/q/47630287
tags question: http://stackoverflow.com/q/47582312
tags question: http://stackoverflow.com/q/47663553
tags question: http://stackoverflow.com/q/47660726
tags question: http://stackoverflow.com/q/47656153
tags question: http://stackoverflow.com/q/47561718
tags question: http://stackoverflow.com/q/47620360
tags question: http://stackoverflow.com/q/47591401
tags question: http://stackoverflow.com/q/47629343
tags question: http://stackoverflow.com/q/47690706
tags question: http://stackoverflow.com/q/47661550
tags question: http://stackoverflow.com/q/47597890
tags question: http://stackoverflow.com/q/47559470
tags question: http://stackoverflow.com/q/47548957
tags question: http://stackoverflow.com/q/47608222
tags question: http://stackoverflow.com/q/47603564
tags question: http://stackoverflow.com/q/47666539
tags question: http://stackoverflow.com/q/47547986
tags question: http://stackoverflow.com/q/47540800
tags question: http://stackoverflow.com/q/47561108
tags question: http://stackoverflow.com/q/47655958
tags question: http://stackoverflow.com/q/47599745
tags question: http://stackoverflow.com/q/47559233
tags question: http://stackoverflow.com/q/47641986
tags question: http://stackoverflow.com/q/47684650
tags question: http://stackoverflow.com/q/47597258
tags question: http://stackoverflow.com/q/47620841
tags question: http://stackoverflow.com/q/47623723
tags question: http://stackoverflow.com/q/47660042
tags question: http://stackoverflow.com/q/47643499
tags question: http://stackoverflow.com/q/47599128
tags question: http://stackoverflow.com/q/47567828
tags question: http://stackoverflow.com/q/47644844
tags question: http://stackoverflow.com/q/47569461
tags question: http://stackoverflow.com/q/47645501
tags question: http://stackoverflow.com/q/47563354
tags question: http://stackoverflow.com/q/47559323

http://stackoverflow.com/comment/82076166
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47558518
has text: train_inputs = (np.asfarray(all_values[1:]) / 255 * 0.99 ) + 0.01
type: Comment

http://stackoverflow.com/a/47641520
accepted answer of: http://stackoverflow.com/q/47640891
has body: Code: from bs4 import BeautifulSoup import urllib.request url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'} req = urllib.request.Request(url, headers=headers) resp = urllib.request.urlopen(req) html = resp.read() soup = BeautifulSoup(html, "html.parser") rivers = soup.select_one("td.sites-layout-tile.sites-tile-name-content-1") data = [ div.text.split('-')[1:] for div in rivers.find_all('div', style='font-size:small') if div.text.strip() ][4:-4] data = {k.strip():v.strip() for k,v in data} print(data) Steps: Select the container tag ('tr.sites-layout-tile.sites-tile-name-content-1') Find all &lt;div style='font-size:small'&gt; children tags, select the text and split by '-'. Create a dictionary from the items in data.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47640891
type: Answer
score: 0

http://stackoverflow.com/comment/82082564
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47558863
type: Comment
has text: Sure, they all work fine. If you have a problem with them, you need to provide a [mcve] of the issue.

http://stackoverflow.com/comment/82240699
type: QuestionComment
has text: Do you have to produce the results via a separate script that writes to stdout, as you've shown? If not, a better design might be to create a function that returns a string holding the result. Then call that function when needed from your Flask application.
comment on: http://stackoverflow.com/q/47641127
score: 0
type: Comment

http://stackoverflow.com/comment/82188408
comment on: http://stackoverflow.com/q/47614983
score: 1
type: Comment
type: QuestionComment
has text: Why is `laptop` a positional argument for function `renting_1`? Shouldn't it not be there? as you are redefining `laptop` in the function anyways.

http://stackoverflow.com/comment/82304735
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47672687
has text: Thank you so much @RoachLod
type: Comment

http://stackoverflow.com/a/47825892
score: 0
has body: You're fetching only the Tweet text (content of the tweet itself), if you look at results['statuses'] object you'll see all tweets you've fetched, and if you print your tweet object, you'll get all the metadata relate to it. I wrote a blog post on how to use Twython with Twitter search API, https://pythonstack.org/2017/12/collecting-data-from-twitter-rest-search-api-using-python/ I hope you find it helpful.
type: Answer
answers question: http://stackoverflow.com/q/47697667

ansible
tags question: http://stackoverflow.com/q/47672974
type: Tag
tags question: http://stackoverflow.com/q/47551111
tag name: ansible
tags question: http://stackoverflow.com/q/47600292

http://stackoverflow.com/q/47610985
has title: Setup data for dynamic topic modelling
tagged with: topic-modeling
score: 2
answer count: 0
upvote count: 2
tagged with: pubmed
downvote count: 0
has body: I'm trying to learn dynamic topic modeling(to capture the semantic changes in the words) from data scrapped from PUBMED. I was able to get the data in the form of xml and was able to extract the "abstract" text and the date information off of it and saved that in the csv format. (But this is just a part of the data.) Format obtained Year|month|day|abstractText I'm planning on using gensim lda for my model I've never really done topic modeling before and need your help with guiding me through this process one step at a time. Questions: Is csv a preferred format to feed into gensim lda? for dynamic modeling, how should the time aspect of the data be captured and used in the model? is there a better way to organize the data than in csv files? Should i use the bodytext instead of the abstract for this? Hope I learn a lot from this. Thanks in advance.
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: gensim
tagged with: text-mining

http://stackoverflow.com/comment/82140107
score: 1
has text: show the code, including the use of `sorted()`
comment on: http://stackoverflow.com/q/47591430
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47581250
downvote count: 0
answers question: http://stackoverflow.com/q/47581248
has body: The problem here, as far as I see it is exactly that last point, the debugger connects to uWSGI / the application process, which is not any of the individual request processes. To solve this, from my situation, it needed 2 things changed, 1 of which is the uWSGI configuration for my app. Our production file looks something like [uwsgi] ... master = true enable-threads = true processes = 5 But here, to give the debugger (and us) an easy time to connect to the request process, and stay connected, we change this to [uwsgi] ... master = true enable-threads = false processes = 1 Make it the master, disable threads, and limit it to only 1 process - http://uwsgi-docs.readthedocs.io/en/latest/Options.html Then, in the startup python file, instead of setting the debugger to connect when the entire flask app starts, you set it to connect in a function decorated with the handy flask function, before_first_request http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_first_request, so the startup script changes to something like, import sys import wsgi_configuration_module sys.path.append('pycharm-debug.egg') import pydevd app = wsgi_configuration_module.app @app.before_first_request def before_first_request(): pydevd.settrace('localhost', port=11211, stdoutToServer=True, stderrToServer=True, suspend=False) print 'connected' # So now, you've limited uWSGI to no threads, and only 1 process to limit the chance of any mixup with them and the debugger, and set pydevd to only connect before the very first request. Now, the debugger connects (for me) successfully once, at the first request in this function, prints 'connected' only once, and from then on breakpoints connect in any of your request endpoint functions without issue.
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/47577016
tagged with: pandas
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/116786680
favorite count: 0
type: Question
has body: I am using Python pandas to read_excel. This is the column I am reading in. My problem is that read_excel isn't counting the empty cells as cells. When I use df2=df1.iloc[0:30], I want it to include those empty cells so those last two data items are not included in my dataframe (this is because these cells are populated daily throughout the month, so those empty cells will exist until the very last day of the month). How do I ensure pandas read_excel includes those empty cells in its dataframe?
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82111903
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82111754
has comment: http://stackoverflow.com/comment/82111404
tagged with: excel
has comment: http://stackoverflow.com/comment/134823334
has answer: http://stackoverflow.com/a/47577369
has comment: http://stackoverflow.com/comment/134819458
has answer: http://stackoverflow.com/a/66237963
has comment: http://stackoverflow.com/comment/134810336
has title: Reading in Empty Cells with `read_excel` in Python pandas

http://stackoverflow.com/comment/82129334
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47585810
type: Comment
has text: "Is an attribute of an object possible dynamically?" - it's not clear what you're asking. Did you mean: "can we set an object attribute dynamically?" if so the answer is "yes"

http://stackoverflow.com/comment/82155637
comment on: http://stackoverflow.com/a/47598730
type: AnswerComment
has text: Then it wouldn't work which is why I said there can only be one instance of "Q:", but I was just trying to present the simplest and easiest to implement possible answer based on the above input. It won't work if your example occurs.
score: 0
type: Comment

http://stackoverflow.com/comment/82131037
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47570035
has text: @martijn-pieters I increased the max size and the request went through. But I don't understand why the connection is closed early when using requests, while both postman and curl get a response from the server. (It's a response that I set, so it's not being generated by Postman etc.)

http://stackoverflow.com/comment/82071352
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/1830618/how-to-find-the-owner-of-a-file-or-directory-in-python. Seems that that doesn't work with windows...
score: 0
comment on: http://stackoverflow.com/q/47556831

http://stackoverflow.com/q/47634848
has title: InsecurePlatformWarning: A true SSLContext object is not available
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49372281
score: 1
has body: I want to setup python project from CentOS to windows. While "pip install requirement.txt" getting following error: c:\python27\lib\site- packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Could not find a version that satisfies the requirement requirements.txt (from versions: ) No matching distribution found for requirements.txt Please help/guide me. I' new with these things
tagged with: ssl
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49372281
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47673713
tagged with: authentication
answer count: 1
favorite count: 0
tagged with: oauth
type: Question
has answer: http://stackoverflow.com/a/48957939
tagged with: python
type: UnansweredQuestion
has title: Python Mendeley SDK API returns error in authentication
has body: I have a mendeley account which I am using from their online version. I created a userid and client secret, saved it in config.yml file from and using it to authenticate. I am using the below code available on their website import yaml from mendeley import Mendeley with open('config.yml') as f: config = yaml.load(f) REDIRECT_URI = 'http://localhost:5000/oauth' mendeley = Mendeley(config['clientId'], config['clientSecret'], REDIRECT_URI) auth = mendeley.start_client_credentials_flow() session = auth.authenticate() This code works fine and I got not errors. But when I am trying to access data using the commands in the example it throws error. For example &gt;&gt; print (session.profiles.me.display_name) mendeley.exception.MendeleyApiException: The Mendeley API returned an error (status: 400, message: No userid found in auth token) &gt;&gt; for document in session.documents.iter(): print document.title mendeley.exception.MendeleyApiException: The Mendeley API returned an error (status: 403, message: Access to this document is not allowed) I am stuck here and do not know how to access the data or articles I have on mendeley fom its API. Any help will be highly appreciated.
linked to: http://stackoverflow.com/q/47777288
tagged with: mendeley
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/82170761
comment on: http://stackoverflow.com/q/47605991
type: QuestionComment
score: 0
has text: Are you sure that the website itself does not limit your downloads as a sort of anti-ddos method?
type: Comment

http://stackoverflow.com/q/47557480
favorite count: 0
tagged with: networkx
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82072497
accepted answer: http://stackoverflow.com/a/47557582
has comment: http://stackoverflow.com/comment/82072548
has comment: http://stackoverflow.com/comment/82072716
tagged with: python
has body: The error reported Python3.5.2\lib\site-packages\networkx\drawing\nx_pylab.py", line 836, in draw_networkx_edge_labels for (n1, n2), label in labels.items(): ValueError: not enough values to unpack (expected 2, got 1) Code map_paths_reduced = [(0, 75), (75, 38), (38, 86), (86, 119), (119, 85), (85, 44), (44, 65), (65, 127), (127, 106), (106, 31)] edge_labels_dict_reduced = {'7': '27.0', '4': '31.0', '2': '17.0', '0': '12.0', '6': '13.0', '1': '16.0', '8': '8.0', '9': '34.0', '3': '6.0', '5': '45.0'} where, len(edge_labels) = 150 G = nx.DiGraph() G.add_nodes_from(range(len(edge_labels)+1)) black_edges = [edge for edge in G.edges()] pos = nx.random_layout(G) G.add_edges_from(map_paths_reduced) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size=100) nx.draw_networkx_labels(G, pos, font_size=1) nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels_dict_reduced) ##ERROR REPORTED HERE nx.draw_networkx(G, pos, arrows=True) return plt.show() When i pass the edge labels dictionary inside nx.draw_networkx_edge_labels using "labels" argument instead of "edge_labels", it shows empty dictionaries as shown in picture. But i am looking for edge labels with key:value entries.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82072590
downvote count: 0
has title: ValueError: not enough values to unpack (expected 2, got 1) NetworkX python 3
has answer: http://stackoverflow.com/a/47557582
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/82106062
type: AnswerComment
has text: Link-only answers are generally [frowned upon](http://meta.stackexchange.com/a/8259/204922) on Stack Overflow. In time it is possible for links to atrophy and become unavailable, meaning that your answer is useless to users in the future. It would be best if you could provide the general details of your answer in your actual post, citing your link as a reference.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47574244

http://stackoverflow.com/q/47660531
tagged with: python
type: UnansweredQuestion
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/82360395
has comment: http://stackoverflow.com/comment/82320083
has answer: http://stackoverflow.com/a/47660765
linked to: http://stackoverflow.com/q/15638650
has title: Finding equal variables in non solvable multi-variables linear equations
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82318526
has comment: http://stackoverflow.com/comment/82284411
favorite count: 0
has answer: http://stackoverflow.com/a/47661372
has body: I am trying to find an algorithm to solve the current problem. I have multiple unknown variables (F1,F2,F3, ... Fx) and (R1,R2,R3 ... Rx) and multiple equations like this: F1 + R1 = a F1 + R2 = a F2 + R1 = b F3 + R2 = b F2 + R3 = c F3 + R4 = c where a, b and c are known numbers. I am trying to find all equal variables in such equations. For example in the above equation I could see that F2 and F3 are equal and R3 and R4 are equal. First equations tells us that R1 and R2 are equal, and second tells us that F2 and F3 are equal, while the third tells us that R3 and R4 are equal. For a more complex scenario, is there any known algorithm that can find all equal (F and R) variables???? (I will edit the question if it is not clear enough) Thanks
type: Question
tagged with: equivalence
answer count: 2
has comment: http://stackoverflow.com/comment/82281399
has comment: http://stackoverflow.com/comment/82280551

http://stackoverflow.com/comment/82285894
comment on: http://stackoverflow.com/q/47661978
type: QuestionComment
has text: @PaulH You mean use "<" and ">" instead of "<=" and ">="? That's not working, still connected.
score: 0
type: Comment

http://stackoverflow.com/q/47640472
type: Question
has comment: http://stackoverflow.com/comment/82240841
has comment: http://stackoverflow.com/comment/82240014
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82241443
has comment: http://stackoverflow.com/comment/82241158
has comment: http://stackoverflow.com/comment/82241325
tagged with: python
has comment: http://stackoverflow.com/comment/82239606
linked to: http://stackoverflow.com/q/17757819
has title: Error while installing Tkinter on python 64bit on windows 64 bit
has comment: http://stackoverflow.com/comment/82241395
has comment: http://stackoverflow.com/comment/82239581
has body: I get the following error when trying to import Tkinter: &gt;&gt;&gt; import Tkinter Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\lib-tk\Tkinter.py", line 38, in &lt;module&gt; import FixTk File "C:\Python27\lib\lib-tk\FixTk.py", line 68, in &lt;module&gt; import _tkinter ImportError: DLL load failed: %1 is not a valid Win32 application. I have a windows 64 bit with python 64 bit. I came across this when trying to use matplotlib. import matplotlib is working but import matplotlib.pyplot fails with the same error as above. I have tried installing matplotlib from https://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib also. And I have installed Tkinter from there too tkinter3000-1.1.1-cp27-cp27m-win_amd64.whl - as seen from the comments that would not have been necessary. I have installed Python 2.7.14 from the python website and this version Download Windows x86-64 MSI installer On starting python on command prompt I get this: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32 but my system type is 64 bit OS x64 based processor.
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82241215
has comment: http://stackoverflow.com/comment/82241089
has comment: http://stackoverflow.com/comment/82240187
has comment: http://stackoverflow.com/comment/82240701
has comment: http://stackoverflow.com/comment/82239648

http://stackoverflow.com/q/47655511
has comment: http://stackoverflow.com/comment/82269444
has comment: http://stackoverflow.com/comment/82269847
downvote count: 2
has comment: http://stackoverflow.com/comment/82269273
upvote count: 1
has body: months=['January','February','March','April','May','June','July','August','September','October','November','December'] usermonth=input('Enter the month: ') if usermonth &gt;=months[0]and usermonth &lt;=months[10]: nextmonth=months(usermonth+1) print(nextmonth) How would I go about defining one up in the index of the user's month? Thanks.
has answer: http://stackoverflow.com/a/47655648
favorite count: 0
has answer: http://stackoverflow.com/a/47655716
has comment: http://stackoverflow.com/comment/82269309
type: Question
has title: python manipulating list after user input
has comment: http://stackoverflow.com/comment/82269805
answer count: 2
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82269183
score: -1

http://stackoverflow.com/q/47546388
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: SQL Timestamp in PostgreSQL
tagged with: psql
has body: I'm trying to understand the raw manner in which PostgreSQL saves timestamp data types. I get 2 different results depending on the client I use: 1. psql # SELECT date_incorporated FROM client; date_incorporated ------------------------ 2017-06-14 19:42:15-04 2. records python module rows = db.query('SELECT date_incorporated FROM client') print(rows[0]) # {"date_incorporated": "2017-06-14T19:42:15-04:00"} Since the psql interface and records module are both supposed to be giving me back the raw data, I can't understand why both are giving me back different formats of the timestamp they have stored. The two differences I see so far are the T's in the middle between the date and time in the records version, and also the differing ways in which it shows the time zone at the end of the string Is one of them altering it? Which one is showing the real data?
tagged with: sql
answer count: 1
has answer: http://stackoverflow.com/a/47548970
accepted answer: http://stackoverflow.com/a/47548970
favorite count: 0
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/82049960
tagged with: python
tagged with: datetime-format

http://stackoverflow.com/comment/82073688
comment on: http://stackoverflow.com/a/47557782
score: 1
type: Comment
type: AnswerComment
has text: Your code works for your dataset. For my dataset, it tells me for the return statement: expected string or bytes-like object

http://stackoverflow.com/q/47564872
has answer: http://stackoverflow.com/a/47564996
has answer: http://stackoverflow.com/a/47565355
has comment: http://stackoverflow.com/comment/82087815
type: Question
has title: Calculate sum of value in python list based of employee name field
has body: Greeting everyone, I have a list in my python file, based from this list how can I calculate sum of the actual_duration for each of the employee A, B and C? Below is my list : [{'employee_name': 'A', 'actual_duration': 14}, {'employee_name': 'A', 'actual_duration': 6}, {'employee_name': 'B', 'actual_duration': 8}, {'employee_name': 'B', 'actual_duration': 22}, {'employee_name': 'C', 'actual_duration': 15}]
possible better answer: http://stackoverflow.com/a/47564996
has comment: http://stackoverflow.com/comment/82087844
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/47565114
has comment: http://stackoverflow.com/comment/82087869
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47565114
score: 0
has comment: http://stackoverflow.com/comment/82087787
has answer: http://stackoverflow.com/a/47565419

http://stackoverflow.com/comment/82184081
comment on: http://stackoverflow.com/a/47612435
has text: Slight nomenclature mixup perhaps? I used AverageSim**s**, you used AverageSim.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82196241
has text: @sniper yes only o and 1.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47618944
score: 0

http://stackoverflow.com/comment/82200710
score: 0
has text: What platform are you testing this on?
comment on: http://stackoverflow.com/q/47621172
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82077413
type: QuestionComment
comment on: http://stackoverflow.com/q/47559799
has text: instead of "a" argument for your open function, you'd have to use "r+". "a" means append, so you can only write to the end of the file. "r+ will let you seek to a position and write anywhere in the file
score: 0
type: Comment

http://stackoverflow.com/comment/82333717
type: AnswerComment
has text: No idea who did. Glad I could help and I hope it saved you a bit of time! (Friendly programming might have had a helpful error kicked back saying something like "there is no tensorflow Constant... did you mean constant?")
comment on: http://stackoverflow.com/a/47687006
type: Comment
score: 0

http://stackoverflow.com/q/47616332
score: 1
downvote count: 0
upvote count: 1
tagged with: pos-tagger
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: nltk
has body: I'm currently trying to train my Python NLTK Part-Of-Speech Tagger to tag German text correctly. In order to do so I'm using of the ClassifiedBasedGermanTagger, from: https://github.com/ptnplanet/NLTK-Contributions/tree/master/ClassifierBasedGermanTagger and a training corpus from this website: http://www.ims.uni-stuttgart.de/forschung/ressourcen/korpora/TIGERCorpus/download/start.html (TIGER Corpus Release 2.2 (July 2012)) I found out that there is a pretty well written tutorial on how to go about this. So right now all I'm trying to do is to recreate the code: https://datascience.blog.wzb.eu/2016/07/13/accurate-part-of-speech-tagging-of-german-texts-with-nltk/ The part that doesn't work for me is this: tagged_sents = corp.tagged_sents() random.shuffle(tagged_sents) The error I get looks like this: File "C:\somedude\lib\random.py", line 274, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'LazyMap' object does not support item assignment Do you have a workaround for this or even an explanation as to why it supposedly worked for the gentleman that wrote that tutorial and why it shows an error for me? Currently I'm using Python 3. Thank you all very much in advance.
has answer: http://stackoverflow.com/a/48581326
tagged with: python
has answer: http://stackoverflow.com/a/47616414
has title: random.shuffle(someLazyMap)
answer count: 2

http://stackoverflow.com/a/47623467
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47623398
score: 1
has body: Here's a solution using defaultdict from collections import defaultdict def lst(profiles_file: TextIO): initial_dict = fix_files(profiles_file) with_n = defaultdict(list) without_n = defaultdict(list) for k, v in initial_dict.items(): for item in v: if '\n' in item: with_n[k].append(item) else: without_n[k].append(item) return [without_n, with_n]

http://stackoverflow.com/q/47659689
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47659762
tagged with: ordereddictionary
tagged with: python
tagged with: dictionary
has body: I thought I set out a simple project for myself but I guess not. I think im using the Ordered dict function long because I keep getting: ValueError: too many values to unpack (expected 2) Code: import random import _collections shop = { 'bread': 2, 'chips': 4, 'tacos': 5, 'tuna': 4, 'bacon': 8, } print(shop) ''' items = list(shop.keys()) random.shuffle(items) _collections.OrderedDict(items) ''' n = random.randrange(0, len(shop.keys())) m = random.randrange(n, len(shop.keys())) if m &lt;= n: m += 1 print(n, " ", m) for key in shop.keys(): value = shop[key] * random.uniform(0.7,2.3) print(key, "=", int(value)) if n &lt; m: n += 1 else: break I would like for this code to mix up the dictionary, then multiply the values by 0.7 - 2.3. Then loop within the range 0-5 times in order to give me few random keys from the dictionary. I have placed ''' ''' over the code that I struggle with and gives me the errors.
accepted answer: http://stackoverflow.com/a/47659779
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47659779
has answer: http://stackoverflow.com/a/47659762
upvote count: 2
has comment: http://stackoverflow.com/comment/82278238
score: 1
has title: Dict with curly braces and OrderedDict
downvote count: 1

http://stackoverflow.com/comment/82082778
comment on: http://stackoverflow.com/a/47562412
score: 1
type: Comment
type: AnswerComment
has text: @cowbert Outside, see tabbing. I'll add some example code to make it clear. You only need it to compile once with the class, not every object.

http://stackoverflow.com/a/47652544
accepted answer of: http://stackoverflow.com/q/47652312
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82263460
has body: I tried: mail = "jim.smith@smth.edu" full_name = mail.split('@')[0] prenom = full_name.split('.')[0] #The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim' pre_name = full_name.split('.') nom = pre_name[1] #The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me print(full_name); print(pre_name); print(nom); print(prenom); and it prints: jim.smith ['jim', 'smith'] smith jim Without any exceptions. Problem: Like comments said: If no "." is used in name (before @), you are probably facing the indexOutOfRange Exception. Possible Solutions: Surround it in if-else block: if len(pre_name) &gt;= 2 or use try-except: try: nom = pre_name[1] except IndexError: nom = pre_name[0]; or use: if "." in full_name: pre_name = full_name.split('.') nom = pre_name[1] General Debugging: use print() earlier. // works until here pre_name = full_name.split('.') print(pre_name) // if no '.' was used, you will see the array contains only 1 element nom = pre_name[1] // problem here?
answers question: http://stackoverflow.com/q/47652312
type: Answer
has comment: http://stackoverflow.com/comment/82381049

http://stackoverflow.com/comment/82260791
type: QuestionComment
has text: Share the relevant html.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47651243

http://stackoverflow.com/q/47625257
has title: Key error when trying to vlookup pandas
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47625342
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47625322
tagged with: python
has answer: http://stackoverflow.com/a/47625322
has answer: http://stackoverflow.com/a/47625342
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has body: I am trying to vlookup values of EW against AD. Dataframe 1 EW 0 A 1 BC Dataframe 2 AD 0 A 1 B 2 BC Then I run: df3 = df1.insert(0, 'AD', df1['EW'].map(df2.set_index('EW')['AD'])) print (df1) Expect output for df3: AD 0 A 1 NaNa 2 BC I keep getting: KeyError: 'EW'
downvote count: 0

http://stackoverflow.com/comment/82254237
score: 0
comment on: http://stackoverflow.com/q/47647649
type: Comment
type: QuestionComment
has text: What is `print (df3.dtypes)` ?

http://stackoverflow.com/a/47579130
has comment: http://stackoverflow.com/comment/82170754
has comment: http://stackoverflow.com/comment/82116064
has comment: http://stackoverflow.com/comment/82115777
has comment: http://stackoverflow.com/comment/82137138
has comment: http://stackoverflow.com/comment/82131304
type: Answer
has comment: http://stackoverflow.com/comment/82131710
has comment: http://stackoverflow.com/comment/82118130
has comment: http://stackoverflow.com/comment/82172514
answers question: http://stackoverflow.com/q/47578807
has comment: http://stackoverflow.com/comment/82144858
has comment: http://stackoverflow.com/comment/82168726
has comment: http://stackoverflow.com/comment/82170904
score: 1
has comment: http://stackoverflow.com/comment/82170741
has comment: http://stackoverflow.com/comment/82135530
downvote count: 0
upvote count: 1
has body: You're trying to save the git repo into the ZipFile directly from the git.Repo.clone_from command. This will not work, as the git library cannot save a repo instantly into a zip file. What you'll have to do is choose a temporary path to save the repo onto, and then give that path to zip_archive.write. What you want is: tempPath = "/Users/abdul/temp/temp_zip" # you can change this, this is temporary git.Repo.clone_from(func_obj.sc_github, to_path=os.path.join(tempPath)) files = os.listdir(tempPath) for singleFile in files: zip_archive.write(os.path.join(tempPath, singleFile), singleFile) # you can now delete the folder at tempPath Instead of: zip_archive.write(git.Repo.clone_from(func_obj.sc_github, to_path=os.path.join(ARCHIVE_NAME))) A sample output from your git repo (https://github.com/arycloud/sis-testing.git): Note: this is the root directory of the zip file, no directories in between. This is using this exact code: import git, os, zipfile zip_archive = zipfile.ZipFile("C:\\Users\\Attoa\\Desktop\\testos.zip", "w") tempPath = "C:\\Users\\Attoa\\AppData\\Local\\Temp\\temp_zip\\" # you can change this, this is temporary git.Repo.clone_from("https://github.com/arycloud/sis-testing.git", to_path=os.path.join(tempPath)) files = os.listdir(tempPath) for singleFile in files: zip_archive.write(os.path.join(tempPath, singleFile), singleFile) I hope this helps!
has comment: http://stackoverflow.com/comment/82115975

http://stackoverflow.com/comment/95704223
score: 1
has text: This didn't, also due to this error: `Error: awscli 1.14.60 is already installed`
type: Comment
comment on: http://stackoverflow.com/a/48722050
type: AnswerComment

http://stackoverflow.com/comment/82075780
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47558488
has text: Yes, this is it. The link to the `multiline demo` is what I expected to have. Would you care to provide it as an answer so that I can accept it. Thanks a trillion @Wiktor Stribiżew.
score: 0

http://stackoverflow.com/comment/82075098
type: Comment
type: QuestionComment
has text: how does that work?
comment on: http://stackoverflow.com/q/47558622
score: 0

http://stackoverflow.com/q/47671720
tagged with: python
has title: Pandas rolling mean and selective indexing by time
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47672448
has answer: http://stackoverflow.com/a/47672448
has body: I've a dataset where I've reindexed it with respect to dates (datetime.datetime). A small sample of the dataframe looks like this, df2: lat lon Press NetLW rounded_dt 1997-11-30 17:00:00 76.15387 -147.62606 998.8 -51.0 1997-11-30 18:00:00 76.15280 -147.60379 1000.0 -50.9 1997-11-30 19:00:00 76.15164 -147.58055 1001.1 -54.4 1997-11-30 20:00:00 76.15037 -147.56047 1002.6 -52.2 1997-11-30 21:00:00 76.14948 -147.54034 1004.2 -51.9 1997-11-30 22:00:00 76.14834 -147.52181 1005.5 -51.3 1997-11-30 23:00:00 76.14777 -147.50568 1006.5 -50.7 1997-12-01 06:00:00 76.14152 -147.42073 1013.3 -44.6 1997-12-01 07:00:00 76.14105 -147.41370 1013.8 -45.4 1997-12-01 08:00:00 76.14072 -147.40661 1014.5 -46.1 1997-12-01 09:00:00 76.14059 -147.40093 1015.0 -43.0 So the time series is daily per hourly continuing for an year. What my aim is? I would like to extract the data based on NetLW for a specific range of days and only for 11 hour and 23 hour for those days. But the NetLW at that hour let's say, 11 hour should be averaged wrt NetLW(10 hour) , NetLW(11 hour) and NetLW(12 hour). What I've done so far? df3 = df2.rolling(window=3, center=True).mean() # to get the rolling mean # I want to extract the dates of interest from df3 dates_list =[] for idx in df2.index: # Winter dates (Dec-March) if idx &gt; datetime.datetime(1997, 11, 30, 23) and idx &lt; datetime.datetime(1998, 3, 1, 0): if idx.hour ==11 or idx.hour == 23: dates_list.append(df3[df3.loc[idx, 'NetLW'] &lt; -30.0]) And then I could concatenate the dates_list in one series/dataframe and get the dates Error message KeyError: True During handling of the above exception, another exception occurred And it points to this line: ---> dates_list.append(df3[df3.loc[idx, 'NetLW'] &lt; -30.0]) I'm expecting to use a boolean dtype to use it as an index for df3 and extract the data. Also, if it is possible to groupby the hour I'm interested in instead of writing multiple loops then please let me know as I'm new to Pandas.

http://stackoverflow.com/q/47636993
has title: Returning more than one output in C extensions?
tagged with: cpython
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has answer: http://stackoverflow.com/a/47637116
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39345995
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82231986
has body: Python allows to return more than one result using commas as separating value. When developing a CPython extension written in C language, is it possible to obtain the same result? How? I'm developing a CPython extension that replaces an existing Python code to do some tests on performance and I will prefer to have the same interface to not change the existing code base. I'm using Python 3.6.
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47637116
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47647693
type: Question
has comment: http://stackoverflow.com/comment/82255771
tagged with: amazon-rekognition
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I'm trying to build an application using this - https://github.com/awslabs/amazon-rekognition-video-analyzer/ Unfortunately, i'm getting a syntaxerror in the build.py file. def write_dir_to_zip(src, zf): '''Write a directory tree to an open ZipFile object.''' abs_src = os.path.abspath(src) for dirname, subdirs, files in os.walk(src): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) The error i'm getting is as follows File "build.py", line 26 arcname)) zf.write(absname, arcname) ^ SyntaxError: invalid syntax Thanks in advance!
tagged with: amazon-web-services
answer count: 0
has title: Invalid Syntax in build.py
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47561078
type: UnansweredQuestion
has title: Django post_save: database not yet updated?
tagged with: django
tagged with: python
score: 0
tagged with: sqlite
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47573787
has body: I'm writing a Django application for ordering stuff. All orders have a certain type Type. If Type.is_common == true, it needs to be included in a delivery no matter if a user orders this type or not. I'm using a post_save signal to check if my db already has a common order for a user for a certain delivery. Here is the code: @receiver(post_save, sender=Order) def create_common_order(sender, instance=None, created=False, **kwargs): """ This signal handler creates common orders (if delivery type definition contains any common types) for every first order of a user for a certain delivery. """ # Don't handle this if the order is not for a delivery if not created or not instance or not instance.delivery: return # Don't handle Order with common types if instance.type.is_common: return # Loop through all types in type definition of delivery for t in Type.objects.all(): # Look for a 'is_common' type if type.is_common: # Get or create an order with the respective values Order.objects.get_or_create( delivery=instance.delivery, user=instance.user, type=type, defaults={'count':1} ) My problem is the following: From time to time it happens that two common orders are created (if two new orders are created at almost the same time). But why? Is the db not yet updated in post_save? How can I prevent this behavior? I'm using a sqlite3 db.

http://stackoverflow.com/comment/82317539
type: Comment
comment on: http://stackoverflow.com/a/47679072
type: AnswerComment
has text: @Curunir I wouldn't say so. If you would e.g. define a `static List<String> words = new ArrayList<String>()` in an `ICommand` class in Java it would behave in the same way.
score: 1

http://stackoverflow.com/a/47601749
accepted answer of: http://stackoverflow.com/q/47601411
has comment: http://stackoverflow.com/comment/82165432
has comment: http://stackoverflow.com/comment/82164939
score: 1
has comment: http://stackoverflow.com/comment/82172038
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You have to use builtin from_bytes() method: x = b'\xea\xd0\x05\x00\x00\x00\xef' number = 360 * float( int.from_bytes(x[1:4], 'big') # get integer from bytes ) / 0xffffff print(number) will print: 292.5274832563092
has comment: http://stackoverflow.com/comment/82164013
has comment: http://stackoverflow.com/comment/82165523
answers question: http://stackoverflow.com/q/47601411
type: Answer

http://stackoverflow.com/comment/82261626
comment on: http://stackoverflow.com/q/47651288
score: 0
type: QuestionComment
has text: What do you see after printing `df.info()`?
type: Comment

http://stackoverflow.com/q/47666438
has comment: http://stackoverflow.com/comment/82292093
has answer: http://stackoverflow.com/a/47666700
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: Code import pandas as pd df = pd.DataFrame({'A': [1, 1, 1, 2, 2], 'B': range(5), 'C': range(5)}) df1 = df.groupby('A').B.agg({'B': ['count','nunique'],'C': ['sum','median']}) df1.columns = ["_".join(x) for x in df1.columns.ravel()] df1 Output B_count B_nunique C_sum C_median A 1 3 3 3 1.0 2 2 2 7 3.5 Warning __main__:1: FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version This was the recommended way to groupby and rename till Pandas 0.20. What is the elegant way to achieve the same df1 output without this warning?
has title: How to groupby() aggregate on multiple columns and rename the multi-index in Pandas 0.21+?
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/47666700
linked to: http://stackoverflow.com/q/44635626
tagged with: sklearn-pandas
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/a/47546353
type: Answer
accepted answer of: http://stackoverflow.com/q/47546162
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: If you want to select items from a QTableWidget you must use the setRangeSelected method, this requires that the range of the selection, in your case would be the respective row and column, then I show an example: class Widget(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) hlayout = QHBoxLayout() self.rbox = QSpinBox(self) self.cbox = QSpinBox(self) hlayout.addWidget(self.rbox) hlayout.addWidget(self.cbox) vlayout = QVBoxLayout(self) vlayout.addLayout(hlayout) nrows = 5 ncols = 5 self.rbox.setMaximum(nrows-1) self.cbox.setMaximum(ncols-1) self.table = QTableWidget(nrows, ncols, self) vlayout.addWidget(self.table) for r in range(nrows): for c in range(nrows): it = QTableWidgetItem("{}-{}".format(r, c)) self.table.setItem(r, c, it) self.rbox.valueChanged.connect(self.selectItem) self.cbox.valueChanged.connect(self.selectItem) self.selectItem() def selectItem(self): self.table.clearSelection() x = self.rbox.value() y = self.cbox.value() self.table.setRangeSelected(QTableWidgetSelectionRange(x, y, x, y), True) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
answers question: http://stackoverflow.com/q/47546162

http://stackoverflow.com/q/47638180
tagged with: bash
has answer: http://stackoverflow.com/a/47648172
answer count: 1
tagged with: python
type: Question
tagged with: subprocess
has title: How can I bypass a command to terminal inside another terminal via python?
type: UnansweredQuestion
has body: In python, we can call any process using subprocess. I have a situation where I have to work with interactive terminal where I need output of few commands, using python code. How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further? I am able to use subprocess module for 2 different command that where 2nd one is dependent on output of first one like ps -aux | grep python first ps -aux can be passed to 1 subprocess obj and that obj will be used as stdin of another subprocess command where grep python will be processed....
score: 0
tagged with: linux

http://stackoverflow.com/q/47577304
has title: PrimaryKeyRelatedField does not include value in validated_data
answer count: 1
tagged with: django
tagged with: python
tagged with: django-rest-framework
has body: I'm creating a serializer that is suppose to create an object on a POST request. However when run serializer.validated_data it does not include currency in the QueryDict. if i for instance change from PrimaryKeyRelatedField to IntegerField it includes it, but that is not optimal when it is suppose to point to a record in another table. Why is it that currency is not being included in validated_data when i use PrimaryKeyRelatedField? serializer class InvoiceSerializer(serializers.ModelSerializer): deposit_amount = serializers.FloatField() receive_amount = serializers.FloatField() currency = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('task', 'deposit_amount', 'receive_amount', 'currency') read_only_fields = ('created_at', 'updated_at', 'currency') def create(self, validated_data): return Invoice.objects.create(**validated_data) When i call request.data in my viewset it returns: {'currency': 2, 'task': 1, 'deposit_amount': 2.01, 'receive_amount': 118652.7} however when i return serializer.validated_data: OrderedDict([('task', 1), ('deposit_amount', 2.01), ('receive_amount', 118652.7)])
score: 0
has answer: http://stackoverflow.com/a/47578682
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/82287890
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47663931
type: Comment
has text: SOLVED: LazyFunction should have been LazyAttribute in date_joined

marker
tag name: marker
tags question: http://stackoverflow.com/q/47583064
type: Tag

http://stackoverflow.com/comment/82048189
has text: This one also gives incorrect results for some of the edge cases
comment on: http://stackoverflow.com/a/47545619
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47642846
has comment: http://stackoverflow.com/comment/82247034
has body: If you want to perform transforms on the certain methods and attributes of a class creation, you do that on the metaclass' __new__ function. Since yu already have a metaclass, all you have to do is to implement its __new__ method to convert any __load__ methods in a classmethod: class StaticLoad(type): __loaded_classes = set() def __new__(metacls, name, bases, namespace): if "__load__" in namespace and not isinstance(namespace["__load__"], classmethod): namespace["__load__"] = classmethod(namespace["load"]) return super().__new__(metacls, name, bases, namespace) def __call__(cls, *args, **kwargs): if cls not in cls.__class__.__loaded_classes: if hasattr(cls, '__load__'): cls.__load__() type(cls).__loaded_classes.add(cls) return super().__call__(*args, **kwargs) (the other change I made was to make explict that "__loaded_classes" should be accessed on the metaclass, not on the class itself).
has comment: http://stackoverflow.com/comment/82246199
upvote count: 2
has comment: http://stackoverflow.com/comment/82245120
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82262741
answers question: http://stackoverflow.com/q/47630203
downvote count: 0

http://stackoverflow.com/q/47663027
tagged with: django-orm
tagged with: django
tagged with: python
has title: Django ORM Annotate boolean field that defines is user member of a team
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47788257
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47788257
has body: models.py from django.db import models class UserGroup(models.Model): members = models.ManyToManyField(User, related_name='members', through='UserGroupMember') class UserGroupMember(models.Model): user = models.ForeignKey(User) usergroup = models.ForeignKey(UserGroup) class Cohort(models.Model): user_groups = models.ManyToManyField(UserGroup) class Team(models.Model): cohort = models.ForeignKey(Cohort) members = models.ManyToManyField(User, related_name='team_members', through='TeamMembers', blank=True) class TeamMembers(models.Model): team = models.ForeignKey(Team) user = models.ForeignKey(User) Single user can be part of only one team within a cohort. I want to annotate the new field (boolean) which tells you is the user assigned to some team in the cohort, something like: User.objects.filter( members__cohort=cohort ).annotate( is_team_member=... ) I am using Python 2.7.13 and Django 1.9.8. Thanks.

http://stackoverflow.com/comment/82290977
has text: Added someting addressing this using `pkgutil`. I somehow left out that part in my original post.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47645630

http://stackoverflow.com/a/47610944
answers question: http://stackoverflow.com/q/47609324
type: AcceptedAnswer
has body: Here is a function that has constant storage and runs in time of order log(x). I cannot think that smaller storage or order of running time is possible. The key idea is to treat x similar to a base-5 number. One way to find the base-5 representation of a number n is to find the first power of 5 that exceeds n, then keep decreasing that power of 5 and find how many of those fit into the number n. My routine is similar to that but removes the sums-of-exponents-of-5 rather than powers of 5. Finding the sum-of-exponents-of-n is easy for increasing powers of 5 due to a simple recurrence relation. There probably is a direct way to find the desired power of 5, but the second half of my function is slower than that so optimizing the first half of my function would not be much of an improvement. I have tested this routine for values of x up to 10,000 and it checks. It is very fast, beyond x=10**100, though checking those results is very slow. Note that I prefer to use the parameter n for an integer value rather than your x. Let me know if you need more explanation. def smallestsumexp5s(n): """Return the smallest integer whose sum of the exponents of 5 in the prime decomposition of i for 1 &lt;= i &lt;= n is greater than or equal to n. """ # Find the power of 5 whose sum passes n powerof5 = 5 sumofexpsof5 = 1 while sumofexpsof5 &lt;= n: powerof5 *= 5 sumofexpsof5 = sumofexpsof5 * 5 + 1 # Cut off pieces of the target to find the desired integer remains = n result = 0 while remains &gt; 0: # Back off to the previous power of 5 powerof5 //= 5 sumofexpsof5 //= 5 # Cut off pieces of the remaining number q, remains = divmod(remains, sumofexpsof5) # Adjust the accumulated result result += q * powerof5 return result
downvote count: 0
has comment: http://stackoverflow.com/comment/82180402
type: Answer
accepted answer of: http://stackoverflow.com/q/47609324
score: 2
upvote count: 2

http://stackoverflow.com/a/47613180
type: Answer
downvote count: 0
has body: This works [item for item in list_dict_01 if not item in list_dict_02]+[item for item in list_dict_02 if not item in list_dict_01]
upvote count: 1
answers question: http://stackoverflow.com/q/47613138
has comment: http://stackoverflow.com/comment/82184632
score: 1
has comment: http://stackoverflow.com/comment/82184699

http://stackoverflow.com/q/47544028
has body: I am trying to create a reconstruction matrix (A) for a image with shape (7500, 81920) and I am getting the error that it is bigger than 2GB. The line where I get the error is the one in which I calculate "our_loss". Does anyone know how I can still use a matrix this large in my program? A = np.random.randn(7500, 81920).astype('float32') y = np.dot(A, v) y_placeholder = tf.placeholder(tf.float32,[None,m]) our_loss = tf.reduce_mean( tf.reduce_sum( (tf.matmul(tf.reshape(G[0], [1, -1]) , A.T) - y_placeholder)**2, 1)) z_optim = tf.train.AdamOptimizer(learning_rate=0.1).minimize(our_loss, var_list=z) for i in range(num_iter): a, closs, b = sess.run([z_optim, our_loss, G],feed_dict={y_placeholder: y})
upvote count: 6
answer count: 0
downvote count: 0
score: 6
has title: Cannot create a tensor proto whose content is larger than 2GB
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82142304
has text: Glad to help! ;)
type: Comment
comment on: http://stackoverflow.com/a/47590129
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82136787
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47580750
has text: While this looks ideal for writing tests, I don't imagine it would be applicable to my project: it requires much changes of the code structure (I would have to break functions up in order to test every subroutine separately), and when it comes to function calls that rely on the flask app context (for example I could be manipulating flask-sqlalchemy data), this testing method wouldn't work either and there's no escape around that. But this has been very educating nontheless, thank you.

http://stackoverflow.com/comment/82156320
type: Comment
comment on: http://stackoverflow.com/q/47596795
type: QuestionComment
has text: Sorry while mocking up data those got added i removed '¬' and added '"' to 'K' element
score: 0

http://stackoverflow.com/comment/82148628
comment on: http://stackoverflow.com/a/47591877
type: AnswerComment
has text: We agree 100%. Though I'm not sure any answer is relevant at all if the interviewer really thinks it's possible to do in `O(1)`.
score: 1
type: Comment

http://stackoverflow.com/comment/82088159
score: 0
comment on: http://stackoverflow.com/q/47564965
has text: @Sarit Did you have checks duplicate db command?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/69641927
has body: As you can see there tensorflow/python/keras/_impl/keras/applications/imagenet_utils.py main purpose of preprocessing for torch is normalizing the color channels accordingly which dataset used the train the networks before. Like we do by simply (Data - Mean) / Std Source code: def _preprocess_numpy_input(x, data_format, mode): """Preprocesses a Numpy array encoding a batch of images. Arguments: x: Input array, 3D or 4D. data_format: Data format of the image array. mode: One of "caffe", "tf" or "torch". - caffe: will convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling. - tf: will scale pixels between -1 and 1, sample-wise. - torch: will scale pixels between 0 and 1 and then will normalize each channel with respect to the ImageNet dataset. Returns: Preprocessed Numpy array. """ if mode == 'tf': x /= 127.5 x -= 1. return x if mode == 'torch': x /= 255. mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] else: if data_format == 'channels_first': # 'RGB'->'BGR' if x.ndim == 3: x = x[::-1, ...] else: x = x[:, ::-1, ...] else: # 'RGB'->'BGR' x = x[..., ::-1] mean = [103.939, 116.779, 123.68] std = None # Zero-center by mean pixel if data_format == 'channels_first': if x.ndim == 3: x[0, :, :] -= mean[0] x[1, :, :] -= mean[1] x[2, :, :] -= mean[2] if std is not None: x[0, :, :] /= std[0] x[1, :, :] /= std[1] x[2, :, :] /= std[2] else: x[:, 0, :, :] -= mean[0] x[:, 1, :, :] -= mean[1] x[:, 2, :, :] -= mean[2] if std is not None: x[:, 0, :, :] /= std[0] x[:, 1, :, :] /= std[1] x[:, 2, :, :] /= std[2] else: x[..., 0] -= mean[0] x[..., 1] -= mean[1] x[..., 2] -= mean[2] if std is not None: x[..., 0] /= std[0] x[..., 1] /= std[1] x[..., 2] /= std[2] return x
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47555829

http://stackoverflow.com/comment/82103150
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47572844
has text: Yes, the example above would use `mobile_list_by_client` if the client has both mobile and fixed products. I'm not sure what you mean by 'be more discerning'. The `get_absolute_url` method can only return one URL, so it's up to you to decide what to return if the client has both.

http://stackoverflow.com/comment/82128849
type: QuestionComment
score: 0
has text: @Nae I think I see the issue. Hmm how to fix it though. SO it changes icon of the message box when you click Custom amount but not other message box. See image above
comment on: http://stackoverflow.com/q/47585497
type: Comment

http://stackoverflow.com/comment/82275417
comment on: http://stackoverflow.com/q/47616756
has text: it is only binary 0 or 1
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47641641
score: 3
answers question: http://stackoverflow.com/q/47640949
has comment: http://stackoverflow.com/comment/82253860
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82242386
has comment: http://stackoverflow.com/comment/82241998
type: Answer
has body: For windows: Check you have installed latest version of chrome browser If not, install latest version of chrome download the latest(or appropriate) version of chromedriver from here Paste the chromedriver.exe file in "&lt;Install Dir&gt;/Python27/Scripts" Folder. The below code should work now: from selenium import webdriver driver = webdriver.Chrome()

http://stackoverflow.com/q/47646548
has comment: http://stackoverflow.com/comment/82252010
answer count: 2
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82252281
has answer: http://stackoverflow.com/a/48544312
downvote count: 0
has comment: http://stackoverflow.com/comment/107707748
has comment: http://stackoverflow.com/comment/82251695
favorite count: 0
type: Question
tagged with: coverage.py
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/36517137
has answer: http://stackoverflow.com/a/47665763
tagged with: python
linked to: http://stackoverflow.com/q/43077589
has body: We are working for getting code coverage by our test cases for the product. But the thing is that coverage tool does not show the files which are not at all hit. We are using coverage command to run our processes like this: coverage run -a --rcfile=/home/coveragerc -L So we get a code coverage of 57%. Which has all the files which are hit. If a file is not hit then it is not included in coverage calculation. So it files which are not hit, are calculated, then actual coverage will be around 45%. Please help how can I achieve it.
has title: How to get code coverage of files not hit by our test cases, it shows only which are hit

http://stackoverflow.com/q/47665450
has answer: http://stackoverflow.com/a/47665497
answer count: 1
tagged with: python-requests
has body: I'm using https://requests-cache.readthedocs.io/en/latest/index.html and I want to know when the cache is hit vs. the web.
favorite count: 0
type: Question
score: 5
upvote count: 5
type: UnansweredQuestion
tagged with: python
has title: Is there a way I can log when python "requests-cache" hits the cache?
downvote count: 0

http://stackoverflow.com/comment/82208974
score: 4
has text: `pass` means do nothing, and doing nothing is decided while compiling, so there is no executable code at `pass`, and finally debugger cannot debug `nothing`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47625526

http://stackoverflow.com/q/47650768
score: 0
has body: I have a time-consuming operation to modify the database which is triggered by request the route，So I want to perform the operation asynchronously without waiting for it to end，and return the state directly. I tried to use threading module in the route,but got this error: The following is the code： define a model: class Plan(db.Model): __tablename__ = 'opt_version_plans' planid = db.Column(db.Integer,primary_key=True) planname = db.Column(db.String(255)) jobname = db.Column(db.String(255)) branch = db.Column(db.String(32)) define function: def test(): time.sleep(20) p = Plan.query.get(1) print p.planname route: @app.route('/') def index(): t = threading.Thread(target=test) t.start() return "helloworld" How can I achieve my needs in this way？
answer count: 0
has comment: http://stackoverflow.com/comment/82262827
has comment: http://stackoverflow.com/comment/82264780
type: Question
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/82264436
has title: get an error when using threading module in flask route

http://stackoverflow.com/a/47559926
has comment: http://stackoverflow.com/comment/82077622
has body: Change averagetracker = open("trackerofquiz.txt", "a") to averagetracker = open("trackerofquiz.txt", "r"). Then, just before the averagetracker.write(averagenumber) line, write averagetracker.close() and averagetracker = open("trackerofquiz.txt", "w"). It should look like this: import linecache averagetracker = open("trackerofquiz.txt", "r") averagenumber = linecache.getline("trackerofquiz.txt", 1).rstrip("\n") print(repr(averagenumber))# to check if it has any strings averagenumber = int(averagenumber)#these 4 lines get the number from the quiztracker for the averagenumber = averagenumber + 1 #average, turns it into an int, adds 1 then turns it back to averagenumber = str(averagenumber)#an str, not sure if you need to turn it back into an str print(repr(averagenumber))# to check if it has any strings averagetracker.close() averagetracker = open("trackerofquiz.txt", "w") averagetracker.write(averagenumber) averagetracker.close() print("success") This is because the 'a' signifies 'append' (write to end of file) whereas 'w' refers to 'write' (replace contents of file). However, you cannot start with 'w' as this will instantly erase the contents of the file (from the program's perspective) so you need to start with 'r' (read) and then open it again with 'w' afterwards. I hope this helps!
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47559799
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47559799

http://stackoverflow.com/comment/82094878
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47568402
type: AnswerComment
has text: @ClockSlave: Python 2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6 and the forthcoming 3.7 *all* convert keys to strings. Python 2.5 did not yet include the `json` library.

http://stackoverflow.com/q/47552767
tagged with: numpy
has comment: http://stackoverflow.com/comment/82064321
has answer: http://stackoverflow.com/a/49059005
has body: [[ 208.47 26. ] [ 202.84 17. ] [ 143.37 10. ] ..., [ 45.99 3. ] [ 159.31 10. ] [ 34.12 4. ]] [[ 58.64 1. ] [ 44.31 19. ] [ 37.89 14. ] ..., [ 46.86 4. ] [ 60.73 5. ] [ 41.91 6. ]] [[ 36.6 4. ] [ 219.29 17. ] [ 64.77 5. ] ..., [ 51.85 37. ] [ 161.26 10. ] [ 53.63 20. ]] [[ 52.97 32. ] [ 51.32 3. ] [ 196.23 4. ] ..., [ 41.39 8. ] [ 47.49 5. ] [ 34.34 3. ]] I have this numpy array entering my function: def initialize_centroids(points, k): """returns k centroids from the initial points""" centroids = points.copy() np.random.shuffle(centroids) print centroids return centroids[:k] Now what the function is currently doing is, shuffling the values and sending the first k of them. I want to basically randomize the values of the first column between 0 and 300 and the second between 0 and 100. How would I do this? This is part of my work on building a K-Means algorithm using Python.
tagged with: python
has comment: http://stackoverflow.com/comment/82063939
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49059005
score: 0
has comment: http://stackoverflow.com/comment/82062528
has title: How can I randomize the values within my numpy array?
answer count: 1
has comment: http://stackoverflow.com/comment/82064062
type: Question

http://stackoverflow.com/a/47548798
upvote count: 1
has comment: http://stackoverflow.com/comment/82055252
has comment: http://stackoverflow.com/comment/82059365
accepted answer of: http://stackoverflow.com/q/47548722
has comment: http://stackoverflow.com/comment/82055968
downvote count: 0
type: Answer
has body: Make the nested dictionary a proxy object too: manager = Manager() self.d = manager.dict() self.d['a'] = manager.dict() or retrieve self.d['a'], mutate that object, and set it back: a = self.d['a'] a[self.w] = self.w self.d['a'] = a self.d is not a regular dictionary; it wraps a dict to track mutations to the object itself, but your value, associated with the key 'a' is not such an object, so mutations to that object are not detected, and the changes are not communicated with the parent process. If you were to use self.d['a'][self.w] = self.w, then self.d['a'] = self.d['a'] the latter would retrieve the still empty dictionary from the parent process and set self.d['a'] back to that empty object; you have to create a local reference to the remote mutable nested dictionary first to ensure you correctly tell the parent process to correctly set it. From the Proxy Objects section of the documentation: If standard (non-proxy) list or dict objects are contained in a referent, modifications to those mutable values will not be propagated through the manager because the proxy has no way of knowing when the values contained within are modified. However, storing a value in a container proxy (which triggers a __setitem__ on the proxy object) does propagate through the manager and so to effectively modify such an item, one could re-assign the modified value to the container proxy: # create a list proxy and append a mutable object (a dictionary) lproxy = manager.list() lproxy.append({}) # now mutate the dictionary d = lproxy[0] d['a'] = 1 d['b'] = 2 # at this point, the changes to d are not yet synced, but by # updating the dictionary, the proxy is notified of the change lproxy[0] = d
has comment: http://stackoverflow.com/comment/82099492
score: 1
answers question: http://stackoverflow.com/q/47548722
type: AcceptedAnswer

http://stackoverflow.com/q/47597483
has body: i want to plot a STL file. I've allready got my Vertex's of the STL-File. The Aim is to get the faces of each triangulation which will done by vtx=np.vstack((Vertex1[i],Vertex2[i],Vertex3[i])) so you can see every n'th entry of Vertex1[n],Vertex2[n],Vertex3[n] belongs to the same face. By tri = a3d.art3d.Poly3DCollection([vtx]) we are getting a collection of 3D polygons and combine it with add_collection3d to plot all 3D polygons. So now my Question is: Is there a way to do the Operation below without a for loop in the sense of making the code faster? import numpy as np import mpl_toolkits.mplot3d as a3d import matplotlib.colors as colors import matplotlib.pyplot as plt Vertex1 = np.random.rand(9000,3) Vertex2 = np.random.rand(9000,3) Vertex3 = np.random.rand(9000,3) ax = a3d.Axes3D(plt.figure()) for i in range(Vertex1.shape[0]): vtx=np.vstack((Vertex1[i],Vertex2[i],Vertex3[i])) tri = a3d.art3d.Poly3DCollection([vtx]) tri.set_color(colors.rgb2hex([0.9,0.6,0.])) tri.set_edgecolor('k') ax.add_collection3d(tri) plt.show() Thanks!
has comment: http://stackoverflow.com/comment/82153230
type: UnansweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82154104
tagged with: python
has title: Faster way for a for loop with vstack in Python Numpy using mpl_toolkits.mplot3d
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47598078
tagged with: mplot3d
type: Question

python-curses
tag name: python-curses
tags question: http://stackoverflow.com/q/47616144
type: Tag
tags question: http://stackoverflow.com/q/47644727

http://stackoverflow.com/comment/82091690
has text: And I also find this website, [CompileUbuntu](http://www.pygame.org/wiki/CompileUbuntu) but there is no condition for Anaconda
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47566955

http://stackoverflow.com/comment/82065678
type: Comment
type: QuestionComment
has text: You're using two different compilers, correct? So I'm guessing that one is better at creating efficient executables in this one instance
comment on: http://stackoverflow.com/q/47554439
score: 1

http://stackoverflow.com/comment/82210604
comment on: http://stackoverflow.com/q/47626441
has text: You are `int`ing twice. Just remove the `int()` at line 11. `numbers` is already a list of `int`.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/47673238
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has body: I made a tkinter app on my mac which runs well, when I run it from the terminal. Now, I want to make an executable version of it, but I get this error message after python setup.py build: error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl' setup.py: import cx_Freeze, sys import os import os os.environ['TCL_LIBRARY'] = "/System/Library/tcl/8.4" base = None if sys.platform == 'Win32': base = "Win32GUI" executables = [cx_Freeze.Executable("multiframe.py", base=base)] cx_Freeze.setup( name="cu", options = {"build_exe": {"packages":["tkinter"]}}, version= "0.01", description = "dasdasd", executables = executables ) I know that something is wrong with the tcl import but I have tcl in Python3.6 folder on windows but I don't in mac
has title: error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl'
has answer: http://stackoverflow.com/a/47676748
has comment: http://stackoverflow.com/comment/82312372
score: 0
answer count: 1
tagged with: macos
type: Question
tagged with: cx-freeze

http://stackoverflow.com/comment/82333367
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47686674
score: 0
has text: @MikeWilliamson Actually I need cans v ice. Terrible miscommunication on my part.

http://stackoverflow.com/a/47681562
score: 0
has body: There are multiple indentation problems in your code. I suggest you revisit your code.
answers question: http://stackoverflow.com/q/47680840
type: Answer

eval
tag name: eval
tags question: http://stackoverflow.com/q/47549209
type: Tag

http://stackoverflow.com/comment/82327471
has text: How about adding a `return None` after the loop?
comment on: http://stackoverflow.com/q/47683745
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47665984
has comment: http://stackoverflow.com/comment/82291150
has answer: http://stackoverflow.com/a/47666026
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82291214
has comment: http://stackoverflow.com/comment/82291180
possible better answer: http://stackoverflow.com/a/47666045
has title: List index out of range error on simple python for loop
tagged with: python
has comment: http://stackoverflow.com/comment/82291168
accepted answer: http://stackoverflow.com/a/47666026
has answer: http://stackoverflow.com/a/47666045
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47666129
answer count: 3
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82291174
has body: Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter. N = [20,40,60,80] for j in N: print(j) for i in range(0,N[j]): print(i) Thanks in advance!
has comment: http://stackoverflow.com/comment/82291178
has comment: http://stackoverflow.com/comment/82291199
type: Question

http://stackoverflow.com/q/47574192
type: UnansweredQuestion
has body: Entering the correct syntax but still cannot convert a tuple to list in python.
tagged with: python
has comment: http://stackoverflow.com/comment/82105221
has answer: http://stackoverflow.com/a/47574376
tagged with: list
answer count: 3
has title: Cannot convert tuple to a list in python
has comment: http://stackoverflow.com/comment/82105170
score: 1
has answer: http://stackoverflow.com/a/47574276
downvote count: 1
favorite count: 0
tagged with: computer-science
type: Question
has answer: http://stackoverflow.com/a/47574270
upvote count: 2

http://stackoverflow.com/q/47565618
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47565727
type: AnsweredQuestion
score: 0
downvote count: 1
answer count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82089290
has title: Python appending field if key is the same
accepted answer: http://stackoverflow.com/a/47565769
has answer: http://stackoverflow.com/a/47565940
has answer: http://stackoverflow.com/a/47566075
has answer: http://stackoverflow.com/a/47565769
possible better answer: http://stackoverflow.com/a/47565727
has body: Hi everyone I have 2 list a = [{'employee_name': 'A', 'total_duration': 0,}, {'employee_name': 'B', 'total_duration': 11.0}, {'employee_name': 'C', 'total_duration': 9.0}, {'employee_name': 'D', 'total_duration':4.0,}, {'employee_name': 'E', 'total_duration': 0}] b = [{'employee_name': 'A', 'actual_duration': 28}, {'employee_name': 'C', 'actual_duration': 22}, {'employee_name': 'D', 'actual_duration': 15}] My desired output is : c = [{'employee_name': 'A', 'total_duration': 0, 'actual_duration': 28}, {'employee_name': 'B', 'total_duration': 11.0 'actual_duration': 0}, {'employee_name': 'C', 'total_duration': 9.0, 'actual_duration': 22}, {'employee_name': 'D', 'total_duration':4.0, 'actual_duration': 15}, {'employee_name': 'E', 'total_duration': 0 'actual_duration': 0}] my question is how can I compare this 2 list and for each employee in list b who is inside list a append the actual_duration inside list a and for employee who isn't then append actual_duration : 0 I tried if a.employee_name == b.employee_name: a.append(b['actual_duration']) else: a.append('actual_duration': 0) but its not working, any help is much appreciated thanks

http://stackoverflow.com/comment/106036681
type: AnswerComment
has text: Convenient tips for latecomers：“from_pandas_dataframe” has been deprecated In networkx 2.0+ . Instead, you can use “from_pandas_edgelist”.
score: 0
comment on: http://stackoverflow.com/a/47646579
type: Comment

http://stackoverflow.com/a/47648863
answers question: http://stackoverflow.com/q/47648750
score: 1
type: Answer
has body: requests.get returns a response object which can be read with the content attribute. In your code you try then to open the requests response object with urlopen and then read that. Try this on line 16 instead. imageFile.write(r1.content)
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47648750

http://stackoverflow.com/q/47561804
has body: When when I try to update Numpy on Anaconda-Navigator Environments section, I get the following error: UnsatisfiableError: The following specifications were found to be in conflict: - keras - numpy ==1.13.3 Use "conda info " to see the dependencies for each package. What can I do?
has comment: http://stackoverflow.com/comment/82081630
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82120974
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82121397
tagged with: python
has title: Anaconda, updating Numpy package, UnsatisfiableError
score: 0
tagged with: anaconda
answer count: 0

http://stackoverflow.com/comment/82283407
comment on: http://stackoverflow.com/a/47661045
type: Comment
score: 0
type: AnswerComment
has text: Well this is handy!

http://stackoverflow.com/a/47669206
has comment: http://stackoverflow.com/comment/82297362
type: Answer
answers question: http://stackoverflow.com/q/47669151
has comment: http://stackoverflow.com/comment/82297224
upvote count: 2
score: 1
has body: Just convert list of keys to set and compare with another set: set(loc.keys()) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'} As @juanpa.arrivillaga kindly noted you don't need to get keys() of dict to convert the into set, you can do it right away: set(loc) == {'latitude', 'longitude', 'timestamp', 'name', 'keywords'} NOTE: To the best answer please refer to @PM2Ring answer
has comment: http://stackoverflow.com/comment/82297496
downvote count: 1

http://stackoverflow.com/comment/82252159
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47646811
score: 0
has text: You say "without using built in functions" and "I know I will need [to use] max()". Which is it? Are you allowed to use builtins or not?

http://stackoverflow.com/comment/82314049
score: 0
type: QuestionComment
has text: I have added my data.txt to the code. Thank you
comment on: http://stackoverflow.com/q/47677212
type: Comment

http://stackoverflow.com/q/47667885
accepted answer: http://stackoverflow.com/a/47668191
tagged with: nested
tagged with: python
has answer: http://stackoverflow.com/a/47668191
tagged with: dictionary
has body: I am trying to access the dictionary elements in python, which looks like this: mydict= {'message':'','result':[{'abc':1,'xyz':2}]} I want to access the value of key 'xyz'.Is there any direct method to access it in python. Any help is greatly appreciated.
has answer: http://stackoverflow.com/a/72512197
type: Question
answer count: 2
has title: indexing nested dictionary elements
has comment: http://stackoverflow.com/comment/82294636
has comment: http://stackoverflow.com/comment/82294571
has comment: http://stackoverflow.com/comment/82294638
possible better answer: http://stackoverflow.com/a/72512197
type: AnsweredQuestion
score: 0

user-interface
tags question: http://stackoverflow.com/q/47583187
tags question: http://stackoverflow.com/q/47606084
tags question: http://stackoverflow.com/q/47692877
tags question: http://stackoverflow.com/q/47617902
tags question: http://stackoverflow.com/q/47650050
tags question: http://stackoverflow.com/q/47691823
tags question: http://stackoverflow.com/q/47618622
tags question: http://stackoverflow.com/q/47570746
type: Tag
tags question: http://stackoverflow.com/q/47589232
tags question: http://stackoverflow.com/q/47690746
tags question: http://stackoverflow.com/q/47664082
tags question: http://stackoverflow.com/q/47659654
tags question: http://stackoverflow.com/q/47614013
tags question: http://stackoverflow.com/q/47541148
tags question: http://stackoverflow.com/q/47676832
tag name: user-interface
tags question: http://stackoverflow.com/q/47560444
tags question: http://stackoverflow.com/q/47692092
tags question: http://stackoverflow.com/q/47654104
tags question: http://stackoverflow.com/q/47684075
tags question: http://stackoverflow.com/q/47619446

aws-cloudformation
tags question: http://stackoverflow.com/q/47674607
tag name: aws-cloudformation
type: Tag

http://stackoverflow.com/comment/82249851
score: 0
type: Comment
type: QuestionComment
has text: it looks like m is an alias for matplotlib.pyplot. so why x,y,z=m(poslon,poslat,postemp)? you can just `x,y,z=(poslon,poslat,postemp)`
comment on: http://stackoverflow.com/q/47645613

http://stackoverflow.com/comment/82298660
comment on: http://stackoverflow.com/q/47662370
has text: Yes I confirm, I will give 250 points for the one that helps me found out the issue. I'll start the bounty as soon as possible, but if someone already found out before I can start it, I will give it to her/him directly
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82189346
type: AnswerComment
has text: thanks to your answer. It works quit efficiently! I actually use `join` to merge x[3], x[4]... to be x[2] (to have more elements in split_data_rdd and elements_set ).
type: Comment
comment on: http://stackoverflow.com/a/47597332
score: 0

http://stackoverflow.com/comment/82115926
has text: Champion! Thank you very much, i just extracted some of the code to other program's and work like a charm. Thanks :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47561834
type: Comment

http://stackoverflow.com/comment/82197223
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47619202
type: Comment
has text: Thanks DeepSpace. Matching the RegEx will only match on that one line if i am not mistaken? How can i then read the follow X amount of lines to see if they start with "description" or "network-object" so i can put the description or network-object under the correct Object-Group in a csv? I would still need to read the next line like i am currently doing wouldnt i?

http://stackoverflow.com/q/47686853
linked to: http://stackoverflow.com/q/47553415
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/64846206
tagged with: python-multithreading
has answer: http://stackoverflow.com/a/64828162
has title: Sqlalchemy on multiple write threads
tagged with: python
has comment: http://stackoverflow.com/comment/82442310
accepted answer: http://stackoverflow.com/a/64828162
has comment: http://stackoverflow.com/comment/82442597
has comment: http://stackoverflow.com/comment/82336656
type: AnsweredQuestion
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/41469509
has body: The following code works in Python 3.6+, not in Python 3.4.3, not sure at what release it fails. Why is this? I was under the impression that sqlalchemy would handle multiple readers/writers to a file-based db, by hiding it behind a serialiser of the calls, probably. Anyway, this is an indication that I'm not handling this right - how to insert on multiple threads, or one thread off the main thread, in versions &lt; 3.6? I attempted this at the sqlalchemy session() level sqlalchemy connection pool on multiple threads but was only able to get it to work with an engine, and now I find out only on 3.6. def insert_inventory_table(conn, table, inventory): conn.execute(table.insert(), inventory) def results_table(conn, table): q = select([table]) data = conn.execute(q).fetchall() print('{!r}'.format(data)) def main_0(): engine = create_engine('sqlite://', connect_args={'check_same_thread' : False}) conn = engine.connect() metadata = MetaData(engine) table = Table('inventory', metadata, Column('item_no', Integer, primary_key=True, autoincrement=True), Column('desc', String(255), nullable=False), Column('volume', Integer, nullable=False) ) metadata.create_all() some_inventory = [{'item_no' : 0, 'desc' : 'drone', 'volume' : 12}, {'item_no' : 1, 'desc' : 'puddle jumper', 'volume' : 2}, {'item_no' : 2, 'desc' : 'pet monkey', 'volume' : 1}, {'item_no' : 3, 'desc' : 'bowling ball', 'volume' : 4}, {'item_no' : 4, 'desc' : 'electric guitar', 'volume' : 3}, {'item_no' : 5, 'desc' : 'bookends', 'volume' : 2}] thread_0 = threading.Thread(target=insert_inventory_table, args=(conn, table, some_inventory[0:3])) thread_1 = threading.Thread(target=insert_inventory_table, args=(conn, table, some_inventory[3:])) thread_0.start() thread_1.start() return conn, table if __name__ == '__main__': conn,table = main_0() results_table(conn, table) Thanks.
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/64846206

text
tags question: http://stackoverflow.com/q/47625950
tags question: http://stackoverflow.com/q/47597942
tags question: http://stackoverflow.com/q/47638670
tags question: http://stackoverflow.com/q/47664874
tags question: http://stackoverflow.com/q/47586162
tags question: http://stackoverflow.com/q/47627477
tags question: http://stackoverflow.com/q/47613061
tags question: http://stackoverflow.com/q/47600315
type: Tag
tags question: http://stackoverflow.com/q/47652467
tags question: http://stackoverflow.com/q/47650158
tag name: text
tags question: http://stackoverflow.com/q/47612285
tags question: http://stackoverflow.com/q/47676152
tags question: http://stackoverflow.com/q/47559382
tags question: http://stackoverflow.com/q/47607180

http://stackoverflow.com/comment/82194639
type: Comment
type: AnswerComment
has text: And how do I create new lists based on the length of the words? I mean, put in one lists all the words with one letter, in another list the words with two words and so on?
comment on: http://stackoverflow.com/a/47618249
score: 0

http://stackoverflow.com/comment/82299558
has text: _Two differents Actors (or more) related with the same User_ when I'm trying to restrict the relation to one-to-one (an user is only related with an actor and viceversa).
comment on: http://stackoverflow.com/q/47661382
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47597289
answer count: 0
has comment: http://stackoverflow.com/comment/82152784
upvote count: 1
type: UnansweredQuestion
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82152981
has comment: http://stackoverflow.com/comment/82152820
has comment: http://stackoverflow.com/comment/82153343
has comment: http://stackoverflow.com/comment/82154384
favorite count: 0
tagged with: sum
has body: Memory limit: 256 MB Time limit: 1 s Hello. We have the following code: N, M = list(map(int, input().split())) stones = list(map(int, input().split())) for __ in range(M): command, index, num = input().split() index, num = int(index), int(num) if command == "S": print(sum(stones[index:num + 1])) elif command == "M": stones[index] = num Where: N is the length of list stones M is number of commands 1 ≤ N, M ≤ 10**5 commands in form {type} {index} {index2 or value} of two types: 'S' to print sum of items in range [index; index2] 'M' to change value of item on index to new 0 ≤ value ≤ 10 This code exceeds the time limit. So, how to optimize it? Sample Input: 9 10 1 1 2 3 5 0 4 9 4 S 2 4 S 8 8 S 0 8 S 4 5 M 5 9 S 0 8 S 4 5 M 0 7 S 1 8 S 0 5 Sample Output: 10 4 29 5 38 14 37 27
tagged with: python
has comment: http://stackoverflow.com/comment/82154014
has comment: http://stackoverflow.com/comment/82153076
tagged with: optimization
type: Question
has title: How to calculate the sum faster

http://stackoverflow.com/q/47545173
has title: Problems when i convert Grib2 to Netcdf4
accepted answer: http://stackoverflow.com/a/47565306
tagged with: netcdf
answer count: 1
has answer: http://stackoverflow.com/a/47565306
tagged with: grib
type: Question
has body: I got some problems when i try to convert some grib files form CFSR. when i use ncl_convert2ncin the unix shell, the nc file information is like this : netcdf flxf01.gdas.197901 { dimensions: ygrid_0 = UNLIMITED ; // (0 currently) lv_DBLL0 = 4 ; variables: // global attributes: :creation_date = "Sun Nov 12 11:29:36 AEDT 2017" ; :NCL_Version = "6.3.0" ; :system = "Linux charcoalp-Lenovo-Erazer-Y50-70 4.10.0-38-generic #42-Ubuntu SMP Tue Oct 10 13:24:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux" ; :Conventions = "None" ; :grib_source = "flxf01.gdas.197901.grb2" ; :title = "NCL: convert-GRIB-to-netCDF" ; } and this only happen when i convert CFSR data grib2 files. here is part of information of the origin file: Nio file: flxf01.gdas.197901.grb2 global attributes: dimensions: lat_0 = 576 lon_0 = 1152 lv_DBLL0 = 4 variables: float TMP_P8_L1_GGA0_avg744h [ lat_0, lon_0 ] center : US National Weather Service - NCEP (WMC) production_status : Operational products long_name : Temperature units : K _FillValue : 1e+20 grid_type : Gaussian latitude/longitude parameter_discipline_and_category : Meteorological products, Temperature parameter_template_discipline_category_number : [8, 0, 0, 0] level_type : Ground or water surface level : 0 type_of_statistical_processing : Average statistical_process_duration : 744 hours (ending at forecast time) forecast_time : 745 forecast_time_units : hours initial_time : 01/01/1979 (00:00) float TMP_P8_L103_GGA0_avg744h [ lat_0, lon_0 ] center : US National Weather Service - NCEP (WMC) production_status : Operational products long_name : Temperature units : K _FillValue : 1e+20 grid_type : Gaussian latitude/longitude parameter_discipline_and_category : Meteorological products, Temperature parameter_template_discipline_category_number : [8, 0, 0, 0] level_type : Specified height level above ground (m) level : 2 type_of_statistical_processing : Average statistical_process_duration : 744 hours (ending at forecast time) forecast_time : 745 forecast_tim…
tagged with: python
tagged with: type-conversion
tagged with: ncl
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47549769
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47548429
score: 0
answers question: http://stackoverflow.com/q/47548429
has body: It really depends on how long you train the net for, and even then, it's possible to have some mismatches. Have you tracked the performance of your model in general? Has you model even converged? You should integrate the TensorBoard into your model to see these things. If your model has not converged (i.e. you didn't train long enough), or it just has bad performance in general, you have your answer. If on the the other hand your model performs well (which I do not think from how your question sounds), and it has converged at say 80% accuracy, it's still possible to get different values. This comes from the fact that 80% accuracy means 80% over all data you tested it on, not an individual data point. So it might get Data point A correct and point B wrong on the first try, but on the second try both of them are switched, but you still have the same accuracy.

http://stackoverflow.com/comment/82089548
has text: list(dict.values())
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47565804

http://stackoverflow.com/comment/82098808
type: QuestionComment
comment on: http://stackoverflow.com/q/47570682
has text: please!!! don't put many commands in one line using `,` which create tuple - it makes code less readable.
score: 1
type: Comment

http://stackoverflow.com/q/47549209
has body: so I'm working with this code which should return the combined version of two matrices from a text file (w/o importing any kind of module). def concatenate(filename): with open(filename, 'r') as myfile: data=myfile.read().split() a=data[0].split() b=data[1].split() a=eval(a[0]) b=eval(b[0]) row_a=len(a) row_b=len(b) col_a=len(a[0]) col_b=len(b[0]) if row_a==row_b: concatenated=[a+b for a,b in zip(*eval(open(filename)))] return concatenated if col_a==col_b: concatenated=[a+b for a, b in zip(*eval(open(filename)))] return concatenated else: print ("Error") The text file might contain something like: [[1,2],[3,4]] [[5,6,7],[8,9,10]] And output: [[1,2,5,6,7],[3,4,8,9,10]] I keep on getting this type error: TypeError: eval() arg 1 must be a string, bytes or code object How do I fix this? Thanks.
has answer: http://stackoverflow.com/a/47549708
has title: Why do I get a Type Error when concatenating matrices?
type: Question
has answer: http://stackoverflow.com/a/47549691
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 2
tagged with: eval
tagged with: matrix

http://stackoverflow.com/a/47643802
type: Answer
answers question: http://stackoverflow.com/q/47637070
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82310728
has body: I think the issue is that because you are passing three cols on the left, sklearn is getting confused. Alternative But as @unutbu said, there is no difference in performance between df.apply and for so I'd just use this: for col in ['sex','embarked','alive']: df[col] = pp.fit_transform(df[col]) But if you really do a one liner, here's how you do it (warning, massive overkill): Add another layer of indentation to the fit, tranform and fit_transform methods as the formatting doesn't work (should match the indentation of the def __init__ method. class MultiColumnLabelBinarizer: def __init__(self,columns = None): self.columns = columns # array of column names to encode` def fit(self,X,y=None): return self # not relevant here def transform(self,X): ''' Transforms columns of X specified in self.columns using LabelEncoder(). If no columns specified, transforms all columns in X. ''' output = X.copy() if self.columns is not None: for col in self.columns: output[col] = LabelBinarizer().fit_transform(output[col]) else: for colname,col in output.iteritems(): output[colname] = LabelBinarizer().fit_transform(col) return output def fit_transform(self,X,y=None): return self.fit(X,y).transform(X) df = MultiColumnLabelBinarizer(columns = ['embarked','alive']).fit_transform(df) Source: Label encoding across multiple columns in scikit-learn
score: 0
accepted answer of: http://stackoverflow.com/q/47637070

http://stackoverflow.com/q/47661686
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82282703
has answer: http://stackoverflow.com/a/47662829
has title: Parse a binary file with Regular Expressions?
score: 0
linked to: http://stackoverflow.com/q/5618988
has answer: http://stackoverflow.com/a/47661912
tagged with: python
has comment: http://stackoverflow.com/comment/82282651
tagged with: regex
has body: I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable ciphertext = re.match(b'\S', ciphertext) It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong? edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47548935
answer count: 1
has title: Type Error using Socket communication even while decoding to byte string
type: Question
has body: Hello I got a problem with a type error I cant get rid off. I have build a server named processA.py and a client processB.py I start the server calling processA and it starts up I start the client calling processB and it starts up Now I input the name of the file I want to send over a socket. The image must be in the same folder as the programms. You can use the sample code from below for reproducing the error. I choose: lena.jpg I get an error in line 15, in of my processA.py: sock.send("EXISTS" + str(os.path.getsize(filenameByte))) TypeError: a bytes-like object is required, not 'str' processA.py ''' Created on 29 Nov 2017 @author: Poor Student ''' import numpy import socket import threading import os def RtrFile(name, sock): filenameByte = sock.recv(1024) filenameStr = filenameByte.decode('ascii') if os.path.isfile(filenameStr): sock.send("EXISTS" + str(os.path.getsize(filenameByte))) userResponse = sock.recv(1024) if userResponse[:2] == 'OK': with open(filenameByte, 'rb') as f: bytesToSend = f.read(1024) sock.send(bytesToSend) while bytesToSend != "": bytesToSend = f.read(1024) sock.send(bytesToSend) else: sock.send("ERR") sock.close() def Main(): host = "127.0.0.1" port = 5000 s = socket.socket() s.bind((host,port)) s.listen(5) print("server started.") while True: c, addr =s.accept() print("client connected ip:&lt; " + str(addr) +"&gt;") t = threading.Thread(target = RtrFile, args=("rtrThread",c)) t.start() s.close() if __name__ == "__main__": Main() processB.py ''' Created on 29 Nov 2017 @author: Poor Student ''' import socket def Main(): host = "127.0.0.1" port = 5000 s = socket.socket() s.connect((host,port)) filename = input("Filename? -&gt; ") if filename != "q": s.send(filename.encode()) data = s.recv(1024) if data[:6] == "EXISTS": filesize = int(data[6:]) message = input("File Exists, " +str(filesize) + "Bytes, download? (Y/N)? -&gt;") if message == "Y" or message =="y": s.send("OK") f = open("new_" + filename, "wb") data = s.recv(1024) totalRecv = len(d…
tagged with: typeerror
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/47551682
score: 0
tagged with: types

http://stackoverflow.com/q/47663378
accepted answer: http://stackoverflow.com/a/47663875
type: Question
has answer: http://stackoverflow.com/a/47663875
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47664178
has title: Django Image Grid Gallery
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47664178
has body: I am trying to setup a grid gallery in my Django website similar to pinterest.com. I have the following HTML code: &lt;div class="row text-center text-lg-left"&gt; &lt;div class="col-lg-3 col-md-4 col-xs-6"&gt; &lt;a href="#" class="d-block mb-4 h-100"&gt; {% for img in imgs %} &lt;img src="/static/img/{‌{ img }}" class="img-thumbnail" alt=""&gt; {% endfor %} &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; Here is my views.py def gallery(request): path = "C:/Users/fela/Pictures/" img_list = os.listdir(path) return render(request, 'gallery.html', {'imgs': img_list}) The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png). The expected result should be similar to pinterest, it should be next to each other to fill up the screen. I have tried using bootstrap 4 and bootstrap 3 with same results.

http://stackoverflow.com/comment/82308645
type: Comment
type: QuestionComment
score: 0
has text: Yes I need to parse them into something. What I mean is not to be restricted to the format. Given such 4 keys with their values, the goal is to come out with what I stated on the question in hoping that people will not be restricted by the format and feel free to restructure it to fit their way. The answer by mshsayem is a good example, he reform them into a json. Anyway, thanks for pointing out the inaccuracy on the question writing, will take extra caution next time.
comment on: http://stackoverflow.com/q/47674398

http://stackoverflow.com/a/47597346
has body: If you're just trying to get integers from size squared to one, just do list(range(size**2, 0, -1)) The -1 step tells range to count down. Use range(size**2, -1, -1) if you want the list to stop at 0 instead of 1
has comment: http://stackoverflow.com/comment/82152848
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47597150

http://stackoverflow.com/q/47572640
has answer: http://stackoverflow.com/a/47573048
tagged with: python
tagged with: copy
tagged with: numpy
type: AnsweredQuestion
has body: I recently found a solution to a problem I find bizarre and would like to better understand the situation. The problem involves over-writing values at specified indices of an array. import numpy as np # create array to overwrite mask = np.ones(10) # first set of index-value pairs idx_1 = [0, 3, 4] val_1 = [100, 200, 300] # second set of index-value pairs idx_2 = [1, 5, 6] val_2 = [250, 505, 650] # third set of index-value pairs idx_3 = [7, 8, 9] val_3 = [900, 800, 700] def overwrite_mask(mask, indices, values): """ This function overwrites elements in mask with values at indices. """ mask[indices] = values return mask # incorrect # res_1 = overwrite_mask(mask[:], idx_1, val_1) # res_2 = overwrite_mask(mask[:], idx_2, val_2) # res_3 = overwrite_mask(mask[:], idx_3, val_3) # &gt;&gt; [ 100. 250. 1. 200. 300. 505. 650. 900. 800. 700.] # &gt;&gt; [ 100. 250. 1. 200. 300. 505. 650. 900. 800. 700.] # &gt;&gt; [ 100. 250. 1. 200. 300. 505. 650. 900. 800. 700.] # correct res_1 = overwrite_mask(mask.copy(), idx_1, val_1) res_2 = overwrite_mask(mask.copy(), idx_2, val_2) res_3 = overwrite_mask(mask.copy(), idx_3, val_3) # [ 100. 1. 1. 200. 300. 1. 1. 1. 1. 1.] # [ 1. 250. 1. 1. 1. 505. 650. 1. 1. 1.] # [ 1. 1. 1. 1. 1. 1. 1. 900. 800. 700.] I was under the impression that [:] applied after an array produced an exact copy of the array. But it seems as though [:] isn't working as it should in this context. What is happening here?
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47573048
favorite count: 0
has title: Why isn't array[:] copying the array?
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/82102746

http://stackoverflow.com/q/47656450
tagged with: python
has comment: http://stackoverflow.com/comment/82481862
has comment: http://stackoverflow.com/comment/82272684
favorite count: 0
type: Question
has body: Hi, I am trying to write a symbolic library for computing 3D polynomials in an analytical fashion (the variable is a real value t, and the monomials of the polynomials are 3D vectors). In particular, I want to compute the cross product of two polynomials (in a follow up to that question ). In Sympy, I found that I can either: Use explicit vector variables (with real values) from the sympy.physics.mechanics package, and in this case the cross product is defined. Use matrix symbols, but the cross product is not defined for those. Is there any way that I can represent symbolically the cross product in sympy? edit: In particular, I am interested in nullifying the cross product of two identical vectors, and taking into account the anticommutative property when factorizing a polynomial in terms of one of the vectors. new edit: To make myself more clear, I want to stay on a "symbolic level". That is, I don't want to develop the terms of my vector along each variable. For instance, here is the code to compute a Bezier curve: from sympy import * init_printing(use_unicode=True) from scipy.special import binom #default control points of a Bezier curve p_is = [symbols('p'+str(i)) for i in range(5)] class Bezier: #eq is the equation of the curve, pis are the stored control point #for special purpose such as the derivatives def __init__(self, deg, eq = None, pis = None): assert(deg) self.deg = deg; n_pts = deg +1 if pis == None: self.pis = p_is[:n_pts] else: self.pis = pis[:]; if eq == None: #computing the bernstein polynoms for a given degree factors = [binom(deg,i) * t**i * (1-t)**(deg-i)*pis[i] for i in range(n_pts)] self.eq = sum(factors); else: self.eq = eq def __repr__(self): res = "Degree : " + str(self.deg) res += "\nEquation : " + self.eq.__repr__() res += "\nwaypoints :\n" + str(self.pis) return res def __str__(self): return self.__repr__() b = Bezier(3) print b # Degree : 3 # Equation : 1.0*p0*(-t + 1)**3 + 3.0*p1*t*(-t + 1)**2 + 3.0*p2*t**2*(-t + 1) + 1.0*p3*t**3 # wa…
has comment: http://stackoverflow.com/comment/82275466
tagged with: sympy
has title: Can I use symbolic cross product operations in sympy
answer count: 1
downvote count: 0
upvote count: 1
tagged with: polynomials
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47674219
accepted answer: http://stackoverflow.com/a/47674219
score: 1
has comment: http://stackoverflow.com/comment/82274687
has comment: http://stackoverflow.com/comment/82275532

http://stackoverflow.com/q/47614999
has title: How to stop NLTK from outputting to terminal when downloading data?
linked to: http://stackoverflow.com/q/2828953
favorite count: 0
type: Question
has body: When I run my program, which is using: nltk.download('wordnet') from nltk.corpus import wordnet I get the following output to my terminal: [nltk_data] Downloading package wordnet to [nltk_data] /Users/.../nltk_data... [nltk_data] Package wordnet is already up-to-date! My program relies on not having this information saved to the terminal and a resulting output file, so how can I prevent the above lines from occurring, or write it to sys.stderr so it doesn't get included instead of it being through print?
tagged with: nltk
accepted answer: http://stackoverflow.com/a/47615030
tagged with: stderr
tagged with: python
has answer: http://stackoverflow.com/a/47616241
possible better answer: http://stackoverflow.com/a/47616241
tagged with: nlp
score: 14
upvote count: 14
linked to: http://stackoverflow.com/q/8391411
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47615030

http://stackoverflow.com/comment/82245345
score: 0
comment on: http://stackoverflow.com/q/47637463
type: Comment
has text: can you show a recursive function that counts?
type: QuestionComment

http://stackoverflow.com/q/47689825
has answer: http://stackoverflow.com/a/47692039
has comment: http://stackoverflow.com/comment/82344366
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82346667
tagged with: python
tagged with: data-science
has comment: http://stackoverflow.com/comment/82338905
upvote count: 4
has body: After applying Imputer.fit_transform() on my dataset I am losing the column names on the transformed data frame. Is there any way to impute it without losing column names??
has comment: http://stackoverflow.com/comment/82342374
score: 3
answer count: 2
tagged with: pandas
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/69963585
has title: Missing values imputation in python
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47569382
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82137334
has answer: http://stackoverflow.com/a/47590129
has body: i'm kinda a Python newbie, so please do not get angry! I want to start a web project which consist on manipulation on a file audio based on a series of mathematical images which I have to analyse. I have around 700 of these images. I have to extract the curve and the points on that curve and from that use the extracted function to manipulate and alter a single file audio. My question is: what library do you suggest?
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/47590129
has comment: http://stackoverflow.com/comment/82105674
score: -1
has title: Python Image analysis
tagged with: image
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82119822

http://stackoverflow.com/a/47650287
has comment: http://stackoverflow.com/comment/82258887
has comment: http://stackoverflow.com/comment/82258953
upvote count: 2
has comment: http://stackoverflow.com/comment/82259006
has body: As per the doc, the error you are seeing will happen only for Django 2.0. Please check your Django version using shell python manage.py shell &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION Also consider using a virtual environment. That is how a project should be set up.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47649854
has comment: http://stackoverflow.com/comment/82259143
answers question: http://stackoverflow.com/q/47649854
score: 2
downvote count: 0

http://stackoverflow.com/comment/126353458
type: Comment
comment on: http://stackoverflow.com/a/47553242
type: AnswerComment
score: 0
has text: This is concise and intuitive; beautiful brain of yours

http://stackoverflow.com/a/47606847
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47604826
type: Answer
has comment: http://stackoverflow.com/comment/82186551
has comment: http://stackoverflow.com/comment/82202419
score: 3
has comment: http://stackoverflow.com/comment/82181964
has body: K-means is not sensitive to feature order. The post you refer to taken about scale, not order. If you look at the kmeans equations, it should be obvious that the order does not matter. There has been research (van Luxbourg, if I recall correctly) that essentially says that if there is a good kmeans result, then it must be easy to find. If you get very different results when running kmeans multiple times, then none of the results is good. There are "n choose k" possible initializations. While they can't be all bad, n_iter will only try very few of them. So there is no guarantee to find the "best".the function will return the one with lowest SSQ, but that does not mean this is the most useful result in the end, unless you only care about SSQ.
answers question: http://stackoverflow.com/q/47604826

http://stackoverflow.com/comment/82204881
has text: @trincot I just don't know WHAT to return from the function. I am SORRY but I am a beginner programmer :(
score: 0
comment on: http://stackoverflow.com/q/47623434
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82335870
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47688252
has text: asking because there is [this issue](https://github.com/bazelbuild/BUILD_file_generator/pull/30) which was fixed Nov 1 2017

http://stackoverflow.com/comment/82267033
has text: I checked out the above link. My problem can also be stated as images taken at a different time with changes in object position, lighting and presence. But the solution that was given is based on pixel by pixel comparison without considering shapes at all and doesn't work with the images with positional and intensity change.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47632513
score: 0

http://stackoverflow.com/comment/82195998
comment on: http://stackoverflow.com/a/47618890
type: Comment
has text: @user9041128 As I mentioned in the answer below the code, you can wrap the entire thing in a `while True`. As for the "levels" it's up to you to implement by a logic you decide on, for example increase the range of the random numbers. I can't write an entire game for you in a SO answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82132245
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47587333
has text: Could you state your setup (Linux flavour and version)
type: Comment

http://stackoverflow.com/q/47639347
accepted answer: http://stackoverflow.com/a/47639390
duplicate of: http://stackoverflow.com/q/32326805
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/7035175
possible better answer: http://stackoverflow.com/a/47639429
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47639429
has answer: http://stackoverflow.com/a/47639390
has comment: http://stackoverflow.com/comment/82237040
favorite count: 0
type: Question
tagged with: numpy
has body: For example, I have a vector like this: v = np.array([2, 4, 1, 7, 9, 3, 5]) I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be: np.array([3, 4, 3, 7, 9, 3, 5]) How can I do it with numpy?
answer count: 2
has comment: http://stackoverflow.com/comment/82237086
linked to: http://stackoverflow.com/q/32326805
tagged with: arrays
tagged with: python
has title: How to create a vector with components bigger than a number in numpy?

http://stackoverflow.com/comment/82189966
type: AnswerComment
has text: Thank you both replies were helpful, the second was just a bit more on topic, anyways the best resource I could find for a basic packet sniffer was here http://www.binarytides.com/python-packet-sniffer-code-linux/
comment on: http://stackoverflow.com/a/47586600
score: 1
type: Comment

row
tags question: http://stackoverflow.com/q/47652839
tags question: http://stackoverflow.com/q/47600468
tags question: http://stackoverflow.com/q/47564206
tags question: http://stackoverflow.com/q/47601487
tag name: row
tags question: http://stackoverflow.com/q/47589034
type: Tag

http://stackoverflow.com/q/47645719
upvote count: 1
favorite count: 0
type: Question
has title: something went wrong when I try add a layer on a matrix of data (python)
tagged with: python
has comment: http://stackoverflow.com/comment/82250076
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47645748
has body: So assume I have a matrix here, a tuple containing tuples of 0: matrix = ((0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0),) I want to add a layer of int(1) on the outside of it, so that it will look like: [[1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1],] first of all, I want to turn this matrix to list, since tuples are not changable: matrix_new = list(map(lambda x: list(x), matrix)) Then I would like to add a row at the beginning and end of it. addrow = list(map(lambda x: 1, range(len(matrix[0])))) matrix_new.insert(0, addrow) matrix_new.append(addrow) so now, if I: for i in matrix_new: print(i) &gt;&gt;&gt; [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, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1] looking good so far. Now I want to add a int(1) in each row of the matrix_new at the beginning and the end: for i in matrix_new: i.insert(0, 1) i.append(1) print(i) somehow it now looks like: &gt;&gt;&gt; [1, 1, 1, 1, 1, 1, 1, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] It seems that the last row is having 2 additional int(1)?????? And now, if I: for i in matrix_new: print(i) I got: &gt;&gt;&gt; [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Now I got the first row also with 2 additional int(1). What could be wrong? I don't understand why this is happening.
tagged with: matrix
score: 1
has answer: http://stackoverflow.com/a/47645748
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82048118
type: Comment
score: 0
has text: As objects are removed from the list you are iterating over, you are upsetting the iteration order; some items are skipped, because the list has been altered in the loop.
type: AnswerComment
comment on: http://stackoverflow.com/a/47545149

http://stackoverflow.com/comment/82332313
has text: see code from your link - `self.file.write(b'{\'product\': [')` - `b` is prefix which means `bytes` data - `b"{'product': ["`. It is not variable. If you use `b` in `write(b)` then you should get error and it may not work correctly. BTW: other prefixes: `u"text"` = unicode data, `r"C:\"` = raw data and you can safely use \ instead of \\ in path.
type: QuestionComment
comment on: http://stackoverflow.com/q/47685800
score: 0
type: Comment

http://stackoverflow.com/a/47664280
type: Answer
answers question: http://stackoverflow.com/q/47664064
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82297974
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82292031
has body: You are using class based views incorrectly. Class based views should be registered with the as_view method. url(r'^parties/approve/([0-9]*$)', views.PartyListView.as_view(), name="Approve Party"), However, in this case, it looks as it would be simpler to make approve_party and send_email regular functions instead of methods of your view. def approve_party(request, party_id): returnObj = {} ... send_email(request, True, party) return HttpResponse(jsonObj, status=200, content_type="application/json") def send_email(request, isApprovalEmail, party): username = request.user.username Then change your URL pattern to: url(r'^parties/approve/([0-9]+$)', views.approve_party, name="approve-party"), I suggest using [0-9]+ instead of [0-9]* to make sure that the URL includes at least one digit, and I would avoid using spaces in URL pattern names.
accepted answer of: http://stackoverflow.com/q/47664064

http://stackoverflow.com/a/47546587
has comment: http://stackoverflow.com/comment/82050593
has comment: http://stackoverflow.com/comment/82050624
score: 0
has comment: http://stackoverflow.com/comment/82051758
has comment: http://stackoverflow.com/comment/82051304
has comment: http://stackoverflow.com/comment/82051024
has comment: http://stackoverflow.com/comment/82050678
type: Answer
has comment: http://stackoverflow.com/comment/82077613
has comment: http://stackoverflow.com/comment/82049950
has comment: http://stackoverflow.com/comment/82051274
has comment: http://stackoverflow.com/comment/82051566
has comment: http://stackoverflow.com/comment/82051161
answers question: http://stackoverflow.com/q/47546420
has comment: http://stackoverflow.com/comment/82051789
has comment: http://stackoverflow.com/comment/82049899
has comment: http://stackoverflow.com/comment/82051114
has body: default = 'category' in model 'post' causing the error , since FK is stored as an integer. Normally we dont use default with Fk. Maybe set it as null=True, blank=True. category = models.ForeignKey(Category, verbose_name="Category", null=True, blank=True) The above answer is incase if the category is not a required field. If it is required just the remove the "default='category'" from the category field of model 'post' from your existing code.
has comment: http://stackoverflow.com/comment/82051597

http://stackoverflow.com/q/47656775
has body: The new Django 2.0 update broke my way of reversing url and printing it to the template. Using regular expression, it would work fine but when using the new simplified way, it returns an error. NoReverseMatch at /blog/archive/ Reverse for 'article' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['blog/article/&lt;int:id&gt;/$'] Here is what I use to print the url, &lt;h3 class="item-title"&gt;&lt;a href="{% url 'blog:article' id=article.id %}"&gt;{{ article.title }}&lt;/a&gt;&lt;/h3&gt; Here is the url pattern, url(r'^blog/article/&lt;int:id&gt;/$', views.article, name='article'), and here is the article function, def article(request, id): try: article = Article.objects.get(id=id) except ObjectDoesNotExist: article = None context = { 'article': article, 'error': None, } if not article: context['error'] = 'Oops! It seems that the article you requested does not exist!' return render(request, 'blog/article.html', context) I haven't found a solution to this yet. Hopefully this post will help others.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47656809
tagged with: django-2.0
upvote count: 2
tagged with: django
tagged with: django-urls
tagged with: python
has title: Reverse URL in Django 2.0
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47656809

http://stackoverflow.com/comment/82040701
comment on: http://stackoverflow.com/q/47541693
score: 0
type: QuestionComment
has text: your loop is infinite, you want break instead of continue
type: Comment

http://stackoverflow.com/comment/82183395
score: 2
has text: for the win!!! im making a search filter and this is how i would prefer it to work. thank you
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47612588

http://stackoverflow.com/comment/82119327
type: Comment
score: 0
has text: @fodma1 I went and added some comments to the views.py file and the urls.py files while running the server and it doesn't restart.
type: QuestionComment
comment on: http://stackoverflow.com/q/47580135

http://stackoverflow.com/q/47580326
tagged with: nlp
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56494309
tagged with: spacy
answer count: 3
has comment: http://stackoverflow.com/comment/82555855
downvote count: 0
has comment: http://stackoverflow.com/comment/82551066
has answer: http://stackoverflow.com/a/56494309
has comment: http://stackoverflow.com/comment/82542055
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47797679
has answer: http://stackoverflow.com/a/53126583
accepted answer: http://stackoverflow.com/a/47797679
has comment: http://stackoverflow.com/comment/82552880
upvote count: 10
score: 10
has title: Extracting a part of a Spacy document as a new document
tagged with: python
tagged with: document
has body: I have a rather long text parsed by Spacy into a Doc instance: import spacy nlp = spacy.load('en_core_web_lg') doc = nlp(content) doc here becomes a Doc class instance. Now, since the text is huge, I would like to process, experiment and visualize in a Jupyter notebook using only just one part of the document - for instance, first 100 sentences. How can I slice and create a new Doc instance from a part of the existing document?

http://stackoverflow.com/comment/82342431
type: QuestionComment
comment on: http://stackoverflow.com/q/47690589
type: Comment
score: 0
has text: Can you please add the full error output to the question? Is it just "Non-ASCII" or is it some UnicodeDecode exception? Looking at your code I wonder if ``os.system("clear")`` and raw escape codes for colors are the best way. Have a look if there are some python modules wrapping this much nicer.

http://stackoverflow.com/q/47664372
type: Question
has answer: http://stackoverflow.com/a/63434284
type: UnansweredQuestion
tagged with: python-unicode
tagged with: python
tagged with: character-encoding
has title: Python 2.7, How to convert (ord>128) string into unicode
has answer: http://stackoverflow.com/a/47664799
tagged with: python-2.7
answer count: 2
downvote count: 0
has body: I am trying to convert a standard string containing >128 chars into Unicode. For example, a='en métro' b=u'en métro' c = whatToDoWith(a) so that I can get c exactly equals to b, in both types and values. In my real program I got the following error when txt = 'en métro' utxt = txt.decode('utf8') File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 3: invalid continuation byte To investigate, I also have the following test code: # -*- coding: utf-8 -*- c='en métro' print type(c) print c d=c.decode('utf8') print type(d) print d a='中文' print type(a) print a b=a.decode('utf8') print type(b) print b and this time result is expected: &lt;type 'str'&gt; en mÃ©tro &lt;type 'unicode'&gt; en métro &lt;type 'str'&gt; ä¸­æ–‡ &lt;type 'unicode'&gt; 中文 I cannot tell what's the different with my real program. I also have the # -*- coding: utf-8 -*- line in it. Can someone point out possible problems?
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82211885
type: QuestionComment
has text: `entrante = Entrante.objects.all().filter(fk_tipo_entrante=2).first()`
comment on: http://stackoverflow.com/q/47627057
score: 0
type: Comment

http://stackoverflow.com/a/50351843
type: Answer
answers question: http://stackoverflow.com/q/47649159
has body: Here's a nice strategy: https://elsampsa.github.io/valkka-examples/_build/html/qt_notes.html#python-multiprocessing Features: You can send Qt signals from the multiprocess You can send Qt signals into the multiprocess
upvote count: 2
has comment: http://stackoverflow.com/comment/122745680
downvote count: 1
score: 1

http://stackoverflow.com/q/47686258
answer count: 1
has answer: http://stackoverflow.com/a/47690511
has title: How to deal with "none" values when inserting into SQL database?
has body: Some rows in my data set are like this: where None is suppose to be integer. Boston (2017) Documentary Jon Dunham 5-Dec-17 100 5 None 63 None When I insert this line into Postgres, where the type of column of None is INTEGER, I got this error: psycopg2.DataError: invalid input syntax for integer: "None" I store the original data in a csv file, it's a really big dataset(around 2000) how should I deal with the None value?
has comment: http://stackoverflow.com/comment/82332181
type: AnsweredQuestion
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/47690511
has comment: http://stackoverflow.com/comment/82332163
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/82335153
has comment: http://stackoverflow.com/comment/82336768
type: Question
score: 0
tagged with: sql

http://stackoverflow.com/comment/82277202
type: Comment
type: QuestionComment
has text: i get an error: AttributeError: 'list' object has no attribute 'split'
comment on: http://stackoverflow.com/q/47659073
score: 0

http://stackoverflow.com/comment/82072774
comment on: http://stackoverflow.com/q/47556992
has text: w.move(e.object,e.x,e.y) w.update() This doesn't work for me
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47580337
type: AnsweredQuestion
tagged with: encode
has comment: http://stackoverflow.com/comment/82118007
has answer: http://stackoverflow.com/a/47581526
has comment: http://stackoverflow.com/comment/82119268
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82118682
has title: Short Rot (N) decode function in python
type: Question
tagged with: decode
linked to: http://stackoverflow.com/q/10576347
accepted answer: http://stackoverflow.com/a/47581526
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82117971
downvote count: 1
favorite count: 0
has body: I'm kinda new to python and I'm wondering how I can turn this rot (n) encode function def rot_encode(n): from string import ascii_lowercase as lc, ascii_uppercase as uc lookup = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n]) return lambda s: s.translate(lookup) print(rot_alpha(13)('Hello World')) To a decode function I don't want to use the built-in functionality of python to encode or decode, I want to recreate it. Thanks in advance

http://stackoverflow.com/q/47663704
tagged with: python
has title: Python Split a phrase into words on space and symbols
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: string
has answer: http://stackoverflow.com/a/47663762
accepted answer: http://stackoverflow.com/a/47663762
type: Question
tagged with: split
possible better answer: http://stackoverflow.com/a/47663819
has answer: http://stackoverflow.com/a/47663819
has body: I'm writing a program where I need to test whether a phrase such as "red car" is present in a variety of sentences: "I bought a new red car", "RED! CAR!", "red#$%^car". I'm having trouble finding a way to separate out the words from the symbols in the last example. My code so far is: exclude = set(string.punctuation) text = text.lower text = ''.join(ch for ch in text if ch not in exclude) text = text.split() for word in phrase: found = False for e2 in text: if word == e2: found = True break if not found: return False return True This causes the last example to be 'redcar' so the words aren't split. All the questions I found on here were talking about delimiters not splitting out two words that are joined by a bunch of symbols. Should I just use text.split for each individual symbol? I was thinking of something like: for ch in exclude: text = text.split(ch) but I was hoping there is a cleaner way to do it.

http://stackoverflow.com/q/47605085
downvote count: 0
has title: Insert list in pandas dataframe cell
has answer: http://stackoverflow.com/a/47605300
tagged with: data-science
favorite count: 0
type: Question
tagged with: pandas
answer count: 5
has body: I have a dictionary where each key has a list of values. Length of the list associated with each key is different. I want to convert the dictionary into a pandas dataframe with two columns 'Key' and 'Values'. Each row having one dictionary key in the 'Key' column and the list of values associated with it in 'Values' column. The dataframe will look as follows: mapping_dict = {'A':['a', 'b', 'c', 'd'], 'B':['aa', 'bb', 'cc']} df = Key Value 0 A ['a', 'b', 'c', 'd'] 1 B ['aa', 'bb', 'cc'] I tried using the answer provided here by modifying it as per my use case. But it didn't output the required answer.
has answer: http://stackoverflow.com/a/62764040
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/50052342
has answer: http://stackoverflow.com/a/70968810
has answer: http://stackoverflow.com/a/47605237
score: 2
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50052342
upvote count: 2
linked to: http://stackoverflow.com/q/26483254
accepted answer: http://stackoverflow.com/a/47605300

http://stackoverflow.com/q/47649854
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82258217
score: 0
has comment: http://stackoverflow.com/comment/82258669
has comment: http://stackoverflow.com/comment/82258388
has answer: http://stackoverflow.com/a/47650287
has comment: http://stackoverflow.com/comment/82258761
has comment: http://stackoverflow.com/comment/82258137
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82258461
has body: In my Mac I use PyCharm run my Django project very well. But in the remote server I use the same commands to run my project: python3 manage.py runserver 8001 The there comes the issue: File "/var/www/html/Qiyun02//user_admin_productmanage_cloudserver/models.py", line 3, in &lt;module&gt; from xxx.qiyun_admin_productconfig_cloudserver.models import ( File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 109, in &lt;module&gt; class Disk(models.Model): File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 110, in Disk diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks') # "SAS", "SSD" and so on TypeError: __init__() missing 1 required positional argument: 'on_delete' I know the on_delete error means. but I mean, in my Mac why there do not shows the error? whether this is related to django version? My local Mac Django version is 1.11.2. The remote server CentOS7.2 version is python-django-1.8.14-1.el7.noarch EDIT Please, I know the on_delete error in there, I mean, in my Mac, there is no the reminds, why I copy to the CentOS7.2 remote server there comes this issue? whether this is caused by django version? EDIT -2 I upgrade the remote server django version to 1.11.2 too. but still have the same error. EDIT -3 From the document: A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. (on_delete isn’t actually required, but not providing it gives a deprecation warning. It will be required in Django 2.0.) You know, my django version is 1.11.2 now in my CentOS7.2 remote server, why there have the issue there? EDIT -4 I don't have a virtual environment. I use bellow command: python3 manage.py shell get the same issue. EDIT -5 In the end, I find my python3 use django 2.0. this is the issue. python3 -m django --version 2.0
downvote count: 1
has title: TypeError: __init__() missing 1 required positional argument: 'on_delete' in remote server CentOS7.2
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82257994
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/19929626
has comment: http://stackoverflow.com/comment/82258557
accepted answer: http://stackoverflow.com/a/47650287

http://stackoverflow.com/a/47684089
upvote count: 3
has comment: http://stackoverflow.com/comment/82328163
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47683415
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47683415
has comment: http://stackoverflow.com/comment/82328723
has comment: http://stackoverflow.com/comment/82356800
has comment: http://stackoverflow.com/comment/82357934
score: 3
has body: numpy.random.multivariate_normal will give you samples drawn from a multivariate Gaussian distribution with mean 0 and variance 1. You want to compute the probability density function (PDF) for this distribution, not draw samples from it. The easiest thing to do is use the scipy.stats.multivariate_normal.pdf function, as follows: m, n = 100, 100 lims = (-3, 3) # support of the PDF xx, yy = np.meshgrid(np.linspace(*lims, m), np.linspace(*lims, n)) points = np.stack((xx, yy), axis=-1) mean = (1, 2) # Whatever your (i, j) is covariance = 25.0 pdf = scipy.stats.multivariate_normal.pdf(points, mean, covariance) pdf now gives the height of the Gaussian function at each of the points in the plane between -3 and 3 on both the x- and y-axes. You can apply this window to whatever images you want, by just doing image * pdf. EDITS: Thanks to CrazyIvan for pointing out the pdf function takes a grid of points directly. Also note that np.linspace(*lims, m) uses Python3-specific tuple-unpacking. If you have an older version, just do np.linspace(lims[0], lims[1], m).
has comment: http://stackoverflow.com/comment/82359154
type: Answer

http://stackoverflow.com/comment/82085722
score: 0
has text: Seems like the answer to every question I've ever asked on here is Pandas. I should probably up my proficiency in it a bit more. Thanks for the help!
type: Comment
comment on: http://stackoverflow.com/a/47563782
type: AnswerComment

http://stackoverflow.com/q/47583704
favorite count: 0
has comment: http://stackoverflow.com/comment/82165099
type: Question
has comment: http://stackoverflow.com/comment/85332156
has comment: http://stackoverflow.com/comment/85328868
tagged with: python
linked to: http://stackoverflow.com/q/33569265
tagged with: retain
tagged with: apply
has comment: http://stackoverflow.com/comment/82125704
tagged with: for-loop
tagged with: pandas
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has body: I have a question like this one (retain function in python). When dealing with time series data, very often the algorithm needs to dynamically referencing the last computed record. For example, I have some stock trading records, and would like to calculate the 'average cost' for the shares I'm holding. The only solution I can think of is iterate over the target DataFrame. It doesn't feels like using the strength of the Pandas DataFrame. Fake Data: import numpy as np import pandas as pd aapl = pd.read_csv('https://raw.githubusercontent.com/ktc312/pandas-questions/master/AAPL_exmaple.csv', parse_dates=['Date']) print aapl Date Quantity Price 0 2017-01-10 1000 117.2249 1 2017-02-10 -500 130.5928 2 2017-03-10 1500 137.5316 3 2017-04-10 -2000 141.5150 4 2017-05-10 500 151.4884 5 2017-06-09 500 147.8657 6 2017-07-10 500 143.9750 7 2017-08-10 -1000 154.7636 8 2017-09-11 -200 160.9215 9 2017-10-10 1000 155.3416 Some needed variable: aapl['Total Shares'] = aapl['Quantity'].cumsum() aapl['Cost'] = aapl['Quantity']*aapl['Price'] print apple Date Quantity Price Total Shares Cost 0 2017-01-10 1000 117.2249 1000 117224.90 1 2017-02-10 -500 130.5928 500 -65296.40 2 2017-03-10 1500 137.5316 2000 206297.40 3 2017-04-10 -2000 141.5150 0 -283030.00 4 2017-05-10 500 151.4884 500 75744.20 5 2017-06-09 500 147.8657 1000 73932.85 6 2017-07-10 500 143.9750 1500 71987.50 7 2017-08-10 -1000 154.7636 500 -154763.60 8 2017-09-11 -200 160.9215 300 -32184.30 9 2017-10-10 1000 155.3416 1300 155341.60 loop through data to get the average cost: def get_ave_cost(df): for index, row in df.iterrows(): if index == 0: df.loc[index,'Ave Cost'] = row['Price'] elif row['Total Shares'] == 0: df.loc[index,'Ave Cost'] = 0.0 else: if row['Quantity'] &gt; 0: df.loc[index,'Ave Cost'] = \ ((df.loc[index - 1,'Ave Cost'] * \ df.loc[index - 1,'Total Shares']) + \ row['Cost'])/row['Total Shares'] else: df.loc[index,'Ave Cost'] = df.loc[index - 1,'Ave Cost'] return df get_ave_cost(stock_trading_records_df) Wanted resu…
has comment: http://stackoverflow.com/comment/103839644
has title: Retain in Pandas, faster way than for loop or apply

http://stackoverflow.com/a/47594458
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/82195806
answers question: http://stackoverflow.com/q/47594331
type: AcceptedAnswer
downvote count: 0
has body: Apparently you have to pass the headers argument because the website is blocking you thinking you are a bot requesting data. I found an example of doing this here HTTP error 403 in Python 3 Web Scraping. Also, the urlopen object didn't support the headers argument, so I had to use the Request object instead. from urllib.request import urlopen, Request from bs4 import BeautifulSoup word = 'house' r = Request('https://www.google.pl/search?&amp;dcr=0&amp;tbm=isch&amp;q='+word, headers={'User-Agent': 'Mozilla/5.0'}) response = urlopen(r).read()
accepted answer of: http://stackoverflow.com/q/47594331
upvote count: 8
has comment: http://stackoverflow.com/comment/139650849

http://stackoverflow.com/comment/82563953
type: QuestionComment
comment on: http://stackoverflow.com/q/47564734
score: 1
type: Comment
has text: I would recommend to consider use of *libgpiod* (in case you can use new kernel): https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/.

http://stackoverflow.com/a/49933388
downvote count: 0
has body: After navigating through the implementation of multiprocessing using PyCharm, I'm convinced that there is no better solution, because Pool started a thread to _maintain_pool() by _repopulate_pool() if any worker process exists--either accidentally or failed to initialize. Check this out: Lib/multiprocessing/pool.py line 244
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47586645
answers question: http://stackoverflow.com/q/47586645
type: AcceptedAnswer

http://stackoverflow.com/q/47553832
accepted answer: http://stackoverflow.com/a/47553863
has answer: http://stackoverflow.com/a/47576949
possible better answer: http://stackoverflow.com/a/47576949
type: AnsweredQuestion
score: 0
answer count: 2
type: Question
has title: Variable written in parentheses at end of expression
has body: I'm going through a CNTK tutorial, and I have the following function: def create_model(features): with C.layers.default_options(init=C.layers.glorot_uniform(), activation=C.ops.relu): h = features for _ in range(num_hidden_layers): h = C.layers.Dense(hidden_layers_dim)(h) r = C.layers.Dense(num_output_classes, activation=None)(h) return r The function itself is not my point of confusion, I'm actually concerned with the syntax on the last two lines before the return statement: h = C.layers.Dense(hidden_layers_dim)(h) and r = C.layers.Dense(num_output_classes, activation=None)(h). What is this (h) that's being written at the end of the line? What is this syntax called and what does it do? I have tried to look it up but I don't even know what to call it in searches.
tagged with: python
has answer: http://stackoverflow.com/a/47553863

http://stackoverflow.com/comment/82212812
type: Comment
comment on: http://stackoverflow.com/a/47626482
score: 0
type: AnswerComment
has text: The children is printed <TreeQuerySet []>. The node is printed as expected the following Bedroom Items Kitchen Wares Modular Kitchen

http://stackoverflow.com/comment/82282077
type: Comment
type: AnswerComment
has text: Maybe some problem with pandas versions, do you use last `0.21.0` ?
score: 0
comment on: http://stackoverflow.com/a/47661061

http://stackoverflow.com/q/47662991
has title: Deploy python app with setup.py and Pipfile
tagged with: setuptools
answer count: 1
favorite count: 0
type: Question
tagged with: pipenv
has body: I have a flask app with a Pipfile and run pipenv run python setup.py sdist to create a package. I copy the package to another system. Usually I would install it with pip and all requirements declared in install_requires in setup.py would be installed automatically. How can I install the package and its requirements and make use of the Pipfile.lock? If I install the package with pip, I could run pipenv install --deploy in the directory it was installed, but how can I reliably retrieve the directory my package was installed in? Is this a good way to do this? I'm looking for the best way to install a python app with setuptools and pipenv.
has answer: http://stackoverflow.com/a/50598601
accepted answer: http://stackoverflow.com/a/50598601
has comment: http://stackoverflow.com/comment/88034627
linked to: http://stackoverflow.com/q/48567245
tagged with: python
has comment: http://stackoverflow.com/comment/87995396
upvote count: 4
score: 4
type: AnsweredQuestion
downvote count: 0

sigmoid
tags question: http://stackoverflow.com/q/47611418
tag name: sigmoid
type: Tag

http://stackoverflow.com/q/47689067
score: 0
answer count: 1
has title: Replacing information in fixed length records in Python
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47689921
tagged with: python
has body: Interestingly enough I found this exact question on this website - for the exact same homework problem no less- but a conclusion was never reached due to insufficient information about the problem. Hopefully, I will have better luck. I am working on my Python 3 homework and I've come to a problem that I am really struggling with. The exact prompt given is: "You will be passed the filename 'P', firstname 'F', lastname 'L', and a new birthday 'B'. Load the fixed length record file in P, search for F,L in the first and change birthday to B. Then save the file." The idea here being that we create a program to change a person's birthday from one unknown to another, using the variables given. Being the impatient person that I am I print()ed P - the file- and know that it is: Adam Smith 11111985Theodore Anderson 03201990Monty Biscuit-Barrel 10181980Adam Smithers 10101960Ruthy Anderson 06062010 The spacing gets lost upon pasting, but the first and last names have a fixed length of 16 each, and the birthdays have a fixed length of 8. The name of the individual who's birthday I am trying to change is: Adam Smithers And that I am trying to change his birthday to: 00000000 I've tried replacing the birthday using slice (as, per our instruction, opening a text file in python turns the file into a string, and therefore immutabel). However, when I try the script: with open(P) as p: new_file = p[0:141] + B + p[161:] I receive the error message " '_io.TextIOWrapper' object is not subscriptable" I've been trying to finagle this for a couple hours now, but haven't gotten any closer. Any suggestions would be appreciated at this point. Thank you
tagged with: slice
has comment: http://stackoverflow.com/comment/82337353
tagged with: immutability

http://stackoverflow.com/comment/82325109
type: AnswerComment
has text: I left out the expand just to demonstrate my error, thank you for your helpful answer. I am in fact using christian's method, seems to be much neater.
comment on: http://stackoverflow.com/a/47680449
score: 0
type: Comment

http://stackoverflow.com/q/47543233
score: 0
tagged with: numbers
has answer: http://stackoverflow.com/a/47543517
answer count: 1
has comment: http://stackoverflow.com/comment/82043620
type: Question
has comment: http://stackoverflow.com/comment/82043612
type: UnansweredQuestion
tagged with: function
has comment: http://stackoverflow.com/comment/82043573
tagged with: python
has title: I need help on combining functions using numbers
has body: I'm new to programming and right now I'm learning about functions and everything related to them. I've been making some example of my own, and I ran into a problem. def test(x): number = x + 1 return (number) def test2(y): number2 = test(y) + 2 print (number2) test2(1) If I print this function, it would work. However I don't understand something. Why is it that when I put number 1 into test2(y), it also goes into test(x)? Why does this happen?

http://stackoverflow.com/a/47563399
has body: You are interpreting things wrong. See the docs for **os.walk**. The 3 variables for your for loop should be root, dirs, and files, in that order. dirs and files are lists, of the directories and files in the current directory respectively. root is the current directory you are in. subdir is being ignored because you are using os.walk incorrectly.
type: Answer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47563262
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47563262

http://stackoverflow.com/comment/82120634
type: AnswerComment
comment on: http://stackoverflow.com/a/47581589
has text: Is there a black friday discount on `text.count()`?
type: Comment
score: 37

http://stackoverflow.com/comment/82278878
type: AnswerComment
has text: @MaxStrange program can runs without `mainloop()` in IDLE because IDLE is created with `tkinter` and it runs `mainloop()` to work.
comment on: http://stackoverflow.com/a/47659673
type: Comment
score: 0

http://stackoverflow.com/a/47562823
type: Answer
has comment: http://stackoverflow.com/comment/82084924
has comment: http://stackoverflow.com/comment/82084808
has comment: http://stackoverflow.com/comment/82084723
score: 0
has comment: http://stackoverflow.com/comment/82084761
has body: Returns True if exactly one of the numbers is less than zero, unless the Boolean parameter is True. In this case [negative == True] it will only return True if both numbers are less than zero. If it doesn't return True, it returns False. def pos_neg(a, b, negative): if not negative: if (a &lt; 0) ^ (b &lt; 0): return True else: return False else: if a &lt; 0 and b &lt; 0: return True else: return False print(pos_neg(-1, 1, False)) # True print(pos_neg(-1, -1, False)) # False print(pos_neg(-1, 1, True)) # False print(pos_neg(-1, -1, True)) # True will print: True False False True
has comment: http://stackoverflow.com/comment/82084901
has comment: http://stackoverflow.com/comment/82084787
answers question: http://stackoverflow.com/q/47562455
has comment: http://stackoverflow.com/comment/82084676

http://stackoverflow.com/comment/82115532
type: QuestionComment
comment on: http://stackoverflow.com/q/47576847
has text: And it's not the cwd?
score: 0
type: Comment

http://stackoverflow.com/q/47578963
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/15056444
score: 0
has answer: http://stackoverflow.com/a/47582963
has title: How to store the return value into a variable after timer event?
has answer: http://stackoverflow.com/a/47581165
type: Question
has comment: http://stackoverflow.com/comment/82115106
tagged with: timer
has comment: http://stackoverflow.com/comment/82116701
answer count: 2
has body: I want to store the final pong position result into a variable after running my timer_event call for one second. I'm not sure how to do so though. Here are my functions def get_final_position(self): return (pong.rect.centerx, pong.rect.centery) def hard_AI_mode(self, pong, paddle): initial_pong_position = (pong.rect.centerx, pong.rect.centery) pygame.time.set_timer(self.get_final_position(), 1000) final_pong_position = ???
has comment: http://stackoverflow.com/comment/82115243
type: UnansweredQuestion

http://stackoverflow.com/q/47601583
tagged with: python
score: -1
tagged with: kivy
has title: Different list for each instance of class
upvote count: 0
has body: I know in python class attributes are shared across instances of a class. I'm trying to write a kivy app in which the first screen has an add button which can be pressed to add more buttons. The buttons are kept track of in a list, and when a new button is created it is added to the list. When a button is pressed the screen switches to another instance of the class that defines the first screen. As it stands, this screen is populated with the list of buttons from the previous screen. Is there a way to have a different list for each instance of the class? from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.properties import NumericProperty, ReferenceListProperty,\ ObjectProperty from kivy.clock import Clock from kivy.uix.screenmanager import ScreenManager, Screen class TasksWindow(Screen): btnHeight=.9 btnList=[] def __init__(self): super(TasksWindow, self).__init__() addBtn = Button(text = "+",pos_hint= {'x': .9,'top': 1},size_hint = (.1,.1)) self.add_widget(addBtn) addBtn.bind(on_press=self.clkAdd) backBtn = Button(text = "Go Back",pos_hint= {'x': 0,'top': 1},size_hint = (.1,.1)) backBtn.bind(on_press=self.clkBack) self.add_widget(backBtn) def clkAdd(self, obj): task = Task() def update(self): for x in range (0, len(self.btnList)): temp = self.btnList.pop(x) if (x == 0): TasksWindow.btnHeight = .9 temp2 = Task() self.btnList.insert(x,temp2) del(self.btnList[len(self.btnList)-1]) self.add_widget(temp2.editBtn) def preupdate(self,dt): bPoint = -1 for x in range (0, len(self.btnList)): self.remove_widget(self.btnList[x]) self.update() def clkBack(self, obj): sm.current = 'Screen 0' class Task(TasksWindow): def __init__(self): if len(TasksWindow.btnList)==0: TasksWindow.btnHeight = .9 self.editBtn = Button(text = "Tap to Edit",pos_hint= {'x': 0,'top': TasksWindow.btnHeight},size_hint = (.9,.1)) self.editBtn.bind(on_press=self.clkEdit) TasksWindow.btnList.append(self) TasksWindow.btnHeight -= .1 def clkEdit(self, obj)…
linked to: http://stackoverflow.com/q/1680528
answer count: 1
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/1680528
has comment: http://stackoverflow.com/comment/82162169
has answer: http://stackoverflow.com/a/47601671
type: UnansweredQuestion

cprofile
tags question: http://stackoverflow.com/q/47564771
type: Tag
tag name: cprofile

http://stackoverflow.com/q/47644958
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82248573
has answer: http://stackoverflow.com/a/47645114
tagged with: optimization
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82248561
score: -1
has body: I've initialized an array of zeros. I'd now like to randomly select positions on the border of the array. If the position is 0, I would then set it to 1, while if it is 1, I would do nothing and repeat the process. Here's what I currently have: D = 50 # lattice dims N = 200 # total number of particles at the end a = np.zeros((D,D)) # playing board array # place particle at the center of the board a[int(D/2), int(D/2)] = 1 border_list = [0, 1, 2, 3] i = 0 while i &lt; N: border = random.choice(border_list) pos = math.floor((D)*random.random()) if border == 0: if a[0, pos] == 0: a[0, pos] = 1 i += 1 if border == 1: if a[pos, 0] == 0: a[pos, 0] = 1 i += 1 if border == 2: if a[int(D-1), pos] == 0: a[int(D-1), pos] = 1 i += 1 if border == 3: if a[pos, int(D-1)] == 0: a[pos, int(D-1)] = 1 i += 1 Seems pretty inefficient to me. Any advice regarding improving it?
has title: Select a random position on the border of an array
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82248666
possible better answer: http://stackoverflow.com/a/47645015
answer count: 2
has answer: http://stackoverflow.com/a/47645015
downvote count: 2
has comment: http://stackoverflow.com/comment/82248614
accepted answer: http://stackoverflow.com/a/47645114

http://stackoverflow.com/q/47695333
duplicate of: http://stackoverflow.com/q/23724136
score: 1
linked to: http://stackoverflow.com/q/240178
upvote count: 1
tagged with: slice
has comment: http://stackoverflow.com/comment/82351098
linked to: http://stackoverflow.com/q/23724136
type: Question
has comment: http://stackoverflow.com/comment/82351595
has comment: http://stackoverflow.com/comment/82351191
has answer: http://stackoverflow.com/a/47695422
has comment: http://stackoverflow.com/comment/82350686
accepted answer: http://stackoverflow.com/a/47695422
has answer: http://stackoverflow.com/a/47695413
possible better answer: http://stackoverflow.com/a/47695413
tagged with: for-loop
downvote count: 0
linked to: http://stackoverflow.com/q/2582138
tagged with: python
has comment: http://stackoverflow.com/comment/82351581
has answer: http://stackoverflow.com/a/47695677
favorite count: 0
has body: Apologies in advance, I loathe to ask such a newb question (this is the first language I'm learning) but there's clearly a gap in my understanding, and I can't find a link to any content which solves the issue I'm experiencing. The below code defines 3 dictionaries, and an empty list. I then run a for loop to populate the list with 30 "Slow Aliens". I then run another loop on the first 10 entries in the list in order to update that particular instance to a "Fast Alien" dictionary. However, I seem to be replacing every dictionary in the list. Any help pointing me to some articles which discuss/solve/educate me further would be appreciatively received. slow_alien = { "Name": "Slow Alien", "Colour": "Green", "Points": 10, "X Position": 15, "Y Position": 20, "Current Speed": "Slow", "Height": 1.8, } medium_alien = { "Name": "Medium Alien", "Colour": "Yellow", "Points": 15, "X Position": 30, "Y Position": 20, "Current Speed": "Medium", "Height": 2.2, } fast_alien = { "Name": "Fast Alien", "Colour": "Red", "Points": 20, "X Position": 45, "Y Position": 20, "Current Speed": "Fast", "Height": 2.6, } aliens = [] for alien in range(30): aliens.append(slow_alien) for alien in aliens[:10]: if alien == slow_alien: alien.update(fast_alien) for alien in aliens: for key, value in alien.items(): print(str(key) + ": " + str(value)) print("") print("The aliens list contains " + str(len(aliens)) + " dictionaries") Thanks, Carl.
tagged with: indexing
has title: Combination of for-loop and index slicing is not returning expected results
type: AnsweredQuestion
answer count: 3

wave
tags question: http://stackoverflow.com/q/47684827
tag name: wave
type: Tag

http://stackoverflow.com/comment/82113418
has text: we installed it with `apt-get install python3.6` I think, and it didn't require that. `tcl/tk` is not even installed....
comment on: http://stackoverflow.com/q/47576339
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47581770
answer count: 1
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47581873
favorite count: 0
has comment: http://stackoverflow.com/comment/82121754
has body: I am looking for an networks. I cant understand that in this page link why we multiply with 2 and after that extract 1 for mean? i know the mean is only: (a+b)/2 so why "2" and "-1" in that code: syn0 = 2 * np.random.random((3, 1)) - 1
tagged with: python
has comment: http://stackoverflow.com/comment/82121137
type: Question
has title: Ann mean for function
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/46846752
type: UnansweredQuestion
score: 0

http://stackoverflow.com/q/47639525
tagged with: jinja2
type: Question
has title: Jinja2 templating options not working in test, but are fine when running server
type: UnansweredQuestion
has body: I receive the following error... ERRORS: ?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option. ...when attempting to run any test suite, with Django 1.11 and its standard test runner. manage.py runserver, however, works just fine. I tracked the error back to the jinja2 templates. My django TEMPLATES setting looks like: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'jinja2')], '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', ], 'environment': 'mysite.jinja2.environment', }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'mysite.context_processors.app_rendering_ctx', ], }, }, ] You'll see there's no loaders key in either of the OPTIONS dicts, so the error is seriously confusing. Stripping out, it's nothing to do with the context processors or environments. It's related to the jinja2 templating... Removing the APP_DIRS key from the first entry lets the tests run: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'jinja2')], 'OPTIONS': { #stuff }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": True,…
tagged with: django
tagged with: python
tagged with: templates
has answer: http://stackoverflow.com/a/47639612
score: 0
answer count: 1

http://stackoverflow.com/comment/82324663
type: AnswerComment
comment on: http://stackoverflow.com/a/47681015
type: Comment
has text: @JokerMartini. Works fine for me - are you sure you copied the code correctly?
score: 0

http://stackoverflow.com/q/47679873
upvote count: 1
tagged with: ocr
favorite count: 0
type: Question
has title: Cannot get pyocr to recognize numbers
type: UnansweredQuestion
tagged with: python
tagged with: tesseract
tagged with: python-tesseract
answer count: 0
score: 1
downvote count: 0
has body: I have extracted a few numbers from images and preprocessed them into a black/white image. Here's an example of what I have: Here is the simple script that tries to identify these numbers: import pyocr import pyocr.builders from PIL import Image tools = pyocr.get_available_tools()[0] filename= "9.png" text = tools.image_to_string(Image.open(filename), lang="eng", builder=pyocr.builders.DigitBuilder()) print text But this results in nothing. I have also tried TextBuilder(), but that also does not match anything. I read that possibly enlarging the image and antialiasing it may help, and I generated this image: But this did not help either. My tesseract version: tesseract 3.05.01 leptonica-1.74.4 libjpeg 9b : libpng 1.6.34 : libtiff 4.0.8 : zlib 1.2.8 Why does it not recognize my digits?

http://stackoverflow.com/comment/82123377
has text: my dataframe says: "Series' object has no attribute 'time'" if i do "times = df.Date.time" , Date is my column and its not an index. i need it as column @Brad Solomon
comment on: http://stackoverflow.com/a/47581984
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82287281
type: QuestionComment
has text: Presumably, you don't have any items in the list where the condition is true.
comment on: http://stackoverflow.com/q/47663982
score: 1
type: Comment

http://stackoverflow.com/q/47566434
has body: s is a string and following code is giving me "None" while executing n=list(s) l = n.reverse() print(l)
has comment: http://stackoverflow.com/comment/116258464
has title: Reverse a list of string giving me none
has answer: http://stackoverflow.com/a/47566487
downvote count: 2
has comment: http://stackoverflow.com/comment/82091197
upvote count: 1
accepted answer: http://stackoverflow.com/a/47566557
has answer: http://stackoverflow.com/a/47566479
linked to: http://stackoverflow.com/q/4280691
has answer: http://stackoverflow.com/a/47566557
possible better answer: http://stackoverflow.com/a/47566487
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47566494
has answer: http://stackoverflow.com/a/47566482
has answer: http://stackoverflow.com/a/47566512
has answer: http://stackoverflow.com/a/47566471
has comment: http://stackoverflow.com/comment/82090818
duplicate of: http://stackoverflow.com/q/4280691
answer count: 7
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82090559
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82285112
score: 0
comment on: http://stackoverflow.com/q/47659675
type: Comment
has text: @Dan-Dev in the context of running an AB test, we are adding about 200 links to a navigation menu. The javascript developer I work with is building the structure of the menu, while I writing a script that will populate the title tag, html text, href and so on. The information is coming from a csv file . This bit I v got working, however beautiful soup tends to encode some of the tags (&) so I have got to find a way to revert them to what they were originally. regarding the extra DIVs, Ihave now idea why BS does that
type: QuestionComment

http://stackoverflow.com/comment/82141522
has text: The dot `.` doesn't match the newline character by default. You have to use the `re.DOTALL` flag. Also if you compile your pattern, the last line is : `scleantext = cleanM.sub('', teststring)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47592280
score: 1

http://stackoverflow.com/comment/82124992
has text: This is a great solution, thank you for sharing it. I acutally used numba already, but still used `np.roll`, which is probably not ideal.
comment on: http://stackoverflow.com/a/47583594
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47598176
upvote count: 0
has comment: http://stackoverflow.com/comment/82155570
downvote count: 1
has comment: http://stackoverflow.com/comment/82154524
has comment: http://stackoverflow.com/comment/82155515
has comment: http://stackoverflow.com/comment/82154662
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/82155262
has body: To the best of my knowledge (and I really like OOP in python), the only way to do this is to create a new class with that specific attribute a.k.a. class Animals: def __init__(self, animals): self.animals = animals def all_eat(self): for animal in animals: animal.eat() Then what you would have to do is: dog = Animal("dog") cat = Animal("cat") giraffe = Animal("giraffe") animals = Animals((dog, cat, giraffe)) animals.all_eat() The reason for this is that python classes themselves do not have callable attributes so you have to call each instance of the class separately.
answers question: http://stackoverflow.com/q/47598004
has comment: http://stackoverflow.com/comment/82155147

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47561327
tags question: http://stackoverflow.com/q/47550789

http://stackoverflow.com/a/47550915
has comment: http://stackoverflow.com/comment/82264304
downvote count: 0
has comment: http://stackoverflow.com/comment/82264533
type: Answer
has comment: http://stackoverflow.com/comment/82264551
upvote count: 4
has comment: http://stackoverflow.com/comment/82256225
has comment: http://stackoverflow.com/comment/82261718
has comment: http://stackoverflow.com/comment/82060131
has comment: http://stackoverflow.com/comment/82215001
has comment: http://stackoverflow.com/comment/82060098
score: 4
has body: What you want is to find the root(s) or zero(s) of an array. This question's answer shows how to do that: How to get values from a graph? Applying the solution to this case here would look as follows: import matplotlib.pyplot as plt import numpy as np # given values y = np.array([0, 38.39, 71.41, 99.66, 123.67, 143.88, 160.61, 174.03, 184.16, 190.8, 193.52]) x = np.array([0, 0.37, 0.74, 1.11, 1.48, 1.85, 2.22, 2.59, 2.96, 3.33, 3.7]) x_val = np.linspace(0,7) plt.plot(x, y, '-') def find_roots(x,y): s = np.abs(np.diff(np.sign(y))).astype(bool) return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1) a = 0.8 b = 150 y_val = np.multiply(a, b) roots = find_roots(x, y-y_val) plt.plot(roots[0],y_val, marker="o") plt.plot([roots[0],roots[0],0],[0,y_val,y_val], "--") plt.xlim(0,None) plt.ylim(0,None) plt.show() If the arrays are monotonically increasing, you may of course also simply interpolate: import matplotlib.pyplot as plt import numpy as np # given values y = np.array([0, 38.39, 71.41, 99.66, 123.67, 143.88, 160.61, 174.03, 184.16, 190.8, 193.52]) x = np.array([0, 0.37, 0.74, 1.11, 1.48, 1.85, 2.22, 2.59, 2.96, 3.33, 3.7]) x_val = np.linspace(0,7) plt.plot(x, y, '-') a = 0.8 b = 150 y_val = np.multiply(a, b) root = np.interp(y_val,y,x) plt.plot(root,y_val, marker="o") plt.plot([root,root,0],[0,y_val,y_val], "--") plt.xlim(0,None) plt.ylim(0,None) plt.show()
answers question: http://stackoverflow.com/q/47548611

http://stackoverflow.com/comment/82072690
has text: Create a [mcve] within your question. Questions dependent on external links will be closed as their value to future readers shouldn't depend upon a link that could break.
comment on: http://stackoverflow.com/q/47556812
score: 0
type: Comment
type: QuestionComment

relationship
tag name: relationship
tags question: http://stackoverflow.com/q/47603418
type: Tag
tags question: http://stackoverflow.com/q/47598556
tags question: http://stackoverflow.com/q/47691050
tags question: http://stackoverflow.com/q/47646312

http://stackoverflow.com/a/47579477
answers question: http://stackoverflow.com/q/47579110
has comment: http://stackoverflow.com/comment/82116104
has body: Another option that doesn't use list.extend. I'd rearrange your code a bit, and try to avoid default parameters: def myflatten(slist): flat = [] if isinstance(slist, list): for item in slist: flat += myflatten(item) else: flat.append(slist) return flat
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/47549304
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82056354
type: UnansweredQuestion
tagged with: python
has body: from sys import platform as sys_pf if sys_pf == 'darwin': import matplotlib matplotlib.use("TkAgg") from tkinter import * from tkinter.ttk import * import ui def init_UI(): main = Tk() main.title('data2knowledge') n = Notebook(main) ProcessTab = Frame(n) MergeTab = Frame(n) LearningTab = Frame(n) ReportTab = Frame(n) AboutTab = Frame(n) n.add(ProcessTab, text = "Process") n.add(MergeTab, text = "Merge") n.add(LearningTab, text = "Learn") n.add(ReportTab, text = "Report") n.add(AboutTab, text = "About") if __name__ == '__main__': '''initialize GUI and start it''' gui = init_UI() gui.mainloop() The error I get when running this code is: AttributeError: 'NoneType' object has no attribute 'mainloop' I believe I need this last if-statement / mainloop() function to get the interface up and running, but I keep getting this error. I really hope someone knows how to solve this! Thanks!
has answer: http://stackoverflow.com/a/47549392
has answer: http://stackoverflow.com/a/47549370
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/47549376
score: 1
downvote count: 1
has title: AttributeError: 'NoneType' object has no attribute 'mainloop'

http://stackoverflow.com/a/47604115
accepted answer of: http://stackoverflow.com/q/47604094
score: 3
answers question: http://stackoverflow.com/q/47604094
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/82167080
type: AcceptedAnswer
downvote count: 0
has body: You must pass the parameter through the lambda function: for x in range(len(compKeys)): compButton = Button(root, text=compKeys[x], command=lambda z=compKeys[x]: compBuDef(z)) compButton.place(x=x*100+200, y=300) or better, iterating over elements: for idx, ckey in enumerate(compKeys): compButton = Button(root, text=ckey, command=lambda z=ckey: compBuDef(z)) compButton.place(x=idx*100+200, y=300)

http://stackoverflow.com/q/47687450
has comment: http://stackoverflow.com/comment/82334303
has comment: http://stackoverflow.com/comment/82334605
has answer: http://stackoverflow.com/a/47687905
has answer: http://stackoverflow.com/a/47687621
possible better answer: http://stackoverflow.com/a/47687621
has comment: http://stackoverflow.com/comment/82334537
accepted answer: http://stackoverflow.com/a/47687905
has comment: http://stackoverflow.com/comment/82334350
has comment: http://stackoverflow.com/comment/82334561
has comment: http://stackoverflow.com/comment/82334313
type: Question
has answer: http://stackoverflow.com/a/47687632
has body: A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this? # -*- coding: utf-8 -*- from __future__ import print_function import random import time def displayIntro(): print("Hello, there! Glad to meet you!") print("Welcome to the world of Pokémon!") print("My name is Maple.") print("People affectionately refer to me as the Pokémon Professor.") print("This world is inhabited far and wide by creatures called Pokémon.") print("For some people, Pokémon are pets.") print("Others use them for battling.") print("As for myself, I study Pokémon as a profession.") print("But first, tell me a little about yourself.") def chooseGender(): gender = "" while gender != "boy" and gender != "girl": gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ") return gender def chooseName(): name = "" name = raw_input("Let's begin with your name. What is it? ") return name def nameConfirmation(): name = chooseName() answer = "" while answer != "yes" and answer != "no": answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ") return answer if answer == "yes": print("I have a grandson.") print("He's been your rival since you both were babies.") print("...Erm, what was his name now?") # raw_input for their name print("...Er, was it") #raw_input for name # Let user pick yes or no # If yes, move on # If no, ask name again print("That's right! I remember now! His name is") #raw_input for name print("your name!") # raw_input for name print("Your very own Pokémon legend is about to unfold!") print("A world of dreams and adventures with Pokémon awaits! Let's go!") if answer == "no": chooseName() displayIntro() chooseGender() chooseName() nameConfirmation() I apologize for not posting the rest of the code sooner. This is the output. Let's begin with your name. What is it? Raven Let's begin with your name. What is it? Raven
has title: Why is my function executing twice?
has comment: http://stackoverflow.com/comment/82334435
tagged with: python
has comment: http://stackoverflow.com/comment/82334349
answer count: 4
has answer: http://stackoverflow.com/a/47687630
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82334457
score: 0

http://stackoverflow.com/comment/82098647
type: Comment
comment on: http://stackoverflow.com/a/47570458
type: AnswerComment
score: 0
has text: variables have been edited but loop is still not running as program is expected to

http://stackoverflow.com/comment/82283732
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47654757
type: Comment
has text: Also, what is the result of `type(bucket_lower_bounds)`? I would expect it to be a `DatetimeIndex`(return type of `pd.date_range`), but it appears to be `Index`.

http://stackoverflow.com/comment/82122504
type: QuestionComment
has text: I have no idea what the "real answer" is - or even if Python 3 is in fact unsupported (that surprises me). But think about it: what would be the return on investment for creating - and supporting - a second product, vs. just one product? How many production systems (i.e. "paying customers") are actually using Python3 (to the exclusion of Python2).? Does Python3 support make economic sense?
comment on: http://stackoverflow.com/q/47582434
score: 0
type: Comment

http://stackoverflow.com/q/47641223
upvote count: 1
score: 1
tagged with: surface
tagged with: scipy
favorite count: 0
type: Question
has body: I'm trying to accomplish something similar. But trying to calculate difference between two interpolated grids. The grids are of different shapes, so cannot use np.subtract to calculate the difference. Any help on how to calculate the difference? #create two interpolated grids from two set of xyz points and calculate difference ixx = np.array(self.ix) iyy = np.array(self.iy) izz = np.array(self.iz) iminx = min(ixx.flat) imaxx = max(ixx.flat) iminy = min(iyy.flat) imaxy = max(iyy.flat) # post surface - get extents pxx = np.array(self.px) pyy = np.array(self.py) pzz = np.array(self.pz) pminx = min(pxx.flat) pmaxx = max(pxx.flat) pminy = min(pyy.flat) pmaxy = max(pyy.flat) ixi = np.arange(iminx, imaxx, self.cellsize) iyi = np.arange(iminy, imaxy, self.cellsize) iX,iY = np.meshgrid(ixi,iyi) iextent = (min(ixi), max(ixi), min(iyi), max(iyi)) pxi = np.arange(pminx, pmaxx, self.cellsize) pyi = np.arange(pminy, pmaxy, self.cellsize) pX,pY = np.meshgrid(pxi,pyi) pextent = (min(pxi), max(pxi), min(pyi), max(pyi)) igrid = griddata((ixx, iyy), izz, (iX, iY), method='linear') pgrid = griddata((pxx, pyy), pzz, (pX, pY), method='linear') # would like to calcualte difference, but this wont work, due to different shapes changegrid = np.subtract(pgrid, igrid) igrid shape is (181, 130), pgrid shape is (184, 126). Another important information is these are spatial grids with overlapping spatial extents. If we just broadcast/extend array shapes, would that be enough? I do not want to subtract the grids at wrong x/y locations. So basically like in GIS/Arcmap how we calculate raster difference at each cell at a particular xy cell location.
tagged with: interpolation
tagged with: numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82284731
has title: create two interpolated grids from two sets of xyz points and calculate difference using python
tagged with: python
has comment: http://stackoverflow.com/comment/82355868
answer count: 0
downvote count: 0

http://stackoverflow.com/q/47573159
type: Question
tagged with: python-3.x
score: 3
accepted answer: http://stackoverflow.com/a/47573525
has title: Remember elements text clicked of names in Selenium?
has answer: http://stackoverflow.com/a/47573525
tagged with: python
has body: As an example lets say I wanted to record all bios of users on SO. Lets say I loaded up: How to click an element in Selenium WebDriver using JavaScript I clicked all users: .user-details a (11 of them) I wrote Extracted text -> to a csv. driver.get(‘Version compatibility of Firefox and the latest Selenium IDE (2.9.1.1-signed)’) I read from csv the users. user: Ripon Al Wasim [Is present again, do not click him] ??? How can this be achieved. As its text. Is something like this accomplish-able or is this a limitation of selenium python? You could click all of them, but lets say you had to scrape 200 pages and common name Bob popped up 430 times. I feel like it is unnecessary to click his name. Is something like this possible with Selenium? I feel like I'm missing something and this is achievable but I am unaware how. You could compare the text of text file and print(elem.get_attribute("href")) -> write that to a file and compare them. If elements were present, delete them but this is text. You could (maybe) put the text in an excel file. I'm not entirely sure if this is possible but you could write the css elements individually beside the text in the excel. And Delete rows where there are matched strings. And then get Selenium to load that up into Webdriver. I'm not entirely convinced even this would work. Is there a sane way of clicking css but ignoring names in a text file you have already clicked.
tagged with: selenium-webdriver
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11947832
upvote count: 3
answer count: 1
downvote count: 0
tagged with: selenium
linked to: http://stackoverflow.com/q/46168963
favorite count: 0

http://stackoverflow.com/comment/82282530
score: 0
type: Comment
type: AnswerComment
has text: Thanks so much! I'm getting a permission error right now. googleapiclient.errors.ResumableUploadError: <HttpError 403 "Insufficient Permission"> My source is SCOPES = 'https://www.googleapis.com/auth/drive.file' Do you know how to fix this?
comment on: http://stackoverflow.com/a/47643512

http://stackoverflow.com/q/47657030
linked to: http://stackoverflow.com/q/710551
score: 1
has comment: http://stackoverflow.com/comment/82307990
has comment: http://stackoverflow.com/comment/82272378
tagged with: python
tagged with: eclipse
has comment: http://stackoverflow.com/comment/82272549
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82272848
upvote count: 1
has title: Python - Best practice of importing modules in the same package?
has body: I am writing a package and the folder structure is like: /package_name __init__.py module_1.py module_2.py If in module_2 I want to import module_1, is it better to do 1) import module_1 or 2) import package_name.module_1 ? Both ways can run successfully. 1) makes more sense to me, because the code is shorter, and also avoids the unnecessary import of __init__.py in approach 2). However when I do 1), the IDE gives an unresolved import error, despite it can run without any problem. And if I do 2) the IDE doesn't give the error. So I am wondering if 2) is the more recommended approach. I am using Python 3.6. My IDE is Eclipse + Pydev. -- edit -- 'import module' or 'from module import' is an entirely different question. I don't see how my question is a duplicate of that one.
favorite count: 0
type: Question

http://stackoverflow.com/q/47617506
has comment: http://stackoverflow.com/comment/82193236
tagged with: python
has title: Password checker error - python
has comment: http://stackoverflow.com/comment/82193994
has comment: http://stackoverflow.com/comment/82194126
has comment: http://stackoverflow.com/comment/82193232
upvote count: 0
has comment: http://stackoverflow.com/comment/82193279
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/82193221
has body: I am trying to make a simple password checker in Python. It should accept a password if it has more than 1 upper and lower case letter and if it is more than 8 characters long. But when I run this I get the "do not continue" option from the if statement. Is there something wrong with the if statement? passwd1 = input("enter your password&gt;&gt;&gt;") passwd2 = input("re-enter your password&gt;&gt;&gt;") lower=0 upper=0 for i in passwd1: if(i.islower()): lower=lower+1 elif(i.isupper()): upper=upper+1 if lower + upper &gt;= 8 and lower&lt;0 and upper&lt;0 and passwd1 == passwd2: print("continue") else: print("do not continue") Thanks
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47617921
has comment: http://stackoverflow.com/comment/82193313
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/82193374

http://stackoverflow.com/comment/82110836
score: 1
type: Comment
type: QuestionComment
has text: Well I think you are taking the wrong approach. If you want to teach Python programming, don't worry about memory locations. If you want to teach memory management, use a low-level language like C.
comment on: http://stackoverflow.com/q/47576775

http://stackoverflow.com/comment/82313524
comment on: http://stackoverflow.com/q/47674761
score: 1
type: Comment
type: QuestionComment
has text: from the code posted here, what I can tell is that you match a point against another point.... which results in 0... cnt and cntImage are already an array of points... and when you do [0] you get the first point... try wihtout [0]. Also, no points = no moments = no difference = 0.0 so it makes sense that it return 0 in the case of no contour.

http://stackoverflow.com/comment/82344448
has text: Can you supply the path as a command-line argument to `pipeMe.exe`?
comment on: http://stackoverflow.com/q/47682803
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82230952
has text: Did you try just `tbl[i, j] += 1` and see what that resolves to? Is that the same thing as B?
score: 0
comment on: http://stackoverflow.com/q/47636137
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47595573
answers question: http://stackoverflow.com/q/47595020
has comment: http://stackoverflow.com/comment/82155762
has comment: http://stackoverflow.com/comment/82150868
has comment: http://stackoverflow.com/comment/82154466
has comment: http://stackoverflow.com/comment/82154139
type: Answer
has comment: http://stackoverflow.com/comment/82150364
has comment: http://stackoverflow.com/comment/82155661
has comment: http://stackoverflow.com/comment/82152202
has comment: http://stackoverflow.com/comment/82155290
has comment: http://stackoverflow.com/comment/82148764
has comment: http://stackoverflow.com/comment/82158046
has comment: http://stackoverflow.com/comment/82155590
has body: A connect times out if the TCP handshake with the server is not finished within a specific time, usually because the server does not respond in time. There might be various reasons for is, like the server being down, getting the wrong IP address for the server during DNS lookup, server being overloaded etc. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) Adding this on the client side on the connection has no use. Adding this on the server side will help if the problem was caused by a crashed server since it will allow the server to bind to the listener address again without waiting and thus the server is faster available again. But, I have no idea if this is really the problem you are facing.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82153400
score: 1
has comment: http://stackoverflow.com/comment/82152368
has comment: http://stackoverflow.com/comment/82152889
has comment: http://stackoverflow.com/comment/82153183

http://stackoverflow.com/q/47598090
score: 1
tagged with: python
has title: How to find inputs of dask.delayed task?
downvote count: 0
upvote count: 1
answer count: 1
tagged with: dask-delayed
has answer: http://stackoverflow.com/a/47598397
accepted answer: http://stackoverflow.com/a/47598397
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: dask
has body: Given a dask.delayed task, I want to get a list of all the inputs (parents) for that task. For example, from dask import delayed @delayed def inc(x): return x + 1 def inc_list(x): return [inc(n) for n in x] task = delayed(sum)(inc_list([1,2,3])) task.parents ??? Yields the following graph. How could I get the parents of sum#3 such that it yields a list of [inc#1, inc#2, inc#3]?

http://stackoverflow.com/q/47649686
has comment: http://stackoverflow.com/comment/82257708
has comment: http://stackoverflow.com/comment/82582353
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu-14.04
has comment: http://stackoverflow.com/comment/82257988
has comment: http://stackoverflow.com/comment/82341097
has body: Running a model and returning result in numpy array, I get Memory error. Versions Ubuntu 14.04.3 LTS EC2 g2.2xlarge image: ami-125b2c72 15GB RAM, 8vCPU Python: Python 2.7.6 numpy.version.version: 1.13.3 *Runs fine in MacOS with 16GB of RAM. Error Using TensorFlow backend. Dataset: 6000 train images. Descriptions: train=6000 Vocabulary Size: 7579 Photos: train=6000 Description Length: 34 Traceback (most recent call last): File "main.py", line 291, in &lt;module&gt; X1train, X2train, ytrain = create_sequences(tokenizer, max_length, train_descriptions, train_features) File "main.py", line 225, in create_sequences return array(X1), array(X2), array(y) MemoryError Code here def create_sequences(tokenizer, max_length, descriptions, photos): """Creates sequences of images, input sequences and output words for an image. X1, X2 (text sequence), y (word) photo startseq, little photo startseq, little, girl photo startseq, little, girl, running photo startseq, little, girl, running, in photo startseq, little, girl, running, in, field photo startseq, little, girl, running, in, field, endseq :param tokenizer: :param max_length: :param descriptions: :param photos: :return: """ X1, X2, y = [], [], [] # Walk through each image identifier. for desc_key, desc_list in descriptions.iteritems(): # Walk through each description for the image. for desc in desc_list: # Encode the sequence. seq = tokenizer.texts_to_sequences([desc])[0] # Split one sequence into multiple X,Y pairs. for i in range(1, len(seq)): # Split into input and output pair. in_seq, out_seq = seq[:i], seq[i] # Pad input sequence. in_seq = pad_sequences([in_seq], maxlen=max_length)[0] # Encode output sequence out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] # Store. X1.append(photos[desc_key][0]) X2.append(in_seq) y.append(out_seq) return array(X1), array(X2), array(y) Memory information MemTotal: 15400948 kB MemFree: 14558676 kB Buffers: 388 kB Cached: 604332 kB SwapCached: 3764 kB Active: 301464 kB Inactive…
has comment: http://stackoverflow.com/comment/82257648
score: 0
has comment: http://stackoverflow.com/comment/82582380
answer count: 0
tagged with: arrays
linked to: http://stackoverflow.com/q/41297634
has comment: http://stackoverflow.com/comment/82258370
has title: Numpy array error MemoryError
type: Question
tagged with: numpy

http://stackoverflow.com/comment/82084312
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47562417
type: Comment
has text: You have indentation problems in your code.

http://stackoverflow.com/a/47640745
has comment: http://stackoverflow.com/comment/82240480
has comment: http://stackoverflow.com/comment/82240866
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82240815
has body: csv readers return a list for each line of the file - your outer loop is iterating over the lines/rows and your inner loop is iterating over items in each row. It isn't clear what you want. but your conditional writes happen for each item in each row. If your intent is to check and see if there is a match in the row instead of items in the row, for row in f : match = False for item in row: lines += 1 #?? #الوسطى match = re.search('شقراء',item) if match: outfile1.write(row) else: outfile6.write(row) You could accomplish the same thing just iterating over the lines in the file without using a csv reader with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f: for line in f: #الوسطى if re.search('شقراء',line): outfile1.write(line) else: outfile6.write(line)
answers question: http://stackoverflow.com/q/47640258
type: Answer
has comment: http://stackoverflow.com/comment/82241114

http://stackoverflow.com/a/47560582
answers question: http://stackoverflow.com/q/47560292
downvote count: 0
has comment: http://stackoverflow.com/comment/82079918
upvote count: 2
type: Answer
has body: You can use a simple regular expression: Find all sequences to be replaced Replace each sequence with its lowercase equivalent import re link1 = 'https://images.trvl-media.com/media/content/expus/email/2016/us/banner/images/image_stor-34461_09_600x250.jpg|%%mis_lx_Offers_mod_Images.LargeImageURL%%' link2 = 'https://www.xxxxxxxx.co.nz/Activities|http://www.xxxxxxxx.co.nz/things-to-do/search?location=%%t.Trip_Intrip_1_dest_City_1%%' links = [link1, link2] for idx, link in enumerate(links): lowers = re.findall(r'%%.*?%%', link) for x in lowers: links[idx] = re.sub(r'%%.*?%%', x.lower(), link) for link in links: print(link) output: https://images.trvl-media.com/media/content/expus/email/2016/us/banner/images/image_stor-34461_09_600x250.jpg|%%mis_lx_offers_mod_images.largeimageurl%% https://www.xxxxxxxx.co.nz/Activities|http://www.xxxxxxxx.co.nz/things-to-do/search?location=%%t.trip_intrip_1_dest_city_1%%
score: 2

http://stackoverflow.com/a/47630330
has comment: http://stackoverflow.com/comment/82218682
has comment: http://stackoverflow.com/comment/82218558
score: 0
has comment: http://stackoverflow.com/comment/82218721
has body: You can get quadratic complexity using O(n) of memory. Make array[0..9] of digit counters (or use another data structure convenient for Python) Walk through the string, increment counter for current digit and add modified array to the list. After that list will contain "cumulative sums" - counts for every digit upto every index (for example, five 2's before 40-th string entry) Now to get count for digit between i-th and j-th entries, just subtract C[j][digit] - C[i][digit] Interesting question - does better complexity solution exist?
has comment: http://stackoverflow.com/comment/82218560
answers question: http://stackoverflow.com/q/47629449
type: Answer
has comment: http://stackoverflow.com/comment/82240769

mysql
tags question: http://stackoverflow.com/q/47629806
tags question: http://stackoverflow.com/q/47636145
tags question: http://stackoverflow.com/q/47661591
tags question: http://stackoverflow.com/q/47599637
tags question: http://stackoverflow.com/q/47643409
type: Tag
tags question: http://stackoverflow.com/q/47665365
tags question: http://stackoverflow.com/q/47613812
tags question: http://stackoverflow.com/q/47568483
tags question: http://stackoverflow.com/q/47588910
tags question: http://stackoverflow.com/q/47645187
tags question: http://stackoverflow.com/q/47620031
tags question: http://stackoverflow.com/q/47624931
tags question: http://stackoverflow.com/q/47665784
tags question: http://stackoverflow.com/q/47602356
tags question: http://stackoverflow.com/q/47601137
tags question: http://stackoverflow.com/q/47573519
tag name: mysql
tags question: http://stackoverflow.com/q/47603405
tags question: http://stackoverflow.com/q/47658519
tags question: http://stackoverflow.com/q/47661458
tags question: http://stackoverflow.com/q/47622988
tags question: http://stackoverflow.com/q/47649792
tags question: http://stackoverflow.com/q/47651327
tags question: http://stackoverflow.com/q/47549851
tags question: http://stackoverflow.com/q/47644739
tags question: http://stackoverflow.com/q/47556259
tags question: http://stackoverflow.com/q/47545511
tags question: http://stackoverflow.com/q/47644459
tags question: http://stackoverflow.com/q/47554658
tags question: http://stackoverflow.com/q/47571343
tags question: http://stackoverflow.com/q/47590361
tags question: http://stackoverflow.com/q/47576843
tags question: http://stackoverflow.com/q/47613626
tags question: http://stackoverflow.com/q/47581682
tags question: http://stackoverflow.com/q/47661764
tags question: http://stackoverflow.com/q/47603148
tags question: http://stackoverflow.com/q/47609552
tags question: http://stackoverflow.com/q/47667051
tags question: http://stackoverflow.com/q/47655847
tags question: http://stackoverflow.com/q/47544450
tags question: http://stackoverflow.com/q/47682800
tags question: http://stackoverflow.com/q/47577170
tags question: http://stackoverflow.com/q/47607002
tags question: http://stackoverflow.com/q/47549788
tags question: http://stackoverflow.com/q/47679434
tags question: http://stackoverflow.com/q/47666068
tags question: http://stackoverflow.com/q/47680917

http://stackoverflow.com/comment/82286820
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47663128
has text: [Catch the exception](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) and inspect/print relevant data to see what might be going on.

http://stackoverflow.com/q/47684855
tagged with: python
has comment: http://stackoverflow.com/comment/82329830
score: 0
tagged with: list
has body: I want to get list of a column values in aggregated function, in pyspark 1.4. The collect_list is not available. Does anyone have suggestion how to do it? Original columns: ID, date, hour, cell 1, 1030, 01, cell1 1, 1030, 01, cell2 2, 1030, 01, cell3 2, 1030, 02, cell4 I want output like below, groupby (ID, date, hour) ID, date, hour, cell_list 1, 1030, 01, cell1, cell2 2, 1030, 01, cell3 2, 1030, 02, cell4 But my pyspark is in 1.4.0, collect_list is not available. I can't do: df.groupBy("ID","date","hour").agg(collect_list("cell")).
has title: pyspark 1.4 how to get list in aggregated function
tagged with: apache-spark-1.4
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47685163
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47669379
tagged with: pyspark

http://stackoverflow.com/comment/82075926
has text: This `def start(adv_id):` and `def add():` should not be repeated again for another view name.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47558985
score: 0

http://stackoverflow.com/a/47597819
downvote count: 0
upvote count: 1
has body: You can apply value_counts() fn to one column of dataframe. Following applies it all columns one by one: for onecol in to_count: print(onecol, ":\n", to_count[onecol].value_counts()) Output: col1 : word1 2 word3 1 Name: col1, dtype: int64 col2 : word5 1 word2 1 word7 1 Name: col2, dtype: int64 col3 : word3 3 Name: col3, dtype: int64
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47597738

http://stackoverflow.com/q/47695462
score: 0
has comment: http://stackoverflow.com/comment/82350630
tagged with: binaryfiles
tagged with: global-variables
has title: binary file from global attribute cdf
tagged with: attributes
type: Question
has body: I am not a python expert but I am using it. What I have is a list of CDF files from which I want to extract a global attribute (which is of type CDF_DOUBLE) and write this variable into a single binary file. I am using pycdf for it. I am able to extract the global attribute, but I am not able to write it into the binary file. Here is the code: #!/usr/bin/env python3 import os import zipfile from spacepy import pycdf input_path = '/home/mypath' filelist = os.listdir(input_path) for filename in filelist: fullfilename = input_path + '/' + filename zfile = zipfile.ZipFile(fullfilename, 'r') cdffile_zip = zfile.extract(zfile.namelist()[0], '/home/scratch/') cdffile = pycdf.CDF(cdffile_zip) zfile.close() glob_attr = cdffile.attrs['MY_GLOBAL_ATTR'] with open('somefile.bin', 'wb') as f: f.write(glob_attr) &lt;-- ***PROBLEM HERE*** f.close() command = 'rm -f {}'.format(cdffile_zip) os.system(command) Thanks for any help
answer count: 0
has comment: http://stackoverflow.com/comment/82350447
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82392364
tagged with: python
has comment: http://stackoverflow.com/comment/82467892

http://stackoverflow.com/q/47646093
has comment: http://stackoverflow.com/comment/82267690
tagged with: pandas
has answer: http://stackoverflow.com/a/47649056
score: 1
has title: Lags data on Pandas dataframes
accepted answer: http://stackoverflow.com/a/47653151
tagged with: sklearn-pandas
type: Question
has answer: http://stackoverflow.com/a/47653151
answer count: 2
upvote count: 2
tagged with: forecasting
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/82256383
downvote count: 1
has body: I'm using sklearn to make a forecast. Usually i will create lagged data to forecasting, this is easy if the feature only consist 1 column. for example: index temperature 1 100 2 80 3 50 4 90 5 110 Usually i will create another column with shifting the temperature value to create lagged data using function like: dataframe.temperature.shift() So my dataframe become: index temperature temperature2 temperature3 1 100 NaN NaN 2 80 100 NaN 3 50 80 100 4 90 50 80 5 110 90 50 Then when i want to forecast, i can fit using code like: x = dataframe.loc[:,('temperature3','temperature2')] y = dataframe.temperature model.fit([x],y) The problem is when i have a lot of column to create lag data, and need more lagged data for each column, my dataframe will be too big. Is there any simple approach that i can use? Thanks! For reference, this is my dataframe: import pandas as pd import talib df = pd.read_csv('..\\data\\uj5.CSV', names=['date','time','open','high','low','close','volume']) df.index = pd.to_datetime(df.date + df.time,format='%Y.%m.%d%H:%M') # assuming this is the 'X', let say i need 100 lags of these column to predict the 'Y' df['CDLBELTHOLD'] = talib.CDLBELTHOLD(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLDOJI'] = talib.CDLDOJI(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLHIKKAKE'] = talib.CDLHIKKAKE(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLLONGLINE'] = talib. CDLLONGLINE(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLSHORTLINE'] = talib.CDLSHORTLINE(df.open.values, df.high.values, df.low.values, df.close.values) df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open.values, df.high.values, df.low.values, df.close.values) df['atr'] = talib.ATR…
favorite count: 0
has comment: http://stackoverflow.com/comment/82255701
has comment: http://stackoverflow.com/comment/82324592
possible better answer: http://stackoverflow.com/a/47649056
type: AnsweredQuestion

http://stackoverflow.com/comment/82202044
type: Comment
has text: There are dozens of questions on this site related to timers, sleep, and the `after` method. Have you done any research before asking this question?
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47621977

http://stackoverflow.com/comment/82103903
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47573416
has text: The `x for y in z` in the list comprehension may look like a generator, but it isn't. The inner workings are different. E.g. a `StopIteration` raised in the `x` part will stop a generator but will bubble out of the list comprehension.

http://stackoverflow.com/comment/82302992
comment on: http://stackoverflow.com/q/47671733
score: 0
type: Comment
type: QuestionComment
has text: I am confused as to why you are using all these string methods for numbers. Can you try to piece together a reproducible example including construction of the mini-df?

http://stackoverflow.com/q/47649694
has answer: http://stackoverflow.com/a/47655073
tagged with: matplotlib
tagged with: python
has body: I have 3 lists x,y,z containing long,lat,value. I am trying to construct a plot using contourf and maskoceans. The result i am getting isn't very good near the coastline. Trying to increase arguments of linspace leads to memory error. Is there a way to achieve better result close to the coastline? My code is as follows: import numpy as np import scipy.interpolate from mpl_toolkits.basemap import Basemap,maskoceans import matplotlib.pyplot as plt x=[23.027008, 22.774524, 23.010211, 22.346053, 21.264416, 21.261967, 21.31769, 21.478437, 21.406678, 21.453064] y=[36.547227, 36.824754, 37.482874, 37.61182, 37.873769, 37.935473, 37.978032, 38.139038, 38.162707, 38.168772] z=[155.15, 354.86, 400.2, 47.16, 188.44, 277.01, 375.12, 87.71, 133.85, 123.56] map =Basemap(projection='mill', llcrnrlat=36.928942,llcrnrlon=21.696255, urcrnrlat=38.03002,urcrnrlon=23.497298, resolution='i') map.drawcoastlines() xi, yi = np.linspace(21,24, 100), np.linspace(36, 39, 100) xi, yi = np.meshgrid(xi, yi) xm,ym=map(xi,yi) rbf = scipy.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) zm=maskoceans(xi,yi,zi,resolution='h',grid=1.25) map.contourf(xm, ym, zm,cmap='jet') map.colorbar() plt.show()
tagged with: scipy
type: Question
tagged with: interpolation
has title: Matplotlib maskoceans results using lists
type: UnansweredQuestion
answer count: 1
score: 0

http://stackoverflow.com/comment/82292132
comment on: http://stackoverflow.com/q/47656071
has text: Delete the `migrations` directory and repeat the whole process again please. If you get the error, please add the command that gave you the error, along with the complete output to your question.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/47545128
has comment: http://stackoverflow.com/comment/82047356
accepted answer: http://stackoverflow.com/a/47545442
answer count: 1
tagged with: pyqt5
upvote count: 1
has answer: http://stackoverflow.com/a/47545442
downvote count: 1
has body: I have a QTableWidget in PyQT5 and I need to go to a specific visual position of the table. How could I do it? When I say visual I mean to give the row and column,then see on the table the given row and column visually
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: qtablewidget
has comment: http://stackoverflow.com/comment/82047189
has comment: http://stackoverflow.com/comment/82047312
has title: Go To Position of Visual Cell on QTableWidget
has comment: http://stackoverflow.com/comment/82047253
has comment: http://stackoverflow.com/comment/82047380
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82047344
tagged with: pyqt

http://stackoverflow.com/comment/82044512
comment on: http://stackoverflow.com/a/47543628
score: 0
type: Comment
has text: Thank you. And the cursor is standard across all interface drivers you're saying? Most likely from [PEP 249](https://www.python.org/dev/peps/pep-0249/)?
type: AnswerComment

http://stackoverflow.com/a/47581428
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82235825
has body: You can use pd.crosstab: pd.crosstab(df.Instrument, df['Date'],values=df['Total Return'], aggfunc='mean') Output: Date 2017-11-27T00:00:00Z 2017-11-28T00:00:00Z 2017-11-29T00:00:00Z Instrument JP3843250006 0.200000 0.349301 0.348086 KYG2615B1014 -8.035714 -10.679612 0.000000
has comment: http://stackoverflow.com/comment/82121469
has comment: http://stackoverflow.com/comment/82209760
has comment: http://stackoverflow.com/comment/82121452
answers question: http://stackoverflow.com/q/47581274
type: Answer
has comment: http://stackoverflow.com/comment/82233994
accepted answer of: http://stackoverflow.com/q/47581274

http://stackoverflow.com/comment/82201441
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47621510
score: 0
has text: Please edit the question instead of adding code and tracebacks in comments.

http://stackoverflow.com/comment/82126863
comment on: http://stackoverflow.com/q/47584427
score: 1
type: Comment
type: QuestionComment
has text: @JDN yeah, if you simply wanted to *mutate* the variable, i.e. `my_memo_dict.clear()`, then you could hack something with `my_func.func_closure` and `my_func.func_code.co_freevars` but since functions are just objects, just add an attribute to it, it's a much cleaner solution. Anyway, hacking the `func_closure` won't allow you to *reassign*, but you could access and modify.

http://stackoverflow.com/comment/82182763
type: QuestionComment
has text: I've added the full traceback I'm seeing. It happens with all images.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47612243

http://stackoverflow.com/a/47673484
answers question: http://stackoverflow.com/q/47673455
downvote count: 0
type: Answer
upvote count: 2
has body: I believe you need to_numeric with parameter errors='coerce' for convert non numeric to NaNs: groupdf['Azimuth [deg]']= pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce') If need remove all columns which are not parseable and no NaNs values in data is possible use boolean indexing and filter by notnull: groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notnull()] In last version of pandas, 0.21.0 is possible use Series.notna: groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notna()]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47673455
score: 2

http://stackoverflow.com/comment/82276227
type: Comment
type: QuestionComment
has text: Are you running the code inside your virtual environment? As in do you activate the venv each time you run the python script?
score: 0
comment on: http://stackoverflow.com/q/47656211

http://stackoverflow.com/q/47555196
has comment: http://stackoverflow.com/comment/98965645
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/98998490
has comment: http://stackoverflow.com/comment/98998780
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/98966723
has comment: http://stackoverflow.com/comment/98962763
has comment: http://stackoverflow.com/comment/98998684
linked to: http://stackoverflow.com/q/129628
linked to: http://stackoverflow.com/q/1784664
tagged with: python
has comment: http://stackoverflow.com/comment/82072359
has comment: http://stackoverflow.com/comment/98999343
has title: Imperative vs Declarative in python
duplicate of: http://stackoverflow.com/q/1784664
has comment: http://stackoverflow.com/comment/98999022
has body: I am trying to get the concepts of imperative vs declarative styles through python. From my understanding the definitions of imperative and declarative are imperative - code all the steps in the desired outcome declarative - code the desired outcome without the steps For example: would this be considered imperative? L = [] for i in range(5): L.append(i*2) and would this version be considered declarative? L = list(map(lambda x: x*2, range(5)))
has comment: http://stackoverflow.com/comment/82067466
has comment: http://stackoverflow.com/comment/99000044
has comment: http://stackoverflow.com/comment/98951732
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82072972
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/98951812
has comment: http://stackoverflow.com/comment/98998977
has comment: http://stackoverflow.com/comment/82072068
has comment: http://stackoverflow.com/comment/82069078

http://stackoverflow.com/q/47565722
type: Question
has answer: http://stackoverflow.com/a/47566436
accepted answer: http://stackoverflow.com/a/47566436
tagged with: celerybeat
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82089473
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I have to add few periodic tasks. I'm using Celery - Redis in Django platform. When I execute the method from shell_plus all is well . However Celery Beat is unable to find the database instance properly. Celery version = 4.1.0. I had previously installed django-celery-beats etc Database = MySQL Where am i wrong. Thanks in advance. Celery Command (venv)$:/data/project/(sesh/dev)$ celery -A freightquotes worker -B -E -l INFO --autoscale=2,1 settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_BROKER_TRANSPORT = 'redis' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 604800} CELERY_RESULT_BACKEND = BROKER_URL CELERY_TASK_RESULT_EXPIRES = datetime.timedelta(days=1) # Take note of the CleanUp task in middleware/tasks.py CELERY_MAX_CACHED_RESULTS = 1000 CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] REDIS_CONNECT_RETRY = True REDIS_DB = 0 BROKER_POOL_LIMIT = 2 CELERYD_CONCURRENCY = 1 CELERYD_TASK_TIME_LIMIT = 600 CELERY_BEAT_SCHEDULE = { 'test': { 'task': 'loads.tasks.test', 'schedule': crontab(minute='*/1'), }, init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.base') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) loads/tasks.py @task() def test(): x = [i.id for i in Load.objects.all()] print (x) Error [2017-11-30 03:52:00,032: ERROR/ForkPoolWorker-2] Task loads.tasks.test[0020e4ae-5e52-49d8-863f-e51c2acfd7a7] raised unexpected: OperationalError('no such table: loads_load',) Traceback (most recent call last): File "/data/project/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return…
downvote count: 0
has title: Celery Beat unable to find database models (django.db.utils.OperationalError)
has comment: http://stackoverflow.com/comment/82089441
answer count: 1
tagged with: django-celery
favorite count: 0
tagged with: celery

http://stackoverflow.com/q/47678702
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82404949
tagged with: python
has comment: http://stackoverflow.com/comment/82411692
score: 0
has title: Tensorflow, tf.case() vs tf.cond() with logical operation
has body: I have 2 tensors X, and Y. X = tf.constant([[-1,-2,-3],[4,5,6]], dtype=tf.float32) Y = tf.constant([[-2,2,2],[-2,2,2]], dtype=tf.float32) The operation I want is: if ((X > 0 and Y > 0) or (X &lt; 0 and Y &lt; 0)): X+Y else: X-Y I followed the sample at the tf.case: Example 2: Pseudocode: if (x &lt; y &amp;&amp; x &gt; z) raise OpError("Only one predicate may evaluate true"); if (x &lt; y) return 17; else if (x &gt; z) return 23; else return -1; Expressions: def f1(): return tf.constant(17) def f2(): return tf.constant(23) def f3(): return tf.constant(-1) r = case({tf.less(x, y): f1, tf.greater(x, z): f2}, default=f3, exclusive=True) The reason tf.case() wouldn't work is that the condition must be a scalar tensor so it wouldn't support a 2D tensor. Each pair contains a boolean scalar tensor and a python callable Tried with tf.cond() and failed: import tensorflow as tf a = tf.constant([[-1,-2,-3],[4,5,6]], dtype=tf.float32) b = tf.constant([[-2,2,2],[-2,2,2]], dtype=tf.float32) zero = tf.fill(tf.shape(a), 0.0) def f1(): return tf.add(a,b) def f2(): return zero c = tf.cond(tf.less(a,b), f1, f2) with tf.Session() as session: r_c = session.run([c]) print (r_c) Here is the error report: Shape must be rank 0 but is rank 2 for 'cond/Switch' (op: 'Switch') with input shapes: [2,3], [2,3].
has comment: http://stackoverflow.com/comment/82317597
tagged with: tensorflow
type: Question
answer count: 0

http://stackoverflow.com/comment/137246017
score: 0
type: AnswerComment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: Comment
comment on: http://stackoverflow.com/a/77847642

http://stackoverflow.com/comment/82095417
score: 0
type: QuestionComment
type: Comment
has text: `spawn` reads the commands to execute from stdin, not from cmd line arguments. Perhaps you should post a bit more of your script. Are you using `spawn` to run a single `scp` command?
comment on: http://stackoverflow.com/q/47568635

http://stackoverflow.com/comment/90247865
type: QuestionComment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177227/discussion-between-imoutidi-and-bhargav-rao).
comment on: http://stackoverflow.com/q/47592566
type: Comment

http://stackoverflow.com/comment/82335879
has text: Thank you very much.Can you give me any link where i can find all commands of tix like when i click on any item it should give me its value(path) and if i check on any parent directory it should check all its child path
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47651333
score: 0

python-3.6
tags question: http://stackoverflow.com/q/47620891
tags question: http://stackoverflow.com/q/47543734
tags question: http://stackoverflow.com/q/47664866
tags question: http://stackoverflow.com/q/47558824
tags question: http://stackoverflow.com/q/47688957
tags question: http://stackoverflow.com/q/47678333
tags question: http://stackoverflow.com/q/47606443
tags question: http://stackoverflow.com/q/47625294
tags question: http://stackoverflow.com/q/47614844
tags question: http://stackoverflow.com/q/47541123
tags question: http://stackoverflow.com/q/47655454
tags question: http://stackoverflow.com/q/47665838
tags question: http://stackoverflow.com/q/47634530
tags question: http://stackoverflow.com/q/47560880
tags question: http://stackoverflow.com/q/47660227
tags question: http://stackoverflow.com/q/47572514
tags question: http://stackoverflow.com/q/47566351
type: Tag
tag name: python-3.6
tags question: http://stackoverflow.com/q/47627900
tags question: http://stackoverflow.com/q/47559489
tags question: http://stackoverflow.com/q/47613823
tags question: http://stackoverflow.com/q/47686795
tags question: http://stackoverflow.com/q/47560798
tags question: http://stackoverflow.com/q/47579904
tags question: http://stackoverflow.com/q/47554439
tags question: http://stackoverflow.com/q/47669681
tags question: http://stackoverflow.com/q/47608865
tags question: http://stackoverflow.com/q/47597405
tags question: http://stackoverflow.com/q/47543600
tags question: http://stackoverflow.com/q/47601738
tags question: http://stackoverflow.com/q/47635770
tags question: http://stackoverflow.com/q/47658626
tags question: http://stackoverflow.com/q/47626733

http://stackoverflow.com/a/47667824
type: Answer
has body: Use shlex.quote: import sys from shlex import quote print(' '.join(quote(s) for s in sys.argv)) in shell: python space_in_argv.py "aa bb" ' " breaking " ' yields: space_in_argv.py 'aa bb' ' " breaking " ' you may also want to include sys.executable, see more detail in the doc.
upvote count: 6
has comment: http://stackoverflow.com/comment/82298879
has comment: http://stackoverflow.com/comment/82294475
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/82329540
accepted answer of: http://stackoverflow.com/q/47667674
answers question: http://stackoverflow.com/q/47667674

http://stackoverflow.com/comment/86687498
type: QuestionComment
comment on: http://stackoverflow.com/q/47581662
has text: have a look at [this](https://github.com/ziplokk1/incapsula-cracker-py3.git), I didn't try it though
score: 0
type: Comment

http://stackoverflow.com/a/47541960
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47541414
has body: You're gonna need to brute-force it, since your data isn't sorted. But you can do it a little more nicely: diffs = [ (k, v[0][1] - v[0][0], v[0][3] - v[0][2], v[0][5] - v[0][4]) for k, v in d.items() ] max(diffs, key=lambda t: t[1])[0] # b - a
type: Answer
accepted answer of: http://stackoverflow.com/q/47541414

selenium
tags question: http://stackoverflow.com/q/47558723
tags question: http://stackoverflow.com/q/47579314
tags question: http://stackoverflow.com/q/47635766
tags question: http://stackoverflow.com/q/47542493
tags question: http://stackoverflow.com/q/47684356
tags question: http://stackoverflow.com/q/47655898
tags question: http://stackoverflow.com/q/47559666
tags question: http://stackoverflow.com/q/47653309
tags question: http://stackoverflow.com/q/47694922
tags question: http://stackoverflow.com/q/47650410
tags question: http://stackoverflow.com/q/47543111
tags question: http://stackoverflow.com/q/47697697
tags question: http://stackoverflow.com/q/47666382
tags question: http://stackoverflow.com/q/47653904
tags question: http://stackoverflow.com/q/47573159
tags question: http://stackoverflow.com/q/47581975
tags question: http://stackoverflow.com/q/47579558
tags question: http://stackoverflow.com/q/47651243
tags question: http://stackoverflow.com/q/47675184
tags question: http://stackoverflow.com/q/47657018
tags question: http://stackoverflow.com/q/47662604
tags question: http://stackoverflow.com/q/47694455
tags question: http://stackoverflow.com/q/47573155
tags question: http://stackoverflow.com/q/47610050
tags question: http://stackoverflow.com/q/47634093
tags question: http://stackoverflow.com/q/47546432
tags question: http://stackoverflow.com/q/47692213
tags question: http://stackoverflow.com/q/47551317
tags question: http://stackoverflow.com/q/47690548
tags question: http://stackoverflow.com/q/47612707
tags question: http://stackoverflow.com/q/47557040
tags question: http://stackoverflow.com/q/47679086
tags question: http://stackoverflow.com/q/47660523
tags question: http://stackoverflow.com/q/47649125
tags question: http://stackoverflow.com/q/47543795
tags question: http://stackoverflow.com/q/47609440
tags question: http://stackoverflow.com/q/47639173
tags question: http://stackoverflow.com/q/47647252
tags question: http://stackoverflow.com/q/47575669
tags question: http://stackoverflow.com/q/47597722
tags question: http://stackoverflow.com/q/47578305
tags question: http://stackoverflow.com/q/47564476
tags question: http://stackoverflow.com/q/47697567
tags question: http://stackoverflow.com/q/47608215
tags question: http://stackoverflow.com/q/47695455
tags question: http://stackoverflow.com/q/47688389
tags question: http://stackoverflow.com/q/47589327
tags question: http://stackoverflow.com/q/47672155
tags question: http://stackoverflow.com/q/47553120
tags question: http://stackoverflow.com/q/47674081
type: Tag
tags question: http://stackoverflow.com/q/47656893
tags question: http://stackoverflow.com/q/47666070
tags question: http://stackoverflow.com/q/47575226
tags question: http://stackoverflow.com/q/47586930
tags question: http://stackoverflow.com/q/47681842
tag name: selenium
tags question: http://stackoverflow.com/q/47607377
tags question: http://stackoverflow.com/q/47658860
tags question: http://stackoverflow.com/q/47563849
tags question: http://stackoverflow.com/q/47695744
tags question: http://stackoverflow.com/q/47680000
tags question: http://stackoverflow.com/q/47647542
tags question: http://stackoverflow.com/q/47574413
tags question: http://stackoverflow.com/q/47665029
tags question: http://stackoverflow.com/q/47679173
tags question: http://stackoverflow.com/q/47636897
tags question: http://stackoverflow.com/q/47647833
tags question: http://stackoverflow.com/q/47641974
tags question: http://stackoverflow.com/q/47556787
tags question: http://stackoverflow.com/q/47616764
tags question: http://stackoverflow.com/q/47563515
tags question: http://stackoverflow.com/q/47615963
tags question: http://stackoverflow.com/q/47692547
tags question: http://stackoverflow.com/q/47631534
tags question: http://stackoverflow.com/q/47586162
tags question: http://stackoverflow.com/q/47640949

http://stackoverflow.com/q/47666978
tagged with: python-docx
type: AnsweredQuestion
has title: Accepting all changes in a MS Word document by using Python
downvote count: 0
has answer: http://stackoverflow.com/a/47747750
answer count: 1
linked to: http://stackoverflow.com/q/38247251
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82442414
has body: I want to be able to accept all changes from a MS Word (.docx) document from Python, preferably using python-docx module. I know how to do in Perl (see below for reference) but would like to have native code in my Python program to do the same. Ide Any idea? use strict; use Win32::OLE qw(in with valof OVERLOAD); use Win32::OLE::Const 'Microsoft.Word'; # wd constants use Win32::OLE::Variant; $Win32::OLE::Warn = 3; my $true = Variant(VT_BOOL, 1); my $false = Variant(VT_BOOL, 0); use File::Spec; use File::Basename; ## Original &amp; New File my $DocFile = &amp;transform_path($ARGV[0]); my $NewFile = ($ARGV[1] ? &amp;transform_path($ARGV[1]) : $DocFile); [ -e $DocFile ] || die "*** Cannot open '$DocFile'\n"; ### Transform path sub transform_path { my $path = shift; if ( ! File::Spec-&gt;file_name_is_absolute($path) ) { my $abs = File::Spec-&gt;rel2abs($path); $path = $abs; } else { $path=~s%/+%\\%g; } return $path; } ## Autoflush $| = 1; ### opening file: try with "new" function, otherwise use "GetActiveObject" my $Word; eval { $Word = Win32::OLE-&gt;GetActiveObject('Word.Application') || Win32::OLE-&gt;new('Word.Application', 'Quit'); }; if ($@) { print "Please open MS Word manually before continuing\n"; print "...Press ENTER to continue...\n"; &lt;STDIN&gt;; $Word = Win32::OLE-&gt;GetActiveObject('Word.Application','Quit'); } print "Opening '$DocFile'\n"; my $document = $Word-&gt;Documents-&gt;Open({FileName =&gt;$DocFile, ConfirmConversions =&gt; 0}); die "Cannot open '$DocFile'\n" unless defined $document; $document-&gt;Activate(); $Word-&gt;ActiveWindow-&gt;ActivePane-&gt;View-&gt;{Type} = wdPrintView; ### Accept all changes print("Accepting all changes\n"); $Word-&gt;ActiveDocument-&gt;{TrackRevisions} = $false; $Word-&gt;WordBasic-&gt;AcceptAllChangesInDoc(); ### Save and Close if ($NewFile eq $DocFile) { $document-&gt;Save(); $document-&gt;Close(); } else { $document-&gt;SaveAs($NewFile); $document-&gt;Close(wdDoNotSaveChanges); } print "Saving in '$NewFile'\n" …
tagged with: http://stackoverflow.com/tag/docx
accepted answer: http://stackoverflow.com/a/47747750
upvote count: 6
score: 6
tagged with: python

http://stackoverflow.com/a/47634162
answers question: http://stackoverflow.com/q/47619691
score: 0
has body: from random import randint numTosses = 100 fileOut = open("data.dat",'w') for index in range(numTosses): fileOut.write(str(index) + "," \ + str(randint(0,1)) \ + '\n' ) fileOut.close() fileIn = open("data.dat",'r') heads = list() tails = list() for line in fileIn.readlines(): fields = line.split(',') if fields[1].strip() == '1': heads.append(1) else: tails.append(1) print("Number of heads is: " + str(len(heads))) print("Number of tails is: " + str(len(tails))) fileIn.close()
type: Answer

http://stackoverflow.com/comment/82124376
has text: Interesting. Is that all the code you have for the testing? I would assume you overwrote `zip` somewhere in your file globally
comment on: http://stackoverflow.com/q/47583259
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47573523
linked to: http://stackoverflow.com/q/47587961
tagged with: python
has body: As I'm new to python. I need to know simple database connectivity with Apache HTTP Server. Just I need to run the below code in Apache HTTP Server. import pyodbc cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};" "Server=DESKTOP-C6;" "Database=demo2017;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute('SELECT * FROM person') for row in cursor: print('row = %r' % (row,)) cursor.close(); cnxn.close(); I have tried to run in python shell. It executed successfully. But with Apache HTTP Server results in 500 Internal Server Error. Also in httpd.conf file: LoadModule pyodbc_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd" Results httpd: Syntax error on line 571 of C:/Apache24/conf/httpd.conf: Can't locate API module structure `pyodbc_module' in file C:/Users/Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd: No error So are there any modules or code that should be imported/modified to run with Apache?
tagged with: pyodbc
tagged with: sql-server
has title: What should be my configuration to load pyodbc module on Apache Server to run simple queries mssql server database
score: 0
has answer: http://stackoverflow.com/a/47584735
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: apache

http://stackoverflow.com/q/47660227
answer count: 2
has answer: http://stackoverflow.com/a/47660386
has comment: http://stackoverflow.com/comment/82279321
tagged with: python
tagged with: python-3.6
has body: Wondering if there is a way to get python to accept "save" or "s" in a input statement to do something every time you enter that into any if/elif/else in the .py file, so i don't have to repeat if/elif/else several times. I want some thing like this a=input("some other question that i want to accept s/save: ") b=input("Again but i dont want 2 if statments: ") rather than. a=input("question: ") if a == "y": print("something") elif a == "y": print("Something") elif a in ("s", "save") print("save") else: print("not option") print("A bunch of other code for 100 lines") a=input("question: ") if a == "y": print("something") elif a == "y": print("Something") elif a in ("s", "save") print("save") else: print("not option") and so on through the code
has comment: http://stackoverflow.com/comment/82279456
type: AnsweredQuestion
score: 0
has title: Getting a input option to happen in all input statements without repeating if/elif/else statments
possible better answer: http://stackoverflow.com/a/47660350
has comment: http://stackoverflow.com/comment/82279477
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47660350
type: Question
accepted answer: http://stackoverflow.com/a/47660386
tagged with: if-statement

http://stackoverflow.com/a/47651936
has comment: http://stackoverflow.com/comment/82295004
answers question: http://stackoverflow.com/q/47651841
type: Answer
has body: You could use float: spam = float(input('choose any number: ')) print('Your number doubled is: ' + str(spam*2))
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47651841

http://stackoverflow.com/q/47573907
tagged with: if-statement
has comment: http://stackoverflow.com/comment/82104657
has body: simplified example: a = False b = True if a and b: #do stuff Does python skip checking for b if a is already recognized as false because only one condition needs to be False for the whole statement to be False? In my case i want to check an array for 3 conditions but want to stop if at least one of them is false (for a better runtime). Can i do if a and b and c: #do stuff or do i have to go the long way with if a: if b: if c: return True else: return False else: return False else: return False or is there another way to check stuff like this?
tagged with: runtime
linked to: http://stackoverflow.com/q/36117583
tagged with: python
has comment: http://stackoverflow.com/comment/82104759
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47573980
has title: Does a two parted condition with "and"/ && stop when one part is already false?
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82104780
linked to: http://stackoverflow.com/q/36550588
has answer: http://stackoverflow.com/a/47573978
has answer: http://stackoverflow.com/a/47573980
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82104473
type: Question
accepted answer: http://stackoverflow.com/a/47573978
tagged with: conditional-statements

http://stackoverflow.com/comment/82242572
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47623439
has text: You should create a clock instance before the main while loop: `clock = pygame.time.Clock()`. Then call `clock.tick(maximum_fps)` in your while loop to limit the game to the `maximum_fps` rate. That means your game won't run faster than for example 60 fps and won't take up more CPU power than needed.
type: Comment

http://stackoverflow.com/comment/82212558
type: AnswerComment
has text: Thank you for your promptly reply. I also tried the code by using `if i == rev`, but the output didn't change(x was printed all over the file). Please allow me to ask one more question, I think the key to my problem is in this sentence **if a name is in neither file, then the zip and score variable from the previous iteration do not change and are written again...** how should I implement it ? Sorry, It hasn't been long since I started learning python.
score: 0
comment on: http://stackoverflow.com/a/47627105
type: Comment

http://stackoverflow.com/comment/82107644
score: 0
type: Comment
type: QuestionComment
has text: Sorry, there were items that I have not tried yet. I will try it immediately. Thank you.
comment on: http://stackoverflow.com/q/47572872

http://stackoverflow.com/q/47662604
upvote count: 7
accepted answer: http://stackoverflow.com/a/47736483
has body: I am steering web whatsapp via selenium via Python, i was wondering if it is possible to change the active (top chat. If a message is recieved, the chat won't be set as active, it will always remain in the background. In Javascript, one can see a list of all chat in the consoles via: Store.chat.models The active chat is stored at position zero, however overwriting the position zero with another chat will not make the chat active. I have found out that there is a variable called "x_active" which changes if a chat is clicked on and view to true (and all others have it as false). e.g.: Store.Chat.models[0].__x_active However setting the variable or true or false in the chrome Console tab did not change anything in the UI, so how can I achieve such behaviour?
favorite count: 0
tagged with: whatsapp
type: Question
has answer: http://stackoverflow.com/a/47736483
has answer: http://stackoverflow.com/a/47827441
score: 7
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/82392138
has comment: http://stackoverflow.com/comment/82395134
possible better answer: http://stackoverflow.com/a/47716462
type: AnsweredQuestion
has title: How to change the active chat in web whatsapp via selenium or javascript with Python 3
has comment: http://stackoverflow.com/comment/132603721
has answer: http://stackoverflow.com/a/47716462
answer count: 3
downvote count: 0
tagged with: selenium

http://stackoverflow.com/q/47646917
favorite count: 0
duplicate of: http://stackoverflow.com/q/1718903
score: 0
duplicate of: http://stackoverflow.com/q/10053286
downvote count: 3
has body: What does "[, ]" mean in Python args? They can be seen in input arguments such as: cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) or scikit-learn; (e.g sklearn.linear_model.LinearRegression): fit(X, y[, sample_weight]) Fit linear model. What does y[, sample_weight] actually mean? Does it mean something like the first dimension in the array? y[:,sample_weight] Update: Thanks for the answers, it means optional. But why are they nested though? threshold2[, edges[, apertureSize[, L2gradient]]]
tagged with: python
has comment: http://stackoverflow.com/comment/82252378
has comment: http://stackoverflow.com/comment/82252375
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/1718903
upvote count: 3
type: UnansweredQuestion
has title: What does "[," mean in Python arguments?
has comment: http://stackoverflow.com/comment/82252269
has comment: http://stackoverflow.com/comment/82252332
linked to: http://stackoverflow.com/q/21165751

http://stackoverflow.com/comment/82189328
score: 0
has text: You imported typer right?
comment on: http://stackoverflow.com/q/47615480
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82223238
has text: @jezrael I'm trying to get values beside d where d is present in both dataframes.
comment on: http://stackoverflow.com/q/47632723
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82279402
comment on: http://stackoverflow.com/q/47660226
type: Comment
has text: Why do you use **or** when you say **and**? Try this: `if diff != "1" and diff != "2" and diff != "3":`
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82315306
type: QuestionComment
type: Comment
has text: You have an error in your explanation: Please enter number24 99 could you fix it so we can help you?
score: 0
comment on: http://stackoverflow.com/q/47678112

http://stackoverflow.com/comment/82346881
comment on: http://stackoverflow.com/q/47693761
has text: FWIW, although that codepoint is 'ZERO WIDTH NO-BREAK SPACE' it's commonly used as the [Byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark), but the BOM is normally only used at the start of UTF-encoded Unicode files. Inside a file, it still operates as a no-break zero-width space.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47627187
type: Question
accepted answer: http://stackoverflow.com/a/47628113
has answer: http://stackoverflow.com/a/47628113
has comment: http://stackoverflow.com/comment/82212076
tagged with: python
has body: I want to place a decorator on every function to log everything happening in the function. i have made a wrapper function and decorator to log the function with decorator. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): r = func(*args, **kwargs) logging.getLogger(__name__) logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def list(self, request): queryset = Mytable.objects.all() if request.GET.get('name'): queryset = queryset.filter(name=request.GET.get('name')) serializer = CheckSerializer(queryset, many=True) logging.info("GET request and returned response") return Response(serializer.data) The problem is log file is not created in this code. Also, it got created on a different project but didnot print anything in log file(empty log file). I want to print a message in log file for everything that is happening, but this doesn't seem to work. Plz help.
score: 2
type: AnsweredQuestion
tagged with: wrapper
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82212371
tagged with: django
has title: python/django logging with decorators
tagged with: logging
favorite count: 0

http://stackoverflow.com/q/47564504
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/53744098
linked to: http://stackoverflow.com/q/47568428
favorite count: 0
type: Question
has title: in self._compute_kernel(X) raise ValueError("X.shape[0] should be equal to X.shape[1]")
has answer: http://stackoverflow.com/a/47568373
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26962159
has answer: http://stackoverflow.com/a/47568449
tagged with: python
tagged with: svm
answer count: 4
has answer: http://stackoverflow.com/a/73735490
has body: In my code in which X and y are the training data: from sklearn.svm import SVC clf = SVC(kernel=lambda x,y:gauss_kernel(x, y, 100) ) print(X.shape[0]) print(X.shape[1]) print(X.shape) clf.fit(X, y) I get the following error: 211 2 (211, 2) /Users/mona/anaconda/lib/python3.6/site-packages/sklearn/utils/validation.py:547: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-23-1f163ab380a5&gt; in &lt;module&gt;() 8 print(X.shape) 9 ---&gt; 10 clf.fit(X, y) 11 plot_data() 12 plot_boundary(svm,-.5,.3,-.8,.6) ~/anaconda/lib/python3.6/site-packages/sklearn/svm/base.py in fit(self, X, y, sample_weight) 185 186 seed = rnd.randint(np.iinfo('i').max) --&gt; 187 fit(X, y, sample_weight, solver_type, kernel, random_seed=seed) 188 # see comment on the other call to np.iinfo in this file 189 ~/anaconda/lib/python3.6/site-packages/sklearn/svm/base.py in _dense_fit(self, X, y, sample_weight, solver_type, kernel, random_seed) 226 X = self._compute_kernel(X) 227 --&gt; 228 if X.shape[0] != X.shape[1]: 229 raise ValueError("X.shape[0] should be equal to X.shape[1]") 230 IndexError: tuple index out of range Here's the customized Gaussian Kernel I wrote: import math def gauss_kernel(x1, x2, gamma): sigma = math.sqrt(gamma) return np.exp(-np.sum((x1-x2)**2)/(2*sigma**2)) How should I fix this? When I look at SVM examples in sklearn, they basically do the same thing. I believe I am neglecting something small but can't pin down the problem when matching with sklearn examples.
score: 1
downvote count: 0

http://stackoverflow.com/q/47642500
has body: I was able to run the regex on multiple files, I want to save the output of this like name_of_file_clean.txt. Trying to find the best way. import os, re import glob pattern = re.compile(r'(?&lt;=CN=)(.*?)(?=,)') for file in glob.glob('*.txt'): with open(file) as fp: for result in pattern.findall(fp.read()): print(result)
accepted answer: http://stackoverflow.com/a/47642600
tagged with: python
has answer: http://stackoverflow.com/a/47642600
has title: looping regex in directory and saving output
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/82243624
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82329171
type: AnswerComment
has text: ... or perhaps try passing the whole anonymous code block (without splitting it) to `read_sql`? (Can't try it right now; no pandas on my phone....)
comment on: http://stackoverflow.com/a/47684776
score: 0
type: Comment

webdriver
tags question: http://stackoverflow.com/q/47649125
tags question: http://stackoverflow.com/q/47608215
tags question: http://stackoverflow.com/q/47601634
tags question: http://stackoverflow.com/q/47672155
tags question: http://stackoverflow.com/q/47694922
type: Tag
tag name: webdriver

http://stackoverflow.com/comment/82128690
type: QuestionComment
score: 0
has text: @MichaelButscher .Appending next_line to words worked. Thanks a lot guys for your help. Cheer!
comment on: http://stackoverflow.com/q/47585163
type: Comment

sql
tags question: http://stackoverflow.com/q/47546388
tags question: http://stackoverflow.com/q/47546804
tags question: http://stackoverflow.com/q/47598954
tags question: http://stackoverflow.com/q/47614949
tags question: http://stackoverflow.com/q/47611774
tags question: http://stackoverflow.com/q/47629806
tags question: http://stackoverflow.com/q/47667945
tags question: http://stackoverflow.com/q/47647413
tags question: http://stackoverflow.com/q/47619682
tags question: http://stackoverflow.com/q/47573423
tags question: http://stackoverflow.com/q/47598252
tags question: http://stackoverflow.com/q/47645297
tags question: http://stackoverflow.com/q/47624931
tags question: http://stackoverflow.com/q/47690446
tags question: http://stackoverflow.com/q/47661041
tags question: http://stackoverflow.com/q/47664579
tags question: http://stackoverflow.com/q/47641803
tags question: http://stackoverflow.com/q/47557311
tags question: http://stackoverflow.com/q/47624566
tags question: http://stackoverflow.com/q/47578485
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/47579701
tags question: http://stackoverflow.com/q/47657951
tags question: http://stackoverflow.com/q/47569747
tags question: http://stackoverflow.com/q/47686258
tags question: http://stackoverflow.com/q/47651097

http://stackoverflow.com/comment/82268305
comment on: http://stackoverflow.com/a/47648398
has text: I see. So there is no command to make it the same size to get around it? My full code is here if useful https://pastebin.com/UdtHtbfn
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47610493
favorite count: 0
has body: I'm super new to Python and programming in general. I am following an example off of youtube on how to make a simple calculator but I wanted to add my ideas and functionalities. More or less I want to make it very versatile. This is the part that is not working out for me. I don't know how to make it work using the two methods I created def main(): while True: Num1() num1 = int.num1() Num2() num2 = int.num2() # Executing the specified calculations with the 'Operation' function (row 13) Operation(num1, num2) # --&gt; followed by another nested while asking if the user wants to make another calculation I want the app to read everywhere that if the user types "exit" it will exit, even if it's asking for a number so I created 2 methods to do so because it wasn't working dealing with the loops and user input directly from main() def Num1(): while True: num1 = input("What is the first number? ") if num1.isdigit(): break elif num1 == 'exit': print("Thank you using the SimpleCalculator. Bye!") time.sleep(3) exit() else: print("I don't understand. Please input a valid number") continue def Num2(): while True: num2 = input("What is the second number? ") if num2.isdigit(): break elif num2 == "exit": print("Thank you using the SimpleCalculator. Bye!") time.sleep(3) exit() else: print("I don't understand. Please input a valid number") continue The problem is that I get this error and I get it but I just don't know how to go about it. Traceback (most recent call last): File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py' Apps/SimpleCalculator.py", line 131, in &lt;module&gt; main() File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py' Apps/SimpleCalculator.py", line 109, in main Operation(num1, num2) NameError: name 'num1' is not defined
has answer: http://stackoverflow.com/a/47610834
has answer: http://stackoverflow.com/a/47610752
has answer: http://stackoverflow.com/a/47610783
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47610767
has title: Don't know how to use methods created
type: Question
has answer: http://stackoverflow.com/a/47610916
score: 0
has answer: http://stackoverflow.com/a/47610668
upvote count: 1
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/comment/82209144
comment on: http://stackoverflow.com/q/47625499
score: 0
has text: Hi! Welcome to Stackoverflow. It would be better if you checkout [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) of your code for future endeavor at Stack overflow. -Thank you
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82093835
score: 0
has text: OK, I will do it, at this point I do not see the "mark a an answer" button , may be it will show up later. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/47567938
type: AnswerComment

http://stackoverflow.com/comment/82199587
score: 0
has text: Please post your answer as an actual answer, not as an edit in the question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47612274

http://stackoverflow.com/a/47656537
has comment: http://stackoverflow.com/comment/82271560
answers question: http://stackoverflow.com/q/47656346
has body: All items in Python are references so if you change one reference other will change too l = [] global l_global l_global = l for i in range(1, 10): l.append(i) print(l) print(l_global) Does it make sense now for your case?
type: Answer
score: 0

http://stackoverflow.com/comment/82339561
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47690250
type: Comment
has text: Please paste your source code as text, not images.

http://stackoverflow.com/comment/82281707
has text: You *should* be using `escapeshellarg` like you did before. The second call to `escapeshellcmd` was the one that was erroneous. I'd test this with filenames like `Program Files/(Untitled 2).txt` and `; touch ~/hacked.txt`
comment on: http://stackoverflow.com/q/47639583
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/138539601
type: AnswerComment
comment on: http://stackoverflow.com/a/77636640
type: Comment
has text: django-cms 4.1 comes with its own `djangocms` command with uses Django's `start-project` management command (and differs from the somewhat outdated djangocms-installer command).
score: 0

http://stackoverflow.com/comment/82042034
comment on: http://stackoverflow.com/q/47542374
type: Comment
type: QuestionComment
has text: hi I clarified my question... first it is a limit on the number of bytes, not characters, sorry for the confusion... second the point why I need this is because of API max request limits.
score: 0

http://stackoverflow.com/q/47585007
answer count: 1
has answer: http://stackoverflow.com/a/47585061
upvote count: 1
favorite count: 0
has body: I am using python 3.xxx I have saved a whole list of strings in my dictionary.. dict = { 'somekey' = '['one','two','three'...]......... *to n*} now if I know the key = 'somekey', how can I retrieve the value, the whole list. I have tried dict.get(key,0) But it is not working.
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82127695
has comment: http://stackoverflow.com/comment/82127714
type: Question
tagged with: python-3.x
has title: Retrieve list if list is a value to a key pair for python dictionary
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/47696189
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: I'm new to Python and am confused as to why the script I've written below isn't working right, I'm at the stage now where I can't see the wood for the trees. I've tried to create the port scanner from the 'Violent Python' book. I believe the book uses Python 2.6 but I'm creating it using Python 3.7. Using hints and tips in other posts on this website I've got the port scanner to do scans of some of the computers on my lab setup, however, the scans always show ports to be 'closed'. I used nmap to scan the computers to make sure I had some open ports to use in my port scanner script. My script is below. import optparse from socket import * from threading import * screenLock = Semaphore(value=1) def connScan(tgtHost, tgtPort): try: connSkt = socket(AF_INET, SOCK_STREAM) connSkt.connect((tgtHost, tgtPort)) connSkt.send('ViolentPython\r\n') results = connSkt.recv(100) screenLock.acquire() print('[+]%d/tcp open'% tgtPort) print('[+]' + str(results)) except: screenLock.acquire() print('[-]%d/tcp closed'% tgtPort) finally: screenLock.release() connSkt.close() def portScan(tgtHost, tgtPorts): try: tgtIP = gethostbyname(tgtHost) except: print("[-] Cannot resolve '%s': Unknown host"%tgtHost) return try: tgtName = gethostbyaddr(tgtIP) print('\n[+] scan results for: ' + tgtName[0]) except: print('\n[+] Scan results for: ' + tgtIP) setdefaulttimeout(1) for tgtPort in tgtPorts: t = Thread(target=connScan, args=(tgtHost, int(tgtPort))) t.start() def main(): parser = optparse.OptionParser('usage %prog '+ '-H &lt;target host&gt; -p &lt;target port&gt;') parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by comma') (options, args) = parser.parse_args() tgtHost = options.tgtHost tgtPorts = [p.strip() for p in options.tgtPort.split(',')] if (tgtHost == None) | (tgtPorts[0] is None): print(parser.usage) exit(0) portScan(tgtHost, tgtPorts) if __name__ == '__main__'…
has comment: http://stackoverflow.com/comment/82352176
has answer: http://stackoverflow.com/a/47696541
has title: Port Scanner Shows All Ports Closed
score: 2
has comment: http://stackoverflow.com/comment/82352174
has comment: http://stackoverflow.com/comment/82352074
answer count: 1
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/112466892
type: Comment
type: AnswerComment
has text: You can still read the .pyc file and some import info is seen as well using Linux "cat" command
comment on: http://stackoverflow.com/a/47637737
score: 0

http://stackoverflow.com/q/47565913
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/82089753
type: AnsweredQuestion
upvote count: 0
has title: How to link to other websites in django?
answer count: 2
accepted answer: http://stackoverflow.com/a/47566024
score: -4
has answer: http://stackoverflow.com/a/47566081
has body: I want to link my buttons to different websites in django website. Contact | LinkedIn | Twitter | Google+ The above href only holds for the urls.py or only to the local pages of the project.
has comment: http://stackoverflow.com/comment/82089694
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47566081
has answer: http://stackoverflow.com/a/47566024
tagged with: http://stackoverflow.com/tag/html
tagged with: hyperlink
tagged with: django

http://stackoverflow.com/comment/82525446
type: QuestionComment
comment on: http://stackoverflow.com/q/47612518
type: Comment
score: 0
has text: For me the code works in normal Python.

http://stackoverflow.com/q/47576716
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/82117134
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47577374
tagged with: argparse
has title: python-daemon + argparse?
tagged with: python-daemon
linked to: http://stackoverflow.com/q/38853812
type: Question
upvote count: 2
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47577374
has body: I made a script that takes a few arguments to run. Originally it could be run automatically with the argument 'auto', but I'm trying to daemonize it so it will run the run the script with the specified arguments as a daemon. The problem is that python-daemon and argparse don't seem to get along when it comes to deciding who parses what. parser = argparse.ArgumentParser(usage='pyfilter.py &lt;file&gt; &lt;options&gt; &lt;actions&gt;') parser.add_argument('file', help='blacklist file containing IPs', type=str) subparsers = parser.add_subparsers(help='help', dest='action') parser_update = subparsers.add_parser('update', help='update help') parser_update.add_argument('-c', '--check', help="check IPs for abuse reports", dest="check", type=str, nargs=1) parser_blacklist = subparsers.add_parser('blacklist', help='create iptables rules for malicious IPs specified' 'in the provided file') parser_clear = subparsers.add_parser('clear', help='clear iptables') parser_auto = subparsers.add_parser('auto', help='automatically run update and blacklist on a loop') parser_auto.add_argument('-i', '--interval', help='specify the loop interval', dest='interval', type=int, nargs=1) parser_auto.add_argument('-c', '--check', help="check IPs for abuse reports", dest="check", type=str, nargs=1) parser.add_argument('-p', '--port', help='specify the port to block', type=int) parser.add_argument('-v', '--verbose', help='write output to screen', nargs=1) args = parser.parse_args() . . . class pyfilterDaemon(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/pyfilter.pid' self.pidfile_timeout = 5 def run(self): while True: update() blacklist() time.sleep(interval) . . . def main(): #handle() d = pyfilterDaemon() daemon_runner = runner.DaemonRunner(d) daemon_runner.start() Here's the commands I've tried to make this work: root@tfof:~# ./pyfilter.py start ERROR: File 'start' not found # argparse parsed 'start' ac…
tagged with: python

http://stackoverflow.com/a/47625614
answers question: http://stackoverflow.com/q/47614742
upvote count: 5
type: Answer
has body: unicode is a python 2 method. If you are not sure which version will run this code, you can simply add this at the beginning of your code so it will replace the old unicode with new str: import sys if sys.version_info[0] &gt;= 3: unicode = str
has comment: http://stackoverflow.com/comment/82240040
score: 5
downvote count: 0

http://stackoverflow.com/comment/82217001
type: QuestionComment
has text: Can you please elaborate "I need to make a query with each value"?
comment on: http://stackoverflow.com/q/47629640
type: Comment
score: 4

http://stackoverflow.com/comment/82306413
has text: I'm glad the answer helped.
score: 0
comment on: http://stackoverflow.com/a/47664608
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47553527
downvote count: 0
has comment: http://stackoverflow.com/comment/82065980
favorite count: 0
tagged with: hex
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/82067702
has comment: http://stackoverflow.com/comment/82066985
accepted answer: http://stackoverflow.com/a/47556727
has comment: http://stackoverflow.com/comment/82067885
upvote count: 2
has comment: http://stackoverflow.com/comment/82068157
has answer: http://stackoverflow.com/a/47556727
tagged with: python
tagged with: pyodbc
has body: I have a code that prints the query from db, I have no problems displaying values for Varchar, int and other format, But the value of Byteary is different. The value on the DB is something like 0xA09080BD1160AB16 but the result in print of python is like b'\x03\x80\x03\x8c\x00\x03\x00S^k\xdb' //not actual value Based on what I have read on the net, there is a conn.add_output_converter(pyodbc.SQL_BINARY, hexToString) but its not working, the pyodbc version is at 4.0.18 import pyodbc def hexToString(binaryString): try: hashString = ["{0:0&gt;2}".format(hex(b)[2:],upper()) for b in binaryString] return '0x' + "".join(hashString) except: return binaryString query = """ select * from myDb.TestDb """ conn_str = ( r'Driver={ODBC Driver 13 for SQL Server};' r'Server=yourserver\test;' r'Database=test;' r'Trusted_Connection=yes;' r'CHARSET=UTF8;' ) cnxn = pyodbc.connect(conn_str) cnxn.add_output_converter(pyodbc.SQL_BINARY, hexToString) cursor = cnxn.cursor() try: cursor.execute(query) row = cursor.fetchone() except MySQLdb.error as err: print(err) else: while row is not None: print(row) row = cursor.fetchone()
has title: pyodbc Binary Column is returning odd characters python
score: 2
tagged with: sql-server
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82068586
answer count: 1

http://stackoverflow.com/comment/82059859
has text: I don't think it is possible with floats. But you can try to convert the float-point in fixed-point numbers represented as int and continue as before. You will have a limited range, depending on the required precision.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47551468

http://stackoverflow.com/a/47682435
has comment: http://stackoverflow.com/comment/82327423
has comment: http://stackoverflow.com/comment/82326755
score: 0
has comment: http://stackoverflow.com/comment/82354377
has comment: http://stackoverflow.com/comment/82349884
has comment: http://stackoverflow.com/comment/82324884
has comment: http://stackoverflow.com/comment/82343750
has body: Shortcut is not a folder, it is just a file pointing to some object. So you can't use it as a directory while moving file. If the shortcut refers to the ftp shared directory, you can use its real path. Or, if the shortcut can be modified and you can't rely on the real path, read its target with separate function: import sys import win32com.client def get_target(path): shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(path) return shortcut.Targetpath get_target("c:\\Users\\my_user\\Desktop\\hello_shortcut.lnk") And then use this path as usual to operate with the file.
answers question: http://stackoverflow.com/q/47682176
type: Answer
has comment: http://stackoverflow.com/comment/82354017
has comment: http://stackoverflow.com/comment/82324316

http://stackoverflow.com/comment/82292250
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47666505
type: AnswerComment
has text: If you want to use arbitrary polygons, you have to use masks.

http://stackoverflow.com/a/68988491
type: Answer
has body: this is my solution : df.iloc[:, 1:] = df.iloc[:, 1:] * 0.001 the first column of df will remain untouched, while the rest is multiplied by 0.001
score: 0
answers question: http://stackoverflow.com/q/47561788

http://stackoverflow.com/a/55511243
accepted answer of: http://stackoverflow.com/q/47597914
answers question: http://stackoverflow.com/q/47597914
type: Answer
has body: I found this corner.py package, documentation here, which does what I needed. Simple example: import corner import numpy as np ndim, nsamples = 2, 10000 np.random.seed(42) samples = np.random.randn(ndim * nsamples).reshape([nsamples, ndim]) figure = corner.corner(samples)
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47684009
type: Question
has title: Python compare/replace keys in dic with values of another dic
has comment: http://stackoverflow.com/comment/82328666
accepted answer: http://stackoverflow.com/a/47684141
has comment: http://stackoverflow.com/comment/82328004
has answer: http://stackoverflow.com/a/47684141
score: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82327973
type: AnsweredQuestion
has body: I'm looking for a way to compare/replace a value of a dictionary with a key of another dictionary like so : DicA = {'abc' : 1 , 'def' : 2 , 'ghi' : 3} DicB = {3: 'klm' , 2 : 'nop' ,1 : 'qrs'} Result should be: DicC = {'abc' : 'qrs' , 'def' : 'nop' ,'ghi' : 'klm'} So the Value "1" in DicA got replaced with "qrs" because they key in DicB(1) matched with the Value in DicA(1) so the result is -> abc : qrs. How do I compare the key with the value of another dictionary?(for loops)? How do I replace it afterwards? Is there a way to use the implemented map() function for this? E.g. map(lambda dicA, dicB):
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82350967
has text: The question asks about a .gif image, and with .gif you don't need PIL or Pillow.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47692897
type: Comment

http://stackoverflow.com/a/47601644
type: Answer
score: 0
has body: This is the way to extract the bytes and shift them into an integer and scale as a float: x = b'\xea\xd0\x05\x00\x00\x00\xef' print(x) int_value = 0 # initialise shift register for index in range(1,4): int_value *= 256 # shift up by 8 bits int_value += x[index] # or in the next byte print(int_value) # scale the integer against the max value float_value = 360 * float(int_value) / 0xffffff print(float_value) Output: b'\xea\xd0\x05\x00\x00\x00\xef' 13632768 292.5274832563092
answers question: http://stackoverflow.com/q/47601411

gaussian
tags question: http://stackoverflow.com/q/47623545
tags question: http://stackoverflow.com/q/47597119
type: Tag
tag name: gaussian

http://stackoverflow.com/a/47608416
type: AcceptedAnswer
downvote count: 0
has body: I believe it is simply your logic that fails in the loop, writing out histogram output: for i in range(3): hist, edges = np.histogram(sciFlat[i].flatten(), bins=rng, range=(minpix,maxpix)) skyval = edges[hist == max(hist)] print(skyval) skySub = sciFlat[i] - skyval sciSky.append(skySub) Histogram provides you with edges of the values, what you most likely want is the midpoint of the edges: for i in range(3): hist, edges = np.histogram(sciFlat[i].flatten(), bins=rng, range=(minpix,maxpix)) mids = edges[:-1] + np.diff(edges)/2 skyval = mids[hist.argmax()] print(skyval) skySub = sciFlat[i] - skyval sciSky.append(skySub) by setting mids instead of edges, your histogram has the same dimensions. To illustrate the difference of edges and mids: sciFlat = np.random.uniform(0,15,100) hist, edges = np.histogram(sciFlat, bins=(sciFlat.max()-sciFlat.min()).astype(int), range=(sciFlat.min(), sciFlat.max())) mids = edges[:-1] + np.diff(edges)/2 hist.size Out[33]: 14 edges.size Out[34]: 15 mids.size Out[35]: 14 plt.hist(sciFlat, bins=(sciFlat.max()-sciFlat.min()).astype(int), range=(sciFlat.min(), sciFlat.max())) plt.plot(mids[hist.argmax()], hist.max(), marker='*', ms=20, c='C3', zorder=1) plt.plot(mids, hist, 'o', zorder=2, c='C1') Star denotes the largest midpoint, as you see, it is between the edges:
accepted answer of: http://stackoverflow.com/q/47607931
type: Answer
answers question: http://stackoverflow.com/q/47607931
score: 4
upvote count: 4

http://stackoverflow.com/q/47614169
has comment: http://stackoverflow.com/comment/82186824
has body: I was wondering if there was any way to access a value in a tuple? for example: a = [('ANTA01H3F', 'LEC02', '17-12-07', '14:00')] and i wanted just '17-12-07' and '14:00'. Is there a way i can get these values and attach them to a string. print("The date is" + '17-12-07' + " and time is" + '14:00')
has answer: http://stackoverflow.com/a/47614193
has answer: http://stackoverflow.com/a/47614212
answer count: 3
downvote count: 0
score: 1
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/82186775
has comment: http://stackoverflow.com/comment/82186800
favorite count: 0
tagged with: python-3.x
tagged with: tuples
type: Question
has answer: http://stackoverflow.com/a/47614189
tagged with: python
has comment: http://stackoverflow.com/comment/82186789
type: UnansweredQuestion
has title: Any way to access values in a tuple?

http://stackoverflow.com/comment/82194470
score: 0
comment on: http://stackoverflow.com/a/47573245
type: Comment
has text: First thing to note is that your hidden size has torch.Size([2, 64, 128] dimensions. We need to correctly reshape it to be (64, 256). Can you try h_1_last = h_1_last.transpose(0,1).contiguous().view(batch_size, -1) and then concatenate both hidden vectors?
type: AnswerComment

http://stackoverflow.com/comment/82290807
type: QuestionComment
comment on: http://stackoverflow.com/q/47665777
score: 0
has text: [pygame.math.Vector2](http://pygame.org/docs/ref/math.html#pygame.math.Vector2) has `normalize()`
type: Comment

http://stackoverflow.com/a/47644764
has body: Glad it was helpful. I'll add it as an answer, so you can accept it, if you like. Just as there is list comprehension, there is dictionary comprehension... It's pretty cool stuff! d2 = {k:d[k] for k in d.keys() if &lt;some_elem&gt; in d[k]} would give you a dict with a subset of the original dict that satisfies your requirements. You would have to fill in the &lt;some_elem&gt; in d[k] portion, because I haven't gone through all your code. You said that this is the main Q you have. Hopefully this gives you enough to solve it.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47643983

http://stackoverflow.com/q/47636101
has body: I have a small question. I have noticed that there is a new plugin for the Tensorboard application for directly plot PR-Curves in Tensorboard. Does anyone know if there is already an integration of this new feature into the TF Object Detection API? I already implemented my own PR-Curves that will be shown in the image section of Tensorboard but the native integration seems to be more useful. Thank you for your help.
has title: Tensorflow Object Detection API and Precision Recall curves
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: tensorflow
score: 3
upvote count: 3
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/82280551
type: QuestionComment
comment on: http://stackoverflow.com/q/47660531
has text: By "more complex scenario", do you mean a situation where there are more than two unknown variables in one equation?
score: 0
type: Comment

http://stackoverflow.com/a/47681793
has body: This should fix it from PIL import Image image = Image.open('./Images\ Folder/testimage.png') image.show() Also if you change folder names to do not have special characters it will be easier to use, let's say renaming Images Folder to Images_folder from PIL import Image image = Image.open('./Images_folder/testimage.png') image.show()
answers question: http://stackoverflow.com/q/47681435
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82323756
has comment: http://stackoverflow.com/comment/82323739
accepted answer of: http://stackoverflow.com/q/47681435

http://stackoverflow.com/q/47638843
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47640249
accepted answer: http://stackoverflow.com/a/47640249
upvote count: 3
has body: (myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze djangorestframework==3.7.3 pkg-resources==0.0.0 (myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django Collecting django Using cached Django-2.0.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 "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in &lt;module&gt; version = __import__('django').get_version() File "django/__init__.py", line 1, in &lt;module&gt; from django.utils.version import get_version File "django/utils/version.py", line 61, in &lt;module&gt; @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ------------------------------------ I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this.
downvote count: 0
tagged with: pip
tagged with: django
tagged with: virtualenv
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/47638883
possible better answer: http://stackoverflow.com/a/47638883
has title: PIP cannot install Django inside VIrtualenv
tagged with: python
has answer: http://stackoverflow.com/a/47821696
has answer: http://stackoverflow.com/a/48294542
answer count: 4

http://stackoverflow.com/q/47661954
has body: I am trying to make a program with tkinter that shows different words when a button is pressed. So my question is the following: say there is a button next question and whenever it is pressed the question that is currently on screen changes to the next one( current one is Q1 -- > button is pressed -- > Q2 replaced Q1), and I only want to have one singe button, not different ones for each question. What should I use to accomplish this? I tried using lists but it didn't work out. Thank you guys in advance!
has comment: http://stackoverflow.com/comment/82283132
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: button
accepted answer: http://stackoverflow.com/a/47662400
has title: Python tkinter multiple commands for one button
has answer: http://stackoverflow.com/a/47662400
tagged with: command
type: Question
tagged with: tkinter

http://stackoverflow.com/comment/82306309
score: 0
type: Comment
type: QuestionComment
has text: I did and above link is not the answer or q clue to solve my issue. Thanks
comment on: http://stackoverflow.com/q/47672908

http://stackoverflow.com/a/47622044
type: Answer
answers question: http://stackoverflow.com/q/47621420
score: 0
has body: Read the tutorial section on dicts. (Reading everything before that would be good too.) Then read the first example in the following section, which is similar to your code. (And I would recommend changing your code to follow the example, except use value instead of v. You can use any name you want for the target name, which repeatedly gets bound to objects yielded by the iterable. You used key, with is a standard name for a dict key. I don't think that dict_key is any better. In your code, the name key is bound to a different key, such as id, media, or text, in no particular order, each iteration. The name binding is like doing an assigment statement, key = 'id', or whatever. I hope this helps.

http://stackoverflow.com/comment/82130172
type: Comment
type: QuestionComment
has text: What do you mean by "Bars"?
score: 2
comment on: http://stackoverflow.com/q/47583175

http://stackoverflow.com/q/47670677
score: 2
upvote count: 2
has title: Python Tkinter multiprocessing progress
has body: For my work, I frequently have to collect reasonably large datasets from a MySQL database, e.g. several parameters for several locations, and store that data in a CSV file per location. For this, I've written a small GUI. Since, the data has to be stored per location, I thought I'd take advantages of my 8-thread CPU and use the multiprocessing package to query the database per location. This works just fine, but I also want to keep track of how far the data retrieval and file writing is. The trick with using multiprocessing together with Tkinter was to put the function that is called in the multiprocessing outside of the GUI class, but how do I get information from that function back into the class? My code so far: from multiprocessing import Process from tkinter import * import os import pandas import pymysql class App: def __init__(self, master): self.master = master self.stations = None self.variables = None self.startdtg = None self.enddtg = None self.outputlocation = "C:/Users/test" self.processes = [] Label(master, text="Locations:").grid(row=0, column=0, sticky=W, columnspan=3) self.locationEntry = Entry(master) self.locationEntry.grid(row=0, column=1, sticky=EW, columnspan=3) Label(master, text="Enter variables:").grid(row=1, column=0, sticky=W) self.varEntry = Entry(master) self.varEntry.grid(row=1, column=1, sticky=EW, columnspan=3) Label(master, text="Start DTG:").grid(row=2, column=0, sticky=W) self.startEntry = Entry(master) self.startEntry.grid(row=2, column=1, sticky=EW) Label(master, text="End DTG:").grid(row=2, column=2, sticky=W) self.endEntry = Entry(master) self.endEntry.grid(row=2, column=3, sticky=EW) Label(master, text="Output location:").grid(row=3, column=0, sticky=W) self.outputEntry = Entry(master) self.outputEntry.grid(row=3, column=1, columnspan=2, sticky=EW) self.startButton = Button(master, text="Start", command=self.get_data) self.startButton.grid(row=5, column=1, sticky=EW) def get_data(self): self.update_variables() self.collect_dat…
downvote count: 0
has comment: http://stackoverflow.com/comment/82303987
tagged with: python
has comment: http://stackoverflow.com/comment/82304508
answer count: 1
has comment: http://stackoverflow.com/comment/82304877
has comment: http://stackoverflow.com/comment/82305065
has comment: http://stackoverflow.com/comment/82301486
type: Question
accepted answer: http://stackoverflow.com/a/47675155
linked to: http://stackoverflow.com/q/7310511
linked to: http://stackoverflow.com/q/42772952
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47675155
linked to: http://stackoverflow.com/q/3044580
has comment: http://stackoverflow.com/comment/82305386
has comment: http://stackoverflow.com/comment/82304247
favorite count: 0
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/82302625
tagged with: tkinter

http://stackoverflow.com/a/47622180
has comment: http://stackoverflow.com/comment/106027244
accepted answer of: http://stackoverflow.com/q/47622102
has comment: http://stackoverflow.com/comment/106031231
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47622102
has body: Can I use the Node.js packages along with Django? No. Django is a Python framework and thus runs in a Python interpreter. That interpreter cannot run node.js modules because those are Javascript and rely on the node.js Javascript engine. If you want to compare things: node.js &lt;==&gt; python (runtime language engines with built-in libraries) express &lt;==&gt; django (frameworks that run in a given runtime) This is kind of confusing because Node.js is a server-side javascript platform Node.js is a Javascript programming environment. It can be used to write servers, but it can also be used as a general purpose scripting environment to do anything you may want to do on your computer, such as implement various build tools. webPack is one such build tool that is written in Javascript to be run in node.js. Its function happens to be packaging client-side Javascript files, but it could be any type of tool. There are many tools written in node.js, particularly tools that are often used by node.js developers (since they already have that environment installed). If you really needed to combine functionality from both node.js and django, then you would have to create two separate programs 1) a python program using django and 2) a node.js program using whatever Javascript libraries you want and then you could communicate between the two programs using whatever IPC mechanism you choose (TCP, stdio, files, etc...).
upvote count: 10
downvote count: 1
score: 9
type: Answer

http://stackoverflow.com/a/47598549
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47598343
has comment: http://stackoverflow.com/comment/82156279
downvote count: 0
has body: If you're fine with converting the empty strings to NaN first you could try using Series.fillna by doing something like this: import numpy as np df = df.replace('', np.nan) df.A = df.A.fillna(df.B) df.C = df.C.fillna(df.D) which gives: df A B C D key 0 A0 NaN C1 NaN K0 1 B1 B1 C2 NaN K1 2 A2 NaN D3 D3 K2 3 B3 B3 D4 D4 K3 Which will fill the missing values in column A with those in column B then set the resulting series to column A in df. We can extend this idea for the case of multiple columns by using a loop: l_cols = df.columns[0::2] # Left columns in the pairs r_cols = df.columns[1::2] # Right columns in the pairs # Go through each pair for l, r in zip(l_cols, r_cols): df[l] = df[r].fillna(df[r]) The columns used for merging can be excluded from the output using: df = df.drop(r_cols, axis=1)
has comment: http://stackoverflow.com/comment/82156300
type: Answer
has comment: http://stackoverflow.com/comment/82156875

http://stackoverflow.com/a/47613677
has comment: http://stackoverflow.com/comment/82185836
has comment: http://stackoverflow.com/comment/82186210
answers question: http://stackoverflow.com/q/47612009
has comment: http://stackoverflow.com/comment/82186595
score: 0
has body: You guessed it right. It is reading line by line till it finds the line which matches the username. readlines reads line by line. Instead use searchfile Try this: #Login Function def login(): passwordAttemptLoop = 0 print("You have chosen to login!\n") while passwordAttemptLoop == 0: usernameAttempt = input("Please print your username below\n") passwordAttempt = input("Please print your password below\n") searchfile = open("usrnmPswd.txt", "r") for line in searchfile: if usernameAttempt in line: loginDetails = line.split() if usernameAttempt == loginDetails[0] and passwordAttempt == loginDetails[1]: passwordAttemptLoop = passwordAttemptLoop + 1 startQuiz() searchfile.close() else: print("Your username and/ or password is incorrect! Please try again!") #MAIN/START MENU Function searchfile reads the file and looks for the line containing the 'username' passed by the user and returns it. You can then do operations on that line. You should keep a number of maximum attempts allowed, with a message to contact the administrator or similar appropriate message in case maximum allowed attempts is crossed. Otherwise the person trying to login will be stuck at this step forever, if he/she has actually forgotten the password
type: Answer

http://stackoverflow.com/comment/82068355
comment on: http://stackoverflow.com/a/47552220
has text: this worked a bit but keeps timing out, what can i do to avoid that
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47575662
has title: How do i get my game to resize with the window
has comment: http://stackoverflow.com/comment/82108941
has answer: http://stackoverflow.com/a/47576055
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: resize
has body: Im wokring on my own version of Pacman and am currently trying to get the window to resize. i read an answer here :https://reformatcode.com/code/python/pygame-how-do-i-resize-a-surface-and-keep-all-objects-within-proportionate-to-the-new-window-size. but it didnt help me in my case. at the i have 2 screen, screen and fake screen. if i set everything to blit on fake screen they appear but dont update themselces (pacman wont move). if i set them to screen they appear and update but dont resize. any help or suggestions would be greatly appreciated. btw its still a work on progress import pygame from Variables import pelletspawns #imports pellet spwans list from different script from pygame.locals import * #Initialisation pygame.init() pygame.display.set_caption("Pacman") myfont = pygame.font.SysFont("monospace", 15) screen = pygame.display.set_mode((448, 576)) #Creates screen object fake_screen = screen.copy() pic = pygame.surface.Surface((50,50)) pic.fill((255,100,100)) clock = pygame.time.Clock() #Creates clock object Fin = False #Declaring Variables FPS = 60 MoveLeft = pygame.K_LEFT MoveRight = pygame.K_RIGHT MoveUp = pygame.K_UP MoveDown = pygame.K_DOWN #Load images PACMAN_MAP = pygame.image.load("images/pacman_map.png").convert_alpha() PACMANSPRITE = pygame.image.load("images/pacman.png").convert_alpha() #pacmans class class SpriteClass(pygame.sprite.Sprite): def __init__(self, image, x, y): self.image = image self.y=y self.x=x self.rect = self.image.get_rect() self.rect.left = self.x self.rect.top = self.y self.rect.width=16 self.rect.height=16 #draws Pacman def draw(self, surface): # blit yourself at your current position surface.blit(self.image, (self.x, self.y)) # move pacman def movement(self): pressed= pygame.key.get_pressed() if pressed[MoveUp]: self.y -= 2 print('key pressed') if pressed[MoveDown]: self.y += 2 print('key pressed') if pressed[MoveLeft]: self.x -= 2 print('key pressed') if pressed[MoveRight]: self.x += 2 print('key pressed') self.rect.left =…
tagged with: window-resize
has comment: http://stackoverflow.com/comment/82108979
score: 0
tagged with: pacman
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/82192389
score: 0
type: AnswerComment
type: Comment
has text: Thanks for trying! Your concepts are too advanced for me though :(
comment on: http://stackoverflow.com/a/47616941

http://stackoverflow.com/q/47609325
has body: I have a pandas dataframe with a table I have parsed from a URL: dfs = pd.read_html('https://pythonprogramming.net/parsememcparseface/', header = 0) for df in dfs: print(df) I have isolated a particular column called Internet Points: df1 = df['Internet Points'] I'd like to filter search this column for Internet Points &gt; 1000. I've tried: if df1 &gt; 10000: print(df1) However, I get an error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
has comment: http://stackoverflow.com/comment/82176994
has answer: http://stackoverflow.com/a/47609430
downvote count: 1
score: -1
linked to: http://stackoverflow.com/q/36921951
favorite count: 0
has comment: http://stackoverflow.com/comment/82177220
upvote count: 0
linked to: http://stackoverflow.com/q/38886080
has comment: http://stackoverflow.com/comment/82177302
tagged with: python
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: pandas
has title: Filtering for criteria in Pandas Dataframe Python

http://stackoverflow.com/comment/82110641
type: QuestionComment
has text: Yes, since `getVowel` is supposed to be doing the work of finding the number of vowels.
score: 0
comment on: http://stackoverflow.com/q/47576803
type: Comment

http://stackoverflow.com/comment/82192705
has text: if the sampling rate is 3 and the sampling time is 4 i want: [10,14,18,22,27,31,35,39,100,104,108,112] @B.M.
comment on: http://stackoverflow.com/q/47617045
score: 0
type: Comment
type: QuestionComment

feature-selection
tags question: http://stackoverflow.com/q/47674670
tags question: http://stackoverflow.com/q/47574478
tag name: feature-selection
type: Tag

http://stackoverflow.com/comment/82327357
comment on: http://stackoverflow.com/q/47665490
has text: NEVER change question - now our answers doesn't fit to your problem. If you have new problem then create new question with button `Add Question`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82178847
comment on: http://stackoverflow.com/q/47581326
has text: @lad2025 hey thanks for taking the time to make a demo using SQL. I wasn't particularly looking for a demo but if it was, I wanted it in python (like what I said above and which the answer has already been given). However, thanks for doing it in SQL. Always nice to see how it could also be implemented using a server language
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47638090
tagged with: templates
has answer: http://stackoverflow.com/a/47638164
type: AnsweredQuestion
has title: if statement in Django template issue
score: 0
possible better answer: http://stackoverflow.com/a/47638178
answer count: 2
tagged with: django
has body: I am trying to compare value inside template of django. if statement is not working here is my code Model class: class Run(models.Model): run_id = models.AutoField(primary_key=True) run_name = models.CharField(unique=True, max_length=30) pms_id = models.ForeignKey('ProcessManagementSystem', db_column = 'pms_id') def __unicode__(self): return self.run_name class ProcessManagementSystem(models.Model): pms_id = models.AutoField(primary_key=True) pms_name = models.CharField(unique=True, max_length=30) def __unicode__(self): return self.pms_name My template {% for run in all_runs %} {{run.pms_id}} {% if run.pms_id == "PMSName1" %} {{run.pms_id}} {% endif %} {% endfor %} the interesting thing is when I am printing {{run.pms_id}} , it is not showing the ID, It is showing pms_name (maybe because of return self.pms_name) So during compare, I am trying to compare with name i.e. "PMSName1" instead of id But still no luck. Any suggestion how to compare? Thanks
type: Question
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/47638164
tagged with: python
has answer: http://stackoverflow.com/a/47638178

http://stackoverflow.com/q/47559993
tagged with: python
has body: I've asked this question in the past here: "Replacing part of string keeps adding extra backslash" but the issue is still proving troublesome to resolve. ISSUE: Using re.sub() I am unable to insert an odd amount of backslashes into part of my string. Assuming I have the following string: sample_string = 'foo_${bar}_${wasd}_asdf$' I want my output string to be the following: new_string = 'foo_\\\\\${bar}_\\\\\${wasd}_asdf$' Here is just a small sample of everything that I have tried: new_string = re.sub(r'\$\{bar\}_\$\{wasd\}', "\\\\\\\\\\${bar}_\\\\\\\\\\${wasd}", sample_string) #new_string ends up being: 'foo_\\\\\\${bar}_\\\\\\${wasd}_asdf$' new_string = re.sub(r'[$][{]', "\\\\\\\\\\${", sample_string) #new_string ends up being: 'foo_\\\\\\${bar}_\\\\\\${wasd}_asdf$' new_string = re.sub(r'[$][{]', r"\\\\\${", sample_string) #new_string ends up being: 'foo_\\\\\\${bar}_\\\\\\${wasd}_asdf$' As you can see, I've treated the replacement string as both a regular string where backslash is used as an escape character, and as a raw string where the backslash is not treated as an escape. Strangely, both methods of approach insert 6 backslashes into new_string rather than 5. Also, here are some outputs below of when I tried to insert a different number of backslashes into sample_string: #Insert 3 backslashes - works as NOT expected new_string = re.sub(r'[$][{]', r"\\\${", sample_string) #new_string ends up being: 'foo_\\\\${bar}_\\\\${wasd}_asdf$' #Insert 4 backslashes - works AS expected new_string = re.sub(r'[$][{]', r"\\\\${", sample_string) #new_string ends up being: 'foo_\\\\${bar}_\\\\${wasd}_asdf$' #Insert 5 backslashes - works as NOT expected new_string = re.sub(r'[$][{]', r"\\\\${", sample_string) #new_string ends up being: 'foo_\\\\\\${bar}_\\\\\\${wasd}_asdf$' #Insert 6 backslashes - works AS expected new_string = re.sub(r'[$][{]', r"\\\\\\${", sample_string) #new_string ends up being: 'foo_\\\\\\${bar}_\\\\\\${wasd}_asdf$' If I could get some help as to why I ca…
tagged with: regex
has title: Issue with Regex substitution to have odd amount of backslashes in final string
has comment: http://stackoverflow.com/comment/82082168
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47560218
has answer: http://stackoverflow.com/a/47560218
tagged with: string
has comment: http://stackoverflow.com/comment/82077884
favorite count: 0
type: Question
upvote count: 2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82078597

http://stackoverflow.com/comment/82236852
type: Comment
type: QuestionComment
score: 0
has text: Understood. I missed that thread that writes to the dictionary.
comment on: http://stackoverflow.com/q/47639137

http://stackoverflow.com/q/47652885
type: AnsweredQuestion
score: 0
has title: How to get a number of same character and their position in a string in Python?
answer count: 3
tagged with: string
has comment: http://stackoverflow.com/comment/82263966
has comment: http://stackoverflow.com/comment/82264887
has comment: http://stackoverflow.com/comment/82264416
type: Question
has answer: http://stackoverflow.com/a/47652943
tagged with: extract
possible better answer: http://stackoverflow.com/a/47653003
accepted answer: http://stackoverflow.com/a/47653000
has body: I have a string, list and start position: s = "NNDRJGLDFDNJASNJBSA82NNNNNDHDWUEB3J4JJX" l = [0, ""] start = 0 Now I want to extract all the N's and their positions in the string. What I have tried so far is: for i in range(len(s)): if s[i] == "N": l[0] = i+start l[1] = s[i] But I only get the last "N" character from the string. Any suggestions?
has answer: http://stackoverflow.com/a/47653003
has answer: http://stackoverflow.com/a/47653000
tagged with: python
has comment: http://stackoverflow.com/comment/82265060

http://stackoverflow.com/a/47613922
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82197421
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/82225185
has comment: http://stackoverflow.com/comment/82201197
has comment: http://stackoverflow.com/comment/82374138
accepted answer of: http://stackoverflow.com/q/47582982
has body: I ran into the same problem and searched for it, here is what I found https://www.kaggle.com/jpopham91/rmlse-vectorized After modified a bit, this seems to work for me,rmsle_K method implemented with Keras and TensorFlow. import numpy as np import math from keras import backend as K import tensorflow as tf def rmsle(y, y0): assert len(y) == len(y0) return np.sqrt(np.mean(np.power(np.log1p(y)-np.log1p(y0), 2))) def rmsle_loop(y, y0): assert len(y) == len(y0) terms_to_sum = [(math.log(y0[i] + 1) - math.log(y[i] + 1)) ** 2.0 for i,pred in enumerate(y0)] return (sum(terms_to_sum) * (1.0/len(y))) ** 0.5 def rmsle_K(y, y0): return K.sqrt(K.mean(K.square(tf.log1p(y) - tf.log1p(y0)))) r = rmsle(y=[5, 20, 12], y0=[8, 16, 12]) r1 = rmsle_loop(y=[5, 20, 12], y0=[8, 16, 12]) r2 = rmsle_K(y=[5., 20., 12.], y0=[8., 16., 12.]) print(r) print(r1) sess = tf.Session() print(sess.run(r2)) Result: Using TensorFlow backend 0.263978210565 0.263978210565 0.263978
type: Answer
answers question: http://stackoverflow.com/q/47582982

http://stackoverflow.com/comment/82120157
has text: If they think the solution is a constant of 1000, then that makes me think that they would have built all the three-digit numbers, and then regex searched for them. It's very common for people to think that operations they didn't actually write/see are "free". I'm pretty sure this would be linear to the length of the string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47581326
score: 68

http://stackoverflow.com/comment/86334648
type: Comment
has text: People tend to be touchy about using `eval`, bear in mind there is a function in the `ast` module called [`literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval), which has a much reduced scope for evaluation and hence is more secure.
type: AnswerComment
comment on: http://stackoverflow.com/a/47667558
score: 1

http://stackoverflow.com/comment/82322451
score: 0
comment on: http://stackoverflow.com/a/47681691
type: AnswerComment
type: Comment
has text: It is removing duplicates, as I used "and"

http://stackoverflow.com/comment/82173649
type: AnswerComment
score: 1
has text: Please provide an answer which would be useful even if the link breaks, i.e. the main message of what is shown in the link should be part the answer.
type: Comment
comment on: http://stackoverflow.com/a/47603601

http://stackoverflow.com/comment/82266953
type: QuestionComment
type: Comment
has text: Again, no clue what your `file.txt` looks like.
comment on: http://stackoverflow.com/q/47654298
score: 0

http://stackoverflow.com/comment/82142445
comment on: http://stackoverflow.com/q/47592399
score: 0
has text: BTW, you probably want to call `f.readlines()` (which returns a list of strings), not `f.read()` (which returns a single string). When iterating the string returned by `f.read()`, you are iterating the contents of your file character by character.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82043412
has text: Also, after I swap the two loops I see that only d[0] works when the "app" loop is first whereas d[0] and d[1] both work when the "pat" loop is first. This means that the list "data" gives default indices based off the first loop's append. But using your data[-1][-1] method still gives an out of index...
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47542769

http://stackoverflow.com/q/47643338
accepted answer: http://stackoverflow.com/a/47645619
has answer: http://stackoverflow.com/a/47645619
type: AnsweredQuestion
score: 0
tagged with: pandas-groupby
has body: Sample input: ID Timestamp Event 1 1 2010-05-31 13:43:45 a 2 1 2010-05-31 13:44:25 a 3 1 2010-05-31 13:44:55 a 4 1 2010-05-31 13:45:35 b 5 1 2010-05-31 13:47:05 b 6 1 2010-05-31 13:47:45 a 7 1 2010-05-31 13:49:45 c 8 1 2010-05-31 13:50:45 b 9 1 2010-06-01 09:20:00 c 10 1 2010-06-01 09:22:00 c 11 1 2010-06-01 09:23:20 c 12 1 2010-06-01 09:24:00 a 13 1 2010-06-01 09:24:15 a 14 1 2010-06-01 09:25:00 b 15 1 2010-06-01 09:25:42 b 16 2 2010-05-31 11:25:38 a 17 2 2010-05-31 11:26:00 c 18 2 2010-05-31 11:26:45 a 19 2 2010-05-31 11:27:10 a 20 2 2010-05-31 11:27:37 a 21 2 2010-05-31 11:29:35 b 22 2 2010-05-31 11:30:25 b . . . . . . . . . . . . This is a pseudocode of what I'm currently doing, but its not working properly # Right now I'm looping through the dataframe, using this pseudocode: for row in df.itertuples(): check for ID match: (say, 1 == 1) check for event match: (say a == a) calculate time duration, check for &lt; 3600 store in a dictionary of the events ('a', 'b',etc = keys), cumulative store this events dictionary for the ID else Increment session accordingly else store the previous occurrence time of the previous event, use it for the next occurrence of the event, using a dictionary; At the same time, find the current event's duration w.r.t. the time stored at the previous changing of the event(in the above line), again check for &lt; 3600 store in a dictionary of the events ('a', 'b',etc = keys), cumulative store this events dictionary for the ID else Increment session accordingly else reset events dictionary to zero values reset the event change dictionary to zero values This is a sample output, but similar to what I want to do. ID a_time b_time c_time Session 1 1 120 200 100 2 2 2 235 340 145 3 . . . . . . . . . . . . Actually there are 7 unique events in all, I've just mentioned 3 to keep it less complicated. {Basically “a_time” = sum of time taken by all occurences the event ‘a’ for the current ID (if the time duration for that occurrence isn’t greater than…
tagged with: pandas
tagged with: dataframe
tagged with: python
type: Question
has title: How to use pandas groupby with aggregation for counting total time taken by a particular event for a particular ID?
answer count: 1
has comment: http://stackoverflow.com/comment/82246332

http://stackoverflow.com/comment/82156042
comment on: http://stackoverflow.com/a/47598797
type: Comment
has text: They are supposed to be integers yes, but I probably messed up somewhere and made them strings haha. I'll look into it.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82043897
comment on: http://stackoverflow.com/a/47542762
type: Comment
score: 0
type: AnswerComment
has text: @carl: I can't give you a suggestion without knowing what the API is doing. If the API is encoding as UTF-8, then my second implementation is correct (note: It's assuming you can hit, but not exceed, the max length; you'd change the test to `>= self.maxblocksize` if the max length was exclusive, not inclusive). But the API might be prefixing it with a byte count, or using UTF-16, or some other approach. You haven't provided sufficient detail.

http://stackoverflow.com/comment/82106274
has text: suppose /opt/apps/ create the virtual environment here virtualenv env now clone the project, after cloning there will be one more folder, created just activate the virtualenv source env/bin/activate go the project folder, run ./manage.py runserver if you want to run in background you can user supervisor
comment on: http://stackoverflow.com/a/47574443
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47690548
has title: Running pyinstaller another pc with Chromedriver
accepted answer: http://stackoverflow.com/a/47780274
favorite count: 0
has body: I am trying to add Chromedriver inside an executable in pyinstaller. While this is possible it seems that I get the below error message when trying to run this on another computer. I have tried a number of posts including this one, but unfortunately, this has not provided desired results. Best case was I could run it on my own computer when chrome exe was in the same folder which was unhelpful. Code 1: Main.py from selenium import webdriver driver = webdriver.Chrome() What I get when running on another pc: Error 1: Cannot find Chrome Path C:\Users\Aperture Science\Desktop\1&gt;123.exe Traceback (most recent call last): File "site-packages\selenium\webdriver\common\service.py", line 74, in start File "subprocess.py", line 709, in __init__ File "subprocess.py", line 997, in _execute_child FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "main.py", line 42, in &lt;module&gt; File "main.py", line 33, in main File "site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__ File "site-packages\selenium\webdriver\common\service.py", line 81, in start selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home [2228] Failed to execute script main How can I get around this? What I get from link provided: Code 2: from selenium import webdriver import os, sys, inspect current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe() ))[0])) chromedriver = os.path.join(current_folder,"chromedriver.exe") driver = webdriver.Chrome(executable_path = chromedriver) driver.get("http://www.imdb.com/") REQUIRES Chrome exe in set path, bundled chrome not read. So packaged chrome does not work as desired.
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/47780274
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82520191
has comment: http://stackoverflow.com/comment/82342973
possible better answer: http://stackoverflow.com/a/71971439
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/82518793
has comment: http://stackoverflow.com/comment/82519246
has comment: http://stackoverflow.com/comment/82519948
has comment: http://stackoverflow.com/comment/82519628
tagged with: python
upvote count: 6
type: Question
has comment: http://stackoverflow.com/comment/82518873
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82519287
answer count: 2
has comment: http://stackoverflow.com/comment/82519135
has comment: http://stackoverflow.com/comment/82519720
has answer: http://stackoverflow.com/a/71971439
tagged with: selenium
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/82520265
linked to: http://stackoverflow.com/q/41030257

http://stackoverflow.com/comment/82158980
comment on: http://stackoverflow.com/q/47599875
type: QuestionComment
score: 0
has text: Did you print out `countries_list` to check if it contains more than one entry?
type: Comment

http://stackoverflow.com/comment/82248406
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47643618
has text: That was it!! Thank you Michael
score: 0

http://stackoverflow.com/comment/82169238
has text: That's exactly it, thank you. So since the variables have already been defined, the array is completely unnecessary?
comment on: http://stackoverflow.com/a/47605309
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/99700969
type: AnswerComment
has text: how can I adjust my frequency right? If i have two years of weekly data, what should be my freq, is freq=52? in htis case it would be empty
comment on: http://stackoverflow.com/a/47610117
type: Comment
score: 8

http://stackoverflow.com/q/47570593
favorite count: 0
has body: I'm stacked, and I need the wisdom of the stackoverflow. I want to create a simple averaging model for sales based on the day of the week from past using pandas. I mean, the model predicts value of Sales for next Monday based on the last 4 Mondays. Also, if there are no enough weeks in the past, just make an average of existing weeks. Sample of my time-series df: weekDay weekNum Sales Date 2013-01-01 2 1 22 2013-01-02 3 1 33 2013-01-03 4 1 44 2013-01-04 5 1 55 2013-01-05 6 1 66 2013-01-06 7 2 76 2013-01-07 1 2 23 2013-01-08 2 2 55 2013-01-09 3 2 34 2013-01-10 4 2 43 2013-01-11 5 2 34 2013-01-12 6 2 53 2013-01-13 7 3 52 2013-01-14 1 3 41 2013-01-15 2 3 31 2013-01-16 3 3 31 2013-01-17 4 3 42 2013-01-18 5 3 23 2013-01-19 6 3 41 2013-01-20 7 4 31 2013-01-21 1 4 31 2013-01-22 2 4 31 2013-01-23 3 4 43 2013-01-24 4 4 53 2013-01-25 5 4 32 2013-01-26 6 4 12 2013-01-27 7 5 41 2013-01-28 1 5 41 2013-01-29 2 5 12 2013-01-30 3 5 76 2013-01-31 4 5 43 2013-02-01 5 5 32 2013-02-02 6 5 54 2013-02-03 7 6 43 2013-02-04 1 6 43 2013-02-05 2 6 12 2013-02-06 3 6 12 2013-02-07 4 6 43 2013-02-08 5 6 22 2013-02-09 6 6 12 What I've tried: ts.resample('D').rolling(28).mean()["Sales"] ts.resample('W-MON').rolling(1).mean()["Sales"] but it didn't help.
tagged with: time-series
type: Question
has comment: http://stackoverflow.com/comment/82098580
tagged with: python
has answer: http://stackoverflow.com/a/47572163
upvote count: 4
has title: pandas: Get an average value of sales for a day of week based on 4 past weeks
score: 4
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47572163
answer count: 1

http://stackoverflow.com/a/47587143
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47587042
has body: shuffle the list once and then pop() returns the last element, reducing the list. &gt;&gt;&gt; from random import shuffle &gt;&gt;&gt; a=[1,2,3,3] &gt;&gt;&gt; shuffle(a) &gt;&gt;&gt; a.pop() 3 &gt;&gt;&gt; a.pop() 2 &gt;&gt;&gt; a.pop() 3 &gt;&gt;&gt; a.pop() 1 edit: to keep track of the index using enumerate from random import shuffle a=[1,2,3,3] b=list(enumerate(a)) shuffle(b) b.pop() (3, 3) docs: enumerate and random.shuffle
answers question: http://stackoverflow.com/q/47587042
has comment: http://stackoverflow.com/comment/82131858
type: Answer
has comment: http://stackoverflow.com/comment/82131896
score: 1
has comment: http://stackoverflow.com/comment/82131720
type: AcceptedAnswer

http://stackoverflow.com/a/47659938
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47659872
accepted answer of: http://stackoverflow.com/q/47659872
has body: You can't convert it to int, you need float. percent = '2837' #input("Enter the % you want to increase by: ") n = "1." + percent k = float(n) print(k)

http://stackoverflow.com/a/47682944
has body: Here is my take on it. l = ["foo bar SOME baz TEXT bob", "SOME foo bar baz bob TEXT", "SOME foo TEXT", "foo bar SOME TEXT baz", "SOME TEXT"] l.sort(key=lambda x: (x.find("SOME")-x.find("TEXT"))*0.9-0.1*x.find("SOME"), reverse=True) print(l) OUTPUT: ['SOME TEXT', 'foo bar SOME TEXT baz', 'SOME foo TEXT', 'foo bar SOME baz TEXT bob', 'SOME foo bar baz bob TEXT'] So what we have done is sorted the list based on major weight to the distance between "SOME" and "TEXT" and some minor weight to the occurrence of "SOME" in the string. Another longer way would be to first group the list based on the their distance between SOME and TEXT. And then sort the each group based on the position of "SOME".
type: Answer
answers question: http://stackoverflow.com/q/47682491
has comment: http://stackoverflow.com/comment/82357819
score: 0

http://stackoverflow.com/a/47640303
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47640229
score: 2
accepted answer of: http://stackoverflow.com/q/47640229
type: Answer
has comment: http://stackoverflow.com/comment/82239365
upvote count: 2
has body: Don't parse the output with Bash. Change the Python script to print in the format you like. For example: from itertools import product from string import ascii_lowercase for t in product(ascii_lowercase, repeat = 3): print(''.join(t))
downvote count: 0

http://stackoverflow.com/q/47540942
has comment: http://stackoverflow.com/comment/82039119
accepted answer: http://stackoverflow.com/a/47541221
has body: For example, I want to be able to inject a behavior if I want to inside a function, but if I don't have a behavior, I want it to have a default behavior class TestDefaultParam: def defaultBehavior(file1, file2): return 2 def action(file1, file2, behave=defaultBehavior): return behave(file1, file2) if __name__ == '__main__': some = TestDefaultParam() print(some.action("test", "test")) If this isn't possible how can I change behavior of action at will? with this code I get this error: Traceback (most recent call last): File ".\test.py", line 10, in &lt;module&gt; print(some.action("test", "test")) File ".\test.py", line 6, in action return behave(file1, file2) TypeError: 'str' object is not callable
tagged with: python
score: -7
linked to: http://stackoverflow.com/q/2709821
has comment: http://stackoverflow.com/comment/82039102
linked to: http://stackoverflow.com/q/14017996
has comment: http://stackoverflow.com/comment/82039346
has comment: http://stackoverflow.com/comment/82039151
duplicate of: http://stackoverflow.com/q/2709821
type: AnsweredQuestion
has title: How to make function arguments optional?
upvote count: 0
has answer: http://stackoverflow.com/a/47541221
answer count: 1
downvote count: 7
has comment: http://stackoverflow.com/comment/82039064
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/73631401

http://stackoverflow.com/comment/82181805
has text: Not the problem, but you really should give things consistent names. Your model is called userinfo, but the form is called NewList and the result of saving is called Event.
comment on: http://stackoverflow.com/q/47611721
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47578974
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82115660
has comment: http://stackoverflow.com/comment/82115679
tagged with: python
has comment: http://stackoverflow.com/comment/82115299
tagged with: checkbox
has comment: http://stackoverflow.com/comment/82116258
has comment: http://stackoverflow.com/comment/82116428
has comment: http://stackoverflow.com/comment/82115865
score: 0
has comment: http://stackoverflow.com/comment/82114981
has answer: http://stackoverflow.com/a/47579741
answer count: 1
has body: I am new to coding and I wrote some code for a calculator I use to solve some stuff at work. I am now stuck trying to add check buttons for "feet" &amp; "meters". I want them to integrate into my equation, that way I wont have to convert them manually beforehand. I will add the second equation for feet once I can figure out how to make them toggle between the two. Here is my code so far: import Tkinter import math from Tkinter import * Lreq = 105 Dref = 1 class compintapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self["bg"] = "grey" ## Title &amp; subtitle labels --------------------------------------- titlelbl = Tkinter.Label(self, text="Wattage Calculator", anchor="center",fg="black",bg="darkorange2") titlelbl.grid(column=0,row=0,columnspan=4,sticky='EW') ## Input Labels -------------------------------------------------- sensitivitylbl = Tkinter.Label(self, text="Loudspeaker sensitivity?", anchor="w",fg="white",bg="SlateGray4") sensitivitylbl.grid(column=0,row=2,columnspan=3,sticky='EW') distancelbl = Tkinter.Label(self, text="Distance from speaker to listening position?", anchor="w",fg="white",bg="SlateGray4") distancelbl.grid(column=0,row=3,columnspan=3,sticky='EW') headroomlbl = Tkinter.Label(self, text="How much headroom for amplifier?", anchor="w",fg="white",bg="SlateGray4") headroomlbl.grid(column=0,row=4,columnspan=3,sticky='EW') wattagelbl = Tkinter.Label(self, text="Total Wattage :", anchor="w",fg="white",bg="SlateGray4") wattagelbl.grid(column=0,row=7,columnspan=3,sticky='EW') ## end of input labels ------------------------------------------------ ## Input Boxes -------------------------------------------------------- #self.sensitivity = Tkinter.DoubleVar() #speakersensitivity = Tkinter.Entry(self,textvariable=self.sensitivity) #speakersensitivity.grid(column=1,row=2,sticky='EW') self.sensitivity = Tkinter.DoubleVar() speakersensitivity = Tkinter.En…
tagged with: calculator
has title: Adding a "if" "then" checkbutton
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82115944
has comment: http://stackoverflow.com/comment/82115152

http://stackoverflow.com/comment/82164270
has text: Where is "method 5"? I don't see it in your post, only a comment about trying to "copy i".
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47602645
type: Comment

http://stackoverflow.com/q/47676972
score: 1
has title: Passing a string variable between two functions in Python
has answer: http://stackoverflow.com/a/47677052
upvote count: 1
tagged with: variables
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47677034
has body: I am having trouble passing a variable from one function to another: def name(): first_name=input("What is your name? ") if len(first_name)==0: print("\nYou did not enter a name!") return name() else: print("\nHello %s." % first_name) return surname() def surname(): last_name=input("\nCan you tell my your last name please?") if len(last_name)==0: print("\nYou did not enter a last name!") return surname() else: print("Nice to meet you %s %s." % (first_name,last_name)) I want the last command to print the inputed first_name from def name() and last name from def surname() I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is: print("Nice to meet you %s %s." % (first_name,last_name)) NameError: name 'first_name' is not defined What am I doing wrong?
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82313009
tagged with: python
has answer: http://stackoverflow.com/a/47680873
answer count: 3

http://stackoverflow.com/a/47599302
has comment: http://stackoverflow.com/comment/82175109
has body: @schwobaseggi has the most straightforward answer for what you want to do, but what you want to do seems like it's asking for trouble. You have one class that does two very different things. Animal is an animal that has a name and eats, and it also keeps track of every animal instance and makes all of them eat. Animal is trying to do what individual animals do and also control a group of animals. It might be better to split this into two different kinds of objects: An animal, and some sort of AnimalGroup like Zoo or Farm or Herd. The AnimalGroup class should be responsible for keeping track of a bunch of instances and make them all do stuff. class AnimalGroup(object): def __init__(self, animal_list): self.animals = animal_list[:] def add_animal(self, animal): self.animals.append(animal) def all_eat(self): for animal in self.animals: animal.eat() then dog = Animal("dog") cat = Animal("cat") giraffe = Animal("giraffe") group = AnimalGroup([dog, cat, giraffe]) group.all_eat() group.add_animal(Animal("pig")) group.all_eat() This separates out the responsibilities of each class and makes things much easier to change later on. You can now have different group behaviors without ever needing to change the animal class. You can have new animal classes that inherit from Animal and you don't need to worry about side effects. for example: class Mammal(Animal) . When I call Mammal.eat, will it update all animals? It might. class variables can be a bit tricky like that. Should it update all animals? No idea. With an AnimalGroup object, you don't need to worry.
type: Answer
accepted answer of: http://stackoverflow.com/q/47598004
answers question: http://stackoverflow.com/q/47598004
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47622244
has comment: http://stackoverflow.com/comment/82203139
score: 0
has comment: http://stackoverflow.com/comment/82203332
type: Answer
answers question: http://stackoverflow.com/q/47622186
has body: In your if statement, you're using an input() method. It doesn't have to be there. Just write: if userinput=="level1": level1() elif userinput=="level2": level2() etc. It's also better to use elif in stead of if.
has comment: http://stackoverflow.com/comment/82203288
has comment: http://stackoverflow.com/comment/82202410
has comment: http://stackoverflow.com/comment/82203262
has comment: http://stackoverflow.com/comment/82203163

http://stackoverflow.com/comment/82325747
type: Comment
comment on: http://stackoverflow.com/a/47683049
type: AnswerComment
has text: What do I do if my Test is located in a different directory? (apart from path append)
score: 0

http://stackoverflow.com/comment/82304157
comment on: http://stackoverflow.com/a/47672045
has text: @saditya If that's running in the main process, it may never break out of whatever loop its in. It looks like you're using a development version, is there not a stable version you could install instead?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82256374
comment on: http://stackoverflow.com/q/47648886
has text: s == j # returns false because in string composed of characters as both are string but with different commas sequence. from str: "{'first': 42, 'second': 21}" and from json: '{"first": 42, "second": 21}'. See the commas sequence are different in both so obviously the comparison will bring false. For two strings need to equal only if they have matching characters at corresponding places.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82271205
has text: Possible duplicate of [What is the difference between a pandas Series and a single-column DataFrame?](https://stackoverflow.com/questions/26047209/what-is-the-difference-between-a-pandas-series-and-a-single-column-dataframe)
comment on: http://stackoverflow.com/q/47655866
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82224312
score: 1
comment on: http://stackoverflow.com/a/47633033
type: Comment
has text: Then use `df['Amount'].T.plot()`
type: AnswerComment

http://stackoverflow.com/comment/82118207
score: 0
comment on: http://stackoverflow.com/q/47580110
type: Comment
type: QuestionComment
has text: No errors as such but will post console feed

http://stackoverflow.com/comment/82338353
has text: Thanks, never done anything through command prompt before so this is extremely helpful.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47689619
type: Comment

http://stackoverflow.com/comment/82331261
type: Comment
type: QuestionComment
has text: I think you've got it backwards - you're attempting to seek on a file that's already closed. What is `merged_file` and has it been closed prior to entering this function?
score: 0
comment on: http://stackoverflow.com/q/47685686

http://stackoverflow.com/q/47636088
has comment: http://stackoverflow.com/comment/82230120
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/47681331
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47681331
has comment: http://stackoverflow.com/comment/82319881
downvote count: 0
has title: Overriding Original image using pillow in python
answer count: 1
favorite count: 0
has body: I'm trying to edit an image using pillow. I see we have only options to save the edited image in new file. Is there a way to override the original image while saving the edited image in pillow? just to know.
type: Question
upvote count: 5
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/82321758

http://stackoverflow.com/comment/82219848
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47629957
has text: I am a bit confused with your desired output. Because in `df1` are not `VA` column. Also if duplicates columns names it is bad too, because it should failed. Can you check it? What is desired output from your input? There are some column(s) from `df1` mapped to `df2` ? Or only `As` ?
score: 0

http://stackoverflow.com/comment/82322374
type: AnswerComment
comment on: http://stackoverflow.com/a/47681199
has text: @RobertP. Correct.
type: Comment
score: 0

http://stackoverflow.com/a/47679461
type: Answer
has comment: http://stackoverflow.com/comment/85835596
has comment: http://stackoverflow.com/comment/85825544
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47675942
has body: You can switch expression tree systems with: import pyomo.core.base.expr as EXPR EXPR.set_expression_tree_format(EXPR.common.Mode.pyomo4_trees) Pyomo4 expressions have been a (long-running) development activity to simplify the expression tree system, improve performance, and most importantly to provide support for pypy. It has not been made the default mostly because while I think it works correctly, it generates slightly different expression trees from what the coopr3 system generated. This impacts a large number of the Pyomo tests and I haven't had the time to resolve all the (2000+) test differences to make sure that the new results are correct. Also, I should point out that [as of Dec 2017] there is a Pyomo branch with a revised version of the pyomo4 expression system (currently dubbed pyomo5). This system has an improved way to ensure expression correctness in the absence of getrefcount() (needed for pypy). Unfortunately, the development of pyomo5 expressions hass diverged from the coopr3/pyomo4 systems sufficiently such that they do not cleanly coexist. When that branch is merged (likely January 2018), both coopr3 and pyomo4 expression systems are expected to be removed from master.
accepted answer of: http://stackoverflow.com/q/47675942
score: 1

http://stackoverflow.com/comment/82133254
type: QuestionComment
comment on: http://stackoverflow.com/q/47587246
score: 0
has text: take an example where you know the answer and post it here so we better understand what is that you actually want so we better understand what you mean by max diverse in this context.
type: Comment

http://stackoverflow.com/q/47597914
has title: How to plot error ellipses from covariance matrix
downvote count: 1
accepted answer: http://stackoverflow.com/a/55511243
favorite count: 0
possible better answer: http://stackoverflow.com/a/68302917
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55511243
has answer: http://stackoverflow.com/a/68302917
tagged with: pandas
score: 1
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/82155110
has comment: http://stackoverflow.com/comment/82154588
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82154241
has body: I fitted my data with some parameters and now I have their optimal values popt and their covariance matrix pcov. I assume that these uncertainties are Gaussian and I would like to have a plot of error ellipses like the one below. Is there some easy way to do it (without manually doing every subplot)? I was looking at pandas.tools.plotting.scatter_matrix which seems somehow close but I do not know ho to apply this to my multivariate Gaussian.
has comment: http://stackoverflow.com/comment/82154027
has comment: http://stackoverflow.com/comment/82155351

http://stackoverflow.com/q/47649972
answer count: 1
downvote count: 0
has body: I store data in csv file as follwing: row = dict_items([('Time ': '2017-12-01T13:54:04'), ('Energy [kWh]': '0.01'), ('Voltage [V]': '221.64'), ('Current [A]': '0.08')]) Now i want to store it like that: ('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'), ('Time ': '2017-12-01T13:54:04','Voltage [V]': '221.64'), ('Time ': '2017-12-01T13:54:04','Current [A]': '0.08')]) so i wrote this code bellow and i define Device="" Value="" for key, value in row.items(): print(row.items()) if key == 'Time': Timevalue = value print(Zeitvalue) Device = key Value = value doc = {'Device':Device, 'Measure':Value , 'Time':Timevalue } i got this error: NameError: name 'Timevalue' is not defined How can i make the Timevalue variable globale to avoid this Problem? Thank you
has comment: http://stackoverflow.com/comment/82258243
has title: NameError: name '`Timevalue`' is not defined
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: elasticsearch
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82258483
has comment: http://stackoverflow.com/comment/82258348
accepted answer: http://stackoverflow.com/a/47656490
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47656490
score: 1

http://stackoverflow.com/a/49140118
accepted answer of: http://stackoverflow.com/q/47644042
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47644042
type: Answer
has body: I finally found what was going on. Because of the approximation cv2.CHAIN_APPROX_SIMPLE, the number of points used to calculate the ellipse was too small. The problem is solved if I use cv2.CHAIN_APPROX_NONE, which takes into account all the points of contour.
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/116086894
comment on: http://stackoverflow.com/a/47561712
type: Comment
type: AnswerComment
score: 1
has text: I tested this and it did not work for me (?!). I put ` import time while True: time.sleep(1) print(1)` in the slot function and it is still blocking the gui.

http://stackoverflow.com/a/47592307
has comment: http://stackoverflow.com/comment/82142076
has body: Try using a with context, which will manage the close (__exit__) operation smoothly at the end of the context: with open(...) as theFile: file_content = theFile.read()
type: Answer
answers question: http://stackoverflow.com/q/47591408
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82142800
downvote count: 0

http://stackoverflow.com/comment/82129377
type: Comment
type: QuestionComment
has text: Hi Phix, This is Django
score: 0
comment on: http://stackoverflow.com/q/47585810

http://stackoverflow.com/comment/82191473
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47616429
type: Comment
has text: for name in grades_dict is the pickle file "pStudent_Quiz_Grades.p" but that for name in grades_dict is basically saying when the script finds the name in the pickle file to print the name + grade. I'm still new to programming... sorry @aBiologist

http://stackoverflow.com/q/47564821
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/82087830
has comment: http://stackoverflow.com/comment/82088625
has comment: http://stackoverflow.com/comment/82087842
has comment: http://stackoverflow.com/comment/82087814
has title: manipulate numpy arrays in a nested list
has comment: http://stackoverflow.com/comment/82087868
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82088688
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47564943
has comment: http://stackoverflow.com/comment/82087934
has body: I am trying to manipulate numpy arrays in a nested list. I have a nested list, and in each inner list, there are several numpy arrays. a = [ [np.random.normal(0,1,[2,3]), np.random.normal(0,1,[4,5]), np.random.normal(0,1, [9, 10])], [np.random.normal(0,1,[2,3]), np.random.normal(0,1,[4,5]), np.random.normal(0,1, [9, 10])], [np.random.normal(0,1,[2,3]), np.random.normal(0,1,[4,5]), np.random.normal(0,1, [9, 10])] ] I want to element-wise compute mean of each of the numpy arrays in each list correspondingly to get a new list b, where elements are the mean of the three np.random.normal(0,1,[2,3]), the mean of the three np.random.normal(0,1,[4,5]), etc. My initial thought was to write down a for-loop to fetch corresponding arrays and compute mean of them and then add to a list. However, this may be a bit slow when having a large number of such arrays or inner list.
has answer: http://stackoverflow.com/a/47564943
has comment: http://stackoverflow.com/comment/82087880

http://stackoverflow.com/a/47638796
has comment: http://stackoverflow.com/comment/82236722
has comment: http://stackoverflow.com/comment/82235925
has body: in python, numbers starting with 0 are in octal base, the 'invalid token' error you're getting must be on a digit greater than 7, which is illegal in a base 8 number. Try using raw_input() instead of input() so that the value won't be evaluated as a number.
type: Answer
has comment: http://stackoverflow.com/comment/82235981
answers question: http://stackoverflow.com/q/47638678
has comment: http://stackoverflow.com/comment/82235857
score: 0

http://stackoverflow.com/a/47679046
has comment: http://stackoverflow.com/comment/82317290
type: Answer
has body: self.words is the words attribute of the ICommand class (it is not copied when you inherit). So when you append to that, it will append to it on ICommand, which will affect every class inheriting from it. Probably, though, a better thing to do would be something like: class Command(object): def __init__(self, words): self.words = words
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47678973
has comment: http://stackoverflow.com/comment/82317258

http://stackoverflow.com/comment/82275471
type: QuestionComment
has text: Pandas has a [describe function](https://pandas.pydata.org/pandas-docs/stable/basics.html#summarizing-data-describe), similar to summary() in R
comment on: http://stackoverflow.com/q/47658342
type: Comment
score: 0

http://stackoverflow.com/q/47687244
has title: Find same object id in odoo 7
tagged with: odoo
tagged with: python
has comment: http://stackoverflow.com/comment/82334738
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has body: I am trying to find same object in Odoo using search. I get back nothing or just "[]" from my search. This is my code: values = [] get_own_data = self.browse(cr, uid, ids) for get_own in get_own_data: get_date = self.pool.get('account.move').search(cr, uid, [('date', 'like', get_new.year)]) if get_date: for new_data in get_date: datas = self.pool.get('account.move').browse(cr, uid, new_data) for data in datas.line_id: product_categ = self.pool.get('product.category').search(cr, uid, [("property_account_income_categ", "=", data.account_id)]) print product_categ print "================" I don't understand why I got nothing. The result doesn't give me good information.
type: UnansweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82338249

http://stackoverflow.com/comment/82254763
score: 0
type: Comment
has text: you can use `matplotlib` and display images on plots. you can use `PIL/pillow` to generate one image with all you images.
type: QuestionComment
comment on: http://stackoverflow.com/q/47648203

http://stackoverflow.com/comment/82153196
comment on: http://stackoverflow.com/q/47594300
type: QuestionComment
has text: @GeoffReedy It is important for my script, basically I need to shuffle until every number is in a position different from the starting one.
type: Comment
score: 0

http://stackoverflow.com/comment/82158118
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47599749
has text: @patrick `Foo.method.__name__` will just be `method`. `__qualname__` might work for that though.

http://stackoverflow.com/a/47666445
has body: I think this is what you are looking for. Hopefully it gets you going. authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']} def get_similar(authors, author): retVal = [] for k, v in authors.items(): if k == author: for value in v: retVal.append(value) if value in authors: for v2 in authors[value]: retVal.append(v2) return sorted(retVal) get_similar(authors, "Harlan Ellison") returns ['Chris Moore', 'Douglas Adams', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Kurt Vonnegut', 'Neil Stephenson', 'Neil Stephenson', 'Richard Morgan', 'Terry Pratchett', 'Terry Pratchett', 'Tom Robbins'] I'll leave it to you to figure out how to remove the duplicates.
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47666287

http://stackoverflow.com/comment/82169995
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47605704
has text: Can you show the part of the code which gives the error
score: 0

http://stackoverflow.com/a/47574699
answers question: http://stackoverflow.com/q/47574261
score: 1
has body: I believe you already have your problem reason. It is indeed the fact that words is empty, and the randrange() method don't handle this kind of input. You can always check if your variable (in this case words) is empty, simply using: if len(words) &gt; 0: wordchoice = randint(0, len(words)-1)
has comment: http://stackoverflow.com/comment/82144265
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/88697353
type: Comment
has text: I wrote it. :D It's an undoc feature so it doesn't show up in the normal docs, but I wrote up a blog post on it back when: https://www.perforce.com/blog/fun-formatting
type: AnswerComment
comment on: http://stackoverflow.com/a/47580676
score: 4

http://stackoverflow.com/q/47625150
has body: I am trying to print to write to a file what type of shipping and item has from bs4 import BeautifulSoup from selenium import webdriver stock_file = r"C:\Users\Tut10\Desktop\PSTool-Python\Final\test.txt" def Home_Depot_Shipping(url): driver = webdriver.Chrome(r"C:\Users\Tut10\Desktop\PSTool-Python\chromedriver.exe") driver.get(url) # open a file to write to file_to_write = open(stock_file, "a") # send that file to me via email or text free_delivery = driver.find_elements_by_xpath(r'//*[@id="buybelt"]/div[2]/div[2]/div/div[2]') for x in free_delivery: #This should print one of the following options # Free Delivery, Standard Delivery, or Receive an email blah blah blah try: if "Free Delivery" in x.text: driver.quit() file_to_write.close() return "\t\t[+] Free Delivery" elif "Get it as soon as tomorrow" in x.text: driver.quit() #file_to_write.write("Cell: " + str(cell) + "[*] Express Delivery " + url + '\n') file_to_write.write("[*] Express Delivery " + url + "\n") file_to_write.close() return "\t\t[*] Express Delivery" elif "Receive an email" in x.text: driver.quit() file_to_write("[-] Out of Stock %s\n" % url) file_to_write.close() return "\t\t[-] Out of stock!" elif "Standard Delivery" in x.text: driver.quit() file_to_write.close() return "\t\t[+] Standard Delivery" except Exception as e: driver.quit() print(e) Home_Depot_Shipping(r"https://www.homedepot.com/p/WEN-8-in-5-Speed-Drill-Press-4208/204853910?keyword=wen+4208") I expect the program to write to the file, if the delivery is express delivery (Get it as soon as tomorrow) or out of stock (Receive an email) Just random, I know the code inside def Home_Depot_Shipping should be indented. It just wasn't copying right here. Ignore that please. It works fine for the Free delivery and standard. When it tries to write to the file though I keep getting this error '_io.TextIOWrapper' object is not callable Any suggestions or help would be greatly appreciated! Thanks
upvote count: 2
type: AnsweredQuestion
tagged with: ioerror
accepted answer: http://stackoverflow.com/a/47625295
has title: _io.TextIOWrapper' object is not callable
score: 1
has answer: http://stackoverflow.com/a/47625295
downvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/47616790
favorite count: 0
type: Question
upvote count: 5
tagged with: python
tagged with: inheritance
has answer: http://stackoverflow.com/a/47616879
has body: I was surprised for that it seems no document to tell how to truncated a derived class to base class in Python. In fact, it may less used. But I'm facing a a problem: Simplified: a base class class Base(object): def __init__(self): self.a = 10 and a derived class: class Derived(Base): def __init__(self): super(Derived, self).__init__() self.b = 10 Now in some situation, I have to merge the datas which may be Derived and Base, and only keep data-fields in Base, so I need a method to truncate the Derived to Base, But I found nothing. I tried to make a get_base method both in Base and Derived, and let it return Base in Derived by super(Derived, self).get_base(), but the returned result still is Derived! I print the Base's __dict__ and found that it only has methods, no user-defined attributes... I'm wondering Is there exists a way to get the data fields of Base from Derived instance(truncate)?
tagged with: class
type: AnsweredQuestion
score: 4
tagged with: oop
has title: In Python, could a Derived class be truncated to base class?
accepted answer: http://stackoverflow.com/a/47616879
answer count: 1
downvote count: 1

http://stackoverflow.com/a/47691455
answers question: http://stackoverflow.com/q/47691050
has comment: http://stackoverflow.com/comment/82342588
has body: If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all models leave this field blank. I do not really like the idea to have a field which is always blank - maybe this is my problem. It kind of is. To define a one-to-many you use ForeignKey, and this will need to be on the PhoneNumber model. This doesn't provide any drawbacks to your approach, as far as I can see. It sounds like the main issue is that you're used to using a library that does this the other way round, and so doing it this way round seems strange to you. I'm afraid I don't understand what you mean by 99.9% of all models leave this field blank They can't leave it blank unless you allow them to by setting null=True, blank=True etc.
type: Answer
has comment: http://stackoverflow.com/comment/82342774
has comment: http://stackoverflow.com/comment/82342650
score: 0

http://stackoverflow.com/comment/82216286
has text: @VinodBhavnani You can try this. ```import simplejson simplejson.loads('["new","bid","inprogress","onhold","completed"]')```
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47629124
score: 0

http://stackoverflow.com/q/47563811
type: UnansweredQuestion
has title: Python making list from values and printing certain results
tagged with: python
score: -1
upvote count: 0
tagged with: list
has body: Here is my code: for i in range(1,76): input('Enter name for guest'+str( i)+': ') ages=int(input('Enter age for guest '+str(i)+':')) for x in range(20,30) in list(ages): print('Number of people in 20s is ' +str(x) ) How do I put the results in a list and print out amount of people aged in their 20s? Thanks.
has comment: http://stackoverflow.com/comment/82086106
has answer: http://stackoverflow.com/a/47563839
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82086758

http://stackoverflow.com/a/47576329
score: 0
answers question: http://stackoverflow.com/q/47576241
has comment: http://stackoverflow.com/comment/82109682
has comment: http://stackoverflow.com/comment/82109893
has comment: http://stackoverflow.com/comment/82110028
type: Answer
has body: You could simplify your logic to sth like the following and not use the string literals 'a', 'b', etc. but the actual variable names: a, b, c, d = sorted( float(input("Enter length of side {}: ".format(x))) for x in 'ABCD' ) if a == b and c == d: # parallel

http://stackoverflow.com/comment/82320745
has text: In a well-defined module like tkinter/Tkinter, using the constants is less important, because the module will probably identify the error. If I write .pack(fill='X'), Tkinter will complain about the 'X'. But in another scenario, in a less well-defined module, that mistake might go uncaught for a while. But if I used Tkinter.X, and I accidentally typed Tkinter.x, it would get flagged... I'm old school! :)
type: Comment
comment on: http://stackoverflow.com/a/47680449
score: 0
type: AnswerComment

http://stackoverflow.com/q/47613626
has comment: http://stackoverflow.com/comment/97040739
has title: Editable CRUD Table with Flask/Python & MySQL
type: UnansweredQuestion
downvote count: 0
has body: I'm trying to implement an editable table with CRUD operations using Python Flask. Basically every tutorial I found uses PHP. I saw two tables that I liked: Patternfly In Line Editing for Table View jQuery Tabledit Example #6 I already have the Python code, that connects to my database: def export_ledger(): cnx = mariadb.connect( user=cfg.db['user'], password=cfg.db['pwd'], database=cfg.db['baseteste'] ) cursor = cnx.cursor() query = """ SELECT ID, data, credito, debito, descricao, valor FROM ledger_teste ORDER BY data DESC """ cursor.execute(query) rows = cursor.fetchall() desc = cursor.description cnx.close() ledger_completo = [dict(itertools.izip([col[0] for col in desc], row)) for row in rows] return json.dumps(ledger_completo) But I still need to write the code to edit shown entries, and to delete entries. I tried Ajax connection with the following JavaScript code inside my HTML with no success: $('#general_ledger').Tabledit({ $.ajax({ url: 'export_ledger', method: 'GET' }).done(function(data){ $('tbody').html(data) tableData() }) } My question is: how to make the JSON that results from this Python code feed the table, and how to add functions to edit and delete entries? Thanks a lot in advance.
has comment: http://stackoverflow.com/comment/91476034
tagged with: jquery
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91475950
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/91476079
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/96945090
answer count: 0

http://stackoverflow.com/q/47603644
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82166612
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
linked to: http://stackoverflow.com/q/7648967
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/82166616
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82166394
tagged with: python
has body: In python 2/3 is it possible to run multiprocessing in threads? And how to set multiprocessing to auto release the memory used by process after it has completed execution, without command join() if I don't need to wait or take some value from process? I found this Scoot S trick: def easy_parallize(f, sequence): from multiprocessing import Pool pool = Pool(processes=8) result = pool.map(f, sequence) cleaned = [x for x in result if not x is None] cleaned = asarray(cleaned) pool.close() pool.join() return cleaned But there are 2 problems here: It still uses join(), and it makes the main program wait for the process to finish before continuing. I'm unsure what's done to clear the process from memory (I'm a newbie to linux commands and don't know how to make sure).
has title: Can we use multiprocessing in threads?
has comment: http://stackoverflow.com/comment/82183149
type: Question

http://stackoverflow.com/comment/82238450
type: Comment
comment on: http://stackoverflow.com/a/47632586
has text: Yes, but it would be easier to see your data - or part of it - to see what is going wrong there.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82233827
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47637293
type: AnswerComment
has text: Do you note any logic in my `__init__.py`?

http://stackoverflow.com/comment/82289345
type: AnswerComment
comment on: http://stackoverflow.com/a/47664794
has text: @Ajax1234 What happens if you change your own example from 'EST' to 'GMT'?
score: 0
type: Comment

http://stackoverflow.com/q/47665788
answer count: 2
tagged with: http://stackoverflow.com/tag/json
has body: Hello I'm a new face to json and I want to ask something about it, anyway here's my code: for key in result1date.keys(): key = sorted(result1date.keys()) currentdate = key print currentdate result1 = firebase.get('/Rooms/Room1/' + currentdate + '/Inspection/Scan-in/Inspector/', None) result2 = firebase.get('/Rooms/Room1/' + currentdate + '/Inspection/Scan-out/Inspector/', None) print result1 print currentdate for key in result1.keys(): inspector = key timeout = result2[inspector]["Time"] # for key in result1date.keys(): # Date = key result1datetime = firebase.get('/Rooms/Room1/'+ currentdate +'/Inspection/Scan-in/Inspector/'+ inspector +'/', None) for key in result1datetime.keys(): key = sorted(result1datetime.keys())[-2] time = key print time print time ch1 = result1datetime[time]["Checklist"]["Entrance louver clean and dust-free"] # ch2 = result1datetime[time]["Checklist"]["Room plate number – clean and well-polished"] ch3 = result1datetime[time]["Checklist"]["Appearance door surface- in good condition"] # ch4 = result1datetime[time]["Checklist"]["Let the door close by itself to test the door closure – in working order"] ch5 = result1datetime[time]["Checklist"]["Eye viewer and fire escape plan in order"] ch6 = result1datetime[time]["Checklist"]["Privacy Sign or Make Up Room Sign"] # ch7 = result1datetime[time]["Checklist"]["Key card holder – in working order"] ch8 = result1datetime[time]["Checklist"]["Switches at the entrance working correctly"] #CLOSET #ch9 = result1datetime[time]["Checklist"]["Let the door close by itself to test the door closure – in working order"] RESERVED FOR DOOR IN WORKING CONDITION ch10 = result1datetime[time]["Checklist"]["Lights in working order"] # items below are sufficient ch11 = result1datetime[time]["Checklist"]["6 Hangers?"] ch12 = result1datetime[time]["Checklist"]["2 bathrobes?"] ch13 = result1datetime[time]["Checklist"]["2 pairs of slippers?"] ch14 = result1datetime[time]["Checklist"]["1 set of iron and board?"] ch15 = result1d…
downvote count: 1
favorite count: 0
type: Question
tagged with: firebase
has title: Looping Over Json Structure To get Multiple Outputs, I'm getting one, Why?
type: UnansweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/82291638
tagged with: python
has answer: http://stackoverflow.com/a/47740455
has answer: http://stackoverflow.com/a/47763475
score: 4

http://stackoverflow.com/comment/82102478
comment on: http://stackoverflow.com/q/47572452
type: Comment
type: QuestionComment
has text: try to do flush before close like `f.flush()`
score: 0

http://stackoverflow.com/q/47550518
type: UnansweredQuestion
has title: opencv segment conntected characters
tagged with: python
linked to: http://stackoverflow.com/q/14211413
has comment: http://stackoverflow.com/comment/82208723
tagged with: tesseract
upvote count: 4
has body: I am trying to do character detect for handwriting letters. Upon recognizing itself, I use tesseract or opencv SVM, and works fine till now. Everything works fine for segment letters until I hit those connected ones. I use the following code to segment letters: # -*- coding: utf-8 -*- import numpy as np import cv2 # from matplotlib import pyplot as plt from os.path import dirname, join, basename import sys from glob import glob trainpic=[] targetdir = dirname(__file__)+'tmporigin' #print glob(join(dirname(__file__)+'/cat','*.jpg')) img = {} debug = True a_num = 0 for fn in glob(join(targetdir, '*')): filename = basename(fn) trainpic.append(cv2.imread(fn, 0)) img_rgb = cv2.imread(fn) img = cv2.imread(fn, 0) image_close = cv2.morphologyEx(img_rgb, cv2.MORPH_CLOSE, np.ones((1, 7), np.uint8)) #if debug: # cv2.imshow('morphology', image_close) # key = cv2.waitKey(0) _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) samples = np.empty((0, 100)) responses = [] # keys = [i for i in range(48, 58)] tmp_list = [] tmpcount = 0 for cnt in contours: print 'contourarea:%s' % cv2.contourArea(cnt) if cv2.contourArea(cnt) &gt; 130: # 50 300 [x, y, w, h] = cv2.boundingRect(cnt) print 'boundingRect width:%s' % w print 'boundingRect height:%s' % h if h &gt; 28: cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (0, 0, 255), 2) roi = img[y:y+h, x:x+w] roismall = cv2.resize(roi, (45, 55)) if debug: cv2.imshow('norm', img_rgb) key = cv2.waitKey(0) # tmp_list.append(roi) tmpfilename = fn if tmpcount == 0 else fn.rsplit('.', 1)[0] + '_' + str(tmpcount) + '.png' cv2.imwrite(tmpfilename, roismall) tmpcount += 1 else: print 'contarea less, skip...' # print img[num].shape a_num += 1 print '%s images processed' % a_num So, its fine to handle letters with inter space like this guy(split to D and B): However, failed to segment connected letters like this: I googled a lot for connected letters and find related links like these two: enter link description here enter l…
tagged with: opencv
score: 3
answer count: 0
linked to: http://stackoverflow.com/q/20194103
has comment: http://stackoverflow.com/comment/82106014
tagged with: image-processing
downvote count: 1
tagged with: ocr
favorite count: 0
type: Question

http://stackoverflow.com/q/47599036
tagged with: python
has answer: http://stackoverflow.com/a/47599756
has title: Calculate average number of visits in last week per id without looping
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47599512
answer count: 2
type: UnansweredQuestion
has body: I have a pandas dataframe with id, date, and number of visits. How to calculate average number of visits in past 7 days (from a given date) per id without looping over every observation in dataframe? The panel is unbalanced, i.e. some dates are missing, so we are not always avaraging over 7. id date visit avg_past_week 0 1 11/03/2017 10 0.0 1 1 11/12/2017 11 0.0 2 1 11/14/2017 12 11.0 3 1 11/15/2017 8 11.5 I need to calculate the last column. Plus, there are many different id's.
downvote count: 0
score: 1
upvote count: 1
tagged with: pandas

http://stackoverflow.com/comment/82226107
comment on: http://stackoverflow.com/q/47612822
has text: I was unable to read in using the pandas read_json function. Thanks I corrected indentation. You can see actual API response via Example Response link
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/78858326
has body: In C# this didn't work for me anymore. In Selenium 4 you can configure now the LogLevel by a SetLevel call, see https://www.selenium.dev/documentation/webdriver/troubleshooting/logging
answers question: http://stackoverflow.com/q/47649125
score: 0
type: Answer

http://stackoverflow.com/comment/82329602
score: 0
has text: I appreciate your answer. I put new_row = [0]*c_trans in i for-loop and fix this problem. Thank you very much.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47677190

http://stackoverflow.com/comment/82061136
comment on: http://stackoverflow.com/a/47552190
type: Comment
score: 0
type: AnswerComment
has text: oh ok, found it! Thanks again @jezrael!

http://stackoverflow.com/a/47543827
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47543631
accepted answer of: http://stackoverflow.com/q/47543631
type: AcceptedAnswer
downvote count: 0
has body: From Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015: Functions like x.append("something") and x.remove("something") mutate a value, and change their values. However, using x=x+["something"] or x=x[:-1] rebind a reference, and create a new value which the variable now points to. Thanks to @timgeb for commenting the video!
upvote count: 1
has comment: http://stackoverflow.com/comment/82044859

http://stackoverflow.com/q/47569054
has body: Recently I am doing animation using python with matplotlib. In the beginning I followed the example searched in the net, which has the following structure: ========================================================================= import matplotlib.pyplot as plot import matplotlib.animation as anim def animate(i): ax.clear() # Re-plot the figure with updated animation data if __name__ == "__main__": fig, ax = plot.subplots(fsigsize=(8,4)) an = anim.FuncAnimation(fig, animate, interval=1) plot.show() ========================================================================= This code seems ok. There is no memory leaks. But the problem is that it runs too slow. Because when re-generating the plot with updated animation data, all the settings of the plot (e.g., set_xlim(), set_ylim(), ploting axes, .... etc) have to be done again and again. Hence I tried to improve the performance in this way: ======================================================================== import matplotlib.pyplot as plot import matplotlib.animation as anim def init(): ax.set_title("....") ax.set_xlim(-1, 1) ax.set_ylim(-10,10) # plot axes, and all the patterns which are fixed in the animation def animate(i): # x[] and y[] are large arrays with updated animation data if ('la' in globals()): la.remove() la, = ax.plot(x, y) if __name__ == "__main__": fig, ax = plot.subplots(figsize=(8,4)) an = anim.FuncAnimation(fig, animate, init_func=init, interval=1) plot.show() ======================================================================== In this way only the major curve "la" is re-ploted. The other fixed parts are done only once in the init() subroutine. Now the animation runs much faster. But serious memory leak appears. Running "top" during animation, I saw that the occupied memory continuously grows up. After testing, I am sure that this statement is the source of memory leaks: la, = ax.plot(x, y) Some discussions indicated that the memory leak is due to the plot "ax" is not closed. But if I do …
downvote count: 1
favorite count: 0
type: Question
has title: Memory leaks in animation using matplotlib with performance consideration
type: UnansweredQuestion
score: 1
tagged with: matplotlib
tagged with: animation
has comment: http://stackoverflow.com/comment/82097113
tagged with: python
has answer: http://stackoverflow.com/a/47570364
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/82077379
comment on: http://stackoverflow.com/q/47557494
score: 0
has text: yeah you should be able to find a tutorial on that. I had the same issue when I tried to save images in batch via javascript. If the files appear in your python view, then there is not much left. Not sure though how exactly, but search for something like "batch upload images django [javascript]"
type: Comment
type: QuestionComment

pycharm
tags question: http://stackoverflow.com/q/47693595
tags question: http://stackoverflow.com/q/47600126
tags question: http://stackoverflow.com/q/47697482
tags question: http://stackoverflow.com/q/47572800
tags question: http://stackoverflow.com/q/47619710
tags question: http://stackoverflow.com/q/47682929
tags question: http://stackoverflow.com/q/47633807
tags question: http://stackoverflow.com/q/47629161
tags question: http://stackoverflow.com/q/47656242
tags question: http://stackoverflow.com/q/47638272
tags question: http://stackoverflow.com/q/47583111
tags question: http://stackoverflow.com/q/47675184
tags question: http://stackoverflow.com/q/47675151
tags question: http://stackoverflow.com/q/47640568
tags question: http://stackoverflow.com/q/47578717
tags question: http://stackoverflow.com/q/47640887
tags question: http://stackoverflow.com/q/47692094
tags question: http://stackoverflow.com/q/47603588
tags question: http://stackoverflow.com/q/47626431
tag name: pycharm
tags question: http://stackoverflow.com/q/47653484
tags question: http://stackoverflow.com/q/47673101
type: Tag
tags question: http://stackoverflow.com/q/47670839
tags question: http://stackoverflow.com/q/47633701
tags question: http://stackoverflow.com/q/47555014
tags question: http://stackoverflow.com/q/47568878
tags question: http://stackoverflow.com/q/47684246
tags question: http://stackoverflow.com/q/47620089
tags question: http://stackoverflow.com/q/47625526
tags question: http://stackoverflow.com/q/47677560
tags question: http://stackoverflow.com/q/47590564
tags question: http://stackoverflow.com/q/47586571
tags question: http://stackoverflow.com/q/47623037
tags question: http://stackoverflow.com/q/47655945
tags question: http://stackoverflow.com/q/47564464

http://stackoverflow.com/q/47582434
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82122504
has answer: http://stackoverflow.com/a/47587635
favorite count: 0
has body: I have been working with Python 2 and Db2. Changing to Python 3 the same library doesn't seem to work. What can I do?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82122501
type: UnansweredQuestion
downvote count: 2
tagged with: db2
tagged with: python
score: -1
has title: Where can I find a Python 3-compatible library for Db2?
has comment: http://stackoverflow.com/comment/82761977
has comment: http://stackoverflow.com/comment/82122565

http://stackoverflow.com/a/47576804
type: Answer
has body: Putting together what we discussed in the comments: You have to one-hot encode because the network architecture requires you to, not because it's Tensorflow's demand. The network is a N-class classifier, so the final layer will have one neuron per class and you'll train the network to activate the neuron matching the class the sample belongs to. One-hot encoding the label is the first step in doing this. About the human-readable labels, the code you're referring to is located in the _find_image_files function, which in turn is used by _process_dataset to transform the dataset from a set of folders to a set TfRecord files, which are a convenient input format type for Tensorflow. The human-readable label string is included as a feature in the Examples inside the tfrecord files as an 'extra' (probably to simplify visualization of intermediate results during training), it is not strictly necessary for the dataset and will not be used in any way in the actual optimization of the network's parameters.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47571018
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47571018

http://stackoverflow.com/comment/82331649
type: AnswerComment
has text: Thanks...that's makes sense...the use of threads crossed my mind but i've never used them. I guess its time i learn how... I removed while loop in main and added ontimer. it works but the s13 stops moving while the player is "jumping".
type: Comment
comment on: http://stackoverflow.com/a/47682726
score: 0

http://stackoverflow.com/a/68847786
has body: As specified by the error use: whitelist_externals = &lt;your command&gt; e.g. my external command is curl then tox.ini looks like [tox] envlist = py3 isolated_build = True [testenv] whitelist_externals = curl deps = pytest chispa pyspark requests requests-mock commands = curl url/hadoop-aws-3.2.0.jar --output ../lib/jars/hadoop-aws-3.2.0.jar curl url/aws-sdk-java-2.jar --output ../lib/jars/aws-sdk-java-2.jar python3 -m pytest
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47642747

http://stackoverflow.com/q/47640449
has body: When running the following code in python 2.7: import numpy I get the result: ImportError: No module named numpy I have however got numpy installed for python 2.7, which is seen when running the following in terminal: pip install numpy I get the following: Requirement already satisfied: numpy in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages Working on macOS10.13.1 What am I missing? Any help will be greatly appreciated!
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47640506
tagged with: python-2.7
linked to: http://stackoverflow.com/q/35929306
upvote count: 0
has title: Can't import numpy in python 2.7
answer count: 1
has comment: http://stackoverflow.com/comment/82239334

http://stackoverflow.com/q/47556065
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82070551
tagged with: python
linked to: http://stackoverflow.com/q/23001156
has comment: http://stackoverflow.com/comment/82070036
has body: I am trying to create the following document in the mongo db but for some reason the document saving the issue object before the data (i presume the default order is by key length). i would like that the issues object will be in the end of the document. i am using PyMongo from flask_pymongo, i also try the following solution: https://stackoverflow.com/a/30787769/5494424 I try to work with bson and OrderedDict but without success this is how i create the dict code in python: gold_apple_report = { "_id": "", "updated_on": "", "data": { "sms": { "status": "todo" }, "catchapp": { "status": "todo" }, "telegram": { "status": "todo" }, "bookmarks": { "status": "todo" }, "calendar": { "status": "todo" }, "call_history": { "status": "todo" }, "contacts": { "status": "todo" }, "files": { "status": "todo" }, "downloads": { "status": "todo" }, "notes": { "status": "todo" }, "posts": { "status": "todo" }, "app_list": { "status": "todo" }, "media": { "status": "todo" }, "locations": { "status": "todo" }, "chats": { "whatsapp": { "status": "todo" }, "telegram": { "status": "todo" }, "skype": { "status": "todo" }, "line": { "status": "todo" }, "viber": { "status": "todo" }, "facebook": { "status": "todo" }, "twitter": { "status": "todo" }, "instagram": { "status": "todo" } } }, "issues": { } } and this is how it appear in the mongoDb: gold_apple_report = { "_id": "", "updated_on": "", "issues": { }, "data": { "sms": { "status": "todo" }, "catchapp": { "status": "todo" }, "telegram": { "status": "todo" }, "bookmarks": { "status": "todo" }, "calendar": { "status": "todo" }, "call_history": { "status": "todo" }, "contacts": { "status": "todo" }, "files": { "status": "todo" }, "downloads": { "status": "todo" }, "notes": { "status": "todo" }, "posts": { "status": "todo" }, "app_list": { "status": "todo" }, "media": { "status": "todo" }, "locations": { "status": "todo" }, "chats": { "whatsapp": { "status": "todo" }, "telegram": { "status": "todo" }, "skype": { "status": "todo" }, "line":…
score: 0
answer count: 0
has title: How to keep order of dict in PyMongo
tagged with: pymongo
has comment: http://stackoverflow.com/comment/82070154
has comment: http://stackoverflow.com/comment/82070951
has comment: http://stackoverflow.com/comment/82069391
type: Question
duplicate of: http://stackoverflow.com/q/23001156

http://stackoverflow.com/comment/82316324
type: Comment
comment on: http://stackoverflow.com/q/47676466
type: QuestionComment
has text: I have never managed to save and load a model in keras.... so I keep the code and use `model.save_weights()` and `model.load_weights()` instead. -- The price is losing the optimizer state.
score: 1

http://stackoverflow.com/a/47618317
accepted answer of: http://stackoverflow.com/q/47617611
has body: Break down the problem into pieces. Start off by making a function that checks if one string is in a sequence of strings: def check_one(string, seqs): for seq in seqs: if string not in seq: return False return True Then make a function that checks all strings by using this function: def check_all(strings, seq): result = [] for string in strings: if check_one(string, seq): result.append(string) return result Then simply call check_all(): short_str_list = ["aga", "ttt", "aca"] seq_list = ["atcgcgtacat", "acatcgggattt", "tttacagtgtgtggg"] print(check_all(short_str_list, seq_list)) # ['aca'] You can also use all() , filter() and list comprehensions to to do this in one line: print([x for x in short_str_list if all(x in y for y in seq_list)]) # ['aca'] print(list(filter(lambda x: all(x in y for y in seq_list), short_str_list))) # ['aca']
answers question: http://stackoverflow.com/q/47617611
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47682907
has comment: http://stackoverflow.com/comment/82427644
has comment: http://stackoverflow.com/comment/82327638
has comment: http://stackoverflow.com/comment/82327737
score: 2
upvote count: 2
downvote count: 0
has body: Instead of for i in range(numPlayers): self.team2players.append(Player(self.composition['point guard'], ...)) you can use for with dictionary self.team2players = []# for position, name in self.composition.items(): #print(position, name) self.team2players.append(Player(name, ...)) BTW: Because you have only one player in self.composition so it will create only one player in self.team2players. Dictionary doesn't keep order so when you will have more players in self.composition then for ... in self.composition may create players in different order. EDIT: When I look at Player(self.composition['point guard'], then it seems you have only one string assigned to self.composition['point guard'] and previous code should works, but when I look on your dictionary it seems you have list with many names assigned to self.composition['point guard']: self.composition = { 'point guard' : [], 'shooting guard': [], 'small forward': [], 'power forward': [], 'centre': [] } and it means you need two for loops self.team2players = []# for position, names_list in self.composition.items(): #print(position, names_list) for name in names_list: #print(name) self.team2players.append(Player(name, ...)) EDIT: If you will keep only one name for every position then you don't need list but you can use string with name or empty string (or None) if there is no name. self.composition = { 'point guard' : None, 'shooting guard': None, 'small forward': None, 'power forward': None, 'centre': None } and you assign name without append() self.composition['point guard'] = 'Jose Calderon' and to create player you need use if to check None self.team2players = [] for position, name in self.composition.items(): if name: # the same as `if (name is not None) and (name != "") and (name != 0) and (name != False) ...: self.team2players.append(Player(name, ...)) #else: # print("you don't have player on position", position)
has comment: http://stackoverflow.com/comment/82327305
answers question: http://stackoverflow.com/q/47682662
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82327038
accepted answer of: http://stackoverflow.com/q/47682662
has comment: http://stackoverflow.com/comment/82326903
type: Answer

http://stackoverflow.com/comment/82165042
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47603069
has text: Please show the contents of your runtime.txt.

http://stackoverflow.com/comment/82047149
type: Comment
score: 0
has text: Also, why are you not just comparing datetime objects?
type: QuestionComment
comment on: http://stackoverflow.com/q/47545090

http://stackoverflow.com/comment/82153473
score: 0
has text: @FJSevilla Thanks a lot for your comment, and I have attached a simple sample, it seems the objectName() does not work well with the MDIarea subwindow. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/47583630
type: QuestionComment

http://stackoverflow.com/a/47617311
upvote count: 1
has comment: http://stackoverflow.com/comment/82438272
type: AcceptedAnswer
has body: This is an open issue in you can see it here: https://github.com/pydata/pandas-datareader/issues/424 This is how i solved based on the comments from github: Check if GoogleDailyReader.url() in pandas_datareader/google/daily.py returns 'http://www.google.com/finance/historical'. If so, change it to 'http://finance.google.com/finance/historical'. (www -> finance) The return value of GoogleDailyReader.url() was 'http://www.google.com/finance/historical' when I downloaded pandas-datareader in PyCharm yesterday. I don't know why. Test it with: import pandas_datareader as pdr c = pdr.google.daily.GoogleDailyReader() c.url # http://www.google.com/finance/historical' pdr.__version__ # '0.5.0'
accepted answer of: http://stackoverflow.com/q/47617127
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47617127
downvote count: 0

http://stackoverflow.com/comment/82055352
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47549277
type: QuestionComment
has text: Don't add `[Solved]` to qour question title. Wait a moment, then you can accept your own answer

http://stackoverflow.com/a/47558097
type: Answer
has body: If I have understood you correctly, what you want to do is you want to access the IPs sequentially and perform some action after that. I can see the keys in your dictionaries have additional quotes. Try displaying d['4']. It will throw an error. To remove this you should use Python's builtin csv reader module. Something like this should work fine: with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) mydict = {rows[0]:rows[1] for rows in reader} Now let's see how you can loop through the dict. for key in d: serialNo = key correspondingIP = d[serialNo][0] correspondingFilename = d[serialNo][1] This should help you to get rid of extra quotes : Remove quotes in python dictionary Let me know if this helps :)
has comment: http://stackoverflow.com/comment/82150957
has comment: http://stackoverflow.com/comment/82090694
has comment: http://stackoverflow.com/comment/82076600
score: 0
answers question: http://stackoverflow.com/q/47557614
has comment: http://stackoverflow.com/comment/82092331

http://stackoverflow.com/q/47695014
has comment: http://stackoverflow.com/comment/82350455
type: AnsweredQuestion
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/47695718
score: 1
has title: Change type of list elements from numpy.int64 to int
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82349377
linked to: http://stackoverflow.com/q/9452775
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82353013
has answer: http://stackoverflow.com/a/47695093
has body: { "key1" : &lt;list of strings&gt;, "key2" : &lt;list of integeres&gt; } I want to change type of 'key2' list to int. I have already tried looping over and using v = int(v) I have also tried mapping int to whole list. map(int, list) Any other way I can accomplish this task? Current Code: integer_columns = ["col1","col2","col3","col4"] for col in integer_columns: col_list = config_data[col] col_list = list(map(int, col_list))
has answer: http://stackoverflow.com/a/47695718
tagged with: python
accepted answer: http://stackoverflow.com/a/47695093

http://stackoverflow.com/comment/106275402
type: AnswerComment
comment on: http://stackoverflow.com/a/47870079
has text: @Kunal Mukherjee.. can you elaborate step#4 ? where and how to implement this
type: Comment
score: 0

decode
tag name: decode
tags question: http://stackoverflow.com/q/47580337
tags question: http://stackoverflow.com/q/47633936
type: Tag

http://stackoverflow.com/a/47542816
has body: I'm not sure why the documentation even mentions base64, but the function requires bytes. So just use: with open(filename, 'rb') as image_file: image = image_file.read() client.detect_text(Image={'Bytes': image})
type: Answer
downvote count: 0
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/47542341

http://stackoverflow.com/q/47540863
has comment: http://stackoverflow.com/comment/82040430
tagged with: python-2.7
linked to: http://stackoverflow.com/q/29968654
answer count: 0
has comment: http://stackoverflow.com/comment/82039417
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82040117
has comment: http://stackoverflow.com/comment/82040326
has body: I've tried several solutions, but I think I'm not really grasping what format matplotlib wants. I want my x axis to go from the epoch time I'm given, to UTC time shown in a format similar to 8:20pm I only need the hour, minute, and am/pm. The Code import csv import matplotlib.pyplot as plt import time import matplotlib.dates as dates import datetime x = [] y = [] with open('myCSVfile.csv','r') as csvFile: plots = csv.reader(csvFile, delimiter=',') for row in plots: # Removing everything after . in epoch time. epochTime = row[0].split('.', 1)[0] dateTime = time.strftime('%H:%M:%S', time.localtime(float(epochTime))) newDateTime = dates.datestr2num(dateTime) x.append(newDateTime) # Removing everything after . in seconds deltaTime = row[1].split('.', 1)[0] y.append(deltaTime) plt.plot_date(x,y, label="blah") plt.xticks( rotation=25 ) plt.xlabel('') plt.ylabel('deltaTime') plt.title('plot title') The Output The x axis is outputting this format 11-28 20 CSV File header="epoch time", "seconds" 1506113708.561633531,1171.27425957 1506114083.970948133,1382.68399167 1506131461.369560006,403.082466364 1506129829.157526598,588.869942665 1506132085.925451203,303.638436317
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82040347
tagged with: matplotlib
tagged with: datetime
has comment: http://stackoverflow.com/comment/82041902
tagged with: python
has title: How can I show UTC time on x axis of matplotlib
duplicate of: http://stackoverflow.com/q/29968654
type: Question

build
tag name: build
type: Tag
tags question: http://stackoverflow.com/q/47544256

http://stackoverflow.com/a/61532727
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/47584123
has comment: http://stackoverflow.com/comment/109108159
has body: This solution has mainly worked with one exception. After copying the slide over to the destination presentation when I open the destination presentation I get the following warning: PowerPoint couldn't read some content in xxx.pptx and removed it. Please check your presentation to see if the rest of it looks ok. The rest of the presentation does look fine and after saving and reopening the warning goes away. Do you know of a way to make it so this warning doesn't appear or if there is a way to resolve it with Python (saving/closing again?).
score: -2
type: Answer

http://stackoverflow.com/a/47668543
score: 0
has body: If you want to processes to 'talk' to each other, you can use the subprocesses module in the Python Standard Library.
answers question: http://stackoverflow.com/q/47668052
type: Answer

http://stackoverflow.com/comment/82229628
type: AnswerComment
comment on: http://stackoverflow.com/a/47629016
has text: Wow, thank you so much for helping me with the implementation! :) However, when I run this widget with my video, it does not play the video too nicely. Here is the output: [link](https://ibb.co/gAFFEb). And so I thought I would try the second method in your code: proxy = QGraphicsProxyWidget() scene.addItem(proxy) but this just gives me a blank canvas with no video playing in the background. [link](https://ibb.co/guzNSw) Any idea on how to solve these issues? Thank you so much!
score: 0
type: Comment

http://stackoverflow.com/comment/82330136
type: AnswerComment
has text: Alternatively (following on from @jon's comment above), you could create a new instance of an 'Android' class from each row of the database and maintain a list of those instances. Finding a matching android would then be a simple matter of iterating over the list.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47685074

http://stackoverflow.com/a/47551302
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47551029
has body: You can first shorten ModelEntityKeys when importing: from xai.string_constants import ModelEntityKeys as mek then alias self.data_all_entity_dict to something shorter: d = self.data_all_entity_dict self.intercept = d[mek.MODEL_ENTITY_DATA][mek.MODEL_FACTORS][mek.INTERCEPT] But actually what I would do would be to keep all the knowledge about the "data_all_entity_dict" structure in one single place and provide getter methods: class ModelEntity: MODEL_ENTITY_DATA = 'model_entity_data' NETWORK_NAME = 'network_name' MODEL_FACTORS= 'model_factors' CLASSES= 'classes' # etc def __init__(self, data): self.data = data @property def model_entity_data(self): return self.data[self.MODEL_ENTITY_DATA] @property def model_factors(self): return self.model_entity_data[self.MODEL_FACTORS] @property def intercept(self): return self.model_factors[self.INTERCEPT] # etc Then from xai.string_constants import ModelEntity entity = ModelEntity(self.data_all_entity_dict) self.intercept = entity.intercept
answers question: http://stackoverflow.com/q/47551029
type: AcceptedAnswer
type: Answer
upvote count: 3

http://stackoverflow.com/q/47620829
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82201702
has body: I have an api call which according to some passed values such as budget and time , returns a list of projects. There will be 100s of projects with there data passed as a json list of objects. I want to cache this result so that I dont have to connect to the backend database every time. I am using flask python for the api dev. Is this kind of code is sufficent taken from Flask Cache doc: @cache.cached(timeout=50, key_prefix='all_comments') def get_all_comments(): comments = do_serious_dbio() return [x.author for x in comments] cached_comments = get_all_comments() Or is there another way to do that? My return Json is like: { "some_attr" : , "another_attr": , "list of projects": [ {"name": ,"budget" : } ...] }
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82200161
downvote count: 1
has comment: http://stackoverflow.com/comment/82200190
favorite count: 0
type: Question
tagged with: flask-cache
type: UnansweredQuestion
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/82200138
tagged with: caching
has comment: http://stackoverflow.com/comment/82200060
has title: How to properly cache the result of an REST API which returns large number of objects
answer count: 0

http://stackoverflow.com/q/47570247
tagged with: node-red
answer count: 1
favorite count: 0
tagged with: mosca
type: Question
has title: Raspberry Pi as mosca mqtt broker,Node-Red and MongoDB
tagged with: mongodb
has body: I'm working on a school project and I'm a little bit overwhelmed. Is the first time that I work with mqtt service and Node-Red. In the structure of the project I have a Raspberry Pi communicated through gpio with a dht11 sensor, I want to communicate the RPi with my VPS where Node-Red is hosted. Finally this Node-Red working as suscriber in mqtt service has to save the data of measures in a MongoDB database and show the data in a graph. Can someone explain me how to communicate RPi and Node? RPi can work as broker and client in mqtt at the same time? Sorry for my English I'm learning.
type: UnansweredQuestion
upvote count: 0
score: -2
downvote count: 2
tagged with: mqtt
tagged with: python
has comment: http://stackoverflow.com/comment/82120397
has answer: http://stackoverflow.com/a/47665233

http://stackoverflow.com/comment/82175633
has text: `x *= y` is equivalent to `x = x * y`. There are some slight differences in implementation for some types, but that's probably nothing you need to worry about at this stage
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47608612
score: 0

http://stackoverflow.com/a/47668191
type: AcceptedAnswer
score: 0
has body: In steps, mydict['result'] returns [{'abc':1,'xyz':2}] mydict['result'][0] returns {'abc':1,'xyz':2} mydict['result'][0]['xyz'] returns 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47667885
answers question: http://stackoverflow.com/q/47667885

http://stackoverflow.com/q/47655938
score: 2
type: AnsweredQuestion
tagged with: listdir
downvote count: 0
tagged with: operating-system
accepted answer: http://stackoverflow.com/a/47656625
tagged with: file
has title: Unexpected print() and os.listdir() functionality
has body: import os target_dir = "xxx.xxx.xx.xx/path/to/file/dir" start_seq = "*** Start Sequence ***" end_seq = "*** End Sequence ***" def tp_parser(file): with open(file) as in_f: lines = in_f.readlines() f_name = in_f.name[12:16] for i, line in enumerate(lines): if line.startswith(start_seq): start_line = i elif line.startswith(end_seq): end_line = i with open("{0}_Target_Map.txt".format(f_name), "w") as out_f: for i, line in enumerate(lines): if start_line &lt;= i &lt; end_line: print(line) # out_f.write(line) for file in os.listdir(os.chdir(target_dir)): tp_parser(file) I wrote this script to look through a directory of files, extract a specific part of each file and write it out to a separate text file. Curious if someone can shine some light on what is happening here... For this part: if start_line &lt;= i &lt; end_line: print(line) # out_f.write(line) If I run the script with print(line) I get back a "UnboundLocalError: local variable 'end_line' referenced before assignment" error. However, running the script with the out_f.write(line) works as intended. Second slightly less annoying problem is this part: for file in os.listdir(os.chdir(target_dir)): tp_parser(file) I can't explain to myself why I have to switch to the working directory(i.e. os.chdir(target_dir)) to actually iterate through the files. I'm aware the os.listdir() by itself returns a list of file names but how is that any different if you pass a os.chdir() argument in os.listdir(). Thanks in advance.
type: Question
upvote count: 2
tagged with: chdir
has answer: http://stackoverflow.com/a/47656625
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/a/47574474
type: AcceptedAnswer
has body: To create the dict you need to apply .to_dict() on a series. Do that by choosing which column, col2 in this case, after set_index. dict_test = df.set_index('col1')['col2'].to_dict() This works because: type(df.set_index('col1')['col2']) == 'pandas.core.series.Series'
accepted answer of: http://stackoverflow.com/q/47552875
type: Answer
answers question: http://stackoverflow.com/q/47552875
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/82143526
type: Comment
score: 0
type: AnswerComment
has text: Thank you. This may solve my problems. I added `log` and `verify` to `scope`. Not `a` as that is a test case local variable. Now my small example works. I did not use the wrapper function, but for some reason `a` is found anyway.
comment on: http://stackoverflow.com/a/47593117

http://stackoverflow.com/comment/82325950
comment on: http://stackoverflow.com/q/47683063
has text: You can't rely on time zone strings because they aren't unique world-wide.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82050103
comment on: http://stackoverflow.com/q/47546510
score: 0
type: Comment
type: QuestionComment
has text: No, this is a QA site, not a free tutoring site. Start with the documentation, google it and if you have many unsuccessful attempts, and google doesn't help, post a question here or open an issue on the repo's github page. Thsi should get you going: https://openpyxl.readthedocs.io/en/default/usage.html#read-an-existing-workbook

http://stackoverflow.com/comment/82303325
type: AnswerComment
has text: @ShekharKoirala Happy to help. Don't forget to accept and upvote the answer :)
comment on: http://stackoverflow.com/a/47670769
type: Comment
score: 0

http://stackoverflow.com/q/47657531
score: 1
favorite count: 0
type: Question
has title: Pyspark inverted index
answer count: 2
accepted answer: http://stackoverflow.com/a/47679402
possible better answer: http://stackoverflow.com/a/47657726
tagged with: pyspark
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47679402
has answer: http://stackoverflow.com/a/47657726
has body: I am creating an inverted index of documents, where the output should contain a word (from the text file) followed by all the files it appeared in. Something like [word1: file1.txt file2.txt] [word2: file2.txt file3.txt] I have written the code but it throws me this error. for k, v in iterator: TypeError: () takes exactly 2 arguments (1 given) Code: from pyspark import SparkContext sc = SparkContext("local", "app") path = '/ebooks' rdd = sc.wholeTextFiles(path) output = rdd.flatMap(lambda (file,contents):contents.lower().split())\ .map(lambda file,word: (word,file))\ .reduceByKey(lambda a,b: a+b) print output.take(10) I cannot figure out a way to emit both key and value (word and the filename) in the map. How can i go about it? In mapreduce, the (word, key) pair can be emitted (key is the filename) but how can this be done in spark?
type: AnsweredQuestion
tagged with: apache-spark

http://stackoverflow.com/q/47625821
score: 0
has answer: http://stackoverflow.com/a/47625935
answer count: 1
downvote count: 1
favorite count: 0
tagged with: knn
type: Question
has body: I'm trying to use Knn on a sample of leaf features. there are 990 row for 194 columns. The second columns is fill with the tree name where leaf come from, it will be the label. from sklearn import model_selection from sklearn.preprocessing import LabelEncoder from sklearn import preprocessing from sklearn import neighbors, metrics X = data.iloc[:, 2: 194] y = data.iloc[:,1] labelencoder = LabelEncoder() y = labelencoder.fit_transform(y) #separate train and test data X_train, X_test, y_train, y_test = \ model_selection.train_test_split(X, y , test_size=0.3) std_scale = preprocessing.StandardScaler().fit(X_train) X_train_std = std_scale.transform(X_train) X_test_std = std_scale.transform(X_test) param_grid = {'n_neighbors':[3,5,7,9,11,13,15]} score = 'accuracy' clf = model_selection.GridSearchCV(neighbors.KNeighborsClassifier(), param_grid, cv=5, scoring=score) #here i got the following error clf.fit(X_train_std, y_train) C:\Users\chrys\Anaconda3\lib\site-packages\sklearn\model_selection_split.py:581: Warning: The least populated class in y has only 4 members, which is too few. The minimum number of groups for any class cannot be less than n_splits=5. % (min_groups, self.n_splits)), Warning) I got that when "cv" >4, "cv" is how many part we have during the crossvalidation. I don't understand because my sample should be widely big enough for being divided by even 10. Here the link of the sample : leaf-sample thank you in advance for any help
tagged with: classification
upvote count: 1
tagged with: scikit-learn
tagged with: python
has title: Scikit-Learn : Error on K-nn Crossvalidation (the least populated class ...)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47625935

http://stackoverflow.com/q/47611418
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/48876126
has title: Neural Network with Sigmoid activation produces all 1's
score: 0
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/82184715
has comment: http://stackoverflow.com/comment/82190070
answer count: 1
has body: I am trying to implement a Convolutional Neural Network in python. The architecture is as follows: INPUT-&gt;[Convolution-&gt;Sigmoid-&gt;Pooling]-&gt;[Convolution-&gt;Sigmoid-&gt;Pooling]-&gt;Fully Connected Layer-&gt; Hidden Layer-&gt;Ouput. input shape: 28*28 Filters/weights shape for COnvolutional layer1: 20*1*5*5 Filters/weights shape for COnvolutional layer2: 40*20*5*5 Activation Function: Sigmoid (1/(1+e^-x)) Due to the large shape of filters/weights, while applying the dot product in COnvolutional Layer 2, the resulting output values are near to 20 or higher which is subsequently resulting in the output after sigmoid activation function values to be all 1's. Output at COnvolutional layer1: [ 0.75810452 0.79819809 0.70897314 0.50897858 0.02901152 0.98447587 0.99995668 0.99999814 0.99912627 0.7885211 0.87708188 0.76611807] ... ... Output at COnvolutional layer2: [ 19.88641441 20.11005634 20.04984707 20.19106394 19.93096274 20.1585536 19.84757161 19.79030395] ... ... output after applying sigmoid on convlayer2: [ 1. 1. 1. 1. 1. 1. 1. 1.] ... ... [ 1. 1. 1. 0.99999 1. 1. 1. 1.] I have found a similar question on this forum: Neural Network sigmoid function . I did not commit the mistakes pointed out in the Tim's answer. But what i couldn't figure out was this: Finally, even with these changes, a fully-connected neural network with all positive weights will probably still produce all 1's for the output. You can either include negative weights corresponding to inhibitory nodes, or reduce connectivity significantly (e.g. with a 0.1 probability that a node in layer n connects to a node in layer n+1). Should i normalize the output after applying sigmoid on convlayer2? or try something else? EDIT: Input data: [[ 3. 0. 0. 3. 7. 3. 0. 3. 0. 11. 0. 0. 3. 0. 0. 3. 8. 0. 0. 3. 0. 0. 0. 2. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 1. 5. 0. 12. 0. 16. 0. 0. 4. 0. 2. 8. 3. 0. 4. 8. 0. 0. 0. 0. 0.] [ 0. 0. 2. 0. 0. 0. 1. 2. 1. 12. 0. 8. 0. 0. 6. 0. 11. 0. 0. 6. 7. 2. 0. 0. 0. 0. 0. 0…
tagged with: sigmoid
type: Question
linked to: http://stackoverflow.com/q/24967484

http://stackoverflow.com/q/47626223
has comment: http://stackoverflow.com/comment/82210288
has comment: http://stackoverflow.com/comment/82210329
has comment: http://stackoverflow.com/comment/82210245
has title: Str.Contains show only True values
has answer: http://stackoverflow.com/a/47627240
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/82210314
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82210459
has body: I am using str.contains on a large dataframe and I need a way such that str.contains returns the records where my str.contains function is True. (the dataframe is several thousand lines long and I am looking for 8 true responses). Thanks! aa = filtered_to_df.body.str.contains('AA') aa.head(10) Out[312]: 15864 False 18040 False 22576 False 28092 False 32800 False 33236 False 38027 False 41222 False 46647 False 87645 False Name: body, dtype: bool
type: UnansweredQuestion
tagged with: contain
tagged with: python
has comment: http://stackoverflow.com/comment/82210242
has comment: http://stackoverflow.com/comment/82210193
has comment: http://stackoverflow.com/comment/82210267
has comment: http://stackoverflow.com/comment/82210255
upvote count: 3

python-telegram-bot
tags question: http://stackoverflow.com/q/47636534
tags question: http://stackoverflow.com/q/47598550
tag name: python-telegram-bot
type: Tag
tags question: http://stackoverflow.com/q/47641314

http://stackoverflow.com/comment/82143421
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47590890
score: 0
has text: @dsgdfg Where can I find the src path ?

http://stackoverflow.com/comment/82164227
comment on: http://stackoverflow.com/a/47602245
score: 0
type: Comment
has text: but what you write: _iteration is faster than recursion_, does then not make much sense
type: AnswerComment

http://stackoverflow.com/a/47643548
answers question: http://stackoverflow.com/q/47642398
score: 0
has body: Given a document, it is trivial to find if a word is in it: &gt;&gt;&gt; "plump" in open("ulysses.txt", 'r').read() True The same approach can be taken with a more elaborate query: &gt;&gt;&gt; query = ["Stately", "plump", "Buck", "Mulligan"] &gt;&gt;&gt; [_ in open("ulysses.txt", 'r').read() for _ in query] [True, True, True, True] The last hint that I'll give, is that the all(iterable) function returns True if the iterable is empty, or if bool(x) evaluates to True for all its values . &gt;&gt;&gt; all([_ in open("ulysses.txt", 'r').read() for _ in query]) True &gt;&gt;&gt; all([_ in open("dubliners.txt", 'r').read() for _ in query]) False And you should have no problem extending this approach to examine more documents.
type: Answer

http://stackoverflow.com/q/47693969
has title: Error in Mongoimport due to the db
has comment: http://stackoverflow.com/comment/82347272
tagged with: pymongo
has comment: http://stackoverflow.com/comment/82347190
has comment: http://stackoverflow.com/comment/82347388
has comment: http://stackoverflow.com/comment/82347112
has comment: http://stackoverflow.com/comment/82347257
tagged with: python
tagged with: jupyter
type: Question
has body: I am a beginner in python and mongodb. I want to import json file named club_members.json to the database which the database didn't exist yet. As far as I know, mongodb will create the db name automatically when the code is run. Here is my code def get_collection(): client = MongoClient('mongodb://localhost:27017') db = client.club mongoimport --db club --colletion members_collection --type json --file club_members.json return None The db variable is made for making database named club which didn't exist yet. But then, it gave me errors like this mongoimport --db club --colletion members_collection --type json --file club_members.json ^ SyntaxError: invalid syntax When I am checking the database list by using client.database_names() function, it returns no club database. So, I think this error is caused by the existence of the db. What should I do to fix it?
score: 0
tagged with: mongodb
answer count: 0
has comment: http://stackoverflow.com/comment/82347304
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82347063

http://stackoverflow.com/comment/82126040
score: 1
type: Comment
has text: I was sure there's a solution using `sorted()`. Looks very neat and simple, thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/47584080

http://stackoverflow.com/comment/82172378
type: Comment
type: QuestionComment
has text: I have two guesses that may be helpful: (1) you should put an ending semicolon at the end of the query, and (2) try to change args into a list, not a tuple.
score: 2
comment on: http://stackoverflow.com/q/47607002

http://stackoverflow.com/q/47607180
favorite count: 0
has title: Python: Delete letters in word which occur more than N times consecutively
has comment: http://stackoverflow.com/comment/82172718
type: Question
has answer: http://stackoverflow.com/a/47607387
has body: Let's say that I have a sentence: sentence = "Eveeery mondayyy I waaake upp" I would like to create a function which deletes all letters which occur more than N times consecutively in a word. So, if I say: N = 2 the result should be: result = Eveery mondayy I waake upp How can I do this in an efficient way ?
has comment: http://stackoverflow.com/comment/82172741
has comment: http://stackoverflow.com/comment/82172767
has answer: http://stackoverflow.com/a/47607319
tagged with: python
has comment: http://stackoverflow.com/comment/82172852
score: -3
tagged with: text
accepted answer: http://stackoverflow.com/a/47607387
has answer: http://stackoverflow.com/a/47607325
has comment: http://stackoverflow.com/comment/82172715
answer count: 4
downvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47607319
has answer: http://stackoverflow.com/a/47607507
upvote count: 1

http://stackoverflow.com/a/47656391
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47656153
has body: The following might give you an idea. It uses an OrderedDict assuming that you want the items in the order of appearance from the original list: from collections import OrderedDict d = OrderedDict() for x, y in zip(l1, l2): d.setdefault(x, []).get(x).append(y) # OrderedDict([('John', [1, 3]), ('Bob', [4]), ('Stew', [7])]) names, values = zip(*((k, sum(v)/len(v)) for k, v in d.items())) # ('John', 'Bob', 'Stew') # (2.0, 4.0, 7.0)
score: 1

http://stackoverflow.com/a/47553564
has comment: http://stackoverflow.com/comment/82064416
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/82064597
has comment: http://stackoverflow.com/comment/82064695
has body: here is another way you can do it import subprocess from subprocess import Popen,CREATE_NEW_CONSOLE command ='cmd' prog_start=Popen(command,creationflags=CREATE_NEW_CONSOLE) pidvalue=prog_start.pid #this will kill the invoked terminal subprocess.Popen('taskkill /F /T /PID %i' % pidvalue)
type: Answer
answers question: http://stackoverflow.com/q/47548242
score: 4

http://stackoverflow.com/a/47591703
score: 3
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47590906
has body: From Flask-RESTful documentation [1]: Alternatively, you can specify a dictionary of iterables that map to HTTP methods and the decorators will only apply to matching requests. def cache(f): @wraps(f) def cacher(*args, **kwargs): # caching stuff return cacher class MyResource(restful.Resource): method_decorators = {'get': [cache]} def get(self, *args, **kwargs): return something_interesting(*args, **kwargs) def post(self, *args, **kwargs): return create_something(*args, **kwargs) In your case it would be: method_decorators = {'post': [auth.login_required]}
answers question: http://stackoverflow.com/q/47590906

http://stackoverflow.com/q/47603024
has comment: http://stackoverflow.com/comment/82165004
favorite count: 0
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47629009
accepted answer: http://stackoverflow.com/a/47629009
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82169565
has body: I'm trying to create a Webots simulation where I want my robot to speak when the Kinect camera detects a person. I have a Kinect V2 hooked up to the USB port and it can detect a person on its own by running my Python code using PyKinect2 and pygame. As the next step, I put that code into the Webots environment and I've added a robot to speak to the user when Kinect detects them. However, when the Kinect starts running and the window pops up, Webots clock stops ticking and the robot doesn't do anything. After I close the Kinect window, the robot speaks the message but that code should have been executed inside the Kinect code, as listed below. I believe this might be a synchronization issue due to Kinect and Webots having their own clocks, but I'm not sure. Even if that's the case, I don't know how to proceed. Any advice is welcome. Here are the relevant parts of my code, I can provide the full code if needed. The Kinect body detection is a slightly modified version of this example: class BodyGameRuntime(object): # ----- other functions here ----- def run(self): # -------- Main Program Loop ----------- while not self._done: # --- frame and window resize logic here # --- Draw skeletons to _frame_surface if self._bodies is not None: # ---------- Body Found ---------- speaker.speak("User detected!", volume=1.0) # Speak to the user for i in range(0, self._kinect.max_body_count): body = self._bodies.bodies[i] if not body.is_tracked: continue joints = body.joints # convert joint coordinates to color space joint_points = self._kinect.body_joints_to_color_space(joints) self.draw_body(joints, joint_points, SKELETON_COLORS[i]) # --- copy back buffer logic here # --- Update the screen with what we've drawn. pygame.display.update() pygame.display.flip() # --- Limit to 30 frames per second self._clock.tick(30) # Close our Kinect sensor, close the window and quit. self._kinect.close() pygame.quit() robot = Robot() speaker = Speaker("Speaker") #timestep = int(robot.getBasicTimeStep…
has comment: http://stackoverflow.com/comment/82167466
has title: Webots robot doesn't speak while trying to use it with an external Kinect
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82165046
tagged with: webots
score: 1
upvote count: 1
tagged with: kinect-v2
tagged with: pygame
has comment: http://stackoverflow.com/comment/82165197

http://stackoverflow.com/q/47629570
type: Question
score: 131
has comment: http://stackoverflow.com/comment/105822827
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57041100
has comment: http://stackoverflow.com/comment/102573700
has answer: http://stackoverflow.com/a/48722050
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/58125072
answer count: 13
downvote count: 1
upvote count: 132
has title: How to resolve "dyld: Library not loaded: @executable_path.." error
has answer: http://stackoverflow.com/a/59207908
tagged with: executable-path
has answer: http://stackoverflow.com/a/48089691
has answer: http://stackoverflow.com/a/67575685
has answer: http://stackoverflow.com/a/47653452
has answer: http://stackoverflow.com/a/71656535
has answer: http://stackoverflow.com/a/71784715
linked to: http://stackoverflow.com/q/23233252
has answer: http://stackoverflow.com/a/78606712
has body: I was trying to check the AWS-CLI version on my MAC OS X. And the below error hit back: dyld: Library not loaded: @executable_path/../.Python Referenced from: /usr/local/aws/bin/python Reason: image not found Abort trap: 6 Any relevant inputs on how to fix this would be highly appreciated.
has answer: http://stackoverflow.com/a/71410749
has answer: http://stackoverflow.com/a/51136525
tagged with: dyld
favorite count: 0
has answer: http://stackoverflow.com/a/58191750

http://stackoverflow.com/a/47639429
has comment: http://stackoverflow.com/comment/82237970
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47639347
has comment: http://stackoverflow.com/comment/82238023
has body: You can also use numpy.clip: &gt;&gt;&gt; np.clip(v, 3, None) array([3, 4, 3, 7, 9, 3, 5]) The second argument is a maximum, but I've given it only a minimum. This can also be provided with an out argument, in this case, if you supply itself as the target, it will work in-place: &gt;&gt;&gt; x = np.clip(v, 3, None, v) &gt;&gt;&gt; id(x), id(v) (4357557104, 4357557104) &gt;&gt;&gt; v array([3, 4, 3, 7, 9, 3, 5]) &gt;&gt;&gt; The docs: out : ndarray, optional The results will be placed in this array. It may be the input array for in-place clipping. `out` must be of the right shape to hold the output. Its type is preserved. This could potentially be useful if you are memory constrained (I believe no intermediate boolean array gets created).
type: Answer
has comment: http://stackoverflow.com/comment/82237774

http://stackoverflow.com/a/47664542
type: Answer
answers question: http://stackoverflow.com/q/47664319
score: 0
has body: To be as generic as possible, you can try this: class Interval(): def __init__(self,left,*args): if args: self.left=left self.right=args else: self.left=left self.right=left def __repr__(self): return("[{},{}]".format(self.left,','.join(map(str, self.right)))) i = Interval(4, 4) print(i) Output: [4,4]

http://stackoverflow.com/comment/82151639
score: 0
has text: What makes you think that this is what's slowing your code down?
type: Comment
comment on: http://stackoverflow.com/q/47596837
type: QuestionComment

http://stackoverflow.com/a/47619597
has body: You need len(group) for size of groups: db=table.groupby(['Type','Quarter']) .filter(lambda group: len(group) &gt; 3) .groupby(['Type','Quarter'])["Price"] .mean() Or use transform: db=table[table.groupby(['Type','Quarter'])['Type'].transform('size') &gt; 3] .groupby(['Type','Quarter'])["Price"].mean()
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47619540
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47619540

http://stackoverflow.com/comment/82163089
type: AnswerComment
has text: @ZerefDragneel If the answer helped, please consider upvoting it so more people can find the answer if they have the same problem
score: 0
comment on: http://stackoverflow.com/a/47602077
type: Comment

http://stackoverflow.com/comment/82116954
comment on: http://stackoverflow.com/a/47577383
type: Comment
score: 0
type: AnswerComment
has text: Is “freeze” actual pythonic term?

http://stackoverflow.com/comment/82162894
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47602043
has text: Why can't you simply call `parse_data` from the `else` clause of `parse_article_page`?

http://stackoverflow.com/comment/82350141
type: AnswerComment
has text: Thank you for this Divakar. As Max says, very simple and elegant (as always)
comment on: http://stackoverflow.com/a/47640534
score: 1
type: Comment

http://stackoverflow.com/q/47578003
has comment: http://stackoverflow.com/comment/82114105
has title: How to reveal letters if correct to what is inputted
downvote count: 1
has answer: http://stackoverflow.com/a/47617282
favorite count: 0
has answer: http://stackoverflow.com/a/47615966
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82114042
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82129785
has body: I am creating a hangman game , where a user will enter a word in which another user will have to guess. I have got the word to print with dashes, however when I input a letter which is in the word, I cannot get it to remove the dashes. #output a game of hangman letters= ["A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"] for i in range(1): print("Welcome to Hangman") word_guess = str(input("Please enter a word for user 2 to guess:")) print("Word to be guessed:"+str(word_guess)) length_of_word=len(word_guess) display=("-"*length_of_word) print("Display:"+str(display)) for i in range(1): print("Welcome to Hangman Player 2") letter_guess=str(input("Please guess a letter:")) if letter_guess in word_guess: print("Yay you have a match") display=display.rstrip(display) print(display)
tagged with: python
score: -1

http://stackoverflow.com/comment/82185948
has text: Need just one author of inputing book's title, not all the authors
type: Comment
comment on: http://stackoverflow.com/a/47613741
score: 0
type: AnswerComment

http://stackoverflow.com/q/47549487
type: Question
has answer: http://stackoverflow.com/a/47549715
upvote count: 2
has title: Anaconda Not Recognized on Windows 8.1 AFTER Adding to Path
type: UnansweredQuestion
tagged with: python
has body: This is starting to get aggravating. I'm getting the typical "conda is not recognized as an internal or external command..." message when trying to run conda in the command line. This is a common issue, and I've found plenty of posts saying to fix it by adding both the Anaconda folder and its script folder to my path. The problem is that I've done this, my path looks like: C:\ProgramData\Anaconda3; C:\ProgramData\Anaconda3\Library\mingw-w64\bin; C:\ProgramData\Anaconda3\Library\usr\bin; C:\ProgramData\Anaconda3\Library\bin; C:\ProgramData\Anaconda3\Scripts; C:\Program Files\Java\jdk-9.0.1\bin; C:\ProgramData\Oracle\Java\javapath; C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\ia32\compiler; C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler; C:\Program Files (x86)\Intel\iCLS Client\; C:\Program Files\Intel\iCLS Client\; C:\Windows\system32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Program Files\Intel\Intel(R) Management Engine Components\DAL; C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL; C:\Program Files\Intel\Intel(R) Management Engine Components\IPT; C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT; c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\; c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\; C:\Program Files (x86)\ATI Technologie Anaconda should clearly be in there. I've tried restarting the terminal, I've tried adding the path variables by hand/from Anaconda's installer/from the terminal, I've tried restarting my computer after doing this...absolutely no luck. Does anyone have any other ideas?
has comment: http://stackoverflow.com/comment/82055977
score: 2
tagged with: anaconda
has comment: http://stackoverflow.com/comment/82067204
has comment: http://stackoverflow.com/comment/82056042
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/62706642
type: Answer
score: 0
has body: The problem for me was that google app engine uses its own python installation (in my case in "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython2\python.exe"). Once I installed pycrypto using that path, it worked fine: .\python.exe -m pip install pycrypto NOTE! Need to run cmd/powershell as administrator!
answers question: http://stackoverflow.com/q/47641437

http://stackoverflow.com/q/47685686
linked to: http://stackoverflow.com/q/11214908
score: 0
has comment: http://stackoverflow.com/comment/82360081
has comment: http://stackoverflow.com/comment/82331614
type: Question
linked to: http://stackoverflow.com/q/31416842
has comment: http://stackoverflow.com/comment/82331333
has answer: http://stackoverflow.com/a/47702133
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82331986
has body: so I have this pandas data table that I wish to write into an excel workbook. I'm using pyexcelerate package. Here's my code: from pyexcelerate import Workbook def df_to_excel(df, path, sheet_name='Sheet 1'): data = [df.columns.tolist(), ] + df.values.tolist() wb = Workbook() wb.new_sheet(sheet_name, data=data) wb.save(path) df_to_excel(df=MergedDataAll, path=merged_file) I didn't have this problem before when I used this same code; but today this error kept popping up: Traceback (most recent call last): File "C:/Users/y/Documents/python codes/DataMerging.py", line 71, in <module> df_to_excel(df=MergedDataAll, path=merged_file) File "C:/Users/y/Documents/python codes/DataMerging.py", line 68, in df_to_excel wb.save(path) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 82, in save self._save(fp) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Workbook.py", line 78, in _save self._writer.save(file_handle) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Writer.py", line 58, in save for s in sheetStream: File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 1045, in generate yield self.environment.handle_exception(exc_info, True) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\jinja2\_compat.py", line 37, in reraise raise value.with_traceback(tb) File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\templates\xl\worksheets\sheet.xml", line 11, in top-level template code {% for x, row in worksheet.get_xml_data() %}{{ worksheet.get_row_xml_string(x) }}{% for cell in row %}{{ cell }}{% endfor %}</row>{% endfor %} File "C:\Users\y\AppData\Roaming\Python\Python36\site-packages\pyexcelerate\Worksheet.py", line 265, in get_xml_data row_data.append(self.__…
tagged with: python
has title: python: writing data to excel file but "cannot close file"?
linked to: http://stackoverflow.com/q/40128217
tagged with: excel
tagged with: pyexcelerate
answer count: 1
linked to: http://stackoverflow.com/q/32269676
has comment: http://stackoverflow.com/comment/82331917
has comment: http://stackoverflow.com/comment/82331410
has comment: http://stackoverflow.com/comment/82331261
has comment: http://stackoverflow.com/comment/82331403

http://stackoverflow.com/comment/82352887
comment on: http://stackoverflow.com/q/47695560
type: QuestionComment
score: 0
has text: The error tells you: `x_image(IMAGE_PIXELS)` makes no sense, as `x_image` is a `Tensor` object, not a function. Try replacing `x_image(IMAGE_PIXELS)` in that line with just `x_image`. I think you will get a new error, as you probably can't use `random.sample()` with a `Tensor`. But that's a different question...
type: Comment

http://stackoverflow.com/a/47626791
downvote count: 0
answers question: http://stackoverflow.com/q/47626733
type: AcceptedAnswer
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47626733
has body: A default value in Python is not reassigned everytime the function is called, it is assigned once and everytime you call the function you will access the same object. Thus if your default value is a mutable object such as a list or a dict, it can be mutated every call. The common way around this is to do the following: class TestClass: def __init__(self, arr=None): self.arr = [] if arr is None else arr

http://stackoverflow.com/q/47569394
tagged with: roc
accepted answer: http://stackoverflow.com/a/47571160
tagged with: python
type: AnsweredQuestion
score: 1
has title: The graph of this ROC curve looks strange (sklearn SVC)
answer count: 1
downvote count: 0
upvote count: 1
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82096591
has comment: http://stackoverflow.com/comment/82099307
has answer: http://stackoverflow.com/a/47571160
favorite count: 0
type: Question
has body: So I constructed a small example with scikit-learns support vector classifier (svm.SVC) in combination with pipelining and Grid Search. After fitting and evaluating, I get a ROC curve that looks very interesting: it only bends once. I thought I would get more of a curve-shape here. Who can explain this behaviour? Minimal working example code: # Imports import sklearn as skl import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn import preprocessing from sklearn import svm from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn import metrics from tempfile import mkdtemp from shutil import rmtree from sklearn.externals.joblib import Memory def plot_roc(y_test, y_pred): fpr, tpr, thresholds = skl.metrics.roc_curve(y_test, y_pred, pos_label=1) roc_auc = skl.metrics.auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area ={0:.2f})'.format(roc_auc)) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show(); # Generate a random dataset X, y = skl.datasets.make_classification(n_samples=1400, n_features=11, n_informative=5, n_classes=2, weights=[0.94, 0.06], flip_y=0.05, random_state=42) X_train, X_test, y_train, y_test = skl.model_selection.train_test_split(X, y, test_size=0.3, random_state=42) #Instantiate Classifier normer = preprocessing.Normalizer() svm1 = svm.SVC(probability=True, class_weight={1: 10}) cached = mkdtemp() memory = Memory(cachedir=cached, verbose=3) pipe_1 = Pipeline(steps=[('normalization', normer), ('svm', svm1)], memory=memory) cv = skl.model_selection.KFold(n_splits=5, shuffle=True, random_state=42) param_grid = [ {"svm__kernel": ["linear"], "svm__C": [1, 10, 100, 1000]}, {"svm__kernel": ["rbf"], …

http://stackoverflow.com/q/47676832
tagged with: user-interface
downvote count: 1
answer count: 1
favorite count: 0
tagged with: tix
type: Question
has title: Adding Tix Widget to Tkinter Container
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47677808
upvote count: 4
tagged with: python-2.7
tagged with: tkinter
has body: I'm working with Tkinter in Python 2.7 on Windows 7, and found the need to create a popup box with a tree-style list of checkboxes. I could not find this in Tkinter, or ttk. I did, however, find it in Tix in the CheckList widget. I got a working standalone example using Tix, but I cannot figure out how to add my Tix.CheckList to my ttk.Frame that controls my main program. Surely I am not forced to use Tix framework from the ground up? import Tix import pandas as pd import Tkinter as tk class TreeCheckList(object): def __init__(self, root): self.root = root self.cl = Tix.CheckList(self.root) self.cl.pack(fill=Tix.BOTH, expand=Tix.YES) self.cl.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white', selectforeground='black', drawbranch=True, pady=5) self.cl.hlist.add('ALL', text='All Messages') self.cl.hlist.add('ALL.First', text='First') self.cl.setstatus('ALL.First', "off") self.cl.hlist.add('ALL.Second', text='Second') self.cl.setstatus('ALL.Second', "off") self.cl.autosetmode() def main(): root = Tix.Tk() top = Tix.Toplevel(root) checklist = TreeCheckList(top) root.update() top.tkraise() root.mainloop() if __name__ == '__main__': main() The above code works in a standalone program using all Tix widgets. However, when I try to implement this into my larger program, I receive a TclError: invalid command name "tixCheckList" To simulate this in the standalone, I changed the lines: root = Tix.Tk() top = Tix.Toplevel(root) to root = tk.Tk() top = tk.Toplevel(root) I was hoping I could just implement a Tix.Toplevel, placing it on a tk.Tk() root, but same issue. Am I only allowed to use Tix frames when using a Tix widget, or am I misunderstanding something? If anyone has good Tix documentation, I would LOVE whatever I can get. It seems good docs on it are few and far between. Or is this same functionality included in ttk and I've just overlooked it? It seems to be one of the only things left out.
score: 3

weblate
tag name: weblate
tags question: http://stackoverflow.com/q/47596899
type: Tag

http://stackoverflow.com/comment/82329409
comment on: http://stackoverflow.com/a/47682928
type: Comment
type: AnswerComment
has text: Okay, I've gotten further and got this to work but I have to actually define the exact instance ID. Not really what I want, because if I have multiple instances that match the Cloudwatch rule, they should get their security group changed too. Any help in parsing the event data as a variable in the lambda script?
score: 0

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/47685174

http://stackoverflow.com/comment/82192440
type: QuestionComment
has text: Hard to tell. As soon as I add a print statement the segfault goes away.
score: 0
comment on: http://stackoverflow.com/q/47617024
type: Comment

http://stackoverflow.com/a/47639246
type: Answer
has body: After finding the max m = max(model), zip the model names to the values and take the names where the value is equal to m . def dominant(names, values): m = max(values) return [name for name, value in zip(names, values) if value == m] Demo &gt;&gt;&gt; model_names = ['is1', 'is5', 'is10', 'im1', 'im5', 'im10'] &gt;&gt;&gt; model_values = [0.1, 0.2, 0.1, 0.3, 0.2, 0.3] &gt;&gt;&gt; dominant(model_names, model_values) ['im1', 'im10']
downvote count: 0
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/47639165
has comment: http://stackoverflow.com/comment/82236807

http://stackoverflow.com/q/47658787
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
has title: Python-Generic method to find child of a webelement
tagged with: python
has answer: http://stackoverflow.com/a/47660910
accepted answer: http://stackoverflow.com/a/47660910
has body: I trying to create a generic method in python to find the child element of a webelement using any locator strategy. Currently I have the below code, please help in completing the method getchildobject in below code. This method should be capable of find the child of the webelement with any locator like xpath, css or id etc getelement="xpath=//div[@id='test']" def get_webelement_Cus(locator): strategy=locator.split("=")[0] locator=locator.replace(locator.split("=")[0]+"=","") if strategy.uppercase()=='XPATH': return driver.find_elements_by_xpath(locator) elif strategy.uppercase()=='CSS': return driver.find_element_by_css_selector(locator) else: return None def getchildobject(webelement,locator): webelement.????????
tagged with: selenium-webdriver

http://stackoverflow.com/comment/82205594
score: 0
has text: Here's a link to the full code on github. https://github.com/amstrudy/nao-ncsu/blob/master/oop_a_star.py
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47623834

http://stackoverflow.com/q/47585444
tagged with: numba
downvote count: 0
tagged with: python
has body: I'm doing some tests to better understand how Numba works with NumPy, here I'm trying to see if Numba can handle out parameter. import numpy as np from numba import njit , jit from time import time @njit def mult(a,b, N = 1000000): c = np.zeros_like(a) for i in range(N): np.multiply(a, b, out=c) return c d = np.asarray([1,2,3,4,5,6,7,8,9]) e = np.asarray([1,2,3,4,5,6,7,8,9]) t = time() e = mult(d,e) print "Time Elapsed :" + str(time() - t) Without using Numba, the code goes well. It's even quicker than using @jit decoration : ~1.2s against ~1.6s with my configuration. Using @njit it leads to that error : LoweringError: unsupported keyword arguments when calling Function(&lt;ufunc 'multiply'&gt;) Though, Reading the Numba 0.15.1 doc. , they say out parameter is supported. What can I do against this ?
accepted answer: http://stackoverflow.com/a/47612730
has answer: http://stackoverflow.com/a/47612730
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
has title: Numba 0.35.0 : Use NumPy out parameter
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/a/47580381
score: 8
upvote count: 8
has body: It seems like you want sort_index on the columns: df.groupby(['type', 'band']).mean().unstack(level=1)\ .sort_index(axis=1, ascending=False) Result: val band C B A type 1 0.210 0.230 0.215 2 0.235 0.223 0.240 As for an arbitrary order: say your order is "C, A, B". Generally, you must just specify this directly. order = list('CAB') df[order]
type: Answer
answers question: http://stackoverflow.com/q/47580313
has comment: http://stackoverflow.com/comment/82118649
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47580313
downvote count: 0

http://stackoverflow.com/comment/82249687
comment on: http://stackoverflow.com/a/47645488
type: Comment
type: AnswerComment
has text: or put that class on the button instead of the link. On first read I thought you were trying to see if they were clicking on the movie link.
score: 0

http://stackoverflow.com/comment/82297758
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47652762
type: Comment
has text: ```blah=dict{a='b'}``` is not a proper syntax, you cannot write that way. You may mean ```blah=dict(a='b')``` with regular parentheses. And the difference between ```blah=dict(a='b')``` and ```blah={a:'b'}``` is that the first calls the constructor ```dict()``` explicitly and the second does not, which means it will take less time to compute. As stated [here](https://stackoverflow.com/questions/664118/whats-the-difference-between-dict-and)

http://stackoverflow.com/comment/82179273
comment on: http://stackoverflow.com/a/47603388
type: Comment
score: 0
type: AnswerComment
has text: @AndyForceno: Sorry, I was mistaken. I've only used the middleware and assumed `PREFERRED_URL_SCHEME` would do what the docs implied it would. It doesn't have Flask choose HTTPS if the request was sent over HTTP, only if you create a request object yourself. HTTP 405 is "method not allowed", which doesn't seem related. I'd fix the certificate issue.

http://stackoverflow.com/q/47636816
tagged with: python
tagged with: image-processing
tagged with: image
has comment: http://stackoverflow.com/comment/82231730
has answer: http://stackoverflow.com/a/47637409
accepted answer: http://stackoverflow.com/a/47637409
has comment: http://stackoverflow.com/comment/82231776
has body: I'm trying to write a script to assist with my Industry Porject but I'm having trouble getting this code working. What it should do is take all Images in a directory Crop them, the crop being the same for every image, then export the cropped image. import sys import os from PIL import Image filepath = "C:\Users\Ellis\Desktop\bunny_test" os.listdir = filepath # Loop through all provided arguments for i in range(1, len(filepath)): try: # Attempt to open an image file #filepath = sys.argv[i] image = Image.open(filepath) except IOError, e: # Report error, and then skip to the next argument print "Problem opening", filepath, ":", e continue # Perform operations on the image here image = image.crop(261, 435, 153, 343) # Split our origional filename into name and extension (name, extension) = os.path.splittext(filepath) # Save the image as "(origional_name)_thumb.jpg image.save("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg')
answer count: 1
tagged with: crop
type: Question
type: AnsweredQuestion
score: 0
has title: Automated Cropping of images using Python

http://stackoverflow.com/comment/82347269
score: 0
type: QuestionComment
has text: please post your code and the url that you are trying to scrape.
type: Comment
comment on: http://stackoverflow.com/q/47693924

http://stackoverflow.com/a/47603584
type: Answer
answers question: http://stackoverflow.com/q/47574968
has body: To address your post-edit question: TensorFlow doesn't have a function that computes Jacobians. The following quote, taken from a Github discussion, sketches how you might compute the Jacobian yourself: Currently, you can compute the Jacobian of, say, a vector, by calling gradients multiple times, one for every scalar component (obtained by slicing) of the original vector, and reassembling the results.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82179202
score: 0
comment on: http://stackoverflow.com/q/47610037
type: QuestionComment
has text: Did you an get error? What's your question?
type: Comment

http://stackoverflow.com/q/47637494
has answer: http://stackoverflow.com/a/47637650
score: 2
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47637764
type: Question
has title: Creating a new column with 0 and 1 values based on regex result
answer count: 2
upvote count: 3
type: UnansweredQuestion
has body: My dataframe has values: data_df 0 student 1 sample text 2 student 3 no students 4 sample texting 5 random sample I use regex to extract rows with word 'student' and my result is as below: regexdf 0 student 2 student I aim to create a new column in the main dataframe with 0 and 1 values. i.e. row 0 should be 1, row 5 should have zero.(As the 'regexdf' has 'student' in row 0 and 2) How do I match the indexes in both and create a column?
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/124641392
comment on: http://stackoverflow.com/a/47580449
type: AnswerComment
has text: This created duplicate column values for each destination. I had to extract the duration and distance using origin (i) and destination (key) inside the second for loop
type: Comment
score: 0

http://stackoverflow.com/comment/82177016
comment on: http://stackoverflow.com/a/47609043
type: Comment
score: 0
type: AnswerComment
has text: it returns : `print(next(iter(request.FILES))) StopIteration`

python-import
tags question: http://stackoverflow.com/q/47576847
tag name: python-import
type: Tag
tags question: http://stackoverflow.com/q/47688957
tags question: http://stackoverflow.com/q/47553142
tags question: http://stackoverflow.com/q/47598869
tags question: http://stackoverflow.com/q/47665182
tags question: http://stackoverflow.com/q/47658112
tags question: http://stackoverflow.com/q/47689265
tags question: http://stackoverflow.com/q/47575934
tags question: http://stackoverflow.com/q/47554689
tags question: http://stackoverflow.com/q/47590623
tags question: http://stackoverflow.com/q/47602302
tags question: http://stackoverflow.com/q/47676426

http://stackoverflow.com/comment/82166290
type: Comment
has text: @cricket_007 sure.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47603665

http://stackoverflow.com/comment/82162869
type: AnswerComment
has text: green tick under the 0?
type: Comment
comment on: http://stackoverflow.com/a/47602009
score: 0

http://stackoverflow.com/q/47686252
answer count: 0
has comment: http://stackoverflow.com/comment/82352697
linked to: http://stackoverflow.com/q/47617718
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82337227
has comment: http://stackoverflow.com/comment/82346257
tagged with: nameerror
score: 0
has comment: http://stackoverflow.com/comment/82344399
has comment: http://stackoverflow.com/comment/94459168
tagged with: python
has title: this shows file not found,one of the problems is Anshuman Misra has a space in it how can i work with find
has comment: http://stackoverflow.com/comment/82332121
has body: build mongoimport command collection = OSM_FILE[:OSM_FILE.find('.')] working_directory = '/Users/Anshuman Misra/Downloads/' json_file = OSM_FILE + '.json' mongoimport_cmd = 'mongoimport -h 127.0.0.1:27017 ' + \ '--db ' + db_name + \ ' --collection ' + collection + \ ' --file ' + working_directory + json_file Before importing, drop collection if it exists (i.e. a re-run) if collection in db.collection_names(): print 'Dropping collection: ' + collection db[collection].drop() Execute the command print 'Executing: ' + mongoimport_cmd subprocess.call(mongoimport_cmd.split(), shell=True)
type: Question

http://stackoverflow.com/a/47620043
has body: myDict.values() will return a list of lists and not something you can ask x in y on, you won't be able to avoid a loop in some flavor similar to Python search in lists of lists ...unless that is you find this time consuming and decide to keep some sort of hash to contain all elements inside the lists contained in myDict.values. Note though that this will take O(len(l)) for each insertion of l into the dictionary.
answers question: http://stackoverflow.com/q/47619946
score: 0
type: Answer

http://stackoverflow.com/q/47670661
downvote count: 0
answer count: 1
tagged with: pyqt5
has body: I have created a dialog with Qt Creator and then translated the .ui file to .py file with pyuic5 dialog.ui -o dialog.py The resulting code is the following class Ui_dialog(object): def setupUi(self, dialog): dialog.setObjectName("dialog") dialog.resize(976, 725) self.verticalLayoutWidget = QtWidgets.QWidget(dialog) self.verticalLayoutWidget.setGeometry(QtCore.QRect(360, 210, 160, 80)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setObjectName("verticalLayout") self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) self.retranslateUi(dialog) QtCore.QMetaObject.connectSlotsByName(dialog) def retranslateUi(self, dialog): _translate = QtCore.QCoreApplication.translate dialog.setWindowTitle(_translate("dialog", "Dialog")) self.pushButton.setText(_translate("dialog", "PushButton")) Now I'm trying to display the dialog from my main window with dialog = QDialog() dialog.ui = Ui_dialog() dialog.ui.setupUi(self) dialog.show() dialog.exec_() The dialog is shown, but it's empty so there's no button or any other widgets I tried!?
favorite count: 0
type: Question
has title: pyqt5 dialog not showing any widgets
upvote count: 2
accepted answer: http://stackoverflow.com/a/47671040
has answer: http://stackoverflow.com/a/47671040
has comment: http://stackoverflow.com/comment/82300378
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/82365030
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47692234
has text: Thank you. So does this mean each discriminator has their own graph? If it was one graph, I'm assuming there would be no need for sharing?
type: Comment

http://stackoverflow.com/comment/82391118
type: AnswerComment
has text: If you adapt my example this shouldn't be necessary, and it will work for decorators where you can't request the maintainer.
type: Comment
comment on: http://stackoverflow.com/a/47689289
score: 0

http://stackoverflow.com/comment/82290471
comment on: http://stackoverflow.com/a/47665404
score: 1
type: Comment
has text: Further, when you tie the Label text to a StringVar() like *data*, when you programmatically update the StringVar value with a call to the `set()` method `data.set('hello')`, you will see the text on the Button magically change, too. That's part of the beauty of the event-driven GUI world of Tkinter. Once configured properly, you can make a change in one place, and it can propagate throughout your GUI.
type: AnswerComment

http://stackoverflow.com/q/47615480
score: 14
downvote count: 0
has answer: http://stackoverflow.com/a/47646275
favorite count: 0
tagged with: mypy
has comment: http://stackoverflow.com/comment/82189570
type: Question
answer count: 2
tagged with: pylint
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82189328
has title: Best practices for generic functions in python
has answer: http://stackoverflow.com/a/79280243
upvote count: 14
has body: I've read a lot about generic classes, and while those are cool, sometimes, I just need a generic function. Here's a small one I wrote: def _matrix_map(self, mapper): """returns the matrix applying the mapper funcfunc""" return {key: mapper(value) for key, value in self._matrix.items()} How is this supposed to be annotated for types. In a statically typed language with generic support, I'd write it something like this private Dictionary&lt;KeyType, ValueType&gt; matrix; private Dictionary&lt;KeyType, T&gt; matrix_map&lt;T&gt;(Func&lt;ValueType, T&gt;) So, I thought I'd write it like this: T = TypeVar('T') def _matrix_map(self, mapper: Callable[[Tile], T]) -&gt; Dict[Coordinate, T]: I got it to pass with mypy like this, but pylint hates this. On the first line: C0103:Invalid class attribute name "T" And on the second line: E0602:Undefined variable 'T' So I feel like I'm doing something wrong, and I could change the variable name (ttt? typ?), but that wouldn't solve the second problem. I can't be the first person to want (statically-typed) generic functions, but I can't find any good resources anywhere. Any recommendations?

http://stackoverflow.com/comment/82235291
comment on: http://stackoverflow.com/a/47637980
score: 0
type: AnswerComment
has text: That makes a lot of sense, Thank you so much!
type: Comment

http://stackoverflow.com/a/47626268
has comment: http://stackoverflow.com/comment/82212120
has body: Rather than a loop, why not filter() with a lambda function? Check it out: &gt;&gt;&gt; l = [["hello","son", 52],["welcome","home",65],["good","work",6]] &gt;&gt;&gt; name = "home" &gt;&gt;&gt; filter(lambda sub_list: name not in sub_list, l) [['hello', 'son', 52], ['good', 'work', 6]] &gt;&gt;&gt; https://docs.python.org/2/library/functions.html#filter for more information on filter(). Hope this helps. Edit: Didn't see your last question about adding another list to get the second answer. Try using the append() method. &gt;&gt;&gt; l = "first", "list" &gt;&gt;&gt; m = ["second", "list"] &gt;&gt;&gt; l.append(m) &gt;&gt;&gt; l [['first', 'list'], ['second', 'list']] &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/82211515
type: Answer
answers question: http://stackoverflow.com/q/47625162
score: 0

http://stackoverflow.com/comment/82376587
comment on: http://stackoverflow.com/a/47707221
type: AnswerComment
score: 0
type: Comment
has text: I've figured it out by following all instructions from the link in the error message. I've stepped forward but still got another error haha. Anyway, Thank you but I'm still confused how I install cx_Oracle or something else in azure notebooks. Actually, I did in my local environment...

http://stackoverflow.com/comment/82289294
type: Comment
has text: @drumhellerb and based on that, I changed 'EST' to 'GMT' (I'm based in UK) and it doesn't throw an error. That's not how I interpret the way it should work from the docs.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47664794

http://stackoverflow.com/q/47619691
answer count: 2
has comment: http://stackoverflow.com/comment/82197638
type: UnansweredQuestion
tagged with: probability
has comment: http://stackoverflow.com/comment/82197569
has comment: http://stackoverflow.com/comment/82197430
upvote count: 1
has body: I'm new to python and i'm doing a probability question on simulate the result of a coin toss. I read the question but I don't understand how to do it. Here's the question: "Does python have the capability to generate a random number? Let’s toss a coin 100 times and write the result to a file where the format of the line is: &lt;int&gt; throw number, &lt;int&gt; coin result {1 for a head and 0 for tails} For example: 1, 1 2, 0 3, 1 Open a file called random.dat and write out the results. Now open the file for reading and read in each line. Extract the result and assign it to a list called heads or tails depending on the result { 1 or 0}. Consider the length of the heads and tails list for different values of the number of coin toss" Can anyone help me with this part of the question? do I need to simulate the probability using a for loop?
downvote count: 7
tagged with: data-science
favorite count: 0
has title: how to coin toss using python?
has comment: http://stackoverflow.com/comment/82197509
tagged with: spyder
tagged with: python
score: -6
has comment: http://stackoverflow.com/comment/82197373
has answer: http://stackoverflow.com/a/47634162
type: Question
has answer: http://stackoverflow.com/a/73004286

http://stackoverflow.com/q/47554283
tagged with: bokeh
possible better answer: http://stackoverflow.com/a/47555475
tagged with: charts
has title: How to use timestamp as chart's x-axis?
type: Question
answer count: 2
tagged with: datetime
has body: I am trying to make a chart with Bokeh and I have a datetime list as below. I would like to set the datetime as my x-axis but seems like Bokeh can't show this chart correctly. Does anyone have a good solution? Thank you. datetime = ['2017-11-23 20:56:16', '2017-11-23 20:56:47', '2017-11-23 21:00:56', '2017-11-23 21:01:26'] p = figure(x_axis_type="datetime", plot_width=800, plot_height=350, title="the trend") p.xaxis.axis_label = "time" p.yaxis.axis_label = "price" p.line(datetime, price, line_width=2) output_file("test.html") show(p)
has answer: http://stackoverflow.com/a/47555629
tagged with: python
has answer: http://stackoverflow.com/a/47555475
has comment: http://stackoverflow.com/comment/82065827
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47555629
score: 0

http://stackoverflow.com/comment/82097628
comment on: http://stackoverflow.com/q/47567966
score: 0
type: Comment
type: QuestionComment
has text: the problem is that `arith == 'A' or 'a'` is the same as `(arith == 'A') or 'a'`, `'a'` is always true. You could do it in this way: `arith.lower() == 'a'`

http://stackoverflow.com/a/47564185
score: 0
has comment: http://stackoverflow.com/comment/82086475
has body: If I've correctly understood, what you're trying to do is aggregate the matching names for a particular BNF Chapter into a set? I'm stealing the answer from muon in this question # if list of unique items is desired, use set df.groupby('A',as_index=False)['B'].aggregate(lambda x: set(x)) # if duplicate items are okay, use list df.groupby('A',as_index=False)['B'].aggregate(lambda x: list(x))
answers question: http://stackoverflow.com/q/47564103
type: Answer
has comment: http://stackoverflow.com/comment/82086399

http://stackoverflow.com/q/47645224
has answer: http://stackoverflow.com/a/68615055
has title: UnicodeDecodeError: 'utf-16-le'
has answer: http://stackoverflow.com/a/47679123
tagged with: ms-access
score: 8
upvote count: 8
favorite count: 0
type: Question
tagged with: utf-16le
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82267479
has answer: http://stackoverflow.com/a/75882723
tagged with: python
has body: I'm trying to pull a list of tables from an access database. The script goes through and displays about a third of the tables and gets the following error: Traceback (most recent call last): File "C:/GageInfo/sourcecode for GageTrakNotify/__test script.py", line 31, in for fld in cursor2.columns(rows.table_name): UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 132-133: illegal encoding Any tips would be appreciated. import pyodbc cursor1 = conn.cursor() cursor2 = conn.cursor() tblCount = 0 for rows in cursor1.tables(): if rows.table_type == "TABLE": tblCount += 1 print(rows.table_name) for fld in cursor2.columns(rows.table_name): print(fld.table_name, fld.column_name) conn.close()
tagged with: pyodbc
tagged with: odbc
answer count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/47659402

http://stackoverflow.com/q/47684827
has body: I'm trying to modify my first Python program. I'm trying to use this repository to do some rudimentary text-to-speech. It does fine, but I want to improve it. From the looks of it, there is a 0.145 second delay between samples played. Not all the samples of my voice will be 0.145 seconds, however, and I want to have each sample play one after the other with no delays or skips. import re import wave import pyaudio import _thread import time class TextToSpeech: CHUNK = 1024 def __init__(self, words_pron_dict:str = 'cmudict-0.7b.txt'): self._l = {} self._load_words(words_pron_dict) def _load_words(self, words_pron_dict:str): with open(words_pron_dict, 'r') as file: for line in file: if not line.startswith(';;;'): key, val = line.split(' ',2) self._l[key] = re.findall(r"[A-Z]+",val) def get_pronunciation(self, str_input): list_pron = [] for word in re.findall(r"[\w']+",str_input.upper()): if word in self._l: list_pron += self._l[word] print(list_pron) delay = 0.0 for pron in list_pron: _thread.start_new_thread( TextToSpeech._play_audio, (pron,delay,)) delay += 0.145 def _play_audio(sound, delay): try: time.sleep(delay) wf = wave.open("sounds/"+sound+".wav", 'rb') p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(TextToSpeech.CHUNK) while data: stream.write(data) data = wf.readframes(TextToSpeech.CHUNK) stream.stop_stream() stream.close() p.terminate() except: pass if __name__ == '__main__': tts = TextToSpeech() while True: tts.get_pronunciation(input('Enter a word or phrase: ')) I've tried getting rid of the threading and delay, but there is some delay still between samples. I'm thinking that I should, instead of incrementing delay by 0.145, increment it by the length of the sample in seconds, but I've looked at the pyaudio documentation, and I have no idea how to do that. Can someone help?
tagged with: python
has comment: http://stackoverflow.com/comment/82331278
has answer: http://stackoverflow.com/a/47687558
tagged with: pyaudio
score: 0
type: UnansweredQuestion
has title: Use pyaudio to play files immediately after the other
tagged with: text-to-speech
answer count: 1
has comment: http://stackoverflow.com/comment/82329774
tagged with: wave
type: Question

http://stackoverflow.com/comment/82248944
score: 0
comment on: http://stackoverflow.com/a/47644801
type: AnswerComment
has text: Thanks! Very helpful! Just for completeness, would you mind adding one more column like `Column('t4', Text)` (note no length is specified for Text) and showing what that maps to (would do it myself, but don't have easy access to a MySQL DB right now)? With that, I think this qualifies as the answer
type: Comment

http://stackoverflow.com/q/47543611
has answer: http://stackoverflow.com/a/47555572
favorite count: 0
has comment: http://stackoverflow.com/comment/82054722
type: Question
score: 3
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47559192
tagged with: python-3.x
tagged with: turtle-graphics
has body: How do I set screen boundaries so when the turtle reaches the edge it will stop or turn around import turtle t=turtle.Turtle() s=turtle.Screen() p=t.xcor() p1=t.ycor() x=300 y=300 s.setup(x,y) t.color("white") s.bgcolor("black") def up(): player=False while player==False: t.speed(1) t.fd(10) def right(): t.speed(0) t.right(90) def left(): t.speed(0) t.left(90) s.onkey(up,"up") s.onkey(right,"right") s.onkey(left,"left") s.listen() I thought this would stop it at the edge of the screen The code below isn't completely done but I didn't know what to change it to while p and p1 != x and y: t.right(90) if p and p1 == x and y: t.speed(0) t.right(180)
upvote count: 3
answer count: 2
has title: How to set screen boundaries python turtle
downvote count: 0

http://stackoverflow.com/q/47580725
tagged with: python-3.x
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82118807
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82118959
has body: Okay there, i have some code in python that opens a file -> process it -> and writes data to other file. def ELECrypt(myFile, outFile, code): Code = list(bytes(code,'utf-8')) with open(myFile, 'rb') as bFil: with open(outFile, 'wb') as bOutFil: while True : data = bytearray(bFil.read(CHUNK_SIZE)) if not data: break processIt(data, Code) bOutFil.write(data) It works fine, but it is too slow. So, i wrote a C++ program that does similar thing and I want to know if it is possible to make it callable from python #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int CHUNK_SIZE = 1*1024*1024; void ELECrypt(ifstream&amp; myFile, ofstream&amp; outFile, unsigned char Code[], int CodeLen){ unsigned char* fChunk = new unsigned char[CHUNK_SIZE]; int readCount; while (myFile.read((char *)fChunk, CHUNK_SIZE) || myFile.gcount() &gt; 0) { ...Processing a data block outFile.write((char *)fChunk, myFile.gcount()); } delete [] fChunk; } Yeah-yeah, I know there might be a lot of work, but i can`t even find where to read about arguments that can be passed by python to c++ extension
tagged with: python-extensions
favorite count: 0
upvote count: 3
score: 3
has title: passing python3 file stream to C++ extern function
tagged with: python
has comment: http://stackoverflow.com/comment/82118720
type: Question
tagged with: c++

http://stackoverflow.com/q/47627200
has title: Split a comma delimited string which may contain commas and escaped quotes between single quotes
has comment: http://stackoverflow.com/comment/82212268
accepted answer: http://stackoverflow.com/a/47627510
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82212204
has comment: http://stackoverflow.com/comment/82212195
has comment: http://stackoverflow.com/comment/82212320
tagged with: http://stackoverflow.com/tag/csv
has body: How do you split a comma delimiter string. The string is a series of comma delimited numbers and words. Words are quoted with single quotes and numbers are not. Words may contain non-delimiting commas which should be fine inside quotes. Words may contain other kinds of quotes which must be escaped by a preceding backslash like so: '','some-mail@some-domain.org','f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406',2827,1378614418 I have tried to use a regex [^\'] to split but that also picks up escaped commas. I have tried literally counting the characters as an alternative but that is deathly slow. Also python's csv reader splits the string on the non-delimiting commas if there are escaped slashes in the string. Perhaps it's not valid CSV? The sub-string list I should have as a result is: [ '', # empty string 'some-mail@some-domain.org', # text like email 'f4c1bfd5-969d-\'4,7\"2a-,b1\'29-42de49eb4406', # text, comma and escaped quotes 2827, # number 1378614418 # number ] This is how I have used the csv module: reader = csv.reader(StringIO(values_string), delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL,skipinitialspace=True) But I get: ['', 'some-mail@some-domain.org', 'f4c1bfd5-969d-\\4', '7\\"2a-', "b1\\'29-42de49eb4406'", '2827', '1378614418']
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82212354
has answer: http://stackoverflow.com/a/47627510
upvote count: 0
has comment: http://stackoverflow.com/comment/82212156
tagged with: python
score: -1
tagged with: regex

http://stackoverflow.com/comment/82267609
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47654716
has text: "it throws an error" -- is there a stack trace that you can [add](https://stackoverflow.com/posts/47654716/edit) to your question?

http://stackoverflow.com/a/47664757
downvote count: 1
answers question: http://stackoverflow.com/q/47664743
has comment: http://stackoverflow.com/comment/82289070
has comment: http://stackoverflow.com/comment/82289326
type: Answer
score: 1
upvote count: 2
has body: I assume you want it in sorted order. Try this c = OrderedDict(sorted(a.items()))
has comment: http://stackoverflow.com/comment/82290526
has comment: http://stackoverflow.com/comment/82288905

http://stackoverflow.com/comment/82452881
comment on: http://stackoverflow.com/a/47693887
score: 0
type: Comment
type: AnswerComment
has text: Thank you for your help.

http://stackoverflow.com/q/47686454
tagged with: python
type: UnansweredQuestion
tagged with: regex
has comment: http://stackoverflow.com/comment/82332623
has comment: http://stackoverflow.com/comment/82332549
score: -1
has body: I am trying to capture the starttime, stoptime, tripduration, from_station_id, to_station_id, gender, birthyear from the following data. trip_id,starttime,stoptime,bikeid,tripduration,from_station_name,to_station_name,from_station_id,to_station_id,usertype,gender,birthyear 431,10/13/2014 10:31,10/13/2014 10:48,SEA00298,985.935,2nd Ave &amp; Spring St,Occidental Park / Occidental Ave S &amp; S Washington St,CBD-06,PS-04,Member,Male,1960 I just want to be able to have the regex identify these items from the code.
has answer: http://stackoverflow.com/a/47686665
has title: Capturing items from comma delimited csv with regex
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82332665
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82332844
has comment: http://stackoverflow.com/comment/82332896

http://stackoverflow.com/q/47692037
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82344084
tagged with: python
has comment: http://stackoverflow.com/comment/82343075
downvote count: 1
has body: I've made a class with some variables being set in the ___init____ and I want to be able to change these variables from methods in that class ie. class example_class: def __init__(self, variable): self.thing = 'variable' def example_method(self): self.thing = 'changed text' def different_method(self): print(self.thing) So before calling "example_method" the value of self.thing is the string 'variable' and then after calling the method "example_method" self.thing now equals 'changed text'. This must be possible but I don't understand how to do it
favorite count: 0
has answer: http://stackoverflow.com/a/47692144
score: 1
tagged with: instance-variables
has title: Changing instance variables from a method in a class
type: Question
upvote count: 2

http://stackoverflow.com/comment/82109060
has text: Try scaling your colors to the range 0 to 1. There may be an option to autoscale, but I am not an expert in colormaps.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47565569

http://stackoverflow.com/comment/82222578
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47616531
has text: Yes...it is working fine as I moved it from GridSearchCV to fit method...thank you so much...I am hoping to parse the log and extract the metrics for each CV

http://stackoverflow.com/q/47666884
has answer: http://stackoverflow.com/a/47666996
type: Question
tagged with: function
has comment: http://stackoverflow.com/comment/82292885
tagged with: python
type: AnsweredQuestion
tagged with: recursion
possible better answer: http://stackoverflow.com/a/47666928
tagged with: boolean
has body: I know how to reverse a string using recursion def reverse(s): if len(s) == 0: return s return s[-1] + reverse(s[0 : -1]) def main() : r = reverse("Hello!") print(r) print("Expected: !olleH") main() However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far: def isReversed(str1, str2): if len(str1) != len(str2): return False I'm not sure how to call the function within itself using two arguments.
has comment: http://stackoverflow.com/comment/82292863
accepted answer: http://stackoverflow.com/a/47666973
answer count: 3
has title: How to check if string1 is the reverse of string2 using recursion (python)
has answer: http://stackoverflow.com/a/47666928
has answer: http://stackoverflow.com/a/47666973
score: 0

http://stackoverflow.com/comment/118443083
type: AnswerComment
comment on: http://stackoverflow.com/a/47630475
has text: _"ALLOWED_HOSTS This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations... A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header"_ [link](https://docs.djangoproject.com/en/3.1/ref/settings/)
type: Comment
score: 0

http://stackoverflow.com/comment/82259325
type: QuestionComment
has text: This seems to be a question about a design decision in a specific third-party library. Why don't you ask the authors of that library?
type: Comment
comment on: http://stackoverflow.com/q/47650465
score: 0

undo
type: Tag
tag name: undo
tags question: http://stackoverflow.com/q/47687564

http://stackoverflow.com/a/47626586
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47626495
accepted answer of: http://stackoverflow.com/q/47626495
type: Answer
has body: 906609 = 913 * 993 Since you are only checking n*(n+1), you wont find that one On the other hand, 289982 = 538 * 539 so that is why you are finding it You should try using a nested loop and multiply the two loop variables together for x in range(999, 99, -1): for y in range(999, 99, -1): product = x * y pali_check(product) You can easily optimise the above to prevent duplicates
score: 0

http://stackoverflow.com/comment/82460358
type: QuestionComment
has text: [this](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.describe.html) might be what you're looking for
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47658342

http://stackoverflow.com/q/47666238
has comment: http://stackoverflow.com/comment/82291616
has body: i made this code that should create a tree for a tris game for every possible outcome of the game from a starting 3x3 list. when doing gen_tree it creates the said three but whe i use the function scorri it shows that only the first nodotris object actually saved his leafs, in fact when scorri searches for child nodes in lista_figli it gets blank lists def gen_tree(griglia): nodo=NodoTris(griglia) nodo.nome=griglia tip=nodo.tipo() vuoti=vuoto(griglia) if tip=='?': x=0 y=0 while x&lt;3: y=0 while y&lt;3: if nodo.nome[x][y]=='': nodof=NodoTris(nodo.nome) nodof.nome=copy.deepcopy(nodo.nome) if vuoti%2==0: nodof.nome[x][y]='x' else: nodof.nome[x][y]='o' nodo.lista_figli.append(nodof) y+=1 x+=1 for n in nodo.lista_figli: gen_tree(n.nome) scorri(nodo)
has title: Why it does not save the nodes of the tree (Python)
answer count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82291973
tagged with: class
score: 0

http://stackoverflow.com/a/47603546
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/47603498
type: Answer
has body: Your condition should be a if condition instead of a while loop because you are not changing the value of x within the while loop and Everytime the condition becomes true and makes a recursive call. Here is a corrected version of it def incr_num(x, y): if x &lt;= y: print x incr_num(x+1, y)
upvote count: 3

http://stackoverflow.com/comment/82052253
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47547403
type: Comment
has text: Thanks. But, how do I search for the regex only on column4 ?

http://stackoverflow.com/comment/82161148
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47601068
has text: @y.j.r Oh ok, I'll post a separate answer then. Is that ok?
type: AnswerComment

http://stackoverflow.com/q/47659325
tagged with: raspberry-pi
answer count: 1
has comment: http://stackoverflow.com/comment/82284859
has comment: http://stackoverflow.com/comment/82277571
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47659450
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1185408
has answer: http://stackoverflow.com/a/47659450
has title: How can I detect a speed from a gps in python?
tagged with: python
has body: I am using a gps chip with my raspberry pi using python for coding and I want to get the speed from the gps and convert it to mph in a loop using a 1 second loop. How can this be accomplished with fairly precise data? I am currently using the following code: From gps import * import time import threading import math import RPi.GPIO as GPIO ## Import GPIO library import time ## Import 'time' library. Allows us to use 'sleep' GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(40,GPIO.OUT) ## Setup GPIO Pin 40 to OUT class GpsController(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.running = False def run(self): self.running = True while self.running: # grab EACH set of gpsd info to clear the buffer self.gpsd.next() def stopController(self): self.running = False @property def fix(self): return self.gpsd.fix @property def utc(self): return self.gpsd.utc @property def satellites(self): return self.gpsd.satellites mph = 15 if __name__ == '__main__': # create the controller gpsc = GpsController() try: # start controller gpsc.start() while True: if gpsc.fix.speed &lt; mph : print "speed is under 15 mph",gpsc.fix.speed print mph GPIO.output(40,GPIO.HIGH) time.sleep(1) GPIO.output(40,GPIO.LOW) time.sleep(1) #GPIO.output(40,True) #time.sleep(.5) #GPIO.output(40,False) #time.sleep(.10) elif gpsc.fix.speed &gt; mph : print "speed (m/s) ",gpsc.fix.speed # GPIO.cleanup() else: print "fine" #GPIO.cleanup() #print "latitude ", gpsc.fix.laif #print "longitude ", gpsc.fix.longitude #print "time utc ", gpsc.utc, " + ", gpsc.fix.time #print "altitude (m)", gpsc.fix.altitude #print "eps ", gpsc.fix.eps #print "epx ", gpsc.fix.epx #print "epv ", gpsc.fix.epv #print "ept ", gpsc.gpsd.fix.ept #print "speed (m/s) ", gpsc.fix.speed #print "climb ", gpsc.fix.climb #print "track ", gpsc.fix.track #print "mode ", gpsc.fix.mode #print "sats ", gpsc.satellites time.sleep(1) #Error #except: # p…
has comment: http://stackoverflow.com/comment/82280031
tagged with: gps
has comment: http://stackoverflow.com/comment/82280262
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82090243
type: Comment
comment on: http://stackoverflow.com/a/47566214
score: 3
type: AnswerComment
has text: The usual dilemma between speed and memory... :)

http://stackoverflow.com/q/47595669
type: AnsweredQuestion
upvote count: 0
tagged with: list
score: -5
answer count: 2
has comment: http://stackoverflow.com/comment/82148798
has comment: http://stackoverflow.com/comment/82148835
has comment: http://stackoverflow.com/comment/82148878
has comment: http://stackoverflow.com/comment/82150815
has body: I have a list of lists: x = [ [4, ‘c’, ‘b’, ‘d’], [2, ‘e’, ‘c’, ‘a’], [5, ‘a’, ‘c’] ] that I need to convert to: x1 = [ [‘c’, 4, 2, 5], [‘b’, 4], [‘d’, 4], [‘e’, 2], [‘a’, 2, 5] ] Explanation: 'c' appears in lists starting with 4, 2, 5 'b' appears in only the list starting with 4 'd' appears in only the list starting with 4 ... obviously this is a toy example, but my real list has about 30 Mb in a flat file. I was trying with a two nested for-loops but it tooks about 5 hours for only the 5% of the file in my MacBook Pro (8GB RAM). Is there an efficient way to do it?
favorite count: 0
has answer: http://stackoverflow.com/a/47595843
possible better answer: http://stackoverflow.com/a/47595843
type: Question
has answer: http://stackoverflow.com/a/47595811
accepted answer: http://stackoverflow.com/a/47595811
downvote count: 5
has comment: http://stackoverflow.com/comment/82148801
has comment: http://stackoverflow.com/comment/82148842
has title: An efficient way to transpose a list of list
tagged with: python
has comment: http://stackoverflow.com/comment/82148913
has comment: http://stackoverflow.com/comment/82148845
has comment: http://stackoverflow.com/comment/82148749

http://stackoverflow.com/comment/82074656
comment on: http://stackoverflow.com/a/47542639
type: AnswerComment
score: 0
type: Comment
has text: `HTML` is file like any image so difference will be `maintype='text', subtype='html'`

http://stackoverflow.com/comment/82041528
comment on: http://stackoverflow.com/a/47541316
score: 0
type: Comment
type: AnswerComment
has text: Okay got it forgot the ax=ax for the first plot. Thanks again.

spyder
tags question: http://stackoverflow.com/q/47619691
tag name: spyder
tags question: http://stackoverflow.com/q/47655242
tags question: http://stackoverflow.com/q/47541000
tags question: http://stackoverflow.com/q/47689601
tags question: http://stackoverflow.com/q/47606443
tags question: http://stackoverflow.com/q/47669663
tags question: http://stackoverflow.com/q/47673851
tags question: http://stackoverflow.com/q/47592850
type: Tag
tags question: http://stackoverflow.com/q/47648133

http://stackoverflow.com/a/72441328
score: 2
upvote count: 2
has body: I tried to follow the tips based on the comments in this post, but even so, there were still other doubts along the process, and I managed to solve the problem and it works perfectly, I would like to share the code to solve the problem superset-keycloak. This aprouch use docker to deploy the superset application.
downvote count: 0
answers question: http://stackoverflow.com/q/47678321
type: Answer

http://stackoverflow.com/q/47565536
has comment: http://stackoverflow.com/comment/82089172
type: AnsweredQuestion
tagged with: bash
has title: Creating a simple calculator using bash and python
score: 0
has comment: http://stackoverflow.com/comment/82089294
type: Question
has comment: http://stackoverflow.com/comment/82089136
accepted answer: http://stackoverflow.com/a/47565785
has body: I am trying to write a small bash function that can do some basic calculations. I added this function to my ~/.bash_profile: pyc() { python -c """from math import *; print($*)""" ;} However, when I want to calculate exp(5), I have to type pyc exp\c(5\) How could we modify the bash function, so that it works for pyc exp(5)
has answer: http://stackoverflow.com/a/47565785
has comment: http://stackoverflow.com/comment/82089125
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82089083
has comment: http://stackoverflow.com/comment/82089224
has comment: http://stackoverflow.com/comment/82089260

http://stackoverflow.com/comment/82089058
comment on: http://stackoverflow.com/q/47565110
type: Comment
type: QuestionComment
has text: That is not what your expected output is showing. Exp is descending, MaxDD is ascending.
score: 0

http://stackoverflow.com/comment/83032247
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47579743
has text: [mimetypes](https://stackoverflow.com/questions/21515098/how-to-check-the-url-is-either-web-page-link-or-file-link-in-python) might help you.

http://stackoverflow.com/q/47660384
tagged with: python
has answer: http://stackoverflow.com/a/47660662
tagged with: pandas
has body: I have a large dataframe, and when reading it, it gives me this message: DtypeWarning: Columns (0,8) have mixed types. Specify dtype upon import or set low_memory=False. It is supposed to be a column of floats, but I suspect a few strings snuck in there. I would like to identify them, and possibly remove them. I tried df.apply(lambda row: isinstance(row.AnnoyingColumn, (int, float)), 1) But that gave me an out of memory error. I assume there must be a better way.
score: 1
tagged with: types
downvote count: 0
answer count: 1
has title: Pandas: Coloumn with mixed datatype; how to find the exceptions
upvote count: 1
tagged with: mixed
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/82118367
has text: totally a side note but I like your cs-go style :)
comment on: http://stackoverflow.com/q/47580575
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/47630967
score: 1
has body: average = 0 sum = 0 for v in data.values(): sum = sum + len(v) average = sum / len(data.keys())
type: Answer
answers question: http://stackoverflow.com/q/47630892
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82174139
has text: you cannot, you need another web server in different port.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47606914
type: QuestionComment

http://stackoverflow.com/comment/82285331
type: QuestionComment
has text: The reason it runs individually is because it is a non-blocking function, calling a shell to open up outside the thread that the program sits on. Thus they will call almost instantly. However if you SSH'd into the machine correctly, the next shell call wouldn't "simultaneously" open up *yet* another window, but rather directly influence the current one.
score: 0
comment on: http://stackoverflow.com/q/47662947
type: Comment

http://stackoverflow.com/comment/82363616
has text: no, the length is the key, and the value is a *`set`* containing a single-element, which is an `int` representing the frequency.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47684302

http://stackoverflow.com/comment/82232950
has text: As the issue does not depend on `nonzero` or its `"busy"` column, why don't you create a [mcve], that would allow people to easily provide you with an answer?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47635939
type: Comment

http://stackoverflow.com/comment/82163466
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47601592
type: QuestionComment
has text: You're constrained to having ~240-character filenames consisting of about ~40 valid characters, so you have 40^240 possible filenames to work with. This means that you can guarantee uniqueness only if your total number of strings is below 1277.

http://stackoverflow.com/comment/82349628
comment on: http://stackoverflow.com/a/47685211
has text: I just wanted to get the Days in the middle of the duration because that makes more sense for my data but that is not relevant for my problem. Thanks for the help! I am not too familiar with Panda but it is another motivation to explore this library.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47590826
score: 1
type: AcceptedAnswer
has body: I think the issue you are describing is covered in the Anaconda troubleshooting documentation, here: Resolution: For Python packages, remove any site-specific directories If you just wish to use the version of tensorflow you have installed in your Anaconda virtual environment (and ignore the version in your ~/.local/lib/python folders) you could export PYTHONNOUSERSITE=True in your Anaconda environment to tell python to ignore your user site packages directory. If you want this to be done automatically for you every time you are running inside your Anaconda environment you could look to save the environment variable as described in the Anaconda documentation, here: Saving environment variables
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47586807
has comment: http://stackoverflow.com/comment/82210956
type: Answer
accepted answer of: http://stackoverflow.com/q/47586807

http://stackoverflow.com/a/47648241
type: Answer
accepted answer of: http://stackoverflow.com/q/47648207
has body: print('Age: ' + age + '\nFavourite Colour: ' + colour + '\nTown of residency: ' + town You forgot the closing )
answers question: http://stackoverflow.com/q/47648207
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82284215
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/82122161
comment on: http://stackoverflow.com/a/47581996
type: Comment
has text: Using lots of variable declarations should be discouraged though. But I agree this is slightly more general...
score: 0
type: AnswerComment

kubernetes
tags question: http://stackoverflow.com/q/47659088
tags question: http://stackoverflow.com/q/47564617
type: Tag
tag name: kubernetes

http://stackoverflow.com/comment/82601862
score: 0
has text: could you show the code that how you issue async call with requests?
comment on: http://stackoverflow.com/q/47665944
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47620501
favorite count: 0
has comment: http://stackoverflow.com/comment/82199679
type: AnsweredQuestion
has title: Pandas deleting my zero index when groupby
tagged with: pandas
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82199595
has comment: http://stackoverflow.com/comment/82198928
type: Question
has comment: http://stackoverflow.com/comment/82199290
has body: I am doing a very basic groupby on a column to have counts for n different columns of the dataframe : counts = (dataframe.groupby(['label'])[best_features_names_ordered[i]].sum() for i in indices) Here is the column 'label' of the dataframe : The other columns are words. My best_features_names_ordered variable is a basic list containing words : The groupby works well, excepted when one of the values of the column 'labels' is equal to 0! Here an example, the labels are equal to {-2, -1, 0, 1, 2} but the 0 has disappeared: However, the labels have the 0 ...: Does pandas delete my 0 index when grouping ? Why ? How can I solve this ? Thanks !
has comment: http://stackoverflow.com/comment/82199486
upvote count: 0
accepted answer: http://stackoverflow.com/a/47628844
answer count: 1
has answer: http://stackoverflow.com/a/47628844
downvote count: 1

hubspot
type: Tag
tag name: hubspot
tags question: http://stackoverflow.com/q/47630449

http://stackoverflow.com/q/47561312
has comment: http://stackoverflow.com/comment/82081251
duplicate of: http://stackoverflow.com/q/13905741
downvote count: 0
has body: I am working on a web scraper, but I have stumbled across this weird behavior when using a string placeholder in a list comprehension (here is a snippet of my code from Pycharm): # -*- coding: utf-8 -*- from arms_transfers.items import ArmsTransferItem import itertools import pycountry import scrapy import urllib3 class UnrocaSpider(scrapy.Spider): name = 'unroca' allowed_domains = ['unroca.org'] country_names = [country.official_name if hasattr(country, 'official_name') else country.name for country in list(pycountry.countries)] country_names = [name.lower().replace(' ', '-') for name in country_names] base_url = 'https://www.unroca.org/{}/report/{}/' url_param_tuples = list(itertools.product(country_names, range(2010, 2017))) start_urls = [base_url.format(param_tuple[0], param_tuple[1]) for param_tuple in url_param_tuples] Here is the error: Traceback (most recent call last): File "anaconda3/envs/scraper/bin/scrapy", line 11, in &lt;module&gt; sys.exit(execute()) File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/cmdline.py", line 148, in execute cmd.crawler_process = CrawlerProcess(settings) File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/crawler.py", line 243, in __init__ super(CrawlerProcess, self).__init__(settings) File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/crawler.py", line 134, in __init__ self.spider_loader = _get_spider_loader(settings) File "/anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/crawler.py", line 330, in _get_spider_loader return loader_cls.from_settings(settings.frozencopy()) File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/spiderloader.py", line 61, in from_settings return cls(settings) File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/spiderloader.py", line 25, in __init__ self._load_all_spiders() File "anaconda3/envs/scraper/lib/python3.6/site-packages/scrapy/spiderloader.py", line 47, in _load_all_spiders for module in walk_modules(name): File "anacon…
tagged with: scrapy
has title: String formatting in a list comprehension
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82080454
has comment: http://stackoverflow.com/comment/82081053
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82080762
has comment: http://stackoverflow.com/comment/82080677
has comment: http://stackoverflow.com/comment/82080571
linked to: http://stackoverflow.com/q/13905741
has comment: http://stackoverflow.com/comment/82081620
score: 4
upvote count: 4
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47561921
has comment: http://stackoverflow.com/comment/82080775
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47561921

http://stackoverflow.com/a/47588180
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47587297
has body: The login form has action set to /login/index/process &lt;form id="login" name="login" class="form-horizontal" enctype="application/x-www-form-urlencoded" action="/login/index/process" method="post" accept-charset="UTF-8"&gt; You need to set LOGIN_URL to the same in order to post the form to the correct URL: LOGIN_URL = "http://www.empaquetador.cl/login/index/process"
answers question: http://stackoverflow.com/q/47587297

http://stackoverflow.com/q/47566985
answer count: 2
has title: How to change the argument of function in a loop (Python)?
tagged with: loops
has answer: http://stackoverflow.com/a/47567174
has comment: http://stackoverflow.com/comment/82091644
type: Question
has comment: http://stackoverflow.com/comment/82091838
tagged with: statsmodels
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82113217
has body: In Python, suppose I have a pandas dataframe with columns labeled Y, X1, X2, X3. I run an OLS regression on Y with X1, X2, X3. I want to store the coefficients from the regression in a list using a loop. How do I change the argument of a function in a loop? The following code does not work. import pandas as pd import statsmodels.api as sm ols = sm.OLS(df'Y',(df'X_1','X_2','X_3')) olsfit = ols.fit(cov_type='HC0') coef = [] for i in range(4): coef.append(olsfit.params.X_i)
tagged with: python
has answer: http://stackoverflow.com/a/47567868
score: 0

http://stackoverflow.com/comment/82202410
type: AnswerComment
has text: Also, remove the calls to your `level` functions after their definition.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47622244

http://stackoverflow.com/comment/82045846
score: 0
has text: Is this a program you wrote? It's not clear if you're asking about your program, or trying to get the text from another program. Can you create a [mcve] that displays the list of files?
type: QuestionComment
comment on: http://stackoverflow.com/q/47544449
type: Comment

http://stackoverflow.com/q/47632801
answer count: 1
favorite count: 0
type: Question
upvote count: 3
score: 3
has title: play Youtube audio with python Discord bot
tagged with: python
has body: Hey i wanted to know if its possible to play youtube audio without doing anything to special. this is my code: if message.content.upper().startswith('!PLAY'): args = message.content.split(" ") url = args[1] author = message.author voice_channel = author.voice_channel vc = await Client.join_voice_channel(voice_channel) player = await vc.create_ytdl_player(url) player.Start() I thought this was enough but i guess not does anyone have some tips on how to do this if its possible?
tagged with: discord
tagged with: youtube
has answer: http://stackoverflow.com/a/66193714
tagged with: audio
tagged with: bots
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82261948
has text: I am, in an other function. If `can_push` return True, I push my data in the database
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47651587

http://stackoverflow.com/comment/82197147
score: 0
has text: please provide a small reproducible sample data set and your desired data set
comment on: http://stackoverflow.com/q/47619540
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47558697
has comment: http://stackoverflow.com/comment/82075313
accepted answer of: http://stackoverflow.com/q/47558535
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47558535
has comment: http://stackoverflow.com/comment/82075245
has comment: http://stackoverflow.com/comment/82075338
has body: You want .groupby: In [1]: import pandas as pd In [2]: import numpy as np In [3]: df = pd.DataFrame(np.random.randint(0, 100, (13, 3))) In [4]: df Out[4]: 0 1 2 0 73 85 15 1 4 56 5 2 30 74 1 3 93 16 9 4 94 97 41 5 37 49 63 6 28 66 10 7 74 35 4 8 1 76 65 9 5 79 27 10 54 33 74 11 99 54 46 12 67 28 77 Simply: In [5]: y_km = [0, 3, 2, 1, 2, 3, 3, 3, 1, 1, 0, 1, 2] In [6]: dfs = {k:g for k,g in df.groupby(y_km)} Now, I've gone ahead and put the data-frames in a dict, but you can do whatever you want. I suggest against a bunch of variables, and rather, keep things together in a container of some sort. Note: In [7]: dfs[0] Out[7]: 0 1 2 0 73 85 15 10 54 33 74 In [8]: dfs[1] Out[8]: 0 1 2 3 93 16 9 8 1 76 65 9 5 79 27 11 99 54 46 In [9]: dfs[3] Out[9]: 0 1 2 1 4 56 5 5 37 49 63 6 28 66 10 7 74 35 4 In [10]: dfs[2] Out[10]: 0 1 2 2 30 74 1 4 94 97 41 12 67 28 77
upvote count: 2
has comment: http://stackoverflow.com/comment/82075309
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47687088
score: 2
answers question: http://stackoverflow.com/q/47687055
upvote count: 2
type: AcceptedAnswer
has body: You can use list comprehension: d['Numbers'] = [i+10 for i in d["Numbers"]] Slightly more verbose: new = [i+10 for i in d['Numbers']] d.update({"Numbers": new})
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47687055

http://stackoverflow.com/q/47585333
has comment: http://stackoverflow.com/comment/82128415
favorite count: 0
type: Question
has title: python 3 float precision change
answer count: 0
has comment: http://stackoverflow.com/comment/82128711
has body: I typed 42.33333333333333333333333333 but I got a different number. I know python has this precision problem, but I don't want to use Decimal to store the number. Is there a way to resolve this? By the way, is there a way to read numbers directly from the Decimal object? I am using eval(repr(Decimal("123"))[9:-2]) to read 123 from it. And I discovered my previous problem when I tried eval(repr(Decimal("42.33333333333333333333333333"))
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82128596
has comment: http://stackoverflow.com/comment/82128749
score: 0
downvote count: 1

http://stackoverflow.com/comment/82096152
type: AnswerComment
comment on: http://stackoverflow.com/a/47552220
score: 0
has text: @Andersson here is the extension of the question: https://stackoverflow.com/questions/47569370/error-shown-when-geting-current-url-of-an-item-in-a-loop-after-using-selenium
type: Comment

http://stackoverflow.com/a/47585635
score: 0
upvote count: 1
downvote count: 1
has body: If you just want the values, use this: sorted(data.values()) If you want the keys associated with the sorted values, use this: sorted(data, key=data.get) Both key and values: sorted(data.items(), key=lambda x:x[1]) Courtesy of: sort dict by value python
has comment: http://stackoverflow.com/comment/82128983
type: Answer
answers question: http://stackoverflow.com/q/47585566

http://stackoverflow.com/comment/82175725
type: QuestionComment
comment on: http://stackoverflow.com/q/47605047
score: 0
type: Comment
has text: @furas While file am I looking at sorry? Or am I to create a new py file.

http://stackoverflow.com/a/47643350
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82246718
answers question: http://stackoverflow.com/q/47643264
has comment: http://stackoverflow.com/comment/82245919
has comment: http://stackoverflow.com/comment/82245412
downvote count: 0
has comment: http://stackoverflow.com/comment/82245827
has body: Let us try this factorize #df['rank']=pd.factorize(df.unit)[0]+1 df['rank']=pd.factorize(df.unit+df.HP.astype(str))[0]+1 df['rank']=df.groupby('HP').rank.transform('min') df Out[335]: HP N-D unit rank 0 24 C1 UD 1 1 24 C2 UD 1 2 24 C3 UD 1 3 7 Q1 UC 2 4 7 Q2 UC 2 5 7 Q3 UC 2 6 7 D1 UA 2 7 7 D2 UA 2 8 7 D3 UA 2 9 5 E1 UB 4 10 5 E2 UB 4 11 5 E3 UB 4
has comment: http://stackoverflow.com/comment/82245894

http://stackoverflow.com/comment/82223382
comment on: http://stackoverflow.com/q/47632671
has text: @VivekKumar is right, this is the easiest way to do this. You can quickly map the nan values using something like `nan_val = str(encoder.transform(['nan'])[0])` to see what the nan corresponds to in your new array.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47580201
upvote count: 2
has comment: http://stackoverflow.com/comment/82119216
downvote count: 0
has body: This is a pivot problem newDF = df.pivot(columns='array_index', values='jet_tagWeightBin', index='HT_jets') Then just rename the columns This gives: array_index 0 1 2 3 4 5 HT_jets 200476 5.0 2.0 1.0 1.0 NaN NaN 319676 1.0 5.0 1.0 5.0 NaN NaN 520111 5.0 1.0 2.0 5.0 5.0 2.0
has comment: http://stackoverflow.com/comment/82119436
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47579955

http://stackoverflow.com/q/47619494
upvote count: 1
answer count: 1
downvote count: 0
tagged with: tk-toolkit
linked to: http://stackoverflow.com/q/23377819
has body: How can I bind Ctrl + Shift + S to a method? Based on this I tried the below code but it doesn't work(print statement isn't run): import tkinter as tk def key(event=None): print("It works!") root = tk.Tk() frame = tk.Frame(root, width=100, height=100) frame.focus_set() frame.bind('&lt;Control-Shift-s&gt;', key) frame.pack() root.mainloop() Also I'd like to know the general answer on how to bind key combinations if possible.
favorite count: 0
has answer: http://stackoverflow.com/a/47619622
linked to: http://stackoverflow.com/q/7402516
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47619622
tagged with: key-bindings
score: 1
tagged with: python
has title: How to bind a combination of keys to a method?
type: Question
tagged with: tkinter

http://stackoverflow.com/q/47682920
has body: I have the following code: items = list() for i in response['Contents']: items[i].append('s3://' + response['Name'] + '/' + i['Key']) items[i].append(i['Key'].rsplit('/', 1)[-1]) items[i].append(i['Size']) response['Contents'] has a schema like this: {u'LastModified': datetime.datetime(, tzinfo=tzlocal()), u'ETag': '"tag"', u'StorageClass': 'STANDARD', u'Key': u'filepath/1/something.jpeg', u'Owner': {u'DisplayName': 'a', u'ID': 'b'}, u'Size': 32} Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...]. How can I extract the values correctly? (I'll be using zip with another list that has column names to create a dict later).
type: Question
has answer: http://stackoverflow.com/a/47683008
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47682967
has comment: http://stackoverflow.com/comment/82325176
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82325224
has answer: http://stackoverflow.com/a/47683050
has title: How to extract values from list to add to another list in python
tagged with: python
has comment: http://stackoverflow.com/comment/82325168

http://stackoverflow.com/a/47680514
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47680395
has body: Assuming you're already working with Python's csv module, here's a longform way of doing it, if you wanted headers. This example uses the DictWriter which is specifically designed to work with dictionaries. import csv form_data = [ {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'}, {'Name': 'Dave', 'Comment': 'Good Food', 'Days Stayed': '14'}, {'Name': 'Steve', 'Comment': 'Room was cosy', 'Days Stayed': '10'} ] with open('output.csv', 'w') as csvfile: # this defines the fields you want from dictionaries # you pass to the writer, and the order in which they should # be emitted in the resulting CSV fields = ['Name', 'Comment', 'Days Stayed'] dw = csv.DictWriter(csvfile, fieldnames) # omit this if you don't want a header written dw.writeheader() for row in form_data: dw.writerow(row) Resulting output.csv looks like this: Name,Comment,Days Stayed Eddie,Nice location,7 Dave,Good Food,14 Steve,Room was cosy,10 You can similarly deserialize using the DictReader class provided by csv. import csv rows = None with open('output.csv') as csvfile: fields = ['Name', 'Comment', 'Days Stayed'] reader = csv.DictReader(csvfile) rows = [row for row in reader] rows will look like this: [{'Comment': 'Nice location', 'Days Stayed': '7', 'Name': 'Eddie'}, {'Comment': 'Good Food', 'Days Stayed': '14', 'Name': 'Dave'}, {'Comment': 'Room was cosy', 'Days Stayed': '10', 'Name': 'Steve'}]

http://stackoverflow.com/comment/82162615
type: QuestionComment
comment on: http://stackoverflow.com/q/47597407
score: 0
has text: Do you have any idea which lines are taking so long?
type: Comment

http://stackoverflow.com/comment/82133347
comment on: http://stackoverflow.com/q/47587633
type: Comment
type: QuestionComment
has text: Have you tried looking into pandas or a similar library?
score: 0

http://stackoverflow.com/comment/82200795
comment on: http://stackoverflow.com/q/47620895
type: QuestionComment
has text: @Piinthesky ya thats my real code
type: Comment
score: 0

http://stackoverflow.com/comment/82208262
has text: Think about what you wrote. Does `[10, 14, 5] > 10` make much sense?
type: Comment
comment on: http://stackoverflow.com/q/47625126
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82306378
score: 0
comment on: http://stackoverflow.com/q/47672231
type: Comment
has text: Thank you for this comment, I have transformed to set, but still get an issue about looping itself. Could you please help me? such as how to get the index of max value inside the nested loop? and soon
type: QuestionComment

http://stackoverflow.com/q/47581333
accepted answer: http://stackoverflow.com/a/47581657
has answer: http://stackoverflow.com/a/47581657
has body: Several GUI toolboxes include events such as on_change which are triggered every time the text in a textbox changes. According to this: https://kivy.org/docs/api-kivy.uix.textinput.html the on_text event should be equal. So, I created a single TextInput box expecting everytime a change a single letter, the content of the box to be displayed in the terminal. This is the code: from kivy.app import App from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout class LoginScreen(BoxLayout): def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.orientation = 'horizontal' self.mytext = TextInput(text='500', multiline = False) self.add_widget(self.mytext) self.mytext.bind(on_text = self.calc) #self.mytext.bind(on_text_validate = self.calc) def calc(self, mytext): print mytext.text class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': MyApp().run() Yet, nothing happens, which obviously means that the calc function is not triggered at all. Mind that the on_text_validate event works fine, because the contents of the box are printed in the terminal when I press Enter. So, did I misunderstand the on_text event, and if so, how can I accomplish my goal?
type: AnsweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: kivy, how to trigger event by text change
score: 5
upvote count: 5
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/47634751
has title: Custom styling pandas dataframe
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82227494
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47634965
accepted answer: http://stackoverflow.com/a/47634965
tagged with: dataframe
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
tagged with: pandas
has body: The documentation shows an example, on how to change the font color of an element conditional on value, which works fine as expected: def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val &lt; 0 else 'black' return 'color: %s' % color s = df.style.applymap(color_negative_red) My question is how to implement a function that instead applies the font color change in the whole row?
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/82345117
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47692751
has text: @gonczor here's the actual error....raise TypeError:view must be callable or a list/tuple in the case of include()
score: 0

http://stackoverflow.com/q/47581334
answer count: 3
has answer: http://stackoverflow.com/a/74203963
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
tagged with: iteration
has title: How to iterate through a list with a Nonetype attribute? (Python)
type: Question
tagged with: network-programming
possible better answer: http://stackoverflow.com/a/47581453
tagged with: python
has body: I'm making a script for LAN host discovery in Python(without scapy yea I know, trying to use the sockets library for a learning experience). I am able to discover hosts but am having trouble separating the live hosts from the ones that returned no response because the only indicator I have is the timeout response(ping, which is either a float or None), but I cannot iterate ping as it can be a nontytpe so I tried to use hasattr to check the hosts, but I get a empty dictionary. Is there a better way I can iterate through the hosts? I can make the list of hosts a dictionary, but that doesn't solve the problem of iterating through nonetypes. Any input is appreciated, thanks. `if __name__ == '__main__': live = [] livee = [] for host, ping in multi_ping_query(subnet).iteritems(): subnet = host, '=', ping print(subnet) live.append(subnet) for ping in live: check = hasattr(ping, 'Nonetype') if check == False: livee.append(host) print(livee) Here is the function for multi_ping_query, I tried tweaking it to return a string if it does not connect however I didn't have much success with that either. def multi_ping_query(hosts, timeout=1, step=512, ignore_errors=False): results, host_list, id = {}, [], 0 for host in hosts: try: host_list.append(socket.gethostbyname(host)) except socket.gaierror: results[host] = None while host_list: sock_list = [] for ip in host_list[:step]: # select supports only a max of 512 id += 1 sock_list.append(PingQuery(ip, id, timeout)) host_list.remove(ip) # use timeout asyncore.loop(timeout) for sock in sock_list: results[sock.get_host()] = sock.get_result() return results
tagged with: ping
accepted answer: http://stackoverflow.com/a/47581577
has answer: http://stackoverflow.com/a/47581577
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47581453

http://stackoverflow.com/comment/82222851
score: 0
comment on: http://stackoverflow.com/q/47591359
has text: `cruda[~mask]=0` will set everywhere except the masked region to black---that's correct. Again, you *cannot pass* `cruda[mask==255]` into the function, as this masked indexing *always returns a linear array* and never returns a 2D array. I don't know what a `glcm` even is, so I don't know what the correct output is. I'm just stating different ways to mask or index the image to get what you want.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47576676
has body: If you're using yocto 2.1 (krogoth) then you need to use the krogoth branch of meta-java. meta-java's master branch can and does use functions that are only in oe-core master (such as oe.path.replace_absolute_symlinks).
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47576023
has comment: http://stackoverflow.com/comment/82220464
answers question: http://stackoverflow.com/q/47576023

http://stackoverflow.com/comment/82246320
type: QuestionComment
comment on: http://stackoverflow.com/q/47639630
score: 0
has text: Although I don't know whether this is a solution for your problem, how about removing the credential file of ``this_file_is_somewhere.json`` and recreating it?
type: Comment

http://stackoverflow.com/comment/82200010
type: AnswerComment
has text: Thank you! Presumably this mean one or more versions in requirements.txt for google-cloud or dependent packages is wrong.
type: Comment
comment on: http://stackoverflow.com/a/47602779
score: 0

http://stackoverflow.com/comment/82293962
comment on: http://stackoverflow.com/a/47664483
score: 2
has text: @M_13 No model will ever take cross-validation into account. CV is just to check the performance of the model on your data. Please read about [cross-validation](http://scikit-learn.org/stable/modules/cross_validation.html)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47664653
tagged with: for-loop
upvote count: 0
downvote count: 2
favorite count: 0
type: AnsweredQuestion
score: -2
accepted answer: http://stackoverflow.com/a/47664700
has body: My objective is transform this list comprehension into for loops : [[x * y for x in [1, 2]] for y in [3, 4, 5]] # gives [[3,6], [4,8], [5,10]] The only thing i can find : List = [] for y in [3, 4, 5]: for x in [1, 2]: List.append([y * x]) # Gives [[3], [6], [4], [8], [5], [10]] I feel silly but i struggle to find the solution.
possible better answer: http://stackoverflow.com/a/47664683
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/47664700
has answer: http://stackoverflow.com/a/47664683
has title: Convert simple list comprehension into for loops
type: Question
answer count: 2

http://stackoverflow.com/q/47577754
tagged with: scikit-learn
has body: I am trying to plot 4 images in a single row. Below is my code. plt.subplot(141) plt.plot(np.arange(50, 450, 50), BNB_df['auc'], 'bo--',label="BNB-AUC") plt.title('docs') plt.subplot(142) plt.plot(np.arange(50, 450, 50), BNB_df['accuracy'],'go-', label="BNB-Accuracy") plt.subplot(143) plt.plot(np.arange(50, 450, 50), LR_df['auc'], 'ro-',label="LR-AUC") plt.subplot(144) plt.plot(np.arange(50, 450, 50), LR_df['accuracy'],'go-', label="LR-Accuracy") plt.show() I don't know how to phrase my problem correctly. If I add this to my project report professor will not like it. How to make this graph wide and spaced equally in a single row?
has title: How to space plots in matplotlib equally without shrinking?
has comment: http://stackoverflow.com/comment/82114056
type: Question
has answer: http://stackoverflow.com/a/47579377
tagged with: matplotlib
tagged with: python
tagged with: numpy
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47579377
answer count: 1

http://stackoverflow.com/comment/82403428
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47700705
has text: You should print out the `params` variable. See if that gets printed twice.

http://stackoverflow.com/comment/82095989
score: 1
type: Comment
has text: Additionally Z needs to be a matrix with len(xx) columns and len(yy) rows. Right now its the same shape as xx. Essentially for every x in xx, and every y in yy Z[y][x] = predict([x,y])
type: QuestionComment
comment on: http://stackoverflow.com/q/47568428

http://stackoverflow.com/q/47622471
upvote count: 3
has answer: http://stackoverflow.com/a/47622734
downvote count: 0
has body: My problem sees me cycling through a long number in order to find the largest product of 5 consecutive digits within said number. I have a solution, but it currently involves the hard coding of the elements' positions, feels/looks hideous and is not scalable (what if I wanted the the sum of the 10 consecutive terms?). Is there a way to "Python" up this solution and nest it or optimise it in some way? n = 82166370484403199890008895243450658541227588666881 N = str(n) Pro = 0 for i in range(0, len(N) - 4): TemPro= int(N[i])*int(N[i+1])*int(N[i+2])*int(N[i+3])*int(N[i+4]) if TemPro&gt; Pro : Pro = TemPro print(Pro ) OS: Windows 7 Language: Python 3
linked to: http://stackoverflow.com/q/45815591
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82203382
has answer: http://stackoverflow.com/a/47622526
has comment: http://stackoverflow.com/comment/82202962
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82202856
tagged with: python
answer count: 2
tagged with: for-loop
has title: How to nest for loops without hard coding the element positions

http://stackoverflow.com/a/47672045
has comment: http://stackoverflow.com/comment/82304240
downvote count: 1
has comment: http://stackoverflow.com/comment/82303753
has body: I'll propose a workaround: it's to turn off printing from python during imports. It's lame but will fix in while they're fixing the forgotten print properly: import sys def write(x): pass saved = sys.stdout.write sys.stdout.write = write from kivy.app import App # works for any import that uses stdout to print stuff sys.stdout.write = saved just save sys.stdout.write, then override it with a method that does nothing, then import. Restore standard output after importing. I've tested it with a custom module that prints stuff when imported, and it suppresses the prints. If it doesn't work, the same thing can be tried with sys.stderr.write
has comment: http://stackoverflow.com/comment/82303676
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82304217
answers question: http://stackoverflow.com/q/47671606
upvote count: 2
has comment: http://stackoverflow.com/comment/82304157

http://stackoverflow.com/q/47661872
tagged with: python
has comment: http://stackoverflow.com/comment/82282990
linked to: http://stackoverflow.com/q/30677241
favorite count: 0
upvote count: 4
score: 4
tagged with: numpy
tagged with: correlation
has title: Fast way reduce noise of autocorrelation function in python?
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/47670308
has body: I can compute the autocorrelation using numpy's built in functionality: numpy.correlate(x,x,mode='same') However the resulting correlation is naturally noisy. I can partition my data, and compute the correlation on each resulting window, then average them all together to compute cleaner autocorrelation, similar to what signal.welch does. Is there a handy function in either numpy or scipy that does this, possibly faster than I would get if I were to compute partition and loop through the data myself? UPDATE This is motivated by @kazemakase answer. I have tried to show what I mean with some code used to generate the figure below. One can see that @kazemakase is correct with the fact that the AC function naturally averages out the noise. However the averaging of the AC has the advantage that it is much faster! np.correlate seems to scale as the slow O(n^2) rather than O(nlogn) that I would expect if the correlation was calculated using circular convolution via the FFT... from statsmodels.tsa.arima_model import ARIMA import statsmodels as sm import matplotlib.pyplot as plt import numpy as np np.random.seed(12345) arparams = np.array([.75, -.25, 0.2, -0.15]) maparams = np.array([.65, .35]) ar = np.r_[1, -arparams] # add zero-lag and negate ma = np.r_[1, maparams] # add zero-lag x = sm.tsa.arima_process.arma_generate_sample(ar, ma, 10000) def calc_rxx(x): x = x-x.mean() N = len(x) Rxx = np.correlate(x,x,mode="same")[N/2::]/N #Rxx = np.correlate(x,x,mode="same")[N/2::]/np.arange(N,N/2,-1) return Rxx/x.var() def avg_rxx(x,nperseg=1024): rxx_windows = [] Nw = int(np.floor(len(x)/nperseg)) print Nw first = True for i in range(Nw-1): xw = x[i*nperseg:nperseg*(i+1)] y = calc_rxx(xw) if i%1 == 0: if first: plt.semilogx(y,"k",alpha=0.2,label="Short AC") first = False else: plt.semilogx(y,"k",alpha=0.2) rxx_windows.append(y) print np.shape(rxx_windows) return np.mean(rxx_windows,axis=0) plt.figure() r_avg = avg_rxx(x,nperseg=300) r = calc_rxx(x) plt.semilogx(r_avg,label="Average A…
has comment: http://stackoverflow.com/comment/82283389
type: Question

http://stackoverflow.com/comment/82210956
has text: Thank you for your clear and kind direction. I solved my problem,
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47590826
type: Comment

http://stackoverflow.com/q/47586526
has body: I have been following the Pagekite installation for Mac at (https://pagekite.net/support/quickstart/). Here are the instructions I have followed: First I download the program (pagekite.py) and I put it into my sites folder. Next I attempt to run Pagekite.py for the first time by running the following command $ pagekite.py --signup but I can only get to step 2 before I get the error: -bash $: command not found I'll admit I am quite new at troubleshooting terminal commands, so if I left out any information let me know. See below-attached screenshot.
type: Question
has comment: http://stackoverflow.com/comment/82131244
tagged with: terminal
has title: Mac Bash Command Not Found for Pagekite Signup
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/82131026
has comment: http://stackoverflow.com/comment/82130747
score: 0
tagged with: bash
has answer: http://stackoverflow.com/a/54511614
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/139337223
type: Comment
type: QuestionComment
has text: Disagree, @BillBell. The confidence interval is build around the point estimate for the difference in the two proportions, which is not a function of the hypothesis, or any of the values related to the hypothesis. The confidence limits are calculated based on how variable that point estimate is.
comment on: http://stackoverflow.com/q/47570903
score: 0

http://stackoverflow.com/q/47663759
answer count: 0
has title: Reshaping train and test sets for LSTMs in Keras
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82310472
has comment: http://stackoverflow.com/comment/82288017
has body: So I've seen a few SO posts and Issue posts on the Keras Github about this but none of these solutions seem to work for me so far. My question relates to the input_shape for an LSTM in Keras. Unlike most examples my problem is a time-series forecasting problem and has nothing to do with the types of classification examples I see all over the place. I would like to know how to reshape my training and test data sets when fitting an LSTM model in Keras. For my use case I'd like to model an LSTM with 82 time-steps and 40 features per batch # train_X, test_X, train_y &amp; test_y are numpy arrays print(train_X.shape, train_y.shape, test_X.shape, test_y.shape) &gt; ((57482, 40), (57482,), (12546, 40), (12546,)) # For my use case I'd like to model an LSTM with 82 time-steps and 40 features per batch # reshape input to be 3D [samples, timesteps, features] train_X = train_X.reshape((train_X.shape[0]/82, 82, train_X.shape[1])) test_X = test_X.reshape((test_X.shape[0]/82, 82, test_X.shape[1])) train_y = train_y.reshape((train_y.shape[0]/82, 82, 1)) test_y = test_y.reshape((test_y.shape[0]/82, 82, 1)) print(train_X.shape, train_y.shape, test_X.shape, test_y.shape) &gt; ((701, 82, 40), (701, 82, 1), (153, 82, 40), (153, 82, 1)) When I now create and LSTM and then attempt to fit it, like so, model = Sequential() model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2]), return_sequences=True)) model.add(LSTM(50)) model.add(Dense(1)) model.compile(loss='mae', optimizer='adam') # fit network history = model.fit(train_X, train_y, epochs=50, batch_size=1, validation_data=(test_X, test_y), verbose=2, shuffle=False) I get the following error, ValueError: Error when checking target: expected dense_15 to have 2 dimensions, but got array with shape (701, 82, 1) I think I understand the concept of the input_shape and batch_size yet I'm clearly not able to reshape my train and test sets to match what Keras requires. What am I doing wrong? Thanks for the help!
tagged with: keras
type: Question
has comment: http://stackoverflow.com/comment/82322937
linked to: http://stackoverflow.com/q/43034960
tagged with: forecasting
has comment: http://stackoverflow.com/comment/82288932
tagged with: python
has comment: http://stackoverflow.com/comment/82288966
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/82322973

http://stackoverflow.com/q/47595771
has comment: http://stackoverflow.com/comment/82150484
has answer: http://stackoverflow.com/a/47595943
has comment: http://stackoverflow.com/comment/82149052
accepted answer: http://stackoverflow.com/a/47595943
upvote count: 1
downvote count: 1
favorite count: 0
has title: list index out of range for while loop
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/47596177
has body: def main(): infile = open('charge_accounts.txt', 'r') chargeAccounts = infile.readlines() index = 0 while index &lt; len(chargeAccounts): chargeAccounts[index] = chargeAccounts[index].rstrip('\n') index += 1 userAccount = input("Please enter a charge account number: ") count = 0 while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]: count += 1 if chargeAccounts[index] == userAccount: print("The account number", userAccount, "is in the list.") else: print("The account number", userAccount, "in not in the list.") main() I'm trying to make a code in python that has the user input a number and checks to see if that number is in a list. When I try to run this code, I get an error that says that the list index is out of range in the while loop. There are only 18 items in the list, and I have the while loop set to terminate at 17(which should be 18 in the list). Edit: It also doesn't work if the while loop is set to chargeAccounts[count] != chargeAccounts[17]: Here's the exact error code: Traceback (most recent call last): File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 23, in &lt;module&gt; main() File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 13, in main while userAccount != chargeAccounts[count] or chargeAccounts[count] != chargeAccounts[17]: IndexError: list index out of range Here's the content of the original text file: 5658845 4520125 7895122 8777541 8451277 1302850 8080152 4562555 5552012 5050552 7825877 1250255 1005231 6545231 3852085 7576651 7881200 4581002
possible better answer: http://stackoverflow.com/a/47596177
has comment: http://stackoverflow.com/comment/82149171
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/a/47655089
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47630767
downvote count: 0
upvote count: 1
has body: I think you're doing something else wrong, i copied all three files and ran it just fine. https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8 here are the full steps: (i really suggest you are in /tmp when you run this) # 1. Create a temp folder # 2. Download all the files into the temp folder # 3. Build the docker image # 4. Run the image in a detached mode -- so we can curl the url # 5. Sleep a little and wait until the app is fully up # 6. Test that it all works # 7. Stop the container (and we don't care about its stdout) mkdir -p dockerapp && \ curl -sL https://gist.github.com/kingbuzzman/b48be91757fc60e97f6a9a189d006bd8/download | tar -xvz -C dockerapp --strip-components=1 && \ docker build -t friendlyhello dockerapp && \ docker run --rm -p 4000:80 --name friendlyhello -d friendlyhello && \ sleep 2 && \ curl -s http://localhost:4000/ -w "\n" && \ docker kill friendlyhello >/dev/null (you can highlight and copy all this straight into your terminal and see this) What we're looking for here is the last line Hello World! Hostname: 979c5e755f64 Visits: cannot connect to Redis, counter disabled which is how we know its running.

http://stackoverflow.com/q/47618427
has comment: http://stackoverflow.com/comment/82195322
linked to: http://stackoverflow.com/q/47613947
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/3474382
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pyzmq
tagged with: zeromq
has title: How to run a zmq and other while True: at the same time independently?
accepted answer: http://stackoverflow.com/a/47643658
has comment: http://stackoverflow.com/comment/82196196
tagged with: python
has answer: http://stackoverflow.com/a/47643658
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/82195398
has body: I have this code for my server: import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5000") while True: message = socket.recv() socket.send(b"World") print "sent" while True: print "done." I have a separate client script that sends a message through zmq to this one whenever i send a message. On the server (this code), if i only have the first while True:, it prints "sent" every time i send a message, and if i only have the second while True:, it prints "done." continuously. But if i put both, it never prints done (or if i switch their order and put both it never prints "sent" when i send a message"). As an output i want it to continuously print "done.", and also print "sent" when I get a message. So something like this: done. done. done. done. done. sent done. lots more done.... Basically i want both loops to run continuously and completely independently of each other. N.B. I have tried using multiprocessing (such as in the 3rd answer here How do I run two python loops concurrently?), but couldn't get that to work either. I tried it as below: import time import zmq from multiprocessing import Process context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5000") i = time.time() def zmq_loop(): while True: message = socket.recv() socket.send(b"World") print "sent" def done_loop(): global i while True: i2 = time.time()-i if i2%2 == 0: print "done." if __name__ == "__main__": Process(target=zmq_loop).start() Process(target=done_loop).start()
has comment: http://stackoverflow.com/comment/82195370

http://stackoverflow.com/q/47684308
type: Question
has comment: http://stackoverflow.com/comment/82328525
tagged with: nginx
type: UnansweredQuestion
tagged with: django
tagged with: devops
tagged with: python
has comment: http://stackoverflow.com/comment/82328400
has body: I use NGINX+GUNICORN+DJANGO and my gunicorn status is active. I want to set up nginx with django. I create a new file named 'mysite'in /etc/nginx/sites-available server { listen 8000 default_server; listen [::]:8000 default_server; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/split/mysite; } location / { include proxy_params; proxy_pass http://unix:/home/split/mysite/mysite.sock; } } saved it and create symbolyc link to /etc/nginx/sites-enabled After that I did sudo service nginx restart and got this: Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details. I went to journalctl -xe -- -- Unit nginx.service has finished shutting down. Dec 07 01:05:17 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server... -- Subject: Unit nginx.service has begun start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit nginx.service has begun starting up. Dec 07 01:05:17 ubuntu nginx[49646]: nginx: [crit] pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory) Dec 07 01:05:17 ubuntu nginx[49646]: nginx: configuration file /etc/nginx/nginx.conf test failed Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Control process exited, code=exited status=1 Dec 07 01:05:17 ubuntu sudo[49639]: pam_unix(sudo:session): session closed for user root Dec 07 01:05:17 ubuntu systemd[1]: FAILED TO START A HIGH PERFORMANCE WEB SERVER AND A REVERSE PROXY SERVER. -- Subject: Unit nginx.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit nginx.service has failed. -- -- The result is failed. Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Unit entered failed state. Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Failed with result 'exit-code'. Dec 07 01:05:42 u…
score: 0
has title: Trouble with nginx and django configuration?
answer count: 1
has answer: http://stackoverflow.com/a/47684784
has comment: http://stackoverflow.com/comment/82328545

http://stackoverflow.com/comment/82255862
has text: your row and column multiplies to 5*10 = 50, so in the textarea you are not even passing more than 50 characters, so how will the error raise, try check len > 10 and check
type: QuestionComment
comment on: http://stackoverflow.com/q/47648632
score: 0
type: Comment

http://stackoverflow.com/a/47662198
score: 0
type: Answer
has body: use the following format to truncate float ("%.Nf") N=number of points after . print("%.3f" %float(area),("Centimeter"))
answers question: http://stackoverflow.com/q/47661999

http://stackoverflow.com/q/47662610
answer count: 1
tagged with: python
tagged with: dictionary
score: 0
has title: Python dictionary comprehension checking if something doesn't exist and setting a value
tagged with: list
has body: I have a dictionary that looks like this old_dict = {"language":"english","gender":"female","job":"ceo"} The only keys i'm interested in are "language","job","hobby" Filtering out using this logic only works for the keys that exist in my original dictionary. dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys if your_key in your_keys } How can I alter this code to add conditions, if the key doesn't exist to set a null/none value to the key. your_keys = ["language","job"] The output i'm looking for is {"language":"english","job":"ceo","hobby":None}
type: Question
has answer: http://stackoverflow.com/a/47662671
type: UnansweredQuestion

http://stackoverflow.com/a/47605281
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47605234
has body: steps:: --open your command prompt and change your directory to C:\Python27\Scripts --make sure that you have install 'pip' or 'easy_install' --if you have pip install then directly give command pip install mrjob or easy_install mrjob it will take few minutes to install the package .once its get completed the check that whether that package is install or not with following command import mrjob

datareader
tags question: http://stackoverflow.com/q/47567365
tags question: http://stackoverflow.com/q/47587680
tag name: datareader
type: Tag
tags question: http://stackoverflow.com/q/47652246

http://stackoverflow.com/q/47572091
tagged with: list
has answer: http://stackoverflow.com/a/47572220
score: 1
has comment: http://stackoverflow.com/comment/82101495
downvote count: 0
answer count: 1
has title: efficient way to iterate list?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: word2vec
upvote count: 1
tagged with: python
has body: I am trying to find the duplicated words in google word2vec, for example, in word2vec, there are two word embeddings for 'Hello' and 'hello'. Here is my code, it's simple but not efficient. def load_w2v(): openfile = '../Pretrained/word2vec/GoogleNews-vectors-negative300.bin' model = gensim.models.KeyedVectors.load_word2vec_format(openfile, binary=True) return model.vocab.keys() if __name__ == '__main__': pre_trained_words = load_w2v() ready_have = [] duplicated_words = [] for word in pre_trained_words: if word.lower() not in ready_have: ready_have.append(word.lower()) else: duplicated_words.append(word) continue However, as the pre-trained google word2vec has 3 million words, my computer has been runing for 18 hours and not finish, so I was wondering is there some effiencient way to get the duplicated words?
has comment: http://stackoverflow.com/comment/82101164

http://stackoverflow.com/q/47557109
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82079453
type: UnansweredQuestion
score: -2
tagged with: datetime
tagged with: python
has title: How do I merge different columns in jupyter?
has comment: http://stackoverflow.com/comment/82071965
has answer: http://stackoverflow.com/a/47567168
tagged with: pandas
has body: I have a Pandas dataframe that contains 6 columns Jaar Maand Dag Uur Minuut R10 0 2003 1 1 0 0 0.00000 1 2003 1 1 0 15 0.00000 2 2003 1 1 0 30 0.00000 3 2003 1 1 0 45 0.00000 but I would like to have a different format for my data, like in Year-Month-Day Hour:Minute R10 0 2003-01-01 00:00 0.00000 ... ... ... ... How can I make from the different columns 3 columns? One for the Year-Month-day, one for the time and one for R10? With python.
upvote count: 0

http://stackoverflow.com/comment/82090832
comment on: http://stackoverflow.com/a/47564195
score: 0
type: AnswerComment
type: Comment
has text: You need to add `%pylab inline` to your imports section to display graphics in the notebook with matplotlib / pylab.

http://stackoverflow.com/q/47627965
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47628019
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47628019
has title: rearrange groups in dataframe based on day and month from another dataframe index
tagged with: pandas
tagged with: python
has body: I have 2 dataframes: df_a datetime var 2016-10-15 110.232790 2016-10-16 111.020661 2016-10-17 112.193496 2016-10-18 113.638143 2016-10-19 115.241448 2017-01-01 113.638143 2017-01-02 115.241448 and df_b datetime var 2000-01-01 165.792185 2000-01-02 166.066959 2000-01-03 166.411669 2000-01-04 167.816046 2000-01-05 169.777814 2000-10-15 114.232790 2000-10-16 113.020661 2001-01-01 164.792185 2001-01-02 161.066959 2001-01-03 156.411669 2002-01-04 167.816046 2002-01-05 169.777814 2002-10-15 174.232790 2003-10-16 114.020661 df_a has information for the year 2016, 2017 and df_b has information for years from 2000 to 2015 (there is no overlap in the years). Can I arrange each group in the df_b dataframe to have the same order in terms of day of year as df_a? A group is defined as rows with the same year e.g. 2000
score: 1
answer count: 1

http://stackoverflow.com/q/47662947
type: Question
has comment: http://stackoverflow.com/comment/82285596
has answer: http://stackoverflow.com/a/47668059
has comment: http://stackoverflow.com/comment/82285331
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82285271
linked to: http://stackoverflow.com/q/89228
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/82285124
has title: How to run Multiple external commands from Python Script
has body: I have a requirement where I have to run these few commands in the terminal using a python script.The requirement is as such: ssh abc.xyz.com After ssh to that machine, ssh to the environment ssh qa and then run few commands in the environment I have tried achieving this using os.system() and using subprocess.call() but no luck. Specifically, I tried doing this : import subprocess from time import sleep subprocess.call("ssh abc.def.com", shell=True) subprocess.call("python", shell=True) sleep(0.3) subprocess.call("ssh qa", shell=True)
score: 0
has comment: http://stackoverflow.com/comment/82285481
has comment: http://stackoverflow.com/comment/82285077
has comment: http://stackoverflow.com/comment/82285691
upvote count: 2
has comment: http://stackoverflow.com/comment/82285601
has comment: http://stackoverflow.com/comment/82285445
has comment: http://stackoverflow.com/comment/82285248
downvote count: 2
has comment: http://stackoverflow.com/comment/82285165
has comment: http://stackoverflow.com/comment/82285256
answer count: 1
favorite count: 0

http://stackoverflow.com/q/47674311
answer count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/47674877
type: Question
upvote count: 40
score: 38
has answer: http://stackoverflow.com/a/47674877
tagged with: apache-spark-sql
possible better answer: http://stackoverflow.com/a/58445360
has answer: http://stackoverflow.com/a/66344486
has answer: http://stackoverflow.com/a/64566859
has answer: http://stackoverflow.com/a/58445360
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/58804304
has title: How to create a sample single-column Spark DataFrame in Python?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59973327
has answer: http://stackoverflow.com/a/63704166
has body: I want to create a sample single-column DataFrame, but the following code is not working: df = spark.createDataFrame(["10","11","13"], ("age")) ## ValueError ## ... ## ValueError: Could not parse datatype: age The expected result: age 10 11 13
tagged with: apache-spark
downvote count: 2

http://stackoverflow.com/a/47562412
has comment: http://stackoverflow.com/comment/113217315
has comment: http://stackoverflow.com/comment/102958870
has comment: http://stackoverflow.com/comment/108984685
has comment: http://stackoverflow.com/comment/133158741
score: 176
has comment: http://stackoverflow.com/comment/106726557
has comment: http://stackoverflow.com/comment/133579743
has comment: http://stackoverflow.com/comment/108984918
has comment: http://stackoverflow.com/comment/98011034
has comment: http://stackoverflow.com/comment/133158589
has comment: http://stackoverflow.com/comment/114036776
has comment: http://stackoverflow.com/comment/108983919
downvote count: 4
has comment: http://stackoverflow.com/comment/133126449
has comment: http://stackoverflow.com/comment/98014709
has comment: http://stackoverflow.com/comment/133159739
has comment: http://stackoverflow.com/comment/110950592
has comment: http://stackoverflow.com/comment/98004765
has comment: http://stackoverflow.com/comment/102962740
has comment: http://stackoverflow.com/comment/114036723
upvote count: 180
has comment: http://stackoverflow.com/comment/82082755
has comment: http://stackoverflow.com/comment/98014723
has comment: http://stackoverflow.com/comment/133135227
has comment: http://stackoverflow.com/comment/82084062
has comment: http://stackoverflow.com/comment/133579598
has comment: http://stackoverflow.com/comment/110950210
has body: Here is how I do it: Class (or group of) is actually a full module. You don't have to do it this way, but if you're splitting a class on multiple files I think this is 'cleanest' (opinion). The definition is in __init__.py, methods are split into files by a meaningful grouping. A method file is just a regular Python file with functions, except you can't forget 'self' as a first argument. You can have auxiliary methods here, both taking self and not. Methods are imported directly into the class definition. Suppose my class is some fitting GUI (this is actually what I did this for first time). So my file hierarchy may look something like mymodule/ __init__.py _plotstuff.py _fitstuff.py _datastuff.py So plot stuff will have plotting methods, fit stuff contains fitting methods, and data stuff contains methods for loading and handling of data - you get the point. By convention I mark the files with a _ to indicate these really aren't meant to be imported directly anywhere outside the module. So _plotsuff.py for example may look like: def plot(self,x,y): #body def clear(self): #body etc. Now the important thing is file __init__.py: class Fitter(object): def __init__(self,whatever): self.field1 = 0 self.field2 = whatever # Imported methods from ._plotstuff import plot, clear from ._fitstuff import fit from ._datastuff import load # static methods need to be set from ._static_example import something something = staticmethod(something) # Some more small functions def printHi(self): print("Hello world") Tom Sawyer mentions PEP-8 recommends putting all imports at the top, so you may wish to put them before __init__, but I prefer it this way. I have to say, my Flake8 checker does not complain, so likely this is PEP-8 compliant. Note the from ... import ... is particularly useful to hide some 'helper' functions to your methods you don't want accessible through objects of the class. I usually also place the custom exceptions for the class in the different files, but import them …
has comment: http://stackoverflow.com/comment/110948821
has comment: http://stackoverflow.com/comment/98004836
has comment: http://stackoverflow.com/comment/108984243
has comment: http://stackoverflow.com/comment/133158709
answers question: http://stackoverflow.com/q/47561840
has comment: http://stackoverflow.com/comment/106733027
has comment: http://stackoverflow.com/comment/110950106
has comment: http://stackoverflow.com/comment/108984996
has comment: http://stackoverflow.com/comment/108984763
has comment: http://stackoverflow.com/comment/82082995
has comment: http://stackoverflow.com/comment/114036648
has comment: http://stackoverflow.com/comment/108984467
has comment: http://stackoverflow.com/comment/82082778
type: Answer
has comment: http://stackoverflow.com/comment/110950621

http://stackoverflow.com/a/47600338
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47600238
has comment: http://stackoverflow.com/comment/82162474
has comment: http://stackoverflow.com/comment/82161867
has comment: http://stackoverflow.com/comment/82161851
has comment: http://stackoverflow.com/comment/82161832
has body: Deploying pure python apps with Pyinstaller is straight forward but it comes tricky especially with a framework like pyqt. The best results i got so far was using cx_freeze which makes sure that all the dependencies are packaged correctly. Here is an extensive walkthrough: https://www.smallsurething.com/a-really-simple-guide-to-packaging-your-pyqt-application-with-cx_freeze/
type: Answer
accepted answer of: http://stackoverflow.com/q/47600238
score: 0
has comment: http://stackoverflow.com/comment/82164159

http://stackoverflow.com/a/47634570
accepted answer of: http://stackoverflow.com/q/47633936
has body: Based on @CommonSense comment to the question. byte_string = s.recv(1024) path = '/home/pi/Desktop/gifs/%s.gif' % byte_string.decode() root = tk.Tk() image1 = tk.PhotoImage(file=path) Thelabel = tk.Label(image=image1) Thelabel.pack() root.update()
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47633936
type: Answer

http://stackoverflow.com/comment/82230508
score: 0
comment on: http://stackoverflow.com/q/47635759
type: Comment
type: QuestionComment
has text: see edit, Im printing the output to a file. still crashs

http://stackoverflow.com/comment/82097139
type: QuestionComment
has text: `KeyError: ' STATE_ABBR'`
comment on: http://stackoverflow.com/q/47569869
score: 0
type: Comment

http://stackoverflow.com/comment/82245566
type: QuestionComment
comment on: http://stackoverflow.com/q/47541028
score: 0
has text: If an absolute path to the `pylint` command isn't working then it sounds like a bug. Feel free to file an issue at https://github.com/microsoft/vscode-python/issues .
type: Comment

http://stackoverflow.com/comment/82051304
has text: Just delete that sqlite3 file. Remove the migrations files. Run makemigrations and migrate. I suppose that will make it work.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47546587
type: Comment

http://stackoverflow.com/a/47558340
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47557601
downvote count: 0
upvote count: 1
has body: Here is how I did it. My solution is not as "fancy" as Scott's but I broke down the steps in my logic. His solution is probably better for a plug-and-play scenario: #reading in dataframe from your text df1 = pd.read_clipboard() # creating an untouched copy of df1 for minpulation df2 = df1.copy() # dropping the duplicates of index and Date to get one row df1 = df1.drop_duplicates(subset=['index', 'Date']) # creating a dictionary of key, value pairs for each column and value kv = dict(zip(df2.Sub_Element, df2.Value)) # creating a datframe out of the above dictionary new_df = pd.DataFrame(kv, index=[0]) # creating temp values to merge on df1['tmp'] = 1 new_df['tmp'] = 1 # merging on the tmp values output_df = df1.merge(new_df, on='tmp') # cleaning up for the output del output_df['Sub_Element'] del output_df['Value'] del output_df['tmp] #output index Date Device Element description eth_ip_addr eth_rxload eth_txload 0 2017-11-28 16:39:00 x y string x.x.x.x 30 9

http://stackoverflow.com/comment/82192208
type: Comment
comment on: http://stackoverflow.com/q/47616887
has text: Then the short answer is: you can't. Please read the article I linked. You probably have an [XY problem](http://xyproblem.info), hence the request for context you seem determined to ignore.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82186063
comment on: http://stackoverflow.com/q/47613809
has text: It slows it down as much as adding a new line to separate statements in JavaScript
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82286045
type: AnswerComment
comment on: http://stackoverflow.com/a/47663163
score: 0
has text: I'm not going to provide the complete solution to your homework. The example above gives you the exact code to create an adjacency list. If you plug this into @TilakPutta's code above instead of the dict you should get the answer
type: Comment

http://stackoverflow.com/comment/84092067
score: 0
type: Comment
type: AnswerComment
has text: I did, no luck.
comment on: http://stackoverflow.com/a/48548056

http://stackoverflow.com/a/47594637
downvote count: 0
has body: Those checks in the form UserPassword == UserPassword.isupper() will not work. Here, you are comparing a string, the password, to a boolean, the result of isX(). Hence, all those checks are False and you get to the else branch (if the length is acceptable). In the case of upper and lowercase chars, you could use UserPassword == UserPassword.upper() instead (just upper, not isupper, and analogously with lower()), i.e. compare the password to it's upper/lowercased version, but for digits this does not work. Instead, you can use any to check if any char is a digit: any(c.isdigit() for c in UserPassword) Edit: You can use UserPassword == UserPassword.upper() to check if the password does not contains any lowercase letters, which is kind of unintuitive. Instead, I'd suggest using any for all the checks and also inversing the condition so the "positive" case is in the ifs body and the "negative" in the else. Something like this: up = UserPassword if 8 &lt;= len(up) &lt;= 24 and any(c.isupper() for c in up) and any(c.islower() for c in up) and any(c.isdigit() for c in up) and any(c.isalpha() for c in up): Or a bit shorter, using a list of functions: if 8 &lt;= len(up) &lt;= 24 and all(any(f(c) for c in up) for f in (str.islower, str.isupper, str.isdigit, str.isalpha)):
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47594473

http://stackoverflow.com/q/47622828
upvote count: 1
tagged with: machine-learning
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47626540
has body: I am new to machine learning thing and python. I have created a simple linear regression model in python . I can test the accuracy of my model but only for the data in my data set , my data set is a csv file which contains a relation between salary and years of experience . But I want to use it in practical life . Like I will input the years of experience and the output will be predicted salary . Here is what I have done so far import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" # Fitting Simple Linear Regression to the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test) I want to modify the above code in such way, that I can give input years of experience and the output will expected salary . Thanks in advance .
has comment: http://stackoverflow.com/comment/82203527
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47622981
has title: How to test machine learning model with real data in python
has answer: http://stackoverflow.com/a/47622981
has answer: http://stackoverflow.com/a/47626540
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/q/47585122
downvote count: 0
has answer: http://stackoverflow.com/a/47585171
has body: How do I check to see how many times the keys in one dict1 exist in dict2. If the keys of dict1 exist in dict2 a variable, val, with an initial value of 4 should be subtracted based on how many times the keys are found. For example dict1 looks like this print dict1 {(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1} and dict2 looks like this print `dict2` {(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100} Since there are two repeat keys between the dicts,val should be equal to 2. if dict2 looks identical to dict1, then val should be 0. Also, dict1 will always be the same size, but dict2 can get quite large, so a fast lookup method would be ideal. Lastly, the values of dicts here don't really mean anything.
has comment: http://stackoverflow.com/comment/82128249
has comment: http://stackoverflow.com/comment/82128061
has answer: http://stackoverflow.com/a/47585141
has title: count how many times keys repeat between dictionaries in python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82127977
possible better answer: http://stackoverflow.com/a/47585161
tagged with: python
tagged with: dictionary
score: 4
has answer: http://stackoverflow.com/a/47585161
has answer: http://stackoverflow.com/a/47585149
answer count: 4
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47585141

http://stackoverflow.com/comment/82311367
type: Comment
type: QuestionComment
has text: Well the python script may not because it is doing something other than I expect. But what I wanted was to get the full area beneath these points and if you the numbers you would get 15 and 25.
score: 0
comment on: http://stackoverflow.com/q/47675074

http://stackoverflow.com/comment/122393807
type: Comment
has text: `print(format(160,'016b'))` Note the extra 0 in front of the 16. That will make it so you number is padded with zeros, rather than spaces.
comment on: http://stackoverflow.com/a/47664916
type: AnswerComment
score: 1

http://stackoverflow.com/a/47615175
type: Answer
has body: I would use np.where in this scenario. import numpy as np df['q'] = np.where(df.Quality &lt; 7, 0, 1))
score: 1
has comment: http://stackoverflow.com/comment/82189309
answers question: http://stackoverflow.com/q/47614865
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47624674
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82222757
has title: Python thread blocks after getting from Queue
tagged with: queue
has comment: http://stackoverflow.com/comment/82208249
type: Question
has body: I have a list of emails i want to validate from same domain. Firstly, I check if the domain allows verfication or is a catchall (accepts all email user as valid). E.g Assuming [a@domain.com, b@domain.com] is the list, I will check if foo-fake@domain.com would be valid, if it is return from function. If not use multiple thread to verify all emails in list - if all fail return the last item. If one is valid and other threads are running stop them and return the valid one. from Queue import Queue import threading import smtplib class MailWorker(threading.Thread): kill = False def __init__(self, in_que, out_que): super(MailWorker, self).__init__() self.in_que = in_que self.out_que = out_que def run(self): while True: email, host = self.in_que.get() self.test_email(email, host) self.in_que.task_done() def test_email(self, email, host, retry=0): status = "Unknown" code = None rand = "info@example.com" try: server = smtplib.SMTP(timeout=20) server.connect(host, 25) server.ehlo_or_helo_if_needed() code, response = server.docmd('mail from:', "&lt;{}&gt;".format(rand)) code, response = server.docmd('rcpt to:', "&lt;{}&gt;".format(email)) if code == 421: while retry &lt; 3: if retry &gt;= 3: server.quit() self.out_que.put((email, "Service not available", code)) server.quit() return self.test_email(email, host, retry=retry) if code == 250: status = 'valid' self.out_que.put((email, status, code,)) except smtplib.SMTPServerDisconnected: while retry &lt; 3: retry += 1 status = "(SMTP Disconnected Unexpectedly) Retry # {}".format(retry) code = -2 time.sleep(2) if retry &gt;= 3: self.out_que.put((email, "SMTP Disconnected", code)) else: return self.test_email(email, host, retry=retry) self.out_que.put((email, status, code,)) def check_email(emails, domain, index=0, is_main=False): email = status = code = None in_que = Queue(maxsize=10) out_que = Queue(maxsize=10) if 'brighthouse' in domain: host = 'brighthouse-co-uk.mail.protection.outlook.com' else: host = 'eu-smtp-inbound-2.mimeca…
has comment: http://stackoverflow.com/comment/82209647
tagged with: python-multithreading
type: UnansweredQuestion

http://stackoverflow.com/comment/82208065
has text: @alecxe nope.. :(
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47624644
type: Comment

http://stackoverflow.com/comment/82258557
score: 2
type: Comment
type: QuestionComment
has text: Do you have a virtual environment ? as per the doc, the error is for django 2.0 only. Please check your version using shell. python manage.py shell. >> import django >> django.VERSION
comment on: http://stackoverflow.com/q/47649854

http://stackoverflow.com/a/47672057
has body: I wouldn't recommend it, but if you really need it, then you can do it this way: class Obj(object): def __init__(self): self.A = 2 self.B = 3 def fun(self, ar): def funA(self): print self.A def funB(self): x = self.B + 4 print self.B for letter in ar: name = 'fun' + letter + '()' exec(name) obj_instance=Obj() obj_instance.fun(['A', 'B']) exec() executes any string that you put in parentheses as if it was python code.
score: 0
has comment: http://stackoverflow.com/comment/82304484
answers question: http://stackoverflow.com/q/47671795
type: Answer

http://stackoverflow.com/a/47682751
answers question: http://stackoverflow.com/q/47682723
score: 1
type: Answer
has body: Cast gamble to a number money_left = int(money_left) - int(gamble)
has comment: http://stackoverflow.com/comment/82324842
has comment: http://stackoverflow.com/comment/82325003
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82212531
comment on: http://stackoverflow.com/a/47616202
score: 0
type: AnswerComment
type: Comment
has text: @csharpcoder and you earned my downvote because I don't believe your answer is useful. Advising indexing a list, even if you used the right loop variable name, over iterating over triples is, well, inadvisable. Note also that your code as-written has a hastily-written typo, and fails on a `NameError`.

http://stackoverflow.com/comment/82355747
has text: u can see the output as well :)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47697667

http://stackoverflow.com/a/47664755
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82289018
has body: You have two issues here. The first is that you're a little confused about list indexes. Lists in python are "zero-indexed" meaning that to get the first element of a list named L you need to do L[0]. Similarly, to get the second, like you need, you do L[1]. The other issue is that all elements from sys.argv are going to be strings, so checking the type won't work. You should try to cast the piece of user input as an int inside a try block and catch a ValueError. It'd look something like this: if __name__ == '__main__': if len(sys.argv) &lt; 2 or len(sys.argv) &gt; 2: help() else: try: insert_by_user = int(sys.argv[1]) print(PWrand(insert_by_user)) except ValueError: print("It need to be an Int!") The code inside the except ValueError: block will only be executed if the user's input cannot be properly cast to an integer.
answers question: http://stackoverflow.com/q/47664687
type: Answer

http://stackoverflow.com/comment/82334187
has text: What is the point in calling `mainloop()` (an infinite loop) inside an infinite loop?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47687058

http://stackoverflow.com/comment/82121665
score: 1
has text: Conceptually you do exactly the same thing. The difference is in the syntax and the APIs.
type: QuestionComment
comment on: http://stackoverflow.com/q/47582033
type: Comment

http://stackoverflow.com/comment/82206968
score: 0
type: Comment
type: QuestionComment
has text: You generally can't just use a negative number in an array index - what are you trying to accomplish there?
comment on: http://stackoverflow.com/q/47586709

http://stackoverflow.com/q/47581072
has answer: http://stackoverflow.com/a/47581283
has comment: http://stackoverflow.com/comment/82119741
tagged with: regex
has title: Regex to find the last instance of a string
has answer: http://stackoverflow.com/a/47582570
type: Question
possible better answer: http://stackoverflow.com/a/47582570
answer count: 2
accepted answer: http://stackoverflow.com/a/47581283
has comment: http://stackoverflow.com/comment/82119833
tagged with: python
has body: I am trying to use REGEX to parse a gherkin file. I have successfully split it into multiple REGEX's to accomplish what I want, but I am having a problem getting the last instance of one of the Values. (?s)(?P&lt;Then&gt;Then.*?)Scenario:|$ returns all instances except the last from # This is a sample .feature file Feature: Authorized Logins Users will have individual logins, gated by passwords. Scenario: Invalid login credentials are entered Given Default Database is loaded And App is available and running When User enters invalid login Then Application should deny login Scenario: Valid login credentials are entered Given Default Database is loaded And App is available and running When User enters valid login And display test case selection screen Then Application should grant login And display test case selection screen Scenario: No database connection Given Database is stopped And App is available and running When User enters valid login Then Application will deny login And inform of no connection The last Then Application will deny login And inform of no connection Doesn't get selected. I have tried various things, but can't seem to get it. Any suggestions? https://regex101.com/r/iiM5X5/2
has comment: http://stackoverflow.com/comment/82119946
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47586224
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/46814823
has comment: http://stackoverflow.com/comment/82137266
has title: Connecting to an SFTP server using pysftp and Python 3 with just the server fingerprint
tagged with: python
accepted answer: http://stackoverflow.com/a/47918427
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I'm in kind of a bizarre situation where I need to connect to an SFTP server for the first time but I can't seem to find a way to get access to the known host entry for the server.I can connect fine if I say: import pysftp cnopts = pysftp.CnOpts() cnopts.hostkeys = None with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts): But apparently that leaves you open to man in the middle attacks. So I attempt to connect with: cnopts = pysftp.CnOpts(knownhosts='config/known_host') cnopts.hostkeys = None with pysftp.Connection(host, username=username, password=password, cnopts=cnopts) as sftp: And I get all manner of error messages. The most recent one is: paramiko.hostkeys.InvalidHostKey The problem is I have no host key because I'm connecting for the first time. I tried to get the key from other connections. I use WinSCP but it stores the key in a registry file and the format is different than known_host. I tried to get it with PuTTY using ssh-keyscan but the server won't even let me start a terminal session. We don't own the box and the hosting provider is unlikely to give us what we need. Am I out of luck? Should I just go ahead and bypass checking the keys?
answer count: 1
downvote count: 0
tagged with: ssh
tagged with: pysftp
has answer: http://stackoverflow.com/a/47918427
linked to: http://stackoverflow.com/q/38939454

http://stackoverflow.com/a/47666285
has comment: http://stackoverflow.com/comment/82292060
type: Answer
has comment: http://stackoverflow.com/comment/82291775
has comment: http://stackoverflow.com/comment/82291947
has body: In def doOnePing() you have defined variable with name myId but you're passing variable as name myID which is why you get the undefined variable error. So as fix replace myId with myID as follows while defining the variable: myID = os.getpid() &amp; 0xFFFF
score: 0
answers question: http://stackoverflow.com/q/47666223
has comment: http://stackoverflow.com/comment/82292049
has comment: http://stackoverflow.com/comment/82291988
has comment: http://stackoverflow.com/comment/82291899
has comment: http://stackoverflow.com/comment/82291839

http://stackoverflow.com/comment/82299860
comment on: http://stackoverflow.com/q/47670181
type: Comment
has text: On another note, you may want to have `is_read` as a DateTimeField instead of BooleanField. This way, you can keep track of when a message was read. You can still write a boolean wrapper around it as well. Just an idea. :-) Happy coding
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82265509
comment on: http://stackoverflow.com/q/47653632
type: Comment
score: 0
type: QuestionComment
has text: use [count](https://www.programiz.com/python-programming/methods/list/count)

http://stackoverflow.com/q/47638093
answer count: 1
has comment: http://stackoverflow.com/comment/82237880
has answer: http://stackoverflow.com/a/47638622
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82241037
has comment: http://stackoverflow.com/comment/82236118
has comment: http://stackoverflow.com/comment/82237856
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82235493
has comment: http://stackoverflow.com/comment/82260183
has body: I have a sorted list of floats where l = [50.1234,50.1221,50.1200,51.5022,51.5021,51.4999,60,002,60.0023,60.0021] I want to group all the floats based on parts per million differences. I have a function: def ComputePPMError(t,e): return (((e- t) /t) * 1e6) What is the most efficient way of doing this? In general I will have a list of objects that have a float property and I will want to do the same thing with a list of objects. For example: class MZ: def __init__(self): self.FileID = "" self.Mass = 0 self.Intensity = 0 self.RT = 0 self.ScanNumber = 0 And now the list will be list = [MZ objects] So the final results will be dictionary of {average mass : list of mz objects} In this example there should be three entries The result is this: l = [{mz1:list of mz Objects (3 entries)},{mz2:list of mz Objects (3 entries)},{mz3:list of mz Objects (3 entries)} So in the above result, the final list contains a dict where the key is the mz values as averages and the values a list of the mz objects that were used to be grouped.
tagged with: python
has comment: http://stackoverflow.com/comment/82239252
has comment: http://stackoverflow.com/comment/82236201
has comment: http://stackoverflow.com/comment/82240652
has comment: http://stackoverflow.com/comment/82235145
score: 0
has title: Search a list of floats
has comment: http://stackoverflow.com/comment/82259937

http://stackoverflow.com/q/47609421
answer count: 3
tagged with: while-loop
possible better answer: http://stackoverflow.com/a/47609547
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47609547
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47609669
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82177537
has title: Create continuous effect for card game
has comment: http://stackoverflow.com/comment/82178658
has answer: http://stackoverflow.com/a/47609639
has comment: http://stackoverflow.com/comment/82177486
tagged with: python
has body: I was trying to figure out the code of some cards of the popular game Hearthstone and reproducing it with Python. I said Hearthstone, but this can apply basically to every card game, like Magic the Gathering etc... Lets say I have a creature on the field: class Creature: def __init__(self,manacost,atk,health): self.manacost = manacost self.atk = atk self.health = health creature = Creature(2,3,2) field = [] field.append(creature) Now, this creature has a continuous effect like "Spells in your hand cost 1 less". That means that WHILE the card is on the field my spells will cost 1 less, and they will return to their original cost as soon the card leaves the field. Then I wrote: class Spell: def __init__(self,manacost): self.manacost = manacost s1 = Spell(1) s2 = Spell(2) s3 = Spell(3) hand = [s1,s2,s3] while creature in field == True: for spell in hand: if spell.manacost &gt;=1: spell.manacost -= 1 At first I expected to end up with all my spells having manacost equal to 0. Instead nothing happened. Typing [x.manacost for x in hand] I get [1,2,3], which are the exact same manacosts I set for the spells in the beginning. How can I do? EDITED POST ANSWERS In the end here is my code fixed (i had to post it here and not in answers cause i didn't have enough characters in the reply slot. class Creature: def __init__(self,manacost,atk,health): self.manacost = manacost self.atk = atk self.health = health def continuous_effect(self): global spellcostdifference spellcostdifference += 1 def continuous_effect_cancel(self): global spellcostdifference spellcostdifference -= 1 class Spell: def __init__(self,manacost): self.manacost = manacost def current_manacost(self): global spellcostdifference return self.manacost - spellcostdifference if spellcostdifference &lt;= self.manacost else 0 spellcostdifference = 0 creature = Creature(2,3,2) s1 = Spell(1) s2 = Spell(2) s3 = Spell(3) hand = [s1,s2,s3] creature.continuous_effect() ## this means the creature is on the field creature.conti…
has answer: http://stackoverflow.com/a/47609669
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82338587
score: 0
comment on: http://stackoverflow.com/q/47667869
type: Comment
type: QuestionComment
has text: They cannot help me. Is there any alternative to upload/download files via on Google Drive with python if I get an security "policies do not allow" error?

http://stackoverflow.com/comment/82080860
has text: interesting question, I'm not too much into the bytes/hex stuff, but what is the code that you actually are using, since I can't get what you have put into the question to make sense, what exactly is your hex_string, and have you used `codecs` anywhere?
comment on: http://stackoverflow.com/q/47561251
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/47621111
has comment: http://stackoverflow.com/comment/82201559
tagged with: python
has comment: http://stackoverflow.com/comment/82201143
has title: Livy How to copy widget
has comment: http://stackoverflow.com/comment/82201490
has body: How can i copy a widget in kivy? But i don't want use copy module. that module cannot edit width or pos etc... #I don't want use this cause can't edit width or pos... from copy import copy copy()
score: 0
answer count: 0
tagged with: kivy
linked to: http://stackoverflow.com/q/25090620
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47672000
has body: I am trying to return a list of numbers that add up to 100 .. 11 times. There are 3 numbers which are generated from a numpy random uniform distribution. I want to add an if statement to see if the 1st, 2nd and 3rd numbers of each list (11 in total).. if plotted would have a Pearson correlation coefficient of >0.99. At the moment, I am only able to generate 1 list of numbers which have a sum equal to 100. I have following code: import math import pandas as pd import matplotlib.pyplot as plt import numpy as np c1_high = 98 c1_low = 75 c2_high = 15 c2_low = 6 c3_high = 8 c3_low = 2 def mix_gen(): while True: c1 = np.random.uniform(c1_low, c1_high) c2 = np.random.uniform(c2_low, c2_high) c3 = np.random.uniform(c3_low, c3_high) tot = c1+c2+c3 if 99.99&lt;= tot &lt;=100.01: comp_list = [c1,c2,c3] return comp_list my_list = mix_gen() print(my_list) so if i was to plot each component.. for example c1... i would get an R^2 value of >0.99. I'm stuck at generating multiple lists inside the same function. I know this can be done outside the function.. using [mix_gen() for _ in range(11)].. but this will not work because I require this additional check of the peasron corr coeff before returning the 11 lists. OBJECTIVE: to return a dataframe with the following values: C1 C2 C3 sum 1 70 20 10 100 2 .. 3 .. 4 .. 5 .. 6 .. 7 .. 8 .. 9 .. 10 .. 11 90 R^2 1 1 1
tagged with: pearson-correlation
has comment: http://stackoverflow.com/comment/82303368
tagged with: python
has title: returning result of a function multiple times within the same function
has comment: http://stackoverflow.com/comment/82303098
accepted answer: http://stackoverflow.com/a/47672437
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47672437
tagged with: pandas
score: 0
answer count: 1
tagged with: loops
type: Question
tagged with: numpy

http://stackoverflow.com/q/47608212
linked to: http://stackoverflow.com/q/20766291
favorite count: 0
type: Question
has body: I'm following Miguel sir's book on flask. I'm stuck in the login function where I send the email confirmation to the user and then after clicking the link it will ask the user to login but after logging in the request.args.get('next') variable is empty hence the confirm function is never executed. I suspect this is caused due to the before_app_request. I'm very new to flask and I've spent two days trying to fix this. Miguels version works fine, mine seem's to be cursed. Someone else's view is really needed. Thanks for reading. view.py @auth.before_app_request def before_request(): print("\tREQUEST ENDPOINT ::"+str(request.endpoint)) print("\tREQUEST ARGS ::"+str(request.args.get('next'))) if current_user.is_authenticated \ and not current_user.confirmed \ and request.endpoint \ and request.endpoint[:5] != 'auth.' \ and request.endpoint != 'static': return redirect(url_for('auth.unconfirmed')) @auth.route('/register', methods=['GET','POST']) def register(): form=RegForm() if form.validate_on_submit(): user=User(fname=form.fname.data, lname=form.lname.data, email=form.email.data, organization_name=form.username.data, password=form.password.data) db.session.add(user) #db.session.commit() token=user.generate_confirmation_token() send_email(user.email,'Confirm your Account','email/auth/confirm',user=user,token=token) flash('A confirmation Email has been sent, Please check your inbox','success') return redirect(url_for('auth.login')) #except Exception as e: # print("LINE 48 EMAIL: "+str(e)) # db.session.rollback() return render_template('Landing/entry.html',form=form) @auth.route('/confirm/<token>') @login_required def confirm(token): if current_user.confirmed: return redirect(url_for('viewhome.home')) if current_user.confirm(token): print('\tENTERED') flash('Account confirmed ','success') else: flash('Invalid Link or Link has expired','Warning') return redirect(url_for('viewhome.home')) @auth.route('/confirm') @login_required def resend_confirmation(): token=current_user…
tagged with: python-3.x
tagged with: flask-login
has comment: http://stackoverflow.com/comment/82174752
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82177671
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47610902
score: 1
has title: Flask request.args.get('next') value disappears after logging in
tagged with: flask
has comment: http://stackoverflow.com/comment/82177372
upvote count: 3
has comment: http://stackoverflow.com/comment/82174769
tagged with: python
has comment: http://stackoverflow.com/comment/82179979

http://stackoverflow.com/q/47680741
has body: Here is my code f["col1"] = df["col1"].astype(float) col1 has values that can't be converted. How would I do something like this: df["col1"] = df["col1"].astype(float, default=0)
upvote count: 1
tagged with: python
tagged with: pandas
has title: How do I do df["col1"].astype(float) with a default for unconvertable values?
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47680791
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47680791
favorite count: 0
type: Question

http://stackoverflow.com/q/47581738
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82121187
has title: pandas df.loc returns blank df
has comment: http://stackoverflow.com/comment/82125026
score: 0
has answer: http://stackoverflow.com/a/47582183
has comment: http://stackoverflow.com/comment/82121909
has body: I'm sure I'm making an obviously mistake, but can't see it. I have a df that looks like this: id year plan grade prior_grade 21 2017 text A B 56 2015 text B B 43 2016 text A C and want to create a new df with only those rows where prior_grade = c. I'm using this to do so: prior_c = (df.loc[(df['prior_grade']=='C')]) which returns an empty df (column names print but no rows when calling prior_c.head()) Again, I'm sure I'm making an obvious mistake, but just can't see it. edit: also tried with less parens and got the same result: prior_c = df.loc[df['prior_grade']=='C']
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/82121596
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82121119

http://stackoverflow.com/q/47575681
has answer: http://stackoverflow.com/a/47575946
has answer: http://stackoverflow.com/a/47575795
downvote count: 0
upvote count: 1
tagged with: text-files
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82111809
has title: Python reading from a text file
linked to: http://stackoverflow.com/q/44095144
possible better answer: http://stackoverflow.com/a/47575946
has body: I am trying to read from a text file and store it into a dictionary. My text file contains values like: G314889730 4.3 G944177112 4.3 G383969021 4.3 G631050911 4.3 G424860434 4.3 G424860434 4.3 G537477205 NA But I am getting an empty dictionary in the end. file = open("myfile","r") HKH = {} for line in file: x = line.split() if len(x)&gt;2: GID = x[0] CRR = x[1] HKH[GID] = CRR print (HKH[GID])
accepted answer: http://stackoverflow.com/a/47575741
has answer: http://stackoverflow.com/a/47575741
tagged with: python
has comment: http://stackoverflow.com/comment/82108250
tagged with: dictionary
has answer: http://stackoverflow.com/a/47575818
duplicate of: http://stackoverflow.com/q/44095144
answer count: 4
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/96726655
type: AnswerComment
comment on: http://stackoverflow.com/a/47580796
score: 0
type: Comment
has text: Thanks, I'll look into it this evening. My code is a bit complex, it would take a bit of time to simplify it down to something shareable and doing so might eliminate what is preventing my pool to die. Let's see what your snippet can help me figure out :)

http://stackoverflow.com/a/47618008
answers question: http://stackoverflow.com/q/47617547
downvote count: 0
has body: Django 2.0 dropped support for python 2. Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series. so you can use 1.11 the LTS django version and it will work just fine,It will be long supported till at least April 2020. Django Roadmap pip install django==1.11.8 The Django 1.11.x series is the last to support Python 2.7. or install python3 and use pip3 or virtualenv with python3 then install django 2.0 Both of the quotes are from Django Docs
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/q/47665798
answer count: 1
tagged with: cloudant
type: Question
has title: How to use get_attachment call upon QueryResult (python cloudant) ?
accepted answer: http://stackoverflow.com/a/47673543
tagged with: python
has answer: http://stackoverflow.com/a/47673543
type: AnsweredQuestion
has body: I've been trying to get attachment image data from documents in Cloudant. I can successfully do it once a document is selected (direct extract with _id, etc). Now trying to do it in combination with "query" operation using selector, I run into trouble. Here is my code. targetName="chibika33" targetfile="chibitest.png" #-------------------------------------------------- # get all the documents with the specific nameField #-------------------------------------------------- myDatabase.create_query_index(fields = ['nameField']) selector = {'nameField': {'$eq': targetName}} docs = myDatabase.get_query_result(selector) #-------------------------------------------------- # get the attachment files to them, save it locally #-------------------------------------------------- count = 0 for doc in docs: count=count+1 result_filename="result%03d.png"%(count) dataContent = doc.get_attachment(targetfile, attachment_type='binary') dataContentb =base64.b64decode(dataContent) with open(result_filename,'wb') as output: output.write(dataContentb) Causes error as; Traceback (most recent call last): File "view8.py", line 44, in &lt;module&gt; dataContent = doc.get_attachment(targetfile, attachment_type='binary') AttributeError: 'dict' object has no attribute 'get_attachment' So far, I've been unable to find any API for converting dict to document object in the python-cloudant-document...[python-cloudant document]: http://python-cloudant.readthedocs.io/en/latest/index.html Any advise would be highly appreciated.
score: 0

http://stackoverflow.com/comment/82054852
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47548676
has text: Its a solution to the Problem.

http://stackoverflow.com/comment/82107336
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47572604
type: Comment
has text: Thanks for the suggestion. I like it. Could you please clarify your "Should use sets for in tests"?

http://stackoverflow.com/q/47587708
type: UnansweredQuestion
tagged with: shopify
tagged with: django
tagged with: python
has title: Storing a users access token in django view
has comment: http://stackoverflow.com/comment/82133303
score: 1
has answer: http://stackoverflow.com/a/47588124
answer count: 1
downvote count: 0
upvote count: 1
has body: I am tryig to store a shopify access token in a django view upon first installation/auth (before they create an account &amp; connect to DB). I am new to django so please be nice. How do I store this access token for usage later on? Can it be stored in "session"? is it already? Here's my repo and python view: def finalize(request): shop_url = request.GET['shop'] auth_code = request.GET['code'] hashed = request.GET['hmac'] ts = request.GET['timestamp'] print("shopURL", shop_url) print("success request") try: r = requests.post('https://'+shop_url+'/admin/oauth/access_token', data = {'client_id':'xx','client_secret':'xx','code':auth_code}) print("request response &gt; &gt; &gt; &gt; ", r.json()) this_response = r.json() print(this_response["access_token"],"this_response[access_token]") # &gt;&gt;&gt;&gt;&gt;&gt; STORE THIS TOKEN SOMEWHERE? request.session['shopify'] = { "shop_url": shop_url, "access_token": this_response["access_token"] } except Exception: messages.error(request, "Could not log in to Shopify store.") return redirect(reverse('shopify_app_login')) messages.info(request, "Logged in to shopify store.") response = redirect(_return_address(request)) request.session.pop('return_to', None) return response
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82133399

http://stackoverflow.com/comment/82243595
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47600263
has text: What version of Beam are you using? Can you include a more complete snippet of your code?

http://stackoverflow.com/comment/82208949
type: QuestionComment
has text: I think network is fine. Because the speed can up to 10MB per second when i read the dataframe from another computer.
comment on: http://stackoverflow.com/q/47591848
score: 0
type: Comment

http://stackoverflow.com/a/47691035
has comment: http://stackoverflow.com/comment/82341407
downvote count: 1
has comment: http://stackoverflow.com/comment/82341216
answers question: http://stackoverflow.com/q/47690558
has body: You could create a tuple of booleans and check it via all. conditions = [] conditions.append(yourVar &lt; 9) conditions.append(yourVar &gt; 20) conditions.append(yourVar &lt;= 3) if all(conditions): print('All conditions are met') else: print('At least one condition results in false)
type: Answer
upvote count: 2
score: 1

http://stackoverflow.com/comment/82328163
type: AnswerComment
has text: I had the issue with "only keyword arguments after * expression" with python 2, no problem with 3. However pdf end up being an array of shape (10000,). Shouldn't it be a matrix of shape (m,n)? Or i need just to reshape pdf to get my M matrix?
type: Comment
comment on: http://stackoverflow.com/a/47684089
score: 0

http://stackoverflow.com/comment/106653810
score: 1
has text: Yes this helped me.. you saved my time :)
comment on: http://stackoverflow.com/a/54650439
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47555417
tagged with: django
tagged with: python
has title: global list on Celery with Django
has comment: http://stackoverflow.com/comment/82069943
score: 0
answer count: 1
tagged with: process
has comment: http://stackoverflow.com/comment/82068966
upvote count: 1
linked to: http://stackoverflow.com/q/32350471
downvote count: 1
favorite count: 0
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/47557743
has body: I'm using Celery and have there a global list since I cannot use global variable in Django. I add items to that list on demand. The problem is that when I try to get the global list from Celery, sometimes I don't get the updated list. For example, I might get empty list when I know I already inserted items to it. I saw here that Celery run with multiple process so I edited the running command of Celery to - celery -A tasks worker -c1and now I should have only one process but still for some reason I have the same problem. Note: when I fail to get the right list and I refresh the page few time I do get the updated list. I think maybe Celery is still run few process instead of one or running few threads but it really shouldn't since I use the flag -c1 EDIT: I think that maybe few workers are running simultaneously. I tried to kill them but each time I kill one, a new one is born somehow. tasks.py from celery import shared_task from celery.task import periodic_task import time import threading global_list = [[],[],[],[],[]] global_list_protection = [[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]],[[],[],[]]] @shared_task def add(log_array, is_protection): i = 0 if (is_protection == "true"): global global_list_protection while (i&lt;len(global_list_protection) and global_list_protection[i]!= [[],[],[]]): i = i+1 if (i&lt;len(global_list_protection)): global_list_protection[i] = log_array return i return -1 if (is_protection == "false"): global global_list while (i&lt;len(global_list) and global_list[i]!= []): i = i+1 if (i&lt;len(global_list)): global_list[i] = log_array return i return -1 return -1 @shared_task def get(is_protection, index): if (is_protection == "true"): global global_list_protection return global_list_protection[int(index)] if (is_protection == "false"): global global_list return global_list[int(index)] return None views.py def send_to_celery(log_array, is_protection): from polls.tasks import add index_save = add(log_array, is_protection) return index_save…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82069042
has comment: http://stackoverflow.com/comment/82071698

http://stackoverflow.com/comment/82306617
has text: You can explode first and then do a groupBy and collect_set. Or write a UDF maybe.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47673889
type: QuestionComment

http://stackoverflow.com/q/47577505
type: Question
has title: ImportError while performing pip install
type: UnansweredQuestion
has body: While in my virtual environment, i'm trying to perform 'pip install .' with a setup.py such as : from setuptools import setup import pbr ... some functions ... setup( name='example', setup_requires=['pbr'], py_modules=['example'], entry_points=''' [console_scripts] example=example:main ''', ) The thing is that i get the following error ImportError: No module named pbr This seems quite legit as i didn't install pbr in my virtual environment BUT i thought that specifying 'setup_requires' would do the trick ... :/ Does someone understand why this does not work and knows how to fix it ? :)
tagged with: pip
tagged with: python
score: -1
upvote count: 0
tagged with: installation
tagged with: setuptools
has answer: http://stackoverflow.com/a/47719224
downvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/58312755
downvote count: 1
answers question: http://stackoverflow.com/q/47694878
type: Answer
upvote count: 2
score: 1
has body: You can escape the double quotes (\") directly in the value of --access-logformat to keep your logs as valid JSON. So if you're running Gunicorn in a Docker container, your Dockerfile could end with something like: CMD ["gunicorn", \ "-b", "0.0.0.0:5000", \ "--access-logfile", "-",\ "--access-logformat", "{\"remote_ip\":\"%(h)s\",\"request_id\":\"%({X-Request-Id}i)s\",\"response_code\":\"%(s)s\",\"request_method\":\"%(m)s\",\"request_path\":\"%(U)s\",\"request_querystring\":\"%(q)s\",\"request_timetaken\":\"%(D)s\",\"response_length\":\"%(B)s\"}", \ "app:create_app()"] Find the rest of the Gunicorn logging options here.

http://stackoverflow.com/a/47569976
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47566568
has body: Optimized solution: import requests, pprint from lxml import etree article_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&amp;retmode=xml&amp;tool=PMA&amp;id=29150897,29149862" response = requests.get(article_url) tree = etree.fromstring(response.content) ids_xpath = '//MedlineCitation/PMID[@Version=1]/text()' article_xpath = '//Article//Title/text()' ymd_xpath = '//PubmedData/History/PubMedPubDate[@PubStatus="medline"]/' \ '*[self::Year or self::Month or self::Day]/text()' full_xpath = '|'.join((ids_xpath, article_xpath, ymd_xpath)) nodes = tree.xpath(full_xpath) result = { nodes[i]: dict(zip(('journal', 'year', 'month', 'day'), nodes[1:])) for i in range(0, len(nodes), 5)} pprint.pprint(result) The output: {'29149862': {'day': '19', 'journal': 'Respirology (Carlton, Vic.)', 'month': '11', 'year': '2017'}, '29150897': {'day': '19', 'journal': 'Respirology (Carlton, Vic.)', 'month': '11', 'year': '2017'}} The crucial xpath expression will extract and arrange the needed nodes in consecutive manner: &lt;id&gt; | &lt;journal&gt; | &lt;year&gt; | &lt;month&gt; | &lt;day&gt;
score: 1

http://stackoverflow.com/comment/82200826
has text: Then you run the simulation twice and only store the result the second time.
score: 0
comment on: http://stackoverflow.com/q/47620895
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82246901
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga Yeah, accessing it from within decorated at runtime is a good idea :) Thank you
comment on: http://stackoverflow.com/q/47643956
score: 0

http://stackoverflow.com/q/47575303
has answer: http://stackoverflow.com/a/47589151
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47589151
favorite count: 0
type: Question
has title: How to use setuptools to create rpm packages for linux
tagged with: rpm
tagged with: linux
has body: I want to build a rpm package for my software. I am only familiar with the classic way of using rpmbuild tool of linux with spec files and source directory. But I read in the documentation of distutils that it can somehow create a RPM package. Setuptools is based on distutils so I am guessing it also has some procedure to build rpm. Although I never practically used any of the two modules, but I always thought that they build their own standalone packages. I have two questions. First is that what is the exact procedure to create a rpm from setuptools. Second is that, is this way more organized than rpmbuild utility? What I researched so far on Internet- Setuptools is mainly used to create a "wheel" package. And it is similar to other packages like rpm or deb, except linux will not directly understand it like RPM. Need to pass bdist_rpm flag during the build process to create a rpm package.(link) I am quite confused with the concept of building and distributing a package. Need some explanation on what i am understanding wrong between setuptools and rpm.
tagged with: python

http://stackoverflow.com/comment/82054072
type: AnswerComment
has text: Unfortunately, the error is becoming even bigger as before
comment on: http://stackoverflow.com/a/47544324
type: Comment
score: 0

http://stackoverflow.com/comment/82242162
comment on: http://stackoverflow.com/q/47641058
type: QuestionComment
has text: Sorry if I made it unclear. Yes it is a mathematical function, I just need generic method for computing its gradient because I don't know its dimensions.
score: 0
type: Comment

http://stackoverflow.com/comment/82293569
type: Comment
has text: Not sure what you mean @juanpa.arrivillaga
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47666565

http://stackoverflow.com/comment/82179404
score: 0
has text: You can use `set_x2_axis()`. You just can't use it when you are also using `set_y2_axis()`. This may be fixed/added in the future, however, it is quite a bit of work and there haven't been many (or any) requests for it so it is unlikely to be added in the short term.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47573928

limit-per-group
tags question: http://stackoverflow.com/q/47603191
tag name: limit-per-group
type: Tag

http://stackoverflow.com/comment/82284731
type: QuestionComment
has text: Any python/Scipy experts? thanks
comment on: http://stackoverflow.com/q/47641223
type: Comment
score: 0

http://stackoverflow.com/comment/82141222
score: 0
type: Comment
type: QuestionComment
has text: "which gives me 18 instead of 20 thanks for the help" - debug your code and come back with your findings. You're welcome!
comment on: http://stackoverflow.com/q/47591978

http://stackoverflow.com/q/47588957
tagged with: pip
score: 1
tagged with: virtualenv
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82240197
has body: I have 2 python libraries which have different version dependecy requirement of numpy library. What is ideal way to use both the libraries. I can't use virtualenv as both the libraries have to be used in the same app.
has title: Import python libraries with different dependency versions
tagged with: python
has comment: http://stackoverflow.com/comment/82135609
tagged with: numpy
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82135078
type: UnansweredQuestion

http://stackoverflow.com/a/47541316
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/82041301
type: Answer
accepted answer of: http://stackoverflow.com/q/47541127
has comment: http://stackoverflow.com/comment/82041169
has body: The structure is create an axes to plot to run the loop to populate the axes save and/or show (save before show) In terms of code: import matplotlib.pyplot as plt import pandas as pd ax = plt.gca() for i in range (1,10): df = pd.read_csv(...) df.plot(..., ax=ax) df.plot.line(..., ax=ax) plt.savefig(...) plt.show()
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82041225
answers question: http://stackoverflow.com/q/47541127
has comment: http://stackoverflow.com/comment/82041528

http://stackoverflow.com/comment/82279613
score: 0
type: Comment
has text: valid_choices = ['1', '2', '3']; if diff not in valid_choices: print ...
type: QuestionComment
comment on: http://stackoverflow.com/q/47660226

http://stackoverflow.com/comment/94887902
comment on: http://stackoverflow.com/a/51261265
score: 0
type: AnswerComment
has text: Yes. Indeed for {,ba,z}sh. Updated.
type: Comment

http://stackoverflow.com/q/47577395
tagged with: python
score: 11
linked to: http://stackoverflow.com/q/14246983
has answer: http://stackoverflow.com/a/47578057
accepted answer: http://stackoverflow.com/a/47578057
has answer: http://stackoverflow.com/a/47577852
answer count: 4
linked to: http://stackoverflow.com/q/3588776
has answer: http://stackoverflow.com/a/47577714
has comment: http://stackoverflow.com/comment/82112153
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82112206
has title: Why doesn't Python have a "__req__" (reflected equality) method?
has comment: http://stackoverflow.com/comment/82112107
tagged with: python-datamodel
has comment: http://stackoverflow.com/comment/82112456
has comment: http://stackoverflow.com/comment/82112453
downvote count: 1
has answer: http://stackoverflow.com/a/77179758
favorite count: 0
possible better answer: http://stackoverflow.com/a/47577852
type: Question
has comment: http://stackoverflow.com/comment/82112713
tagged with: python-internals
upvote count: 12
has body: I have a little helper class: class AnyOf(object): def __init__(self, *args): self.elements = args def __eq__(self, other): return other in self.elements This lets me do sweet magic like: &gt;&gt;&gt; arr = np.array([1,2,3,4,5]) &gt;&gt;&gt; arr == AnyOf(2,3) np.array([False, True, True, False, False]) without having to use a list comprehension (as in np.array(x in (2,3) for x in arr). (I maintain a UI that lets (trusted) users type in arbitrary code, and a == AnyOf(1,2,3) is a lot more palatable than a list comprehension to the non-technically savvy user.) However! This only works one way! For example, if I were to do AnyOf(2,3) == arr then my AnyOf class's __eq__ method never gets called: instead, the NumPy array's __eq__ method gets called, which internally (I would presume) calls the __eq__ method of all its elements. This lead me to wonder: why does Python not allow a right-sided equivalent to __eq__? (Roughly equivalent to methods like __radd__, __rmul__, et cetera.)

http://stackoverflow.com/comment/82410725
type: QuestionComment
type: Comment
score: 0
has text: you can see example of how this works in Azure Notebooks
comment on: http://stackoverflow.com/q/47570793

http://stackoverflow.com/comment/82192814
type: Comment
score: 0
type: AnswerComment
has text: @user6335453 Seems Django is not installed (or maybe a wrong version). Whats installed on your Heroku virtual env?
comment on: http://stackoverflow.com/a/47616922

http://stackoverflow.com/comment/82079639
has text: why do you check `K_UP` for second player if it uses `K_w` and `K_s`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47560867

http://stackoverflow.com/comment/82148835
score: 2
has text: Looks like he's trying to count what "keys" each letter appears in, where keys are just the first element of each list.
comment on: http://stackoverflow.com/q/47595669
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82186508
score: 0
type: Comment
has text: @th0r Updated my answer. I hope it helps (I have not been able to thoroughly test it as at the moment I am on my Windows partition)
type: AnswerComment
comment on: http://stackoverflow.com/a/47612682

http://stackoverflow.com/q/47601076
favorite count: 0
has body: Given I have a really large task graph, my_delayed.visualize() either is impossible to generate or is too dense to be visually useful. If I have key for a particular task, can I specify a particular depth or x number of parents and children to visualize? For example: from dask import delayed @delayed def inc(x): return x + 1 def inc_list(x): return [inc(n) for n in x] task = delayed(sum)(inc_list(inc_list([1,2,3]))) task.visualize(n_parents=1) Would generate the below graph without the crossed out nodes.
type: Question
tagged with: dask
has answer: http://stackoverflow.com/a/47601399
type: UnansweredQuestion
answer count: 1
has title: How can I visualize a subgraph of a dask graph?
upvote count: 1
tagged with: python
tagged with: dask-delayed
score: 1
downvote count: 0

http://stackoverflow.com/q/47664687
downvote count: 1
favorite count: 0
has body: I'm new user of stackoverflow, besides I'm not an English guy, so I'm sorry for my english. I was programming in python 'til I got a mistake tho I'm not able to figure out what's wrong... #!/usr/bin/env python2.7 from random import choice import sys def help(): print ("Please, you need to introduce a Int in this way: PWrand 10") def PWrand(insert_by_user): chars = 'ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuwxyz0123456789!-_:.,;&amp;)(' for password in range(insert_by_user): sys.stdout.write(choice(chars)) #Command Line if __name__ == '__main__': if len(sys.argv) &lt; 2 or len(sys.argv) &gt; 2: help() elif (type(sys.argv[2]) != int): print("It need to be an Int!") else: insert_by_user = (sys.argv[2]) print(PWrand(insert_by_user)) So, this is what I take. Traceback (most recent call last): File "./passwordrandom.py", line 24, in &lt;module&gt; elif (type(sys.argv[2]) != int): IndexError: list index out of range Thank you all!
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/82288901
tagged with: range
tagged with: python
type: Question
has title: Sys.argv python error list index out of range
has comment: http://stackoverflow.com/comment/82288717
has answer: http://stackoverflow.com/a/47664755
answer count: 2
has comment: http://stackoverflow.com/comment/82288766
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82288775
tagged with: sys
tagged with: argv
has comment: http://stackoverflow.com/comment/82288822
has answer: http://stackoverflow.com/a/47664759

http://stackoverflow.com/comment/82253055
has text: Yes, I know but how to scrap the information I want to content?
score: 0
comment on: http://stackoverflow.com/q/47647162
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47674204
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47673868
downvote count: 0
answers question: http://stackoverflow.com/q/47673868
type: Answer
has comment: http://stackoverflow.com/comment/82307465
has comment: http://stackoverflow.com/comment/82308297
score: 2
upvote count: 2
has body: What about slightly different approach? first let's create a DF from the sortedlist of tuples: In [272]: df = pd.DataFrame(np.sort(np.array(tuples), axis=1), columns=['c1','c2']) In [273]: df Out[273]: c1 c2 0 1 2 1 1 3 2 1 4 3 2 3 4 2 4 5 3 4 6 1 2 7 1 3 8 1 4 9 2 3 10 2 4 11 3 4 now we can count pairs using Pandas technique: In [274]: res = df.groupby(['c1','c2']).size() In [275]: res Out[275]: c1 c2 1 2 2 3 2 4 2 2 3 2 4 2 3 4 2 dtype: int64 Accessing data in multi-index DF: In [277]: res.loc[(1,2)] Out[277]: 2 In [278]: res.loc[(2,4)] Out[278]: 2 we can also unstack the resulting DF, which will give us: In [279]: res.unstack(fill_value=0) Out[279]: c2 2 3 4 c1 1 2 2 2 2 0 2 2 3 0 0 2 Or as proposed by @Dark: In [280]: pd.Series(count).unstack(fill_value=0) Out[280]: 2 3 4 1 2 2 2 2 0 2 2 3 0 0 2

http://stackoverflow.com/a/47578062
answers question: http://stackoverflow.com/q/47577303
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47577303
upvote count: 1
has comment: http://stackoverflow.com/comment/82114463
has body: I change the Month to datetime format, you would like it back, you can do,df.Month.dt.year*100+df.Month.dt.month, and in my solution I did not using column Month_LM df.Month=pd.to_datetime(df.Month,format='%Y%m') df['Rev']=df.groupby('Group').apply(lambda x :x.Revenue.shift()* (x.Month.dt.year*12+x.Month.dt.month).diff().eq(1)).replace(0,np.nan).values df Out[1080]: Group Store Month Revenue Month_LM Rev 0 Group1 A 2016-11-01 10 201610 NaN 1 Group1 A 2016-12-01 20 201611 10.0 2 Group1 A 2017-01-01 30 201612 20.0 3 Group1 B 2016-11-01 50 201610 NaN 4 Group1 B 2017-01-01 70 201612 NaN 5 Group1 B 2017-02-01 80 201701 70.0 6 Group2 C 2016-11-01 90 201610 NaN 7 Group2 C 2016-12-01 100 201611 90.0 8 Group2 C 2017-02-01 120 201701 NaN
type: Answer
has comment: http://stackoverflow.com/comment/82114438

http://stackoverflow.com/comment/82130409
comment on: http://stackoverflow.com/a/47586365
has text: Interesting, I have never encountered the .shape command. What is that doing to the dataframe? The assignment which I am completing assumes an exponential growth pattern rather than the normal 1+% like you've completed in the code above.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47680363
has body: In general, you want to compare your subsection matrix B with every possible subsection matrix of the reference matrix A (so that it has the same size, as a matrix B) and find the most similar piece. By comparison, I mean the estimation of the difference, e.g. if B_i is some subsection of matrix A, you can calculate: d_i=sum(sum(sum((B_i-B).^2))); After that, you need to find the minimum of $d_i$. If you are working with big matrices A(NxNxN) and B(MxMxM), there are (N-M)^3 possible submatrices B_i with the same size as matrix B. The algorithm will be quite expensive. However, there is an alternative implementation using convolutions. You can take a look at the Particle Image Velocimetry algorithm, that is really similar to your problem.
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47679648
upvote count: 1

http://stackoverflow.com/q/47687061
has title: Not reading lesser or greater than input properly
linked to: http://stackoverflow.com/q/20449427
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47687116
has answer: http://stackoverflow.com/a/47687176
type: UnansweredQuestion
has body: So this is the problem section in a simple "Is your amount greater than or less than 50?" program. This section is entirely independent, but it doesn't work. If my input is 50 or anything less, it says "Sorry, not enough money." But strangely, from 100 and on, it also registers those amounts as "Sorry, that is not enough money." I've tried a bunch of things with it and I can't get it to work! What am I missing? Thank you! money_amount = input("Type your amount with no quotations.") if money_amount &lt;= "50": print ("Sorry, that is not enough money.") quit() else: print ("Yay!")
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/47687254
duplicate of: http://stackoverflow.com/q/20449427
score: 0
answer count: 3

http://stackoverflow.com/comment/82135746
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47577488
has text: Thank you. That also works. However, the other solution is a little more robust as it will also work if there is not a empty line in between the data blocks.

http://stackoverflow.com/comment/82088805
has text: Why do you think that they're wrong?
type: QuestionComment
score: 3
type: Comment
comment on: http://stackoverflow.com/q/47565436

http://stackoverflow.com/a/47607065
upvote count: 4
has body: You just need the builtin tuple(): source = {'I like': 14, 'you like': 12, 'he likes': 2} target = { tuple(k.split()):source[k] for k in source} print(target) Output: {('I', 'like'): 14, ('you', 'like'): 12, ('he', 'likes'): 2} p.s. Don't use dict as a variable name.
accepted answer of: http://stackoverflow.com/q/47606995
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47606995

http://stackoverflow.com/a/47670437
score: 0
accepted answer of: http://stackoverflow.com/q/47656709
type: Answer
answers question: http://stackoverflow.com/q/47656709
has body: The meeting organizer is available on CalendarItem objects as item.organizer.
type: AcceptedAnswer

http://stackoverflow.com/q/47641493
has comment: http://stackoverflow.com/comment/82241981
has body: I am trying to render html to pdf and include it as a django action, however, for some odd reason, I seem to keep getting the issue that the object has no attribute 'some_attribute'. My view looks like this: class CreatePdf(ContextMixin, View): def get_context_data(self, obj, request): cxt = {'some_attribute': obj.some_attribute, 'today': date.today()} return cxt def create_pdf(self, some_template, some_dict={}): template = get_template(some_template) html = template.render(some_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue()) return None And the action, which had the purpose to call everything and do all the magic, looks like this: def get_pdf(self, obj, request): pdf_view = views.CreatePdf() pdf = pdf_view.create_pdf('templates/some_template.html', pdf_view.get_context_data(obj,request)) return HttpResponse(pdf) I thought, that using get_context_data will get the fields of the selected object in the admin field, however, it seems to through me the same error. Last, but not least, in my admin.py I have: class MyAdmin(admin.ModelAdmin): actions = [get_pdf]
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/37949198
has title: 'WSGIRequest' object has no attribute 'some_attribute'
answer count: 1
has comment: http://stackoverflow.com/comment/82241469
type: Question
accepted answer: http://stackoverflow.com/a/47641789
has answer: http://stackoverflow.com/a/47641789
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82241558

http://stackoverflow.com/a/47595391
score: 0
has body: Simple solution assuming all the rows are of the same length c = len(a[0]) [row[:c/2] + [0] * (c/2) for row in a]
type: Answer
answers question: http://stackoverflow.com/q/47593815

http://stackoverflow.com/comment/82305004
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47671283
has text: yeah, I did call it from a browser as GET

http://stackoverflow.com/comment/82246718
type: Comment
comment on: http://stackoverflow.com/a/47643350
type: AnswerComment
has text: @AntonvBR check the update change to pd.factorize(df.unit+df.HP.astype(str))[0]+1, should be work
score: 0

http://stackoverflow.com/a/47679437
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84824261
has body: Like @Sraw said, don't manually logout users from user_loader. That should only return the user for given id or None: @login_manager.user_loader def user_loader(user_id): return SessionUser.find_by_session_id(user_id) # hits the database The above answers your quesion: When the database can't find the id, I want the user to be logged out. Now, to answer your second question: I want show a message the user has been logged out (and I only want to show this once) Here's the ways a user can be logged out: user_id is not in your database (the user was deleted) user_id is not in the user's browser cookie session (has not logged in yet, or cleared their cookies) You called flask_login.logout_user, which removes user_id from session Here's a working mini-app that flashes a message when the user is logged out: from flask import current_app as app, flash, redirect, render_template, session from flask_login import login_manager, login_required, logout_user @login_manager.user_loader def user_loader(user_id): return SessionUser.find_by_session_id(user_id) @app.route('/logout') @login_required def logout(): logout_user() if session.get('was_once_logged_in'): # prevent flashing automatically logged out message del session['was_once_logged_in'] flash('You have successfully logged yourself out.') return redirect('/login') @app.route('/login', methods=['GET', 'POST']) def login(): if app.current_user.is_authenticated: # already logged in return redirect('/home') if request.method == 'POST': user = SessionUser.find_by_session_id(request.data['user_id']) if user: login_user(user) session['was_once_logged_in'] = True return redirect('/home') flash('That user was not found in the database.') if session.get('was_once_logged_in'): flash('You have been automatically logged out.') del session['was_once_logged_in'] return render_template('/login.html') @app.route('/home') @login_required def home(): return 'You are logged in as {0}.'.format(app.current_user.id) Contents of login.html: {% wit…
downvote count: 0
has comment: http://stackoverflow.com/comment/84827001
has comment: http://stackoverflow.com/comment/82360048
answers question: http://stackoverflow.com/q/47670382
has comment: http://stackoverflow.com/comment/84780628
type: Answer

http://stackoverflow.com/a/47549412
has comment: http://stackoverflow.com/comment/82066181
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82064237
has comment: http://stackoverflow.com/comment/82064774
has comment: http://stackoverflow.com/comment/82066451
has comment: http://stackoverflow.com/comment/82066074
has comment: http://stackoverflow.com/comment/82064892
has comment: http://stackoverflow.com/comment/82066821
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/132014461
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82066568
has body: I would recommend you avoid using regular expressions for this and instead attempt to convert each entry into a valid datetime object. If the conversion fails, you then know it is not in the correct format. This would then also cope correctly with all the various 30 or 31 type month length issues. Secondly, it can be extended easily to spot your second date format of Jan-12: from datetime import datetime import csv with open('train.csv', 'rb') as f_input, open('sample.txt', 'wb') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) header = next(csv_input) for row in csv_input: for date_format in ['%m/%d/%y', '%b-%y']: try: converted = datetime.strptime(row[3], date_format) csv_output.writerow([row[0], row[1], converted.strftime(date_format)]) except ValueError: pass Giving you two entries for your data as follows: 1,1,12/02/12 2,3,Jan-12
has comment: http://stackoverflow.com/comment/82066860
accepted answer of: http://stackoverflow.com/q/47547403
has comment: http://stackoverflow.com/comment/82064092
answers question: http://stackoverflow.com/q/47547403

http://stackoverflow.com/q/47660325
type: UnansweredQuestion
tagged with: layout
tagged with: wxpython
tagged with: python
has comment: http://stackoverflow.com/comment/82280204
has title: wxPython Scroll Panel Spacing Issue
tagged with: python-2.7
tagged with: wxwidgets
score: 0
has comment: http://stackoverflow.com/comment/82282657
linked to: http://stackoverflow.com/q/21431366
has body: I have tried to follow question and answer from this site regarding making a scrolly window with bitmaps, but I can't get it behave how I expected it to. This is the panel code: class ScrollyPanel(wxScrolledPanel.ScrolledPanel): def __init__(self, parent): wxScrolledPanel.ScrolledPanel.__init__(self, parent, style=wx.VSCROLL, size=(200,200)) self.__sizer = wx.WrapSizer() self.SetupScrolling(scroll_x = False) self.addButton(200) self.SetSizer(self.__sizer) self.Bind(wx.EVT_SIZE, self.onSize) self.SetAutoLayout(True) self.Layout() def addButton(self, num): size = wx.Size(100, 100) for i in range(1, num): btn = wx.Button(self, wx.ID_ANY, "btn"+str(i), size = size) self.__sizer.Add(btn, 0, wx.ALL) def onSize(self, evt): size = self.GetSize() vsize = self.GetVirtualSize() self.SetVirtualSize((size[0], vsize[1])) evt.Skip() I was expected closely aligned bitmaps of 100 x 100, but I am getting largely space bitmaps that aren't equally spaced. Here is a screenshot of what I am seeing. I am totally confused as I cannot see any borders. I am using wxPython 3 on Python 2.7.10
type: Question
has comment: http://stackoverflow.com/comment/82282371
answer count: 0

http://stackoverflow.com/q/47686304
tagged with: typescript
type: Question
has title: CSRF Token is not set..How to set CSRF cookie in Typescript?
has body: as title I have no idea how to set CSRF token inside my typescript file, I am a beginner about typescript and CSRF Token. This is the typescript file I use to post my info. getUsers2() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let body2 = { site: this.selectedSite, zone: this.selectedZone, user: this.username, categoryType: this.problemType, ser: 'High', conNo:'012-8888888' }; this.http.post('http://localhost:8000/apidb/report/', JSON.stringify(body2), {headers: headers}) .map(res =&gt; res.json()) .subscribe(data =&gt; { console.log("herererererere" ,data); }); this.restProvider.getUsers2().then(data2 =&gt; { this.locations = data2; console.log(this.locations); }); } Inside my setting.py I have already install the middleware 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', 'corsheaders.middleware.CorsMiddleware', ] In my views.py I not sure about is this correct or not def report(request): import pdb; pdb.set_trace() if request.method == 'POST': z1= site(country_site="New Penang Site") site.save() else: return HttpResponse(request.method, content_type="application/json") When I post a data to my API it shows me that CSRF is not set.. Can anyone provide me any tutorial or guideline about this problem ?? Thanks !!
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47686334
answer count: 1
tagged with: django-csrf

http://stackoverflow.com/q/47660370
has comment: http://stackoverflow.com/comment/82279608
answer count: 1
tagged with: objloader
has comment: http://stackoverflow.com/comment/82281078
upvote count: 1
has comment: http://stackoverflow.com/comment/82279743
downvote count: 1
favorite count: 0
tagged with: pyopengl
type: AnsweredQuestion
has body: There's error in OBJFILELOADER.py file from the link - https://www.pygame.org/wiki/OBJFileLoader . I think there's python2 to python3 version error, however I tried changing the raise ValueError thing and used obj as obj=(filename) But still there's lots of errors. I took the .obj file from blender, I don't think that's the issue. Can anyone tell me the exact objfileloader for Python3 Error - Traceback (most recent call last): File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 41, in __call__ return self._finalCall( *args, **named ) TypeError: 'NoneType' object is not callable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "run.py", line 28, in &lt;module&gt; obj = OBJ('robotbase.obj') File "/home/warted/COMMAND CENTRE/SEDS/GUI/Simulate/objloader.py", line 97, in __init__ glNormal3fv(self.normals[normals[i] - 1]) File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/latebind.py", line 45, in __call__ return self._finalCall( *args, **named ) File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 677, in wrapperCall pyArgs = tuple( calculate_pyArgs( args )) File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/wrapper.py", line 438, in calculate_pyArgs yield converter(args[index], self, args) File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arrayhelpers.py", line 112, in asArraySize handler = typ.getHandler( incoming ) File "/home/warted/anaconda3/lib/python3.6/site-packages/OpenGL/arrays/arraydatatype.py", line 53, in __call__ typ.__module__, type.__name__, repr(value)[:50] TypeError: ('No array-type handler for type builtins.type (value: &lt;map object at 0x7f6bf0f8f4a8&gt;) registered', &lt;function asArrayTypeSize.&lt;locals&gt;.asArraySize at 0x7f6c01d6a620&gt;)
tagged with: blender
has answer: http://stackoverflow.com/a/47660960
has comment: http://stackoverflow.com/comment/82279821
accepted answer: http://stackoverflow.com/a/47660960
has title: Error in OBJFileLoader
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82279659
has comment: http://stackoverflow.com/comment/82280494
linked to: http://stackoverflow.com/q/46609928
type: Question
score: 0

http://stackoverflow.com/q/47651993
tagged with: python
tagged with: regex
tagged with: text-extraction
has comment: http://stackoverflow.com/comment/82262133
has comment: http://stackoverflow.com/comment/82262160
has answer: http://stackoverflow.com/a/47652399
accepted answer: http://stackoverflow.com/a/47652399
answer count: 1
tagged with: string
type: Question
type: AnsweredQuestion
score: 0
has title: How to extract only one string from regex in Python?
has body: I have been trying to build a simple account manager sort of application for myself using Python which will read SMS from my phone and extract information based on some regex patterns. I wrote a complex regex pattern and tested the same on https://pythex.org/. Example: Text: 1.00 is debited from ******1234 for food Pattern: (account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*) Result: from ******1234 However, when I try to do the same in Python using the str.extract() method, rather than getting a single result, I am getting a dataframe with a column for each group. Python code looks like this: all_sms=pd.read_csv("all_sms.csv") pattern = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)' test = all_sms.extract(pattern, expand = False) Output of the python code for the message above: 0 from 1 2 NaN 3 NaN 4 NaN 5 ******1234 6 1234 7 1234 8 9 10 I am very new to Python and trying to learn by hands-on experience, it would be really helpful if someone can point out where I am going wrong with this?

http://stackoverflow.com/a/47600371
answers question: http://stackoverflow.com/q/47599875
score: 0
has body: Try this script. It should give you the country names along with corresponding currencies. You didn't require to use headers for this site. from bs4 import BeautifulSoup import urllib.request url = "http://www.worldatlas.com/aatlas/infopage/currency.htm" resp = urllib.request.urlopen(urllib.request.Request(url)).read() soup = BeautifulSoup(resp, "lxml") for item in soup.select("table tr"): try: country = item.select("td")[0].text.strip() except IndexError: country = "" try: currency = item.select("td")[0].find_next_sibling().text.strip() except IndexError: currency = "" print(country,currency) Partial Output: Afghanistan afghani Algeria dinar Andorra euro Argentina peso Australia dollar
accepted answer of: http://stackoverflow.com/q/47599875
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/82199218
has text: I works for me with `textvariable=` when I remove `state="readonly"`.
comment on: http://stackoverflow.com/q/47620213
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82139326
has text: Reading this, three things stand out: 1) This was the very first question of the interview, 2) they specifically mention Pi (an irrational number) and 3) the ambiguous "constant of 1000". As the answers state it's not possible, making me wonder whether this was a trick question and with a sufficiently long test string, all combinations could be expected to repeat an equal number of times. Was this an interactive question between you an interviewer? Just a different perspective to the `O(n)` answers if you got the impression it had to be constant time.
comment on: http://stackoverflow.com/q/47581326
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47595077
has comment: http://stackoverflow.com/comment/82160298
answers question: http://stackoverflow.com/q/47594898
has comment: http://stackoverflow.com/comment/82155786
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47594898
has body: It means that the data that you're getting is not a valid JSON. It'll be also more pythonic if you had used format functions or %s placeholders: url_template = ( 'https://air.makemytrip.com/air/screen/ifsearch?tripType=O&amp;' 'itinerary=%(source)s-%(dest)s-D-%(date0)s&amp;paxType=A-1&amp;' 'cabinClass=%(c1)s' ) page = requests.get(url_template % locals(), verify=False, timeout=15).json()

http://stackoverflow.com/q/47647282
has comment: http://stackoverflow.com/comment/82276953
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82277196
has body: I have tried multiple iterations of code to get this done but cant seem to find a good solution. Been at it for days. Here is the XML data I am returning from an API: 14:00:42 14:00:42 16:00:00 FIN 123 123 1 <receive_time>2017/11/25 12:12:02</receive_time> 123 123 123 Example Example <config_ver>0</config_ver> <time_generated>2017/11/25 12:12:00</time_generated> 192.168.1.1 192.168.1.1 192.168.1.1 192.168.1.1 Example 10.0.0.0-10.255.255.255 United States Example Example Example Example <inbound_if>Example</inbound_if> <outbound_if>Example</outbound_if> Example <time_received>Example</time_received> Example 1 123 80 123 80 123 no no no no yes no no no no no no no no tcp Example 0 <dg_hier_level_1>0</dg_hier_level_1> <dg_hier_level_2>0</dg_hier_level_2> <dg_hier_level_3>0</dg_hier_level_3> <dg_hier_level_4>0</dg_hier_level_4> <vsys_name>Legacy</vsys_name> <device_name>Example</device_name> <vsys_id>123</vsys_id> 463 <bytes_sent>393</bytes_sent> <bytes_received>70</bytes_received> 4 Example 0 Example 0 <pkts_sent>3</pkts_sent> <pkts_received>1</pkts_received> <session_end_reason>Example</session_end_reason> <action_source>Example</action_source> 1 <receive_time>2017/11/25 12:12:02</receive_time> Example Example Example Example Example <config_ver>0</config_ver> <time_generated>2017/11/25 12:12:00</time_generated> 192.168.1.1 192.168.1.2 Example Example 10.0.0.0-10.255.255.255 10.0.0.0-10.255.255.255 Example Example Example Example <inbound_if>Example</inbound_if> Example <time_received>Example</time_received> 0 1 123 123 0 0 123 no no no no no no no no no no no no no tcp Example 0 <dg_hier_level_1>0</dg_hier_level_1> <dg_hier_level_2>0</dg_hier_level_2> <dg_hier_level_3>0</dg_hier_level_3> <dg_hier_level_4>0</dg_hier_level_4> <vsys_name>Example</vsys_name> <device_name>Example</device_name> <vsys_id>0</vsys_id> 70 <bytes_sent>70</bytes_sent> <bytes_received>0</bytes_received> 1 Example 0 Example 0 <pkts_sent>1</pkts_sent> <pkts_received>0</pkts_received> <session_end_r…
has comment: http://stackoverflow.com/comment/82255712
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47660586
tagged with: pandas
has comment: http://stackoverflow.com/comment/82277279
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82252975
linked to: http://stackoverflow.com/q/47453372
has comment: http://stackoverflow.com/comment/82276190
accepted answer: http://stackoverflow.com/a/47660586
tagged with: http://stackoverflow.com/tag/xml
has title: Parse XML to Pandas DataFrame to CSV
type: Question
tagged with: api
has comment: http://stackoverflow.com/comment/82275795

http://stackoverflow.com/comment/93392646
comment on: http://stackoverflow.com/a/47611701
has text: Hope you don't mind me bringing this back up, but would you know I could do this but with "--onefile" mode on pyinstaller? The problem there is the directory for "_sounddevice_data" is in a temp folder that only exists while the script is running, so there's no way for me to place the "libportaudio64bit.dll" file in there.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/47689817
has body: Given this code import tkinter canvas = tkinter.Canvas() canvas.pack() i = 0 k = 1 while True: canvas.create_text(100, 0+i, text="Python 3.6!", fill="red") canvas.update() canvas.create_rectangle(0, 0, canvas["width"], canvas["height"], fill=canvas["background"]) canvas.after(3) i = i + k if i==-1 or i==265: k = -k we can see that with each cycle of while loop the movement of the text slows down. Now, since we are re-rendering the whole canvas multiple times a second, no wonder that it is slow. However, why is it slowing down with time? Is it due to the great amount of objects text and rectangle objects piling up? Can this be avoided?
has comment: http://stackoverflow.com/comment/82339285
accepted answer: http://stackoverflow.com/a/47690980
type: Question
tagged with: python-3.x
tagged with: tkinter
answer count: 2
has answer: http://stackoverflow.com/a/47690980
tagged with: tkinter-canvas
downvote count: 0
possible better answer: http://stackoverflow.com/a/47690996
upvote count: 1
has title: Render time increasing with time
has answer: http://stackoverflow.com/a/47690996
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82339768
score: 1
tagged with: python

pandas-groupby
tags question: http://stackoverflow.com/q/47681739
type: Tag
tags question: http://stackoverflow.com/q/47542980
tags question: http://stackoverflow.com/q/47657932
tags question: http://stackoverflow.com/q/47643338
tags question: http://stackoverflow.com/q/47564103
tags question: http://stackoverflow.com/q/47647464
tags question: http://stackoverflow.com/q/47693001
tags question: http://stackoverflow.com/q/47633005
tags question: http://stackoverflow.com/q/47617499
tags question: http://stackoverflow.com/q/47580313
tags question: http://stackoverflow.com/q/47617188
tags question: http://stackoverflow.com/q/47623209
tags question: http://stackoverflow.com/q/47552206
tags question: http://stackoverflow.com/q/47666438
tags question: http://stackoverflow.com/q/47552110
tags question: http://stackoverflow.com/q/47583210
tags question: http://stackoverflow.com/q/47602097
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/47595319
tags question: http://stackoverflow.com/q/47543392
tags question: http://stackoverflow.com/q/47588971
tags question: http://stackoverflow.com/q/47594945
tags question: http://stackoverflow.com/q/47617111

http://stackoverflow.com/comment/82061983
type: AnswerComment
has text: `NONE` is a valid identifier, though; I think for the purposes of this question we can just assume that it is defined previously.
type: Comment
comment on: http://stackoverflow.com/a/47552753
score: 2

http://stackoverflow.com/q/47615528
has title: How to enable/disable a line of code without the usage of if statements?
tagged with: python
has comment: http://stackoverflow.com/comment/82189572
has comment: http://stackoverflow.com/comment/82189517
downvote count: 1
has comment: http://stackoverflow.com/comment/82189560
score: 1
has answer: http://stackoverflow.com/a/47615623
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82189410
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/82189355
has comment: http://stackoverflow.com/comment/82189507
has body: Say that you have 2 print statements: print ("Hi") print ("Hello") And you comment out the second line resulting in: print ("Hi") #print ("Hello") This would only execute the first line on runtime, ignoring the second. My question is, is there a way to enable the second line during runtime without having to manually go to the script and remove it? I'd like to do through user input, but also without the usage of if statements because my code is getting over saturated with "ifs" and wish to do something different.
type: UnansweredQuestion

http://stackoverflow.com/comment/82096240
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47543909
type: QuestionComment
has text: I went through the logs today and I see that there seems to be repeated calls to tempfile.py and random.py until I just kill the process as it never ends. I'm not sure which part of the pandas module also calls it

http://stackoverflow.com/a/47583816
type: AcceptedAnswer
downvote count: 0
has body: For the case where you provide no further information or only specify number of partitions, the partitioning logic in read_sql_table only works for numbers, because we need a way to make ordered divisions between the minimum and maximum values. Apparently, but the query (to get the max/min) is returning a string for this case. read_sql_table can still work, but you will need to define the divisions to split on yourself, and supply them with the divisions keyword, e.g., ddf = dd.read_sql_table("table name", "mysql://user:pass@ip:port/Dbname", 'index_col', divisions=['aardvark', 'llama', 'tapir', 'zebra']).head() Alternatively, the string in question certainly looks like a number, so you might need to update the schema of the table to make sure it is interpreted as a number.
has comment: http://stackoverflow.com/comment/82190764
answers question: http://stackoverflow.com/q/47573519
has comment: http://stackoverflow.com/comment/82214906
accepted answer of: http://stackoverflow.com/q/47573519
upvote count: 2
has comment: http://stackoverflow.com/comment/82125245
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82228389

http://stackoverflow.com/a/47574584
answers question: http://stackoverflow.com/q/47574518
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82106018
upvote count: 3
downvote count: 0
has body: You are indexing from 1 instead of zero. What you can do is subtract 1 and then add 1 to the remainder again: month = (month - 1) % 12 + 1

http://stackoverflow.com/q/47647319
has title: Quote only the required columns using pandas to_csv
tagged with: pandas
has answer: http://stackoverflow.com/a/47666381
has comment: http://stackoverflow.com/comment/82253126
downvote count: 0
has comment: http://stackoverflow.com/comment/82256058
score: 7
upvote count: 7
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/64323493
tagged with: export-to-csv
tagged with: quoting
answer count: 2
has body: I need to generate a csv using pandas to_csv function. I tried quote=csv.QUOTE_NONNUMERIC. But for one of the date time column I dont need double quotes. Is there a way to select the columns for which we want double quotes?

http://stackoverflow.com/comment/82132333
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47587027
has text: Once selected, can I print the source of the selected form to verify that I have the right form?

http://stackoverflow.com/comment/82107184
type: Comment
comment on: http://stackoverflow.com/a/47557743
type: AnswerComment
score: 0
has text: Yes but it's a great amount of temporal data so it doesn't feel right

http://stackoverflow.com/a/47586970
type: Answer
accepted answer of: http://stackoverflow.com/q/47586719
has body: Assuming at least one of 'src_big' / 'xsrc_big'is present, you could do: Python 3.x src_big = [x['photo'].get('src_xbig', x['photo']['src_big']) for _, x in photos['response'].items()] Python 2.7 src_big = [x['photo'].get('src_xbig', x['photo']['src_big']) for _, x in photos['response'].iteritems()]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47586719
score: 0

http://stackoverflow.com/comment/82186434
score: 0
type: Comment
has text: yeah, I noticed that after the fact, the function wasen't even being called with post data.
type: AnswerComment
comment on: http://stackoverflow.com/a/47613825

http://stackoverflow.com/q/47569108
possible better answer: http://stackoverflow.com/a/47569190
favorite count: 0
upvote count: 17
has answer: http://stackoverflow.com/a/47569526
type: Question
tagged with: tuples
has answer: http://stackoverflow.com/a/47569190
has title: Sort tuple list with another list
tagged with: python
downvote count: 5
has body: I have a tuple list to_order such as: to_order = [(0, 1), (1, 3), (2, 2), (3,2)] And a list which gives the order to apply to the second element of each tuple of to_order: order = [2, 1, 3] So I am looking for a way to get this output: ordered_list = [(2, 2), (3,2), (0, 1), (1, 3)] Any ideas?
accepted answer: http://stackoverflow.com/a/47570669
has comment: http://stackoverflow.com/comment/82117249
answer count: 4
has comment: http://stackoverflow.com/comment/82095641
has answer: http://stackoverflow.com/a/47570669
has comment: http://stackoverflow.com/comment/82117442
has comment: http://stackoverflow.com/comment/82117517
type: AnsweredQuestion
score: 12
tagged with: list
has comment: http://stackoverflow.com/comment/82095741
linked to: http://stackoverflow.com/q/12814667
has answer: http://stackoverflow.com/a/47569494
has comment: http://stackoverflow.com/comment/82115316
tagged with: sorting
has comment: http://stackoverflow.com/comment/82103753
has comment: http://stackoverflow.com/comment/109352712

http://stackoverflow.com/comment/82114188
comment on: http://stackoverflow.com/q/47578486
type: QuestionComment
has text: Since `mylist[i].method(a,b)` is slow, could be better not using for loop?
type: Comment
score: 0

http://stackoverflow.com/comment/82322993
score: 0
comment on: http://stackoverflow.com/a/47636062
type: Comment
type: AnswerComment
has text: Thank you, there is example code with requests at https://github.com/Zaargh/ocr.space_code_example/blob/master/ocrspace_example.py , but unless I'm missing something obvious I still don't understand how to pipe the output from : library.MagickWriteImages(resource_pointer,"output.jpeg".enc‌​ode("ASCII"), False) to an Image() instance, without writing to disk.

http://stackoverflow.com/a/47663197
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82291054
type: Answer
has body: From the docs: Enabling the still statistics pass will override fixed white balance gains (set via awb_gains and awb_mode). I would bet that awb_mode gets set back to something other than off when you change still_stats. Exact same problem seems to be reported here.
has comment: http://stackoverflow.com/comment/82288656
answers question: http://stackoverflow.com/q/47662978

http://stackoverflow.com/comment/85781470
has text: I have a similar use-case, can you describe the goal of transferring the lidar data to the parquet format?
comment on: http://stackoverflow.com/q/47671676
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47683474
type: Question
has answer: http://stackoverflow.com/a/47684383
has comment: http://stackoverflow.com/comment/82327768
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82327177
has comment: http://stackoverflow.com/comment/82327540
tagged with: python-3.x
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82326692
has body: I am having troubles figuring out how to store multiple .csv files into a dictionary and then print the keys and values separately. I have to take 6 .csv files all containing different information and load them into a dictionary(s) and then write a code so that I am able to isolate the key from the various values its associated with so that I can print ie. "animal" eats "prey1, prey2, etc". I think I have to do each file separately, so 6 different loops to get the right output for each list of key/values, but everything I've tried has given me an error message. Here is an examples of a csv file and the expected output: file1.csv: Rabbit,Grass Snake,Mouse Mouse,Grass Output: Predator and prey: "Rabbit eats grass" "Snake eats mouse" "Mouse eats grass" this is the code I have so far for one file: import sys import csv inf = open("file1.csv", "r") reader = csv.reader(inf) data = {} for row in reader: for i in data.keys(): print(data[i], "eats", i) I know its not right but I'm not sure how to isolate a key in a dictionary when its a .csv file. I am new to coding so any help would be greatly appreciated! :) I am using python3. thanks!!
has answer: http://stackoverflow.com/a/47684260
has title: Load .csv files into dictionary and print keys and values separately

http://stackoverflow.com/q/47587581
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47587931
has title: sound parameter cannot be gotten
has body: sound parameter cannot be gotten.I wrote codes def common(request): if request.FILES: file = request.FILES['sound'].temporary_file_path() return HttpResponse(' OK ') else: file = None return HttpResponse(' NG ') I send wav file via POSTMAN like Now if I set sound parameter in POSTMAN,always NG is returned.I really cannot understand why this program do so.I print out request.FILES so is printed out.So am I wrong to write the way of writing if-else statement branch?How should I fix this?
has answer: http://stackoverflow.com/a/47587931
tagged with: django
tagged with: python

http://stackoverflow.com/q/47683705
has answer: http://stackoverflow.com/a/47684167
type: Question
has body: Currently I have a loop that contains: df = pandas.read_pickle(filepath) the files are ~ 100 mb. However since it is looping through these many times, it is taking up a lot of memory and then eventually I get a memory error. Is there a way to do this where I can close the file once I get the dataframe? My code is correct because I've tested it with less files. I just want an alternative to reading large pickle files without taking up too much memory after I read it.
has title: How to read pickle files without taking up a lot of memory
accepted answer: http://stackoverflow.com/a/47684167
has comment: http://stackoverflow.com/comment/82329546
tagged with: pickle
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
tagged with: python

http://stackoverflow.com/comment/82388719
type: AnswerComment
has text: You are welcome! Please check the answer as the selected one if this worked for you!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47690535

http://stackoverflow.com/comment/82117241
has text: Because floating point math is approximate *and* .1 cannot be exactly represented as a floating point number. So in neither case are you actually dividing by .1, you're dividing instead by two *different* approximations of .1, one that is smidge less than .1 and one that's a smidge more.
comment on: http://stackoverflow.com/q/47579918
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47585380
answer count: 2
has comment: http://stackoverflow.com/comment/82128518
has answer: http://stackoverflow.com/a/47585430
possible better answer: http://stackoverflow.com/a/47585430
upvote count: 0
has comment: http://stackoverflow.com/comment/82128566
tagged with: variables
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82128528
has comment: http://stackoverflow.com/comment/82128623
has title: Testing variable throwing errors
has body: I'm working on a lab testing software - I'm at the backbone stage, and I'm just trying to test if the emergency stop will recognize a failure before it gets too far along. Here is the code: import sys def main(argv): currentTempAverage = 0; testingPlaced = False typeOfTesting = False issue="False" class labTesting(object): def __init__(self,currentCondition,emergencyStop=0): self.output = labLog() Conditions = [] self.status = "OPEN" self.beginningCondition = currentCondition self.EndingCondition = "" self.output.log("Testing opened") if float(currentCondition) &gt; float(self.beginningCondition*1.003): issue="True" if (issue=="True") and float(currentCondition) &lt; float(beginningCondition*1.002): self.output.log("YIKES!") self.status="CLOSED" if (emergencyStop): self.emergencyStop = currentCondition - emergencyStop self.output.log("stop loss") def close(self,currentCondition): if currentCondition &gt; (self.beginningCondition * 1.012717049): self.status = "CLOSED" self.EndingCondition = currentCondition def tick(self, currentCondition): def showTesting(self): testingStatus = "Entry Condition: "+str(self.beginningCondition) self.output.log(testingStatus) Basically, it's checking levels, and if the levels reach a certain point - issue=true, because it may become an issue. If the levels become lower, it does the emergency stop. Depending how I do it, it throws errors. Traceback (most recent call last): File "/home/DDesm/Desktop/w/labtest/testing.py", line 18, in tick if (issue=="True") and float(currentPrice) &lt; float(entryPrice*1.002): UnboundLocalError: local variable 'issue' referenced before assignment Thanks!
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47585412
accepted answer: http://stackoverflow.com/a/47585412
type: AnsweredQuestion

http://stackoverflow.com/comment/82162053
comment on: http://stackoverflow.com/a/47601252
type: Comment
has text: Should be available in `{{ form_data.address }}`. I am not able to test the code right now.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47667945
tagged with: parameters
has title: Django query passing parameters into values()
score: 2
type: AnsweredQuestion
tagged with: sql
downvote count: 0
has comment: http://stackoverflow.com/comment/82294774
has answer: http://stackoverflow.com/a/47668082
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82294823
type: Question
upvote count: 2
has body: I have a Django query like this and I want to be able to pass the "values" param from a variable. Reason for this I can standardize all my list values otherwise it will be hardcoded on every values. So for example, this works: employee_list = Employee.objects.all().values("id", "username").order_by('id') But I cannot do this. It doesnt work: val_params = ["id", "username"] employee_list = Employee.objects.all().values(val_params).order_by('id') what kind of val_params can i use to pass into values() ? Is there a way to do this ?
accepted answer: http://stackoverflow.com/a/47668082
tagged with: database
tagged with: django
tagged with: python

http://stackoverflow.com/a/47566871
type: Answer
has comment: http://stackoverflow.com/comment/82188634
score: 0
answers question: http://stackoverflow.com/q/47566796
has comment: http://stackoverflow.com/comment/82176752
has body: You might use tweepy for the library side of things. Use the official search API for getting the tweets: GET https://api.twitter.com/1.1/search/tweets.json?q=%23abcd Where the query parameter can be a string or a hashtag. (%23 being the url encoded #) More information is available here: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html Note : Search API is OAauth authenticated, so you'll need to include your access tokens to the API call.

http://stackoverflow.com/a/47681877
answers question: http://stackoverflow.com/q/47681601
has body: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c = [] c = list( set(a).intersection(set(b)) ) print (c) The code is self explanatory given that you have basic knowledge of sets.
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/47683774
accepted answer of: http://stackoverflow.com/q/47683436
type: Answer
has comment: http://stackoverflow.com/comment/82353827
has body: This appears to be a LLVM vs GCC thing - see example in compiler explorer here, which is less noisy than what numba spits out. I get a bit lost in the assembly, but fairly clear that the GCC output has a loop (the jge to .L6) and the clang output does not. See also this issue on the GCC bugtracker. On my machine (Windows x64) numba is not significantly slower than smart, only about 9 ns. This overhead appears to be due to the type dispatch mechanism of numba - if you elide it by picking a specific overload, the numba version is faster than the python one Here are my timings In [73]: %timeit numba_sum(10000) 182 ns ± 1.69 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [74]: %timeit smart(10000) 171 ns ± 2.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # pick out int64 overload i64_numba_sum = numba_sum.get_overload((numba.int64,)) In [75]: %timeit i64_numba_sum(10000) 94 ns ± 1.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
score: 8
answers question: http://stackoverflow.com/q/47683436
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82330946
upvote count: 8

http://stackoverflow.com/comment/82302625
type: Comment
type: QuestionComment
score: 0
has text: @Nae Looks promising, but I was thinking more in the line of text, with options like "In queue", "Collecting data", "Writing output".
comment on: http://stackoverflow.com/q/47670677

http://stackoverflow.com/comment/82360321
type: Comment
has text: MatthiasK: My example code shows using `self.filename` in the `XPSPlotApp.plot_file()` method that was added. What more do you want? What's an example of "using" it in another class? What other class? Each `tk.Frame` subclass receives a `controller` argument when it's constructed. That object is an instance of `XPSPlotApp` and will have a `filename` attribute once the `"Open"` menu item has run the `browse_file()` method.
type: AnswerComment
comment on: http://stackoverflow.com/a/47685198
score: 0

http://stackoverflow.com/comment/82201262
type: Comment
type: QuestionComment
score: 0
has text: Use the number you got from the user instead of 64 in your `range(1, 64)`?
comment on: http://stackoverflow.com/q/47621670

http://stackoverflow.com/comment/82075406
comment on: http://stackoverflow.com/q/47558810
has text: The species came from an excel file (.xlsx) that we converted to a csv file
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47561298
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/82080343
downvote count: 1
tagged with: regex
possible better answer: http://stackoverflow.com/a/51368403
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47561619
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51368403
accepted answer: http://stackoverflow.com/a/47561619
score: 5
has title: python regex, remove escape characters and punctuation except for apostrophe
has comment: http://stackoverflow.com/comment/82080492
upvote count: 6
tagged with: python
has body: I have a string that looks like this: "aaa\n\t\n asd123asd water's tap413 water blooe's" How can I remove all escape characters, numbers, and punctuation except apostrophe using regex? I'm pretty new to regex, and would appreciate it if you can explain what each expression means, if the regex formula is to be complicated
has answer: http://stackoverflow.com/a/47561428
has comment: http://stackoverflow.com/comment/82080612

http://stackoverflow.com/comment/82298862
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47669979
type: QuestionComment
has text: So use `print(output.loc[str(df.loc[i,'item_id']),word]).iat[0]` for select first value only.

http://stackoverflow.com/q/47643798
has answer: http://stackoverflow.com/a/47643939
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82246825
upvote count: 0
downvote count: 2
answer count: 1
has title: tkinter - pictures from for loop do not appear
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/16424091
has body: I'm making a tkinter application in python, in which I have a frame where I want to show 4-5 pictures. The code above the hashtags is working fine, it shows 1 pictures. But the code below the picture is bad for some reason. It doesn't show anything, but it should show 4 pictures. Do I need to make a list from the PhotoImages or is something wrong with the self-s? Thanks self.photo = PhotoImage(file=onlyfiles[0]) self.photo = self.photo.subsample(4, 4) label=Label(self, image=self.photo) label.pack() ################################################ image_labels = [] for i in range(len(onlyfiles)): # 4 self.gombi = PhotoImage(file=onlyfiles[i]) self.gombi = self.gombi.subsample(4, 4) image_labels.append(Label(self, image=self.gombi)) image_labels[i].pack()
score: -2
has comment: http://stackoverflow.com/comment/82246836
accepted answer: http://stackoverflow.com/a/47643939
has comment: http://stackoverflow.com/comment/82246807
tagged with: python
linked to: http://stackoverflow.com/q/37515847

http://stackoverflow.com/comment/82041225
score: 0
type: AnswerComment
has text: In the code from my answer there is only one single figure and that figure is saved.
comment on: http://stackoverflow.com/a/47541316
type: Comment

http://stackoverflow.com/comment/82110867
type: Comment
score: 0
has text: Ok then you might need a for loop
type: AnswerComment
comment on: http://stackoverflow.com/a/47562735

scroll
type: Tag
tags question: http://stackoverflow.com/q/47552951
tags question: http://stackoverflow.com/q/47605073
tag name: scroll

http://stackoverflow.com/q/47608018
tagged with: git
score: 3
has answer: http://stackoverflow.com/a/47608086
upvote count: 3
has title: unable to find tessdata for Tesseract
has body: Hi I am new to python and tesseract. I am using anaconda distribution and trying to use pytesseract-ocr when I try to get the data from image it gives me following error: tesseract imageSample1.jpg test.txt digits // output Tesseract Open Source OCR Engine v3.04.01 with Leptonica Error opening data file /anaconda/envs/_build/share/tessdata/eng.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory. Failed loading language 'eng' Tesseract couldn't load any languages! Could not initialize tesseract. So first this there is no such /anaconda/envs/_build/share/tessdata/ directory. I have anaconda3 folder. I downloaded end.traindata from git. but not sure where to put that data. Am I doing some thing wrong. Need some help. thank you.
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47608113
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: pytesser

web-scraping
tags question: http://stackoverflow.com/q/47666070
tags question: http://stackoverflow.com/q/47614973
tags question: http://stackoverflow.com/q/47679962
tags question: http://stackoverflow.com/q/47682159
tags question: http://stackoverflow.com/q/47638267
tags question: http://stackoverflow.com/q/47576276
tags question: http://stackoverflow.com/q/47561116
tags question: http://stackoverflow.com/q/47647938
tags question: http://stackoverflow.com/q/47695744
tags question: http://stackoverflow.com/q/47651795
tags question: http://stackoverflow.com/q/47599875
tag name: web-scraping
tags question: http://stackoverflow.com/q/47586162
tags question: http://stackoverflow.com/q/47540852
tags question: http://stackoverflow.com/q/47685300
tags question: http://stackoverflow.com/q/47558723
tags question: http://stackoverflow.com/q/47635766
tags question: http://stackoverflow.com/q/47598154
tags question: http://stackoverflow.com/q/47697567
tags question: http://stackoverflow.com/q/47670928
tags question: http://stackoverflow.com/q/47582179
tags question: http://stackoverflow.com/q/47653309
type: Tag
tags question: http://stackoverflow.com/q/47697697
tags question: http://stackoverflow.com/q/47542091
tags question: http://stackoverflow.com/q/47565038
tags question: http://stackoverflow.com/q/47541274
tags question: http://stackoverflow.com/q/47669376
tags question: http://stackoverflow.com/q/47635866
tags question: http://stackoverflow.com/q/47578144
tags question: http://stackoverflow.com/q/47614874
tags question: http://stackoverflow.com/q/47552417
tags question: http://stackoverflow.com/q/47628667
tags question: http://stackoverflow.com/q/47647833
tags question: http://stackoverflow.com/q/47575321
tags question: http://stackoverflow.com/q/47647162
tags question: http://stackoverflow.com/q/47603383
tags question: http://stackoverflow.com/q/47640891
tags question: http://stackoverflow.com/q/47570467
tags question: http://stackoverflow.com/q/47630124
tags question: http://stackoverflow.com/q/47673088
tags question: http://stackoverflow.com/q/47665289
tags question: http://stackoverflow.com/q/47618469
tags question: http://stackoverflow.com/q/47648750
tags question: http://stackoverflow.com/q/47581662
tags question: http://stackoverflow.com/q/47557989
tags question: http://stackoverflow.com/q/47560644
tags question: http://stackoverflow.com/q/47604044
tags question: http://stackoverflow.com/q/47541320
tags question: http://stackoverflow.com/q/47650531
tags question: http://stackoverflow.com/q/47687349
tags question: http://stackoverflow.com/q/47575155
tags question: http://stackoverflow.com/q/47569935

http://stackoverflow.com/comment/82111195
type: Comment
comment on: http://stackoverflow.com/a/47557702
type: AnswerComment
has text: I hope you didn't use uppercase 'Subs'. If not, please show your entire code.
score: 1

http://stackoverflow.com/comment/82132105
type: Comment
type: QuestionComment
has text: Could you please post your code? Also, what is the size of your data? (since the error mentions `Memory Error` )
comment on: http://stackoverflow.com/q/47587081
score: 0

http://stackoverflow.com/a/47641378
has body: First off, you should always use with statements when working with files. The benefits of this are well documented. So this: usrFile_write = open(textfile, "a") usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":") print("New Account Created!\n") usrFile_write.close() Becomes: with open(textfile, "a") as usrFile: usrFile.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":") print("New Account Created!\n") Now, working in a plain text file, you can't really edit specific lines. In order to update an existing user entry, you will have to delete the existing entry and create a new one in its place. This requires reading through the file and re-writing the whole thing, except for the specific line. You can put this into a generalized deleteUser function for re-use later on: def deleteUser(username): with open(textfile, "r") as usrFile: lines = usrFile.readlines() with open(textfile, "w") as usrFile: for line in lines: if line.split(":")[0] != username: usrFile.write(line) Then, to modify a user, you delete their entry and then create a new one with the new information. This ought to cover you for now. I recommend looking into using a database like sqlite in the long term, this job is much better suited for it.
score: 0
answers question: http://stackoverflow.com/q/47641246
has comment: http://stackoverflow.com/comment/82241563
type: Answer

http://stackoverflow.com/comment/82279638
comment on: http://stackoverflow.com/a/47660186
type: AnswerComment
has text: @Manjunath I added a try/except to fix that scenario
score: 0
type: Comment

http://stackoverflow.com/a/66344486
type: Answer
answers question: http://stackoverflow.com/q/47674311
has body: See my farsante lib for creating a DataFrame with fake data: import farsante df = farsante.quick_pyspark_df(['first_name', 'last_name'], 7) df.show() +----------+---------+ |first_name|last_name| +----------+---------+ | Tommy| Hess| | Arthur| Melendez| | Clemente| Blair| | Wesley| Conrad| | Willis| Dunlap| | Bruna| Sellers| | Tonda| Schwartz| +----------+---------+ Here's how to explicitly specify the schema when creating the PySpark DataFrame: df = spark.createDataFrame( [(10,), (11,), (13,)], StructType([StructField("some_int", IntegerType(), True)])) df.show() +--------+ |some_int| +--------+ | 10| | 11| | 13| +--------+
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47684802
has body: I have a list of keywords and I want to go through a directory looking for filename that contain the keyword. If found, binds the matching keyword and file path to a dictionary. keywords = ['mon', 'tue', 'wed'] dict = {} directory = os.fsencode(r"my_dir") for file in os.listdir(directory): filename = os.fsdecode(file) ext = Path(file).suffix if filename in keywords: filepath = os.path.join(directory, filename, ext) dict[keyword] = filepath So at the end I want something like this: {'mon': 'F:\mon_001.txt', 'tue': 'F:\tue_999.txt', 'wed': 'F\wed_123.txt'} Now how do I find the match?
accepted answer: http://stackoverflow.com/a/47684866
has answer: http://stackoverflow.com/a/47684866
has title: To check if filename has substring of a word in a list
answer count: 2
has comment: http://stackoverflow.com/comment/82329178
has answer: http://stackoverflow.com/a/47684854
type: Question
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47684854
tagged with: python

http://stackoverflow.com/comment/82235036
has text: python 3 does it matter?
score: 0
comment on: http://stackoverflow.com/q/47638267
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82066414
score: 0
type: AnswerComment
has text: Do you mean replace `from config import app_config` with something else? Changing that line to `from ..config import app_config` leads to a `ValueError: Attempted relative import in non-package `
type: Comment
comment on: http://stackoverflow.com/a/47554505

http://stackoverflow.com/a/47607507
type: Answer
has body: You can try this with a function without importing any external module: sentence = "Eveeery mondayyy I waaake upp" def no_dublicate(senten,N): final=[] for word in senten.split(): track=[] for chara in word: track.append(chara) if track.count(chara)&gt;N: track.remove(chara) final.append(track) return ' '.join(["".join(item) for item in final]) print(no_dublicate(sentence,2)) output: Eveery mondayy I waake upp
answers question: http://stackoverflow.com/q/47607180
score: 0

http://stackoverflow.com/comment/82063667
comment on: http://stackoverflow.com/q/47545329
score: 0
type: Comment
type: QuestionComment
has text: I think that a related field on a One2many cannot be called like a Many2one related one, ie: many2one.related, I think it should be one2many.many2onefromotherclass.related , maybe that's one of the issues

http://stackoverflow.com/q/47627698
has comment: http://stackoverflow.com/comment/82220772
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82213583
tagged with: django
has comment: http://stackoverflow.com/comment/82219266
has body: I googled and read many articles but got confused in multiple table join. My models looks like- class ProductCategory(models.Model): category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) category_image = models.ImageField(upload_to='category', null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.category_name) class ProductSubCategory(models.Model): category = models.ForeignKey(ProductCategory) sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.sub_category_name) class Product(models.Model): category = models.ForeignKey(ProductCategory) sub_category = models.ForeignKey(ProductSubCategory) product_name = models.CharField(max_length=200,blank=True, null=True) product_price = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) # is_discountable = models.CharField(max_length=3, default='Yes', choices=option) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.product_name) class ProductColor(models.Model): product = models.ForeignKey(Product) product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True) product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True) class …
has title: Django join multiple models using django ORM
type: Question
has comment: http://stackoverflow.com/comment/82217608
has answer: http://stackoverflow.com/a/47628168
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82218555
has comment: http://stackoverflow.com/comment/82213136
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47628083
has comment: http://stackoverflow.com/comment/82220674

http://stackoverflow.com/comment/82051161
has text: That is not what I had actually in mind. I meant to drop the database not to clear the data. Flush just clears the database(https://docs.djangoproject.com/en/1.11/ref/django-admin/#flush). Which db are you using? Postgres?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47546587
type: Comment

http://stackoverflow.com/comment/82646964
comment on: http://stackoverflow.com/q/47610050
type: Comment
has text: @FlorentB. "This feature is broken in the PyInstaller 3.0 release"
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82197934
type: AnswerComment
has text: You could also do `simple_walker.extend(choices)`
comment on: http://stackoverflow.com/a/47558524
type: Comment
score: 1

timer
tag name: timer
tags question: http://stackoverflow.com/q/47571412
tags question: http://stackoverflow.com/q/47558622
tags question: http://stackoverflow.com/q/47578963
type: Tag

http://stackoverflow.com/q/47572872
has comment: http://stackoverflow.com/comment/82106983
has comment: http://stackoverflow.com/comment/82106754
type: Question
has comment: http://stackoverflow.com/comment/82107644
linked to: http://stackoverflow.com/q/5329001
has comment: http://stackoverflow.com/comment/82107567
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82106815
has comment: http://stackoverflow.com/comment/82107190
has title: Python Kivy: In Xcode9.1 and OS high sierra, I build failed with 73 issues
has body: Please help me. I have a big problem and cannot solve in 46hours. at first, look at my pict. My picture Second look this URL. How to build ipa in kivy I certainly did build as described in the URL. But still error happening like my picture. And 73!! so many problem. Please somebody tell me how to fix it. cython is 0.23 kivy is 1.10.0 and here is toolchain status: Added picture of about "Enable bitcode"
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/82107078
has comment: http://stackoverflow.com/comment/82107378
has comment: http://stackoverflow.com/comment/82107469
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/82106944

http://stackoverflow.com/comment/82248699
has text: @ThuYeinTun your solution `sys.stdout.flush()` didn't work however you are correct with your explanation. Curses creates an object and write to it, when it exist it destroys that object leaving no record of the writing: so the question now is how to force out the buffer
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47644727

http://stackoverflow.com/q/47661395
type: Question
tagged with: numpy
has title: Adding string values from previous row to next row in Pandas
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82282119
score: 0
accepted answer: http://stackoverflow.com/a/47662002
tagged with: pandas
has answer: http://stackoverflow.com/a/47662002
has comment: http://stackoverflow.com/comment/82281934
answer count: 1
has body: I have a dataframe that every once in a while separates the text from the first cell in a row into two rows and fills the column values as None and NaN in the first row and then fills the actual column values into the second row. Here is an example: df House_Type Area Shape Blue House 3456 circle Red house 2345 square Small Green NaN None House 987 square On these occasions I want to add the string from the first cell in house type of the split row (Small Green) to the the first cell of house type in the second part of the split row (House). Example below for reference. The end result looking something like this: df House_Type Area Shape Blue House 3456 circle Red house 2345 square Small Green NaN None Small Green House 987 square I wrote a function to do this but it just comes back looking like the original dataframe. I'm not sure what I'm missing here. Code: def row_clean(df): for i in range(0, len(df)): if df.Shape.values[i] == None: df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1] return df

http://stackoverflow.com/a/47696339
downvote count: 1
answers question: http://stackoverflow.com/q/47696010
type: Answer
has body: use _Thread_stop(): MyPinger._Thread__stop()
upvote count: 2
score: 1

http://stackoverflow.com/q/47596338
favorite count: 0
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/47596361
tagged with: django
tagged with: python
score: -1
type: AnsweredQuestion
has title: Django Invalid Syntax error def index(request)
has comment: http://stackoverflow.com/comment/82150436
has answer: http://stackoverflow.com/a/47596361
answer count: 1
has body: File "/home/david/Django-Development/csruipa/ruth/urls.py", line 3, in &lt;module&gt; from ruth import views File "/home/david/Django-Development/csruipa/ruth/views.py", line 4 def index(request) ^ SyntaxError: invalid syntax enter code here this is my urls.py from django.conf.urls import url from ruth import views urlpatterns = [ url(r'^$', views.index, name="index"), ] and this is the view.py from django.shortcuts import render from django.http import HttpResponse def index(request) return HttpResponse("Hello World") this is the main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^ruth/', include('ruth.urls')), url(r'^admin/', admin.site.urls), ] I'm following django tutorial here https://docs.djangoproject.com/en/1.11/intro/tutorial01/ my error said it's on line 4 this line def index(request) and on urls.py on line 3 which is this from ruth import views on the main urls.py line 6 was the error which is this url(r'^ruth/', include('ruth.urls')), line I'm new to python, I need some help thanks.
downvote count: 1

http://stackoverflow.com/comment/82255989
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47648632
has text: yeah so thats working, you were not passing more than 50 characters thus no error was raised

http://stackoverflow.com/comment/82045864
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47544476
has text: You're `return`ing inside the loop. A function *stops* when it `return`s.
score: 2

http://stackoverflow.com/comment/107283831
comment on: http://stackoverflow.com/a/49525132
score: 0
type: Comment
type: AnswerComment
has text: This worked for me!. run 'DELETE FROM alembic_version' on the db terminal on your local or on the server. Thanks.

http://stackoverflow.com/a/47640038
has comment: http://stackoverflow.com/comment/82253243
type: Answer
has comment: http://stackoverflow.com/comment/82264858
has body: For merging across multiple dfs, consider the chain merge with reduce. Alternatively, if using one column, run horizontal merge with pd.concat() setting axis=1 but prior to that set the index of each dataframe to the join column. Afterwards, you can then sort on your final dataframe only once. Do note: unlike other data analytics tools, in pandas you do not need to sort pior to merging. Merge with reduce (only matched idcodes across all dfs will be kept, otherwise use a left join) from functools import reduce ... dfList = [wave68, wave69, wave70, wave71] finaldf = reduce(lambda left, right: pd.merge(left, right, on=['idcode']), dfList).sort_values(['idcode']) Merge with pd.concat (any unmatched idcodes will retain NaNs) dfList = [wave68, wave69, wave70, wave71] finaldf = pd.concat([df.set_index('idcode') for df in dfList], axis=1).sort_index()
score: 0
answers question: http://stackoverflow.com/q/47638340
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47638340

http://stackoverflow.com/a/47576120
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47563074
score: 4
has body: Code See regex in use here ((?&lt;= )[\w.]+$)(?=[\s\S]*(?&lt;= )(\1)$) With the s modifier on (single line) as seen in the regex demo here ((?&lt;= )[\w.]+$)(?=.*(?&lt;= )(\1)$) Note: For some reason the pattern above (with single line mode enabled) results in a timeout on regex101. I've tested the code under Code Generator and it works just fine (doesn't timeout when used in code). Explanation ((?&lt;= )[\w.]+$) Capture the following into capture group 1 (?&lt;= ) Positive lookbehind ensuring what precedes is a space [\w.]+ Match any word character or the dot character one or more times $ Assert position at the end of the line (?=[\s\S]*(?&lt;= )(\1)$) Positive lookahead ensuring what follows matches [\s\S]* Any character any number of times. (We don't use the dot here because it won't match newline characters. You can actually replace [\s\S] with . if you turn on the single line flag, which forces . to also match newlines) (?&lt;= ) Positive lookbehind ensuring what precedes is a space (\1) Capture the following into capture group 2 \1 Matches the same text as most recently matched by capture group 1 $ Assert position at the end of the line In layman's terms, it's matching the entire file name if it's after a space and before the end of the line. Then it's looking ahead to find a duplicate with the same rules (space before, end of line after).
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47563074
downvote count: 0

http://stackoverflow.com/comment/82127407
comment on: http://stackoverflow.com/a/47584330
type: Comment
has text: Great! That indeed did do the trick. Thanks so much for your help!
score: 0
type: AnswerComment

http://stackoverflow.com/q/47580887
has answer: http://stackoverflow.com/a/73429654
answer count: 3
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82151487
tagged with: image-processing
has answer: http://stackoverflow.com/a/47597086
tagged with: image
favorite count: 0
type: Question
has title: Adjust size and position of bounding boxes while keeping it somewhat centered
downvote count: 2
has answer: http://stackoverflow.com/a/74353588
has comment: http://stackoverflow.com/comment/82130308
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82151926
has body: I have a bunch of images with respective bounding box co-ordinates (x,y,w,h). Some of the bounding boxes are rectangular, so firstly I want to make them square while still centered on the region of interest. Using the following example of an apple, with a bounding box on the stalk, I'd want to expand the box to a square while still keeping it centered on the stalk. Secondly, after I've extracted out the contents of the bounding box, I want to capture contextual information by increasing the bounding box size by n pixels and extracting and then repeat. After that, I want to shift the geometric center of the region of interest just by a few pixels and repeat the multiple bounding box extraction. Like the below image, where the differently colored boxes represent the different boxes I want to extract. The right image shows the small shift in center that I want to achieve. I have an idea on how to do this in numpy, but are there any higher-level functions/libraries that would help me with defining the bounding box and manipulating it as such?
tagged with: opencv
upvote count: 3

http://stackoverflow.com/comment/82474849
score: 0
has text: @AlexanderReynolds that would be awesome. I will start working on it. I will take a little more time for me as i am new to python. Thanks for all the suggestions.
type: Comment
comment on: http://stackoverflow.com/q/47660439
type: QuestionComment

http://stackoverflow.com/comment/82321880
type: AnswerComment
has text: Of course i can do that :), it was my fault for assuming others would know im expecting default selection behaviors to be applied.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47681015

http://stackoverflow.com/comment/82347109
has text: another example is when I enter 2 and random_number = 43 but it'll print out "lower"
comment on: http://stackoverflow.com/a/47693490
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82101153
score: 0
comment on: http://stackoverflow.com/q/47571727
type: QuestionComment
has text: but the point is that using this code the last number would be summation not the first.
type: Comment

http://stackoverflow.com/a/73004286
type: Answer
answers question: http://stackoverflow.com/q/47619691
has body: Well I have one better with Speech Recognition you can use it without speech recognition just scroll down import random from numpy import true_divide import pyttsx3 import speech_recognition as sr engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voices', voices[0].id) def speak(audio): print(f"Computer: {audio}\n") engine.say(audio) engine.runAndWait() def takeCommand(): r = sr.Recognizer() def SpeakText(command): engine = pyttsx3.init() engine.say(command) engine.runAndWait() try: with sr.Microphone() as source2: print("Computer: Listening...") r.adjust_for_ambient_noise(source2, duration=0.2) audio2 = r.listen(source2) MyText = r.recognize_google(audio2, language="en") MyText = MyText.lower() print("You:"+MyText) except Exception as e: speak("Sir, Please Pardon") return None return MyText if __name__ == "__main__": while True: query = takeCommand() if "toss a coin" in query: speak("sir, what times should the coin be flipped") toss=int(takeCommand()) tail=0 head=0 for i in range(toss): val=random.randint(0,1) if(val==0): print("Tails") tail=tail+1 else: print("Heads") head=head+1 speak("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss)) Code without speech recognition toss=int(input("enter number of times you want to flip the coin") tail=0 head=0 for i in range(toss): val=random.randint(0,1) if(val==0): print("Tails") tail=tail+1 else: print("Heads") head=head+1 print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
score: 0

http://stackoverflow.com/comment/82251755
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47611352
has text: Yes you are right, really helped...thank you :)

pyside2
tags question: http://stackoverflow.com/q/47575981
tags question: http://stackoverflow.com/q/47584343
type: Tag
tag name: pyside2

http://stackoverflow.com/q/47585653
type: Question
has answer: http://stackoverflow.com/a/47585701
type: UnansweredQuestion
tagged with: python
has title: returning rows within range in pandas MultiIndex
score: 0
has body: I have a dataframe that looks like: count year person a.smith 1 2008 b.johns 2 c.gilles 3 a.smith 4 2009 b.johns 3 c.gilles 2 in which both year and person are part of the index. I'd like to return all rows with a.smith for all years. I can locate a count for a specific year with df.loc[(2008, 'a.smith)], which outputs 1. But if I try df.loc[(:,'a.smith)], I get SyntaxError: invalid syntax. How do I use df.loc for a range of index values in a MultiIndex?
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/82188411
has text: I think you have used the wrong version of python on server (probably 2.x). You'd better confirm the version number of server's python.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47614844

http://stackoverflow.com/comment/82239977
has text: Ignacio has the right answer, but you will also never get to the right answer section because it is in the while loop, which tests for equality already. If they are equal, it will go past the while loop and end.
score: 0
comment on: http://stackoverflow.com/q/47640771
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82343564
comment on: http://stackoverflow.com/q/47692094
type: Comment
type: QuestionComment
score: 0
has text: @strippenzieher: ooops, implicit return, right. Embarrassing, but I'll accept an answer.

http://stackoverflow.com/comment/82140835
type: AnswerComment
type: Comment
has text: guess I'm learning more pandas like this than all the time I spent looking at the docs, thank you
score: 0
comment on: http://stackoverflow.com/a/47591622

http://stackoverflow.com/comment/82325339
comment on: http://stackoverflow.com/a/47682925
has text: `operator.pow` is a better match for Python's `**` operator than `math.pow`. (It produces integer outputs from integer inputs, for one thing.)
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47689316
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82338467
score: 0
answer count: 0
has body: I'm trying to figure out what happens when files of varying sizes are uploaded to the server at the same time and their collective size exceeds that of the memory. More specifically, what does Django do then? Does virtual memory come into play or are the files moved to disk? According to Django documentation, you can specify the FILE_UPLOAD_MAX_MEMORY_SIZE value which decides whether the temp file remains in memory or goes to disk. If I set this value to, say, 50 GB, and I send one or more files at the same time to the server, AND my RAM is only 16 GB, what happens then? I'm asking this question because I need to encrypt the files I receive at the server without saving them flat anywhere in the disk, even as a temporary file, due to sensitivity of the data. I want to make sure that under no circumstance the file(s) will be moved from the (volatile) memory to (secondary) disk storage in its original form.
tagged with: file
has comment: http://stackoverflow.com/comment/82337815
tagged with: memory
type: Question
has comment: http://stackoverflow.com/comment/82337844
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82338041
has title: What happens when server request files exceed memory size?

http://stackoverflow.com/comment/82066084
comment on: http://stackoverflow.com/a/47554467
type: AnswerComment
score: 0
has text: didn't dv but looking at the testwebsite there is an image ` ` that doesn't seem to have any image format
type: Comment

rss
type: Tag
tags question: http://stackoverflow.com/q/47607330
tag name: rss
tags question: http://stackoverflow.com/q/47625950

http://stackoverflow.com/q/47608132
has title: Momentum and Angular momentum with sympy
score: 0
tagged with: sympy
answer count: 1
type: Question
has body: How do I calculate the momentum and angular momentum a force causes on an object (in a vacuum) using python/sympy I'm looking for a library to do this, I'm not stuck to sympy, but an answer with sympy will be fine (To not make the question too broad). What have I tried? Well, I tried reading the documentation for sympy and realized it is not directed at programmers, but physics students.
has answer: http://stackoverflow.com/a/47624351
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47682842
score: 0
type: UnansweredQuestion
has title: Can I save the keyboard input in a list?
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82325070
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47683885
tagged with: python-3.x
tagged with: python
tagged with: pygame
has body: I have a code, where pressing a key reproduces a sound generated by the computer, my concern is, how can I store the keys in the order they were pressed in a list and print it? Here is the code: from array import array import pygame from pygame.mixer import Sound, get_init, pre_init class Note(pygame.mixer.Sound): def __init__(self, frequency, volume=.1): self.frequency = frequency Sound.__init__(self, self.build_samples()) self.set_volume(volume) def build_samples(self): period = int(round(get_init()[0] / self.frequency)) samples = array("h", [0] * period) amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 for time in range(period): if time &lt; period / 2: samples[time] = amplitude else: samples[time] = -amplitude return samples pre_init(44100, -16, 1, 1024) pygame.init() screen = pygame.display.set_mode([640, 480], 0) sounds = {} keymap = {pygame.K_p: 880, pygame.K_r: 440} while True: key_pressed=[] evt = pygame.event.wait() if evt.type == pygame.QUIT: break elif evt.type == pygame.KEYDOWN: if evt.key in keymap: note = Note(keymap[evt.key]) note.play(-1) sounds[evt.key] = note key_pressed.append(note) elif evt.type == pygame.KEYUP: if evt.key in sounds: sounds.pop(evt.key).stop()

http://stackoverflow.com/q/47598760
has title: How to get specific terms from a python loop
has comment: http://stackoverflow.com/comment/82155800
has answer: http://stackoverflow.com/a/47598793
tagged with: python
has answer: http://stackoverflow.com/a/47598957
has body: I have a list A. A = ['1','2','3','4','5','6','7','8','9','10','11','12'] I want to search the character 7 and if found,i would like the character before and after it get back as result. desired result = ['6','7','8'] The numbers i have got from a loop.I am a newbie to Python.
tagged with: python-3.x
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/47598903
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47598808
downvote count: 0
has comment: http://stackoverflow.com/comment/82155653
tagged with: loops
has answer: http://stackoverflow.com/a/47598945
has comment: http://stackoverflow.com/comment/82155664
favorite count: 0
type: Question
answer count: 5

http://stackoverflow.com/comment/82242451
type: QuestionComment
comment on: http://stackoverflow.com/q/47641058
score: 0
type: Comment
has text: "Does the dimension of calling the function change from call to call?" No, because it is a mathematical function. "Or should your implementation just be able to handle all kind of a-priori known dimensions?" Yes

http://stackoverflow.com/q/47602121
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47602140
type: Question
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9542738
has body: I need some help with searching a single list for two different pieces of data, how could this be done so that if this if both pieces of data it will output the values are found.
tagged with: list
has answer: http://stackoverflow.com/a/47641099
upvote count: 3
has answer: http://stackoverflow.com/a/47602153
downvote count: 2
has title: How to search a list for two items in Python3
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/82163065

http://stackoverflow.com/comment/82357905
score: 0
type: QuestionComment
has text: No, I don't need `df**2`, it was just the simplest example I've found. Let say, for instance, that for each df on a list, I want to create `df_foo = pd.read_csv(name(df)+"_foo.csv")`, then process it and merge by `df = merge(df,df_foo,on='some_field')`. How do you do that?
type: Comment
comment on: http://stackoverflow.com/q/47675185

http://stackoverflow.com/comment/82325885
has text: https://stackoverflow.com/questions/34458251/plot-over-an-image-background-in-python/34459284#34459284
score: 1
comment on: http://stackoverflow.com/q/47680573
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82100636
type: AnswerComment
has text: Actually, specifying `model_instance.price = str(new_price)` did the trick, weird though as it was already a string! Thanks!
score: 0
comment on: http://stackoverflow.com/a/47571773
type: Comment

http://stackoverflow.com/comment/82163315
score: 2
comment on: http://stackoverflow.com/q/47581326
type: Comment
type: QuestionComment
has text: Obligatory honest description of a [Job Interview](https://www.youtube.com/watch?v=YHy06FMsezI).

http://stackoverflow.com/q/47642424
tagged with: django
has comment: http://stackoverflow.com/comment/82246529
tagged with: python
has comment: http://stackoverflow.com/comment/82246420
score: 0
linked to: http://stackoverflow.com/q/7101703
has comment: http://stackoverflow.com/comment/82246235
has comment: http://stackoverflow.com/comment/82246053
linked to: http://stackoverflow.com/q/9629661
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/82246582
type: Question
has comment: http://stackoverflow.com/comment/82246002
has comment: http://stackoverflow.com/comment/82243854
has answer: http://stackoverflow.com/a/47644116
has body: Given the following model: class Team(models.Model): name = models.CharField(max_length=50) others = DictField() And the following code: bahia = Team() bahia.name = "E.C. Bahia" bahia.others = {"title": "Ninguém nos Vence em Vibração!!!"} bahia.save() vicetoria = Team() vicetoria.name = "E.C. Vicetoria" vicetoria.others = {"title": "Vice de tudo!"} vicetoria.save() I want to find the object that have the word vence, (case insensitive) contained in title value of the field others. I tried something like: teams = Team.objects.filter(others__title__icontains="vence") that gives me the following error: FieldError: Join on field 'others' not permitted. Did you misspell 'title' for the lookup type? I also already tried: teams = Team.objects.filter(others__icontains={"title":"vence"}) that returns None and I know there is at least one collection as result. SOLUTION: teams = Team.objects.raw_query({"others.title": {"$regex" : "vence", "$options": "i"}}) The i option makes the search insensitive.
has title: How to use icontains in a key value of a DictField in Django queryset?
has comment: http://stackoverflow.com/comment/82246502
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/47563065
type: Question
answer count: 2
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47563130
possible better answer: http://stackoverflow.com/a/47563144
downvote count: 1
has comment: http://stackoverflow.com/comment/82084064
has answer: http://stackoverflow.com/a/47563144
tagged with: object
type: AnsweredQuestion
has body: I am new in python and I have one problem :/ In the function get longest name I want to return the name of the person but instead of it I am keeping returning just link? of this person. Could you help me and say where it is a problem? Thank you :) class Person: def __init__(self, name, year_of_birth, degree): self.name = name self.year_of_birth = year_of_birth self.degree = degree self.mentor = None self.mentees = [] def create_mentorship(mentor, mentee): mentee.mentor = mentor mentor.mentees.append(mentee) def get_longest_name(people): return (max(people, key=lambda word: (len(word), word))) people = {} people['martin'] = Person('Martin', 1991, 'phd') people['peter'] = Person('Peter', 1995, 'bc') get_longest_name(people) I am getting.... -> 'martin' I should get.... -> 'Martin'
score: 1
has title: Linking to the object
accepted answer: http://stackoverflow.com/a/47563130
has comment: http://stackoverflow.com/comment/82084065
favorite count: 0

http://stackoverflow.com/a/47658485
has comment: http://stackoverflow.com/comment/82293931
has body: this should work as long as you have a json file available at: &lt;SCRIPT_PATH&gt;/test_param_jsons/MyClass_params.json Also, in order to avoid KeyError you'll need to ensure that your input json file contains key: value, test_class_name : test_name import json, os from builtins import * class MyClass: def get_test_params (self, test_class_name = None, test_name = None): with open(os.path.join(os.path.dirname(__file__),"test_param_jsons\\params.json"), 'r') as test_data: test_json = json.load (test_data) try: return test_json[test_class_name][test_name] except KeyError as e: print ('KeyError: {}'.format (e)) def mymain(self, test_name): ''' mymain is defined to accomodate your requirement to use __class__ as a parameter ''' test_params = self.get_test_params (self.__class__.__name__, test_name = test_name) return test_params if __name__ == '__main__': test_name = 'sth' myclass = MyClass () result = myclass.mymain (test_name) print (result)
has comment: http://stackoverflow.com/comment/82354135
type: Answer
has comment: http://stackoverflow.com/comment/82317232
answers question: http://stackoverflow.com/q/47657424
score: 0
has comment: http://stackoverflow.com/comment/82305707

http://stackoverflow.com/comment/82267086
type: QuestionComment
comment on: http://stackoverflow.com/q/47653833
has text: In Python 3, you can see the actual Arabic letters if you print the encoded string: print("كتب رامى ناجى")
score: 0
type: Comment

http://stackoverflow.com/comment/82077407
type: AnswerComment
has text: Very infrequently, if ever. As I said before, I could include a variable at the top of the class that maps between methods and tags. However this is more difficult to maintain, and gets especially messy if I am inheriting from ExampleClass and have additional tags in the child class.
comment on: http://stackoverflow.com/a/47559529
type: Comment
score: 0

http://stackoverflow.com/comment/82187080
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47614010
has text: I ran a few tests. Nothing wrong with your code here. Paste a snapshot of your "text" maybe? What is the index where it is actually present?
type: Comment

http://stackoverflow.com/q/47624437
has body: My requirement is to add the digits in an integer received as an input from the user. The integer is first converted to String and then the string is converted to list. After converting the string to list, I am iterating through each element in the list and performing a sum to display the final result. I have seen some simple programs in the internet which uses 'map' and 'sum' command to get the final result. I wanted to use a list to iterate the elements. Can someone please help me find out the mistake in the program? number=int(input("Enter the number:")) total=0 mystr=str(number) mylist=list(mystr) print mylist for element in mylist: total=total+element print total I am observing the below mentioned error, RESTART: C:\SKANAKAV\at&amp;t\Python\Aricent_Python\python_scripts\Find the Sum of Digits in a Number\test_map.py Enter the number:234 ['2', '3', '4'] Traceback (most recent call last): File "C:\SKANAKAV\at&amp;t\Python\Aricent_Python\python_scripts\Find the Sum of Digits in a Number\test_map.py", line 16, in &lt;module&gt; total=total+element TypeError: unsupported operand type(s) for +: 'int' and 'str'
has answer: http://stackoverflow.com/a/47624504
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47624461
tagged with: python
score: -1
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/82217729
type: UnansweredQuestion
has title: Observing TypeError: Not sure how to fix this error

http://stackoverflow.com/comment/82142089
has text: @PhillipD I have posted my code.
comment on: http://stackoverflow.com/q/47592399
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82321171
type: Comment
has text: I don't think you need to sort the list here
type: AnswerComment
comment on: http://stackoverflow.com/a/47680242
score: 0

http://stackoverflow.com/a/47563408
type: Answer
has body: You can get about a factor of two speed improvement over [df.loc[df['days_diff'].isnull()... here by using pd.Series.fillna, optionally with the argument 'inplace=True' to replicate the behavior of df.loc. date = pd.Timestamp('20160101') df = pd.date_range('20160301', '20160831', freq='7D').to_series().reset_index() df[0] = [pd.Timedelta('nat')]*25+[pd.Timedelta(days=99), pd.Timedelta(days=45)] df.columns = ['outofservicedatetime', 'days_diff'] df Out[258]: outofservicedatetime days_diff 0 2016-03-01 NaT 1 2016-03-08 NaT 2 2016-03-15 NaT 3 2016-03-22 NaT 4 2016-03-29 NaT 5 2016-04-05 NaT 6 2016-04-12 NaT 7 2016-04-19 NaT 8 2016-04-26 NaT 9 2016-05-03 NaT 10 2016-05-10 NaT 11 2016-05-17 NaT 12 2016-05-24 NaT 13 2016-05-31 NaT 14 2016-06-07 NaT 15 2016-06-14 NaT 16 2016-06-21 NaT 17 2016-06-28 NaT 18 2016-07-05 NaT 19 2016-07-12 NaT 20 2016-07-19 NaT 21 2016-07-26 NaT 22 2016-08-02 NaT 23 2016-08-09 NaT 24 2016-08-16 NaT 25 2016-08-23 99 days 26 2016-08-30 45 days %timeit df['days_diff'].fillna(df['outofservicedatetime']-date) 1.29 ms ± 41.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) df['days_diff'].fillna(df['outofservicedatetime']-date) Out[260]: 0 60 days 1 67 days 2 74 days 3 81 days 4 88 days 5 95 days 6 102 days 7 109 days 8 116 days 9 123 days 10 130 days 11 137 days 12 144 days 13 151 days 14 158 days 15 165 days 16 172 days 17 179 days 18 186 days 19 193 days 20 200 days 21 207 days 22 214 days 23 221 days 24 228 days 25 99 days 26 45 days Name: days_diff, dtype: timedelta64[ns] %timeit df.loc[df['days_diff'].isnull(), 'days_diff'] = df['outofservicedatetime'] - date 2.46 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
score: 0
answers question: http://stackoverflow.com/q/47550705

http://stackoverflow.com/a/47669177
has body: Here is a solution that works on arbitrary depth list-of-list-of-list...s. It uses itertools.count, list comprehension and recursion. import random import itertools def create(minchld = 2, mxchld = 4, p0 = 0.5, mxdpth = 4): return [0 if mxdpth==0 or random.random() &lt; p0 else create(minchld, mxchld, p0, mxdpth-1) for i in range(random.randint(minchld, mxchld))] def fill(zeros): odd = itertools.count(start=1, step=2) def replace(zeros): return [next(odd) if i==0 else replace(i) for i in zeros] return replace(zeros) zeros = create() print(zeros) print(fill(zeros)) Sample runs: # [[0, 0, [0, 0, 0]], 0, [0, 0, [[0, 0, [0, 0]], [[0, 0, 0], 0, 0], 0, 0], 0], 0] # [[1, 3, [5, 7, 9]], 11, [13, 15, [[17, 19, [21, 23]], [[25, 27, 29], 31, 33], 35, 37], 39], 41] # [0, [0, [0, [0, 0]]]] # [1, [3, [5, [7, 9]]]] # [[[0, [0, [0, 0]], [[0, 0, 0, 0], 0], [[0, 0], 0]], 0, 0, [[[0, 0, 0], [0, 0, 0, 0], [0, 0, 0], [0, 0, 0]], 0, 0]], 0] # [[[1, [3, [5, 7]], [[9, 11, 13, 15], 17], [[19, 21], 23]], 25, 27, [[[29, 31, 33], [35, 37, 39, 41], [43, 45, 47], [49, 51, 53]], 55, 57]], 59]
answers question: http://stackoverflow.com/q/47667719
score: 0
type: Answer

http://stackoverflow.com/comment/82313276
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47677101
has text: what error you got?
score: 0

http://stackoverflow.com/comment/82224177
comment on: http://stackoverflow.com/q/47632723
score: 0
type: QuestionComment
has text: @jezrael Wait nevermind, no issue. I think Excel seems a bit more reliable. Also is it normal to be able to read from an excel file/csv while its open. I feel like that will cause corruption issues, or at least with csv it does. Excel seems to work more consistently or is that just me.
type: Comment

python-keyring
type: Tag
tag name: python-keyring
tags question: http://stackoverflow.com/q/47600448

http://stackoverflow.com/a/47638999
answers question: http://stackoverflow.com/q/47638896
has body: It is not recommended to do it they way you used dict via a string but you could: posts.append(dict(eval(newDictionaryItem))) Better would be to just use a normal dict assignment: newDictionaryItem = {'author': {'nickname': userName}, 'body': userMessage} posts.append(newDictionaryItem)
score: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82236534
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82236497
accepted answer of: http://stackoverflow.com/q/47638896

http://stackoverflow.com/comment/82191570
type: Comment
comment on: http://stackoverflow.com/q/47616680
score: 1
type: QuestionComment
has text: you think you don't need to run migrations on public server?

http://stackoverflow.com/a/47618025
answers question: http://stackoverflow.com/q/47616764
has comment: http://stackoverflow.com/comment/82205304
has comment: http://stackoverflow.com/comment/82210461
has comment: http://stackoverflow.com/comment/82204917
has comment: http://stackoverflow.com/comment/82211289
has comment: http://stackoverflow.com/comment/82209442
type: Answer
has comment: http://stackoverflow.com/comment/82194932
has comment: http://stackoverflow.com/comment/82211410
score: 0
accepted answer of: http://stackoverflow.com/q/47616764
has body: In example 1. You are iterating over a string. In example 2, you are iterating over a list. Try this example which may demonstrate the issue: import random lines = ['--profile-directory=Person 1', '--profile-directory=Person 2', '--profile-directory=Person 3', '--profile-directory=Person 4', '--profile-directory=Person 5'] # This returns a string. myline = random.choice(lines) # iterate over a string (x = string char). for x in (myline): print(x) # iterate over a tuple (x = tuple item). for x in (myline,): print(x) The above uses a string and a tuple though the tuple is similar to the list used in example 2 with using [] which encloses foo[random_index] to become the list [foo[random_index]]. Edit: As per request from comment, a possible solution as I do not have the environment for actual testing. import random from selenium import webdriver with open('C:\\Users\\Hoxton\\Pictures\\1\\ad.txt') as r: lines = r.readlines() myline = random.choice(lines).strip() # Add string to a list. if type(myline) is str: myline = [myline] # Display myline print(repr(myline)) Profiles = [] # obsolete? dataDir = "--user-data-dir=C:\\Users\\Hoxton\\AppData\\Local\Google\\Chrome\\User Data" for x in myline: indexes = [index for index in range(len(myline))] random.shuffle(indexes) chrome_options1 = webdriver.ChromeOptions() chrome_options1.add_argument(dataDir) chrome_options1.add_argument(x) driver = webdriver.Chrome(chrome_options=chrome_options1) driver.get('https://www.google.com') Edit: Added type str check for myline in case you change from a random string to a sequence sequence type for some reason.
type: AcceptedAnswer

http://stackoverflow.com/a/54897630
upvote count: 2
has comment: http://stackoverflow.com/comment/96628910
score: 1
has comment: http://stackoverflow.com/comment/96624176
downvote count: 1
has body: Here's how: from sklearn.metrics import r2_score class MetricsCallback(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): if epoch: print(self.validation_data[0]) x_test = self.validation_data[0] y_test = self.validation_data[1] predictions = self.model.predict(x_test) print('r2:', r2_score(prediction, y_test).round(2)) model.fit( ..., callbacks=[MetricsCallback()]) Reference Keras 2.2.4
answers question: http://stackoverflow.com/q/47676248
type: Answer

http://stackoverflow.com/comment/82088917
has text: yes by packet I mean message.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47552166

steamworks-api
tag name: steamworks-api
type: Tag
tags question: http://stackoverflow.com/q/47643901

http://stackoverflow.com/a/47695252
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47690873
downvote count: 0
has comment: http://stackoverflow.com/comment/82352050
has body: Ok, so for what you want to achieve, you need to change the approach completely and use asyncio equivalents of socket methods as well as replacement for bare standard input handling. The following code works on Python >= 3.5 and requires aioconsole Python package which can be installed with pip install aioconsole. server.py import asyncio import aioconsole class StreamWrapper(object): """This class is used to make socket stream created by server available for send_messgaes() function""" def __init__(self): self.reader = None self.writer = None async def send_messages(stream_wrapper, stdin): # Wait asynchronously until server part initializes socket stream while stream_wrapper.writer is None: await asyncio.sleep(0.1) writer = stream_wrapper.writer # Asynchronusly read from standard input async for message in stdin: if message.decode().strip() == "q": writer.close() exit() else: # Send message through the socket writer.write(message) def receive_messages_wrapper(stream_wrapper, stdout): """Wrapper function which adds stream_wrapper and stdout to the scope of receive_messages()""" async def receive_messages(reader, writer): # Copy socket stream reference to stream wrapper stream_wrapper.reader = reader stream_wrapper.writer = writer # Asynchronusly read messages from the socket async for message in reader: stdout.write('\nClient: {}'.format(message.decode())) stdout.write("Server: ") # Wrapper returns receive_messages function with enhanced scope - receive_messages() can "see" stream_wrapper and stdout return receive_messages async def run_server(loop): """Initialize stdin and stdout asynchronous streams and start the server""" stdin, stdout = await aioconsole.get_standard_streams() stream_wrapper = StreamWrapper() # Asynchronously execute send_messages and start_server() await asyncio.gather( send_messages(stream_wrapper, stdin), asyncio.start_server(receive_messages_wrapper(stream_wrapper, stdout), '127.0.0.1', 8888, loop=loop) ) # Run the server on the event loop lo…
has comment: http://stackoverflow.com/comment/107444683
type: Answer
answers question: http://stackoverflow.com/q/47690873
score: 2

http://stackoverflow.com/q/47621419
type: UnansweredQuestion
tagged with: python
has title: Tensorflow: InvalidArgumentError when feeding numpy ndarray to placeholder
score: 0
tagged with: placeholder
tagged with: types
answer count: 1
tagged with: feed
has answer: http://stackoverflow.com/a/47621950
has body: I want to run a simple neural network of 3 input "neurons" (with three features: height, weight, body fat) and 2 output "neurons" to classify new data, via softmax logistic regression, into either male or female). I made up this data just to practice data input to the model. Just like in the MNIST tutorial on the tensorflow website, but much simpler and tangible (instead of 784 input features -all the pixels of a given MNIST image- I only have 3, and instead of several batches to train our model I just want to train it several times in the same data). I am aware this could be done via simpler algorithms, like k-means clustering. But I just want to learn how to input data when it is small. I get this: InvalidArgumentError: You must feed a value lue for placeholder tensor 'Placeholder' with dtype float I don't know why... because I have converted the list values into np.float32 (which is the same as tf.float32) and I check it right before defining the function. Yet, I still get this annoying error. No matter what I change, I always get this error when loading into the first palceholder: X. This is my code: #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import tensorflow as tf import time #TRAINING DATA #3 VIs en columna #est, pes, %gb_fat persones = np.asarray([[175,70,2], #H [155,45,15], #F [190,85,8], #H [185,90,7], #H [169,60,3], #H [150,40,13], #F [173,69,12]], dtype = np.float32) #H # H , D --&gt; one-hot!! etiquetes = np.asarray([[1,0], [0,1], [1,0], [1,0], [1,0], [0,1], [1,0]], dtype = np.float32) #TESTING DATA persones_evaluacio = np.asarray([[190,89,4], #H [155,52,16], #D [171,55,18]], dtype = np.float32) #D etiquetes_evaluacio = np.asarray([[1,0], [0,1], [0,1]], dtype = np.float32) #WE TEST THE DATATYPES print("dades dels nombres: ",type(persones[0][0])) print("tipus estructura de dades de la matriu: ", type(persones)) time.sleep(3) print("files de la matriu:") time.sleep(0.5) for i in range(len(persones)): print(persones[i]) time.sleep(0.5…
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/82352658
has text: Show your main project urls.py.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47696515

http://stackoverflow.com/q/47625659
accepted answer: http://stackoverflow.com/a/47626482
has comment: http://stackoverflow.com/comment/82210431
has body: I am using django-mptt for category model. I want to show a list of categories and sub-categories as in the screenshot. The way I could show is all the list without any structure like below BEDROOM ITEMS ALMIRAH 2 PIECE ALMIRAH 3 PIECE ALMIRAH BED DOUBLE SIZE LOW BED QUEEN SIZE LOW BED This way its hard to know which one is parent category and which one is child category and grand-child category etc. I could either show the above way or show only the parent category using Category.objects.root_nodes() here is my model, views and template class Category(MPTTModel): name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(null=True, blank=True, upload_to=upload_furniture_image_path) slug = models.SlugField(max_length=200, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) def furniture(request, slug): instance = get_object_or_404(Furniture, slug = slug) cart_obj, new_obj = Cart.objects.new_or_get(request) categories = Category.objects.all() context = { 'furniture': instance, 'cart': cart_obj, 'categories': categories } return render(request, 'furnitures/furniture.html', context) &lt;div class="panel-body"&gt; &lt;ul class="nav nav-pills nav-stacked category-menu"&gt; {% for category in categories %} &lt;li&gt;{{category.name}}&lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; So my question is how could I separate Parent Category and child category so I can show as in screenshot? Here is the parent category with its children and grand children
tagged with: django
tagged with: django-models
tagged with: python
tagged with: django-mptt
has title: show category and sub-categories in hierarchy
type: AnsweredQuestion
tagged with: django-views
score: 1
has answer: http://stackoverflow.com/a/47626482
has comment: http://stackoverflow.com/comment/82209248
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82210403
favorite count: 0
type: Question

http://stackoverflow.com/comment/82184017
comment on: http://stackoverflow.com/a/47612435
has text: Now I get the error though that AverageSims does not exist.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47686227
tagged with: python
score: 22
upvote count: 22
has answer: http://stackoverflow.com/a/69609606
tagged with: plot
has comment: http://stackoverflow.com/comment/83280617
tagged with: statsmodels
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48068113
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82334236
type: UnansweredQuestion
has body: Given the some randomly generated data with 2 columns, 50 rows and integer range between 0-100 With R, the poisson glm and diagnostics plot can be achieved as such: &gt; col=2 &gt; row=50 &gt; range=0:100 &gt; df &lt;- data.frame(replicate(col,sample(range,row,rep=TRUE))) &gt; model &lt;- glm(X2 ~ X1, data = df, family = poisson) &gt; glm.diag.plots(model) In Python, this would give me the line predictor vs residual plot: import numpy as np import pandas as pd import statsmodels.formula.api from statsmodels.genmod.families import Poisson import seaborn as sns import matplotlib.pyplot as plt df = pd.DataFrame(np.random.randint(100, size=(50,2))) df.rename(columns={0:'X1', 1:'X2'}, inplace=True) glm = statsmodels.formula.api.gee model = glm("X2 ~ X1", groups=None, data=df, family=Poisson()) results = model.fit() And to plot the diagnostics in Python: model_fitted_y = results.fittedvalues # fitted values (need a constant term for intercept) model_residuals = results.resid # model residuals model_abs_resid = np.abs(model_residuals) # absolute residuals plot_lm_1 = plt.figure(1) plot_lm_1.set_figheight(8) plot_lm_1.set_figwidth(12) plot_lm_1.axes[0] = sns.residplot(model_fitted_y, 'X2', data=df, lowess=True, scatter_kws={'alpha': 0.5}, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8}) plot_lm_1.axes[0].set_xlabel('Line Predictor') plot_lm_1.axes[0].set_ylabel('Residuals') plt.show() But when I try to get the cook statistics, # cook's distance, from statsmodels internals model_cooks = results.get_influence().cooks_distance[0] it threw an error saying: AttributeError Traceback (most recent call last) &lt;ipython-input-66-0f2bedfa1741&gt; in &lt;module&gt;() 4 model_residuals = results.resid 5 # normalized residuals ----&gt; 6 model_norm_residuals = results.get_influence().resid_studentized_internal 7 # absolute squared normalized residuals 8 model_norm_residuals_abs_sqrt = np.sqrt(np.abs(model_norm_residuals)) /opt/conda/lib/python3.6/site-packages/statsmodels/base/wrapper…
has title: Poisson Regression in statsmodels and R
favorite count: 0
type: Question

http://stackoverflow.com/comment/82164088
score: 0
comment on: http://stackoverflow.com/q/47602278
type: Comment
type: QuestionComment
has text: @ElisByberi it's half learning to be honest; making correct use of `__new__` we could implement the factory pattern in a different way for it looks a bit nicer..

http://stackoverflow.com/comment/82177703
type: Comment
comment on: http://stackoverflow.com/a/47609423
score: 0
type: AnswerComment
has text: What is the meaning of `e % op`?

http://stackoverflow.com/q/47644286
has body: I am trying to open graphics in a new window using the command %matplotlib qt in ipython/spyder, but it shows following error %matplotlib qt Traceback (most recent call last): File "&lt;ipython-input-1-4460ac8d7abe&gt;", line 1, in &lt;module&gt; get_ipython().magic(u'matplotlib qt') File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2160, in magic return self.run_line_magic(magic_name, magic_arg_s) File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2081, in run_line_magic result = fn(*args,**kwargs) File "&lt;decorator-gen-105&gt;", line 2, in matplotlib File "/usr/lib/python2.7/site-packages/IPython/core/magic.py", line 188, in &lt;lambda&gt; call = lambda f, *a, **k: f(*a, **k) File "/usr/lib/python2.7/site-packages/IPython/core/magics/pylab.py", line 100, in matplotlib gui, backend = self.shell.enable_matplotlib(args.gui) File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2950, in enable_matplotlib pt.activate_matplotlib(backend) File "/usr/lib/python2.7/site-packages/IPython/core/pylabtools.py", line 309, in activate_matplotlib matplotlib.pyplot.switch_backend(backend) File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 231, in switch_backend _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 60, in pylab_setup [backend_name], 0) File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in &lt;module&gt; from .backend_qt5 import ( File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 18, in &lt;module&gt; import matplotlib.backends.qt_editor.figureoptions as figureoptions File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in &lt;module&gt; import matplotlib.backends.qt_editor.formlayout as formlayout File "/usr/lib64/python2.7/site-packages/matplotlib…
tagged with: qt4
tagged with: pyqt4
answer count: 1
accepted answer: http://stackoverflow.com/a/47644894
tagged with: python
has answer: http://stackoverflow.com/a/47644894
type: AnsweredQuestion
score: 0
tagged with: matplotlib
type: Question
has title: %matplotlib qt ends in error - calls PyQt5 instead of PyQt4

django-views
tags question: http://stackoverflow.com/q/47631589
tags question: http://stackoverflow.com/q/47618289
tags question: http://stackoverflow.com/q/47561693
tags question: http://stackoverflow.com/q/47615196
tags question: http://stackoverflow.com/q/47639833
tags question: http://stackoverflow.com/q/47625659
tags question: http://stackoverflow.com/q/47557494
tags question: http://stackoverflow.com/q/47564597
tags question: http://stackoverflow.com/q/47574438
tags question: http://stackoverflow.com/q/47626696
tags question: http://stackoverflow.com/q/47627344
tags question: http://stackoverflow.com/q/47623026
tags question: http://stackoverflow.com/q/47642400
tag name: django-views
tags question: http://stackoverflow.com/q/47683278
tags question: http://stackoverflow.com/q/47578556
tags question: http://stackoverflow.com/q/47601770
tags question: http://stackoverflow.com/q/47627293
tags question: http://stackoverflow.com/q/47602225
type: Tag
tags question: http://stackoverflow.com/q/47563013
tags question: http://stackoverflow.com/q/47567666
tags question: http://stackoverflow.com/q/47680047
tags question: http://stackoverflow.com/q/47684719
tags question: http://stackoverflow.com/q/47671120
tags question: http://stackoverflow.com/q/47644824
tags question: http://stackoverflow.com/q/47609001
tags question: http://stackoverflow.com/q/47676426

http://stackoverflow.com/q/47563954
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82448865
has comment: http://stackoverflow.com/comment/82107807
has comment: http://stackoverflow.com/comment/82086003
tagged with: python
has comment: http://stackoverflow.com/comment/83125007
has body: I am reading a page containing the following: 40 I tried different ways: UrlOpen = urllib2.urlopen(url) UrlRead = UrlOpen.read() ReadSource = UrlRead.decode('utf-8') print ReadSource print UrlRead print requests.get(url).text soup = BeautifulSoup(urllib2.urlopen(url)) tags = soup.findAll("li", { "class" : "[ c-product-detail__box ] [ js-box ] "}) #for ... print tag and every time I get this: Some of the values are missing and the capital letters are lowered. Could you please help me with it?
has title: urllib2 has trouble reading values with special characters
tagged with: urllib2
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82097436
favorite count: 0

http://stackoverflow.com/comment/82260150
comment on: http://stackoverflow.com/q/47650892
has text: I am getting all ten digits on Windows too.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47666642
has comment: http://stackoverflow.com/comment/82293043
has comment: http://stackoverflow.com/comment/82292513
has title: Adding an hyperlink in MSWord by using python-docx
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/134730067
has answer: http://stackoverflow.com/a/47666747
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47666747
score: 14
upvote count: 14
answer count: 1
has body: I am trying to add an hyperlink in a MS Word document using docx module for Python. I searched everywhere (official doc, StackOverflow, Google) but found nothing. I would like to do something like: from docx import Document document = Document() p = document.add_paragraph('A plain paragraph having some ') p.add_hyperlink('Link to my site', target="http://supersitedelamortquitue.fr") Anyone got an idea on how to do that?
downvote count: 0
tagged with: python-docx

http://stackoverflow.com/q/47561768
tagged with: urwid
has comment: http://stackoverflow.com/comment/82081583
answer count: 1
has answer: http://stackoverflow.com/a/65365254
accepted answer: http://stackoverflow.com/a/65365254
favorite count: 0
type: Question
has body: I am creating a configurator that lets users choose from a set of legal values. For each legal value I create a Choice (which is essentially a MenuButton). If the user selects a Choice, then the choice changes the value to its caption. Notice that the Choice with the current value has a different attribute than the others. I'd like to loop through the choices after a pick is made and change the attributes to match the new value. I can loop through the choices by passing the legal_choices list to all the Choices (or do something more clever) but I don't know how to write code that loops through a list of widgets and changes their attributes. for vv in leg_values: choice = Choice(vv, self, item) if vv == self.get_var(item): choice = urwid.AttrMap(choice,'cur_value') legal_choices.append(choice) var_item = SubMenu(top,item,legal_choices) Does anyone know how to change attributes on a widget in urwid?
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
has title: urwid changing a display attribute
downvote count: 0

http://stackoverflow.com/comment/82196746
type: AnswerComment
has text: basicly it is the correct way , but since im dealing with vbulletin hashes it comes like that hash:salt the salt contains all possible chars so whatever the separator is will cause always problem unless using base64 or encoding it , thanks anyway
comment on: http://stackoverflow.com/a/47611662
score: 0
type: Comment

http://stackoverflow.com/comment/82285859
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47663158
has text: @EricDuminil It's not clear what the OP exactly wants regarding this behavior (ok, I could have asked)

http://stackoverflow.com/comment/82044858
score: 0
comment on: http://stackoverflow.com/q/47543734
type: Comment
type: QuestionComment
has text: If "ve" is in the current directory, then run `ve\Scripts\activate.bat`.

http://stackoverflow.com/q/47658596
favorite count: 0
has comment: http://stackoverflow.com/comment/84230169
type: Question
has answer: http://stackoverflow.com/a/53686955
has title: Strange mixing of system + homebrew Python with LLDB
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51261265
tagged with: macos
linked to: http://stackoverflow.com/q/33587130
answer count: 4
has comment: http://stackoverflow.com/comment/84147275
tagged with: lldb
has answer: http://stackoverflow.com/a/55035284
tagged with: homebrew
downvote count: 0
upvote count: 21
score: 21
has answer: http://stackoverflow.com/a/47658597
has body: When I attempt to run the Python interpretter within lldb, I'm seeing: $ lldb (lldb) script Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 52, in &lt;module&gt; import weakref File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D. When I inspect what version of Python was launched, Python reports that it should be the Homebrew Python (which is symlinked into this location): &gt;&gt;&gt; sys.executable '/usr/local/opt/python/bin/python2.7' However, asking the Python version returns the version associated with the default system Python installation, e.g. &gt;&gt;&gt; sys.version_info sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0) And, just to confirm, the Python version at the binary path above is indeed different (note the difference in the micro version): $ /usr/local/opt/python/bin/python2.7 --version Python 2.7.14 $ /usr/bin/python --version Python 2.7.10 To make things more confusing, the name _remove_dead_weakref does exist in the _weakref module for my Homebrew Python installation, but not the default system installation: $ /usr/bin/python -c "import _weakref; print _weakref._remove_dead_weakref" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute '_remove_dead_weakref' $ /usr/local/opt/python/bin/python2.7 -c "import _weakref; print _weakref._remove_dead_weakref" &lt;built-in function _remove_dead_weakref&gt; Any idea what could be causing this apparent cross-talk between my Python installations with LLDB? How can I prevent this?

http://stackoverflow.com/a/47792968
type: Answer
answers question: http://stackoverflow.com/q/47591223
accepted answer of: http://stackoverflow.com/q/47591223
type: AcceptedAnswer
has body: I solved the problem by using a non interavtive (that means no javascript library like plotly or d3) by using pythons matplotlib for the plotting task.
score: 0

http://stackoverflow.com/comment/82892979
score: 0
has text: @guettli hope this is useful to you. ps: have answered quite a few of your questions recently :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47674185
type: Comment

http://stackoverflow.com/a/47574270
has comment: http://stackoverflow.com/comment/82105448
answers question: http://stackoverflow.com/q/47574192
has body: I can't be sure given only the linked code, but it looks like you have overwritten list with something else that just returns or prints its argument. To recover it, you could just restart the interpreter or do real_list = type([]).
has comment: http://stackoverflow.com/comment/82105366
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/47595091
has answer: http://stackoverflow.com/a/78664390
upvote count: 16
answer count: 3
has answer: http://stackoverflow.com/a/47595517
tagged with: matplotlib
downvote count: 0
score: 16
has body: I am trying to update my matplotlib in virtualenv and now it seems everything crashed :( what I did till now is basically, source ~/myenv/bin/activate pip install -U matplotlib I had previously matplotlib 1.3 now if I activate py virtual environment and check the matplotlib version it shows 2.1 but I cannot import Axes3D from matplotlib. &gt;&gt;&gt; import importlib &gt;&gt;&gt; importlib.import_module('mpl_toolkits.mplot3d').__path__ Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/nld/python-2.7.6-freya/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/usr/vir_python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/__init__.py", line 6, in &lt;module&gt; from .axes3d import Axes3D File "/home/usr/vir_python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 32, in &lt;module&gt; from matplotlib.cbook import _backports ImportError: cannot import name _backports I working on linux platform and using Python 2.7. Further problem, I saw, If I just open virtual python, without activating the virtualenv, I get matplotlib 2.1 $:~&gt; myenv/bin/python Python 2.7.6 (default, Apr 15 2014, 11:17:36) [GCC 4.3.4 [gcc-4_3-branch revision 152973]] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import matplotlib &gt;&gt;&gt; matplotlib.__version__ '2.1.0' but if I activate the virtual environment and then open the virtual python with I get matplotlib 1.3.1 or old matplotlib. $:~&gt; source myenv/bin/activate (vir_python)$:~&gt; myenv/bin/python Python 2.7.6 (default, Apr 15 2014, 11:17:36) [GCC 4.3.4 [gcc-4_3-branch revision 152973]] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import matplotlib &gt;&gt;&gt; matplotlib.__version__ '1.3.1' I did the following as per Karthik's suggestion : First activated the virtual python (vir_python) $: pip install matplotlib==2.1.0 (vir_python) $: p…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54453999
type: UnansweredQuestion
has title: Updating matplotlib in virtualenv with pip
tagged with: pip
tagged with: python
tagged with: virtualenv

http://stackoverflow.com/comment/82105940
score: 0
type: Comment
has text: it return the year 1970, my file does not contain that year
type: AnswerComment
comment on: http://stackoverflow.com/a/47574300

http://stackoverflow.com/comment/82131272
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47586571
has text: Have you tried to create a project by using one of these frameworks? Or search the web about? Maybe you should

http://stackoverflow.com/q/47642201
has answer: http://stackoverflow.com/a/47642263
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82242853
answer count: 3
accepted answer: http://stackoverflow.com/a/47642379
tagged with: pandas
has answer: http://stackoverflow.com/a/47642379
has comment: http://stackoverflow.com/comment/82242898
has comment: http://stackoverflow.com/comment/82243206
possible better answer: http://stackoverflow.com/a/47642263
downvote count: 1
favorite count: 0
type: Question
has body: I try to sort dataframe shown below by date using df.sort_values(by='date') however it doesn't work. Any ideas how can I do this to be sure that it is sorted properly? symbol date open close high low 0 GOOG 2007-01-03 232.77 233.56 238.09 230.32 1 GOOG 2007-01-05 241.01 243.35 243.51 238.82 2 GOOG 2007-01-04 234.27 241.39 241.73 233.94 ... 2692 GOOG 2017-11-30 1022.37 1021.41 1028.49 1015.00 2693 GOOG 2017-11-29 1042.68 1021.66 1044.08 1015.65 2694 GOOG 2017-12-01 1015.80 1010.17 1022.49 1002.02
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82243087
has title: How can I sort DataFrame by date in Python?
upvote count: 5
linked to: http://stackoverflow.com/q/37787698
has comment: http://stackoverflow.com/comment/82242928
tagged with: dataframe
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/47642295
score: 4

http://stackoverflow.com/q/47666654
tagged with: oop
has body: I am trying to draw the mandelbrot sequence with python's turtle graphics. I am using two classes, one to represent the mandelbrot sequence. class Mandelbrot: def __init__(self,c,limit=50): self.__limit = int(limit) self.__colormap = ['black','white'] self.__cardinality = limit z = 0 for i in range(limit): z = z * z + c if abs(z) &gt; 2: self.__cardinality = i return def getColor(self): if self.__cardinality == self.__limit: return self.__colormap[0] return self.__colormap[1] The other class represents the turtle display. import turtle from mandelbrot import * class Display: def __init__(self): self.t = turtle.Turtle() self.t.ht();self.t.turtlesize(1) self.t.speed(0) turtle.tracer(2000,0) for x in range(-150,151): for y in range(-150,151): self.t.color(Mandelbrot(turtleConvert(x,y)).getColor()) self.t.goto(x,y) def turtleConvert(x,y): #converts from turtle pixels to the complex plane return complex((x/300)*4,(y/300)*4) When I make an instance of the display class, the program runs but only prints the lower half of the fractal. Could anyone provide a solution? This is a picture of my result.
linked to: http://stackoverflow.com/q/40984799
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9342861
tagged with: mandelbrot
tagged with: turtle-graphics
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47668276
tagged with: python
has answer: http://stackoverflow.com/a/47680228
score: 4
linked to: http://stackoverflow.com/q/9242241
tagged with: fractals
upvote count: 4
has title: Mandelbrot Sequence with Python's Turtle
answer count: 2

http://stackoverflow.com/comment/82228311
type: AnswerComment
has text: https://docs.djangoproject.com/en/1.10/topics/serialization/#natural-keys
comment on: http://stackoverflow.com/a/47634825
type: Comment
score: 0

http://stackoverflow.com/q/47613809
answer count: 1
score: -3
upvote count: 1
has title: Does ';' slow python program?
type: AnsweredQuestion
has body: I'm used to Java and Javascript, so I hate not using ';' at the end of a line. Does it slow a python program being an interpreted language?
tagged with: performance
has comment: http://stackoverflow.com/comment/82186063
tagged with: python
has comment: http://stackoverflow.com/comment/82186039
accepted answer: http://stackoverflow.com/a/47614263
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82186033
has answer: http://stackoverflow.com/a/47614263
downvote count: 4
has comment: http://stackoverflow.com/comment/82186092
has comment: http://stackoverflow.com/comment/82237496

http://stackoverflow.com/comment/82217729
type: Comment
comment on: http://stackoverflow.com/q/47624437
type: QuestionComment
has text: Hi, if you feel an answer solved your problem please accept it by clicking on the green check mark next to it
score: 0

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/47544073
tag name: python-packaging

http://stackoverflow.com/a/48984258
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47678246
accepted answer of: http://stackoverflow.com/q/47678246
has body: A colleague told me how to do it but would not post an answer. The trick is to implement __new__() and set the instance' class with this cool magic: class MyEnhancedServer(MyServer): def __new__(cls, config): self = cls.create(config) self.__class__ = cls.__class__(cls.__name__, (cls, ), {}) return self
type: Answer

http://stackoverflow.com/a/47568348
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82094276
answers question: http://stackoverflow.com/q/47568211
accepted answer of: http://stackoverflow.com/q/47568211
has comment: http://stackoverflow.com/comment/82094363
has body: Let's create a dictionary: &gt;&gt;&gt; d = {'guitar':'Jerry', 'drums':'Mickey' } Now, let's dump it to a file: &gt;&gt;&gt; import json &gt;&gt;&gt; json.dump(d, open('1.json', 'w')) Now, let's read it back in: &gt;&gt;&gt; json.load(open('1.json', 'r')) {'guitar': 'Jerry', 'drums': 'Mickey'} Taking better care of file handles The above illustrates the json module but was sloppy about closing files. Better: &gt;&gt;&gt; with open('1.json', 'w') as f: ... json.dump(d, f) ... &gt;&gt;&gt; with open('1.json') as f: ... json.load(f) ... {'guitar': 'Jerry', 'drums': 'Mickey'}
type: Answer
has comment: http://stackoverflow.com/comment/82094242
has comment: http://stackoverflow.com/comment/82094167
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/47556992
has comment: http://stackoverflow.com/comment/82071570
downvote count: 0
accepted answer: http://stackoverflow.com/a/47558914
has comment: http://stackoverflow.com/comment/82071533
has comment: http://stackoverflow.com/comment/82072246
has comment: http://stackoverflow.com/comment/82071713
has title: Python tkinter performance issue
favorite count: 0
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82072169
has comment: http://stackoverflow.com/comment/82071918
has body: I wanted to create a block physics based game, but the fps drops down really fast. I tried to optimise it as much as I could and it is still pretty low fps (200 block give me about 20 fps). Does anyone have any idea how to optimise my block game ? I was planning to add more but seeing this problem i might give up. This is my code: from tkinter import * import math import random import time master = Tk() w = Canvas(master,width=600,height=600) w.pack() tileSize = 20 def randomColor(): r = math.floor(random.random() * 255) g = math.floor(random.random() * 255) b = math.floor(random.random() * 255) return '#%02x%02x%02x' % (r, g, b) class newElement: def __init__(self,x,y): x = math.floor(x/tileSize) * tileSize y = math.floor(y/tileSize) * tileSize self.x = x self.y = y self.vx = 0 self.vy = 0 self.width = tileSize self.height = tileSize self.id = random.random() self.color = randomColor() elements = [] def mouse(event): global mouseX,mouseY mouseX,mouseY = event.x,event.y canPlace = True for y in range(0,len(elements)): e = elements[y] dx = e.x + e.width/2 - mouseX dy = e.y + e.height/2 - mouseY if math.sqrt(dx*dx+dy*dy) &lt; 20: canPlace = False break if canPlace: elements.append(newElement(mouseX,mouseY)) mouseX = 0 mouseY = 0 w.bind("&lt;B1-Motion&gt;",mouse) elements.append(newElement(300,50)) elements.append(newElement(300,100)) def collision(rect1,rect2): return rect1.x &lt; rect2.x + rect2.width and rect1.x + rect1.width &gt; rect2.x and rect1.y &lt; rect2.y + rect2.height and rect1.height + rect1.y &gt; rect2.y def distance(rect1,rect2): dx = rect1.x - rect2.x dy = rect2.y - rect2.y return math.sqrt(dx*dx+dy*dy) lastCall = time.time() def engine(): global lastCall w.delete("all") w.create_line(0,590,600,590) for i in range(0,len(elements)): e = elements[i] gravity = 0.1 e.vy += gravity e.x += e.vx e.y += e.vy if e.y + e.height &gt;= 590: e.y = 590-e.height e.vy = 0 for x in range(0,len(elements)): e1 = elements[x] if e.id == e1.id or distance(e,e1) &gt; 14.14:…
has comment: http://stackoverflow.com/comment/82071619
has comment: http://stackoverflow.com/comment/82072774
has comment: http://stackoverflow.com/comment/82072324
has comment: http://stackoverflow.com/comment/82071722
has answer: http://stackoverflow.com/a/47558914
tagged with: python
has comment: http://stackoverflow.com/comment/82072039
has comment: http://stackoverflow.com/comment/82071551
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47557731
possible better answer: http://stackoverflow.com/a/47557731
answer count: 2
has comment: http://stackoverflow.com/comment/82072326
upvote count: 2
has comment: http://stackoverflow.com/comment/82072249
has comment: http://stackoverflow.com/comment/82072384

http://stackoverflow.com/comment/82169072
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47605199
has text: What is the error which is coming?
type: Comment

http://stackoverflow.com/q/47654317
has answer: http://stackoverflow.com/a/47654588
tagged with: jupyter-notebook
type: Question
tagged with: oracle-database
has title: Automatic manipulation of data in Oracle with Jupyter Notebook (Windows & OS X)
has body: I have a table with 5 columns and an empty column in oracle. I am searching for a way to pull that table from Oracle, use it in the Jupyter Notebook to add data in that empty column (through executing the python script) and then INSERT the table into Oracle again. I know i could just export the table from Oracle manually, run it through the notebook and use the import in Oracle manually, but i am searching for a way that i could do all those steps as an automatic daily job. I am using both windows and OS x, so it would be cool if there would be both solutions to this problem. Best regards &amp; thank you in advance
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47654588
answer count: 1

http://stackoverflow.com/comment/82198201
comment on: http://stackoverflow.com/a/47619958
score: 0
type: AnswerComment
has text: Hard for me to imagine that would be possible since python will calculate the 4/9 before sympy has a chance to see it, no? Of course you could just wrote a short wrapper if you don't want to type out Rational.
type: Comment

http://stackoverflow.com/q/47637111
tagged with: excel
has comment: http://stackoverflow.com/comment/82232519
has comment: http://stackoverflow.com/comment/82232918
downvote count: 2
answer count: 1
tagged with: vba
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82233008
tagged with: algorithm
upvote count: 0
type: UnansweredQuestion
score: -2
has title: Big perfect rectangle from small rectangles with subjectivities
tagged with: python
has body: I want to arrange rectangles which will form a big perfect rectangle with no spaces- big rectangle size known. I prefer to do it in Excel but even python could be a good solution. - for starting idea of algorithms is also welcome. Each rectangle has a size length and width ( no flipping allowed)and a Y level. I know for sure that there is a solution and I know exactly the big rectangle size. If I will put the big rectangle on axis, the Y axis will have few (3-10) levels for example the points (0,100) (0,250) (0,1000). The bottom of each small rectangle should start on a level pre-defined (Y axis) So actually for each level I have the specific rectangles the I need to decide the order. My input looks like: rec. number Width Hight starting level (Y axis) Expected output if the big rectangle bottom left point will be on (0,0) axis: Rec. No. bottom left point where the rec. should start Any Ideas ? I know that it is a hard problem but I have small number of rectangle .. Thank you
has answer: http://stackoverflow.com/a/47637636

http://stackoverflow.com/a/47926465
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47676660
has body: Ok, I found a solution to this, although I couldn't workout how to select all text I was able to clean up my script to get the desired result: def checkEditFUNC(self, item, column): ''' Allows editing of certain items in the table :param item: item name :param column: Column number ''' # To allow editing only in column 1 and 2 if column == 1: # Makes Row editable item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) else: item.setFlags(item.flags() &amp; ~QtCore.Qt.ItemIsEditable)
type: Answer
accepted answer of: http://stackoverflow.com/q/47676660

http://stackoverflow.com/q/47689410
has body: I am trying to implement a neural network model on Tensor flow but seems to be having problems with the shape of the placeholders. I'm new to TF, hence it could just be a simple misunderstanding. Here's my code and data sample: _data=[[0.4,0.5,0.6,1],[0.7,0.8,0.9,0],....] The data comprises of arrays of 4 columns, the last column of each array is the label. I want to classify each array as label 0, label 1 or label 2. import tensorflow as tf import numpy as np _data = datamatrix X = tf.placeholder(tf.float32, [None, 3]) W = tf.Variable(tf.zeros([3, 1])) b = tf.Variable(tf.zeros([3])) init = tf.global_variables_initializer() Y = tf.nn.softmax(tf.matmul(X, W) + b) # placeholder for correct labels Y_ = tf.placeholder(tf.float32, [None, 1]) # loss function import time start=time.time() cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y)) # % of correct answers found in batch is_correct = tf.equal(tf.argmax(Y,1), tf.argmax(Y_,1)) accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) optimizer = tf.train.GradientDescentOptimizer(0.003) train_step = optimizer.minimize(cross_entropy) sess = tf.Session() sess.run(init) for i in range(1000): # load batch of images and correct answers batch_X, batch_Y = [x[:3] for x in _data[:2000]],[x[-1] for x in _data[:2000]] train_data={X: batch_X, Y_: batch_Y} # train sess.run(train_step, feed_dict=train_data) # success ? a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data) I got the following error message after running my code: ValueError: Cannot feed value of shape (2000,) for Tensor 'Placeholder_1:0', which has shape '(?, 1)' My desired output should be the performance of the model using cross-entropy; the accuracy value from the codeline below: a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data) I would also appreciate any suggestions on how to improve the model, or a model that is more suitable for my data.
tagged with: neural-network
accepted answer: http://stackoverflow.com/a/47690404
has title: Implementation of a neural model on Tensor-flow
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47690404
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/82368296
has text: Did you look at "interfacing with external C code" in the Cython documentation? Step one is to obtain .lib and .h files from the "build a C library" procedure. Step two is to use "cdef extern from <header.h>". Step three is to add your .lib file to the "libraries" keyword of the Python extension.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47563101
type: QuestionComment

http://stackoverflow.com/q/47578902
upvote count: 1
has comment: http://stackoverflow.com/comment/82118862
tagged with: ipython
has comment: http://stackoverflow.com/comment/82114912
has body: I need to write a function lastfirst(lst) that mimics the game of inverting words: basically if given a list of words, it returns the one that has the first letter different from the last word's letter, else it returns none. For example if i have a list composed of list = ['car,'rap','fun'] it should return the string'fun' or else None. I wrote this code: def lastfirst(lst): ...: new = [] ...: for x in lst: ...: string = x[0] ...: new.append(string) ...: string1 =x[-1] ...: new.append(string1) ...: return new ...: That returns me the first and last letter of every word, but I don't know how to proceed from here. Also ideally it should start from the last letter of the first element and ignore the last letter of the last element.
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: Question
has title: Function that mimics the game of inverting words
has comment: http://stackoverflow.com/comment/82118547
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82115747
has comment: http://stackoverflow.com/comment/82116956
score: 0

http://stackoverflow.com/comment/82518612
has text: it turns out that this was not quite right in the end. @jezrael provided the final necessary tweak so look here: https://stackoverflow.com/questions/47765551/numpy-conditional-np-where-replace/47766753?noredirect=1#comment82518385_47766753
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47763764
type: Comment

http://stackoverflow.com/comment/82188869
type: AnswerComment
score: 0
has text: @HongliBu Which two statements?
comment on: http://stackoverflow.com/a/47615169
type: Comment

http://stackoverflow.com/comment/82048210
comment on: http://stackoverflow.com/q/47545711
has text: What do you think `000` evaluates to?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47568966
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82097365
has body: I wrote cnn program with tensorflow, but it can not learn well. The data set is cifar-10, and the task of classifying color images into 10 classes. This is the code. from __future__ import print_function import tensorflow as tf import os import numpy as np import cv2 import random NUM_CLASSES = 10 IMG_SIZE = 32 STEPS = 5000 BATCH_SIZE=20 train_img_dirs = ["airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"] train_image = [] train_label = [] config = tf.ConfigProto( gpu_options=tf.GPUOptions( per_process_gpu_memory_fraction=0.1 ) ) for i, d in enumerate(train_img_dirs): files = os.listdir('./' + d) for f in files: img = cv2.imread('./' + d + '/' + f) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) img = img.flatten().astype(np.float32)/255.0 train_image.append(img) tmp = np.zeros(NUM_CLASSES) tmp[i] = 1 train_label.append(tmp) train_image = np.asarray(train_image) train_label = np.asarray(train_label) def weight_variable(shape,name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial,name=name) def bias_variable(shape,name): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial,name=name) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Input layer x = tf.placeholder(tf.float32, [None, 32*32*3], name='x') y_ = tf.placeholder(tf.float32, [None, 10], name='y_') x_image = tf.reshape(x, [-1, 32, 32, 3]) # Convolutional layer 1 W_conv1 = weight_variable([5, 5, 3, 32],"W_conv1") b_conv1 = bias_variable([32],"b_conv1") h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # Convolutional layer 2 W_conv2 = weight_variable([5, 5, 32, 64],"W_conv2") b_conv2 = bias_variable([64],"b_conv2") h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # Convolutional layer 3 W_conv3 = weight_variable([5, 5, 64, 128],"W_c…
score: 0
has comment: http://stackoverflow.com/comment/82095963
tagged with: deep-learning
answer count: 0
has title: Why can not my CNN learn cifar-10 dataset well?
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82096940
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82095886

http://stackoverflow.com/comment/82072303
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47557311
has text: `[line for line in big_list if line[-1] == '78100']`
type: Comment

http://stackoverflow.com/q/47619038
has comment: http://stackoverflow.com/comment/82196204
has body: I want to get combinations of True/False in n length (the order does not matter). So if the length is 3, the result would be: [[True, True, True], [True, True, False], [True, False, False], [False, False, False]] And if it would be 2, then the result would be: [[True, True], [True, False], [False, False]] How would I do this? I tried using itertools.product, but it also lists for example [True, False] and [False, True], while it should just make one of them (so switching the order of elements in arrays wouldn't result in duplicates).
upvote count: 2
answer count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/47619072
has answer: http://stackoverflow.com/a/47619757
has comment: http://stackoverflow.com/comment/82201394
favorite count: 0
has answer: http://stackoverflow.com/a/47621009
type: Question
has comment: http://stackoverflow.com/comment/82196109
has title: Get combinations of True and False in a given length
has comment: http://stackoverflow.com/comment/82196103
type: UnansweredQuestion
tagged with: python
score: -1

http://stackoverflow.com/comment/82292560
comment on: http://stackoverflow.com/q/47666699
score: 2
type: QuestionComment
type: Comment
has text: use spacy's ner and you can also train the spacy model with your data.

http://stackoverflow.com/a/47675362
answers question: http://stackoverflow.com/q/47675074
type: Answer
has comment: http://stackoverflow.com/comment/82312327
has comment: http://stackoverflow.com/comment/82311432
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82352481
accepted answer of: http://stackoverflow.com/q/47675074
has body: You have implicitly that x = [0, 1, 2, 3, 4], remember that in programming almost everywhere and everything starts with 0. Also, usually, upper limits are not inclusive. For y that means a rectangle with vertices (0,0), (0,1), (4,0), and (4,1) plus a triangle with vertices (0,1), (4,5), and (4,1). The rectangle has an area of 4*1=4 and the triangle 4*4/2=8 totaling an area of 12. For y1 you have a rectangle with vertices (0,0), (0,5), (4,0), and (4,5), thus giving you and area of 20.
has comment: http://stackoverflow.com/comment/82311569

http://stackoverflow.com/comment/82320140
type: Comment
type: QuestionComment
has text: Why don't you just try? It looks simple enough.
comment on: http://stackoverflow.com/q/47678568
score: 1

http://stackoverflow.com/comment/82297723
has text: @Stark: sorry, it's not boolean indexing. It's an *index array*.
comment on: http://stackoverflow.com/q/47669389
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47617718
has answer: http://stackoverflow.com/a/47617867
tagged with: nameerror
has title: Python - "NameError: name 'filename' is not defined"
answer count: 1
downvote count: 3
favorite count: 0
type: Question
tagged with: mongodb
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has body: Build mongoimport command collection = filename[:filename.find('.')] working_directory = 'C:/Users/Anshuman Misra/Downloads/' json_file = filename + '.json' mongoimport_cmd = 'mongoimport -h 127.0.0.1:27017 ' + \ '--db ' + db_name + \ ' --collection ' + collection + \ ' --file ' + working_directory + json_file Before importing, drop collection if it exists (i.e. a re-run) if collection in db.collection_names(): print 'Dropping collection: ' + collection db[collection].drop() Execute the command print 'Executing: ' + mongoimport_cmd subprocess.call(mongoimport_cmd.split())

http://stackoverflow.com/comment/82081957
comment on: http://stackoverflow.com/a/47560363
type: Comment
score: 0
type: AnswerComment
has text: Does not address key error. OP wants actual city name not NaN see below for full answer

http://stackoverflow.com/comment/82129103
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47585195
type: Comment
has text: Exactly, thank you!

http://stackoverflow.com/q/47644570
tagged with: ruby
has comment: http://stackoverflow.com/comment/82247824
has comment: http://stackoverflow.com/comment/82247857
downvote count: 2
tagged with: javascript
tagged with: python
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/82247899
has title: What my Regexp should be?
has answer: http://stackoverflow.com/a/47656811
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47644895
upvote count: 1
possible better answer: http://stackoverflow.com/a/47656811
has answer: http://stackoverflow.com/a/47644895
has body: I am trying to get all check constraints from string definition looking like this CREATE TABLE products( id INT PRIMARY KEY NOT NULL, price REAL, title TEXT, CONSTRAINT price_check CHECK ( price &gt; 0), constraint title_check CHECK (length(title) &gt; 5 AND (price &lt;= 100.0)) ); with following regexp /CONSTRAINT\s+(\w+)\s+CHECK\s+\((.+?)\)/i but it does't match second constraint, only constraint title_check CHECK (length(title) part of it. How should I change my regexp (if can at all) to get this to work? Specific language dialect of regexp doesn't matter. Thanks for help.
favorite count: 0
has comment: http://stackoverflow.com/comment/82248422
type: Question

http://stackoverflow.com/q/47623370
downvote count: 1
has comment: http://stackoverflow.com/comment/82206260
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82206190
accepted answer: http://stackoverflow.com/a/47624065
has comment: http://stackoverflow.com/comment/82205888
has body: import Tkinter as tk import os, time, smtplib top = tk.Tk() top.withdraw() def pause(n): time.sleep(n) def clear(): os.system('cls') def valueGET(val1, val2): top.withdraw() user = val1 + "@gmail.com" pswd = val2 try: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(user, pswd) except smtplib.SMTPAuthenticationError: print "Sorry, wrong password and/or username" pause(1) clear() login() print "sucess" def login(): top.deiconify() L1 = tk.Label(top, text="User Name") L1.grid(row=0, column=0) E1 = tk.Entry(top, bd = 5) E1.grid(row=0, column=1) L1 = tk.Label(top, text="Password") L1.grid(row=1, column=0) E2 = tk.Entry(top, bd = 5, show="*") E2.grid(row=1, column=1) submit = tk.Button(top, text="Submit", width=15, command=lambda: valueGET(E1.get(), E2.get())) submit.grid(row=3, column=1) top.mainloop() def main(): print "Do you wish to proceed?" cont = raw_input("&gt; ").lower() if cont[0] == "y": clear() login() print "pass" main() pardon me for not describing the question accurately enough but I honestly cant think of another way of putting it. When I run the code it goes all the way through to valueGET() and if the user and pass is correct it should (i think break out of the try block - which it does because i put a basic print statement to test that. But then it goes straight to the login again and stops at the submit button (i ran it through visual studio to see where it was getting stuck and it looks like its there). SO anyways, if anyone could help clarify this it would be great... much thanks in advance
has answer: http://stackoverflow.com/a/47624065
tagged with: python
has title: code keeps on returning to a submit button for some reason
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82204739
has comment: http://stackoverflow.com/comment/82204705
score: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/82342521
score: 0
type: AnswerComment
has text: Well then create a new question with the log output you are seeing.
type: Comment
comment on: http://stackoverflow.com/a/47690186

http://stackoverflow.com/comment/82251612
has text: Noted. Sorry for the 1000 questions, I'm just trying to understand how the original author of the source code I'm working with achieved that. I still have a lot to learn.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47646332
type: Comment

http://stackoverflow.com/comment/82152546
comment on: http://stackoverflow.com/a/47597204
type: Comment
has text: Temporary disabling is a great suggestion, if there is no 'real' solution, I'll stick with this!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82058326
type: Comment
type: QuestionComment
has text: @pyd is my solution helpful?
comment on: http://stackoverflow.com/q/47549421
score: 0

http://stackoverflow.com/a/47562851
has comment: http://stackoverflow.com/comment/82109529
type: Answer
upvote count: 2
has body: You are supposed to tear down the session after each request. The page on SQLAlchemy from the Flask website offers this snippet: from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() Even then, concurrent edits to the same object are not safe. If you want your select-update to be atomic, you will need to change the isolation level on your session (see this answer).
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47560689

http://stackoverflow.com/comment/82318265
score: 0
comment on: http://stackoverflow.com/a/47678936
type: AnswerComment
has text: here `boo` does not execute your `foo` function, just returns dict of chunks for each dataframe in the given dict. from your example, you should be able to use foo(boo(ddf, 6) here. dict comprehension here just groups each df into chunks and store them as period: df pair in a new dictionary - one new dict for each dataframe in the initial dictionary
type: Comment

http://stackoverflow.com/a/47586683
upvote count: 1
downvote count: 0
type: Answer
has body: Below you will see the types of projects supported by pycharm professional. I've personally used Flask, ant it works great.
answers question: http://stackoverflow.com/q/47586571
score: 1

http://stackoverflow.com/comment/82372872
type: QuestionComment
has text: @jmunsch I had appended the code to the question
comment on: http://stackoverflow.com/q/47686294
score: 0
type: Comment

http://stackoverflow.com/a/47578140
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47577850
has body: You could use this library https://requests-mock.readthedocs.io/en/latest/index.html and do something like &gt;&gt;&gt; import requests &gt;&gt;&gt; import requests_mock &gt;&gt;&gt; with requests_mock.Mocker() as m: ... m.get(self.url+'/somepath', text='mocked response') ... requests.get(self.url+'/somepath').text ... 'mocked response'
type: Answer
has comment: http://stackoverflow.com/comment/82113795

http://stackoverflow.com/q/47574261
favorite count: 0
has answer: http://stackoverflow.com/a/47574699
has answer: http://stackoverflow.com/a/47574352
type: AnsweredQuestion
answer count: 3
has body: Traceback (most recent call last): File "C:\Users\happy\Documents\Python\Python Hangman Files\Python Hangman EXE.py", line 253, in &lt;module&gt; wordchoice = randint(0, len(words)-1) File "C:\Users\happy\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 220, in randint return self.randrange(a, b+1) File "C:\Users\happy\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 198, in randrange raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (0,0, 0) I got this error, and I don't know what its referring to, or what is wrong with the code, thanks in advance for your help.
has comment: http://stackoverflow.com/comment/82105241
downvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/47574352
type: Question
has comment: http://stackoverflow.com/comment/82105261
score: -2
tagged with: error-handling
upvote count: 1
has answer: http://stackoverflow.com/a/47574343
possible better answer: http://stackoverflow.com/a/47574343
has title: I just got a large error message ive never seen before, what does it mean?

http://stackoverflow.com/comment/82115474
score: 0
type: Comment
type: QuestionComment
has text: @Kevin Actually, I think *it is* the cause of the problem. This is a recursive call.
comment on: http://stackoverflow.com/q/47579110

http://stackoverflow.com/comment/82222059
type: AnswerComment
has text: thanks a lot, I will try to see why I get the syntax error, really appreciate your help!
comment on: http://stackoverflow.com/a/47607547
score: 0
type: Comment

http://stackoverflow.com/comment/82220560
score: 0
comment on: http://stackoverflow.com/a/47627329
type: Comment
type: AnswerComment
has text: Strange :( :(:(

http://stackoverflow.com/comment/82127947
type: Comment
comment on: http://stackoverflow.com/a/47585116
type: AnswerComment
has text: Very informative, thank you.
score: 0

http://stackoverflow.com/q/47602610
answer count: 2
has comment: http://stackoverflow.com/comment/82167911
downvote count: 0
upvote count: 1
tagged with: python
tagged with: elasticsearch-py
type: AnsweredQuestion
tagged with: kibana
possible better answer: http://stackoverflow.com/a/47603043
has title: how to feed data to Elasticseach as Integer using Python?
has body: i am using this python script to feed my data to elasticsearch 6.0. How can i store the variable Value with type float in Elasticsearch? I can't use the metric options for the visualization in Kibana, because all the data is stored automatically as string from elasticsearch import Elasticsearch Device="" Value="" for key, value in row.items(): Device = key Value = value print("Dev",Device, "Val:", Value) doc = {'Device':Device, 'Measure':Value , 'Sourcefile':filename} print(' doc: ', doc) es.index(index=name, doc_type='trends', body=doc) Thanks EDIT: After the advice of @Saul, i could fix this problem with the following code: import os,csv import time from elasticsearch import Elasticsearch #import pandas as pd import requests Datum = time.strftime("%Y-%m-%d_") path = '/home/pi/Desktop/Data' os.chdir(path) name = 'test' es = Elasticsearch() #'Time': time , #url = 'http://localhost:9200/index_name?pretty' doc = { "mappings": { "doc": { "properties": { "device": { "type": "text" }, "measure": { "type": "text" }, "age": { "type": "integer" }, "created": { "type": "date", "format": "strict_date_optional_time||epoch_millis" } } } } } #headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} #r = requests.post(url, data=json.dumps(data), headers=headers) r= es.index(index=name, doc_type='trends', body=doc) print(r)
accepted answer: http://stackoverflow.com/a/47626400
has answer: http://stackoverflow.com/a/47603043
has answer: http://stackoverflow.com/a/47626400
tagged with: elasticsearch
score: 1
has comment: http://stackoverflow.com/comment/82164156
favorite count: 0
type: Question

http://stackoverflow.com/q/47658017
has answer: http://stackoverflow.com/a/56867797
possible better answer: http://stackoverflow.com/a/56867797
type: Question
tagged with: python-3.x
has title: How do I turn django's settings object into a dict?
tagged with: django-settings
has comment: http://stackoverflow.com/comment/82274869
downvote count: 0
has comment: http://stackoverflow.com/comment/82275211
tagged with: django
has answer: http://stackoverflow.com/a/47658300
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49432455
type: AnsweredQuestion
answer count: 5
has answer: http://stackoverflow.com/a/47660077
has comment: http://stackoverflow.com/comment/82345609
accepted answer: http://stackoverflow.com/a/47660077
has comment: http://stackoverflow.com/comment/82274844
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82345611
has answer: http://stackoverflow.com/a/47658345
has body: What I have: from django.conf import settings def settings_to_dict(settings) cfg = { 'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY, 'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY, # repeat ad nauseum } return cfg instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings)) What I'd like (using Django 1.11): from django.conf import settings instance = SomeClassInstantiatedWithADict(**settings.to_dict()) I've tried: from django.conf import settings instance = SomeClassInstantiatedWithADict(**settings.__dict__) which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!

http://stackoverflow.com/a/49736367
has body: This is due to an open issue inside sklearn. This is confirmed here
type: Answer
has comment: http://stackoverflow.com/comment/106012779
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/102694023
accepted answer of: http://stackoverflow.com/q/47548178
has comment: http://stackoverflow.com/comment/117544762
answers question: http://stackoverflow.com/q/47548178

http://stackoverflow.com/q/47546035
has title: Python - Add to json list via Python
has body: My json file { "people": [] } My python code with open("people.json") as jsonFile: load = json.load(jsonFile) data = { "fname": "Jason", "lname": "Scott", "age": 32, "job": "web developer", "spouse": "Jane Scott" } load["people"].append(data) jsonFile.close() I want to add to the list from my python file, with my code above, the json file remains unchanged.
type: Question
tagged with: arrays
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/47546080
has answer: http://stackoverflow.com/a/47546080
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/47601487
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47602013
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82161765
score: 0
has title: How to append multiple rows to csv file using python
tagged with: row
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: Im trying to append user inputted data to rows , however im having no luck. Counter is a user defined global variable which i have created elsewhere in the code. when the data is appended, instead of moving to another line it just rewrites the same line over and over and as a new user of python i have no idea what im doing wrong. def AppendCsv(): NumberOfNamesToBeAdded() with open ('Graph.csv', 'a') as graphFile: graphFileWriter=csv.writer(graphFile) for x in counter: graphFileWriter.writerow([ID, Name,Cost,Date1])
has answer: http://stackoverflow.com/a/47602013
tagged with: append
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82171373
has comment: http://stackoverflow.com/comment/82161679
answer count: 1

http://stackoverflow.com/a/63868615
upvote count: 1
has body: A four-liner solution based on Check if string ends with one of the strings from a list: folder = '.' suffixes = ('xls', 'txt') filter_function = lambda x: x.endswith(suffixes) list(filter(filter_function, glob(os.path.join(folder, '*'))))
answers question: http://stackoverflow.com/q/47655205
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/q/47672231
score: 1
answer count: 1
has title: Python nested loop and update set
tagged with: nested
has comment: http://stackoverflow.com/comment/82307917
has comment: http://stackoverflow.com/comment/82309582
upvote count: 1
tagged with: loops
has body: I am a new student and now I am learning diversity in a set. I want to implement the greedy heuristic algorithm, this algorithm is quite easy, but I am stuck in the code. Greedy heuristics generally make use of two sets: the set X of available items and the set S which contains the selected ones. Items are iteratively moved from X to S and vice versa until |S| = k. Items are moved one-by-one from X to S until k of them have been selected. The item that is moved each time is the one that has the maximum item-set distance setdist from S. The item-set distance/setdist, denoted as following: The algorithm looks like this: This is my current code: from scipy.spatial import distance k = 5 # this is just sample set, the real set is complex. S = [1,9] X = [3,4,5,6,7,8,103,1035,2009] i = 1 while i &lt; k: mylist =[] for a in range(0, len(X)): d = 0 for b in range(0, len(S)): ed = distance.euclidean(X[a],S[b]) if ed &gt; d: d = ed listku = [(X[a],S[b]), d] #print(listku) mylist.append(listku) max_dis = max(mylist,key=lambda item:item[1]) i = i + 1 From that code, I can get the max_dis, which is [(2009, 1), 2008.0] and I am stuck here. The next step is, I want to take 2009 from max_dis [(2009, 1), 2008.0] then append to S and looping iteratively. The expected output maybe: [1,9,103,1035,2009] this set is the optimum one/has max diverse.
has answer: http://stackoverflow.com/a/47675589
has comment: http://stackoverflow.com/comment/82316766
favorite count: 0
has comment: http://stackoverflow.com/comment/82303432
type: Question
has comment: http://stackoverflow.com/comment/82306378
has comment: http://stackoverflow.com/comment/82308291
type: UnansweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82308095
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82307357
tagged with: distance
has comment: http://stackoverflow.com/comment/82308610

http://stackoverflow.com/comment/82365593
has text: Probably you can use `gridspec.GridSpecFromSubplotSpec`, yes. For the case in the question however I would suggest to use an axes divider. I updated the answer.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47656917
type: Comment

http://stackoverflow.com/comment/82350536
has text: Why would it be ? It would be a little (little) bit more complex though. What have you tried ?
comment on: http://stackoverflow.com/a/47656498
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82082864
type: Comment
type: QuestionComment
has text: Another thing, if you are trying to visualize data in real-time i would suggest using tools like `elasticsearch` with `kibana` You can basically send the data and read it in realtime
score: 0
comment on: http://stackoverflow.com/q/47562382

http://stackoverflow.com/comment/82048003
type: AnswerComment
has text: @Sebastian Admittedly yes, but I'm betting that constant factor is pretty big, and you should see the difference for moderately sized inputs (yes, for large inputs, this ends up becoming slow due to the combinatorial nature of the problem).
comment on: http://stackoverflow.com/a/47545491
type: Comment
score: 0

http://stackoverflow.com/comment/82129146
has text: Ok, that's interesting. It's printing my values for the first column, but then a second column of "nan" values. I assume that's the equivalent of null, so there's a second column of null values for some reason. The related text strings are extremely long so it's a really cluttered view, otherwise I'd post an example here. I'm looking in to why I've got a second column right now, thanks! Hopefully that's the source of my problem.
comment on: http://stackoverflow.com/q/47584862
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47590556
downvote count: 1
score: 0
type: Answer
has body: Not sure if I get your question right but you could use fill_between(). I don't know if pandas can do what you're asking for. Since it's not a lot of data the resulting plot is not very spectacular. from io import StringIO import matplotlib.patches as patches # Just preparing the data .. data = """ start,end,event,counts 2016-10-02 16:58:00,2016-10-02 17:28:00,700,181 2016-10-03 07:07:00,2016-10-03 07:35:50,800,174 2016-10-03 07:36:00,2016-10-03 08:05:00,100,175 2016-10-04 19:47:00,2016-10-04 20:02:00,50,91 2016-10-05 08:09:00,2016-10-05 08:17:00,100,49 """ df = pd.read_table(StringIO(data), sep=',') df.start = pd.to_datetime(df.start) df.end = pd.to_datetime(df.end) # Plotting .. fig = plt.figure(figsize=(16, 4.5)) ax = fig.gca() for index, r in df.iterrows(): x = (r.start.value, r.end.value) h = r.counts ax.fill_between(x, 0, h)
accepted answer of: http://stackoverflow.com/q/47590122
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47590122
upvote count: 1

http://stackoverflow.com/a/66926261
has body: Your STATICFILES_DIR is a tuple, it should be a list. You have it enclosed in parentheses whereas it should be this: STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]
score: 0
answers question: http://stackoverflow.com/q/47561505
type: Answer

http://stackoverflow.com/comment/82196902
type: Comment
type: AnswerComment
has text: @Terrornado : 100% agree with you , even though it servers the purpose , packing unpacking concept is better approach
comment on: http://stackoverflow.com/a/47616202
score: 2

http://stackoverflow.com/comment/82148927
has text: Thanks for you code! I'm pretty sure that it'd work, but I want to know why my code doesn't even though the bs4 doc mentions that it supports regular expressions for **find()**.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47593556
type: AnswerComment

http://stackoverflow.com/comment/82113072
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47568505
has text: How is `csv_label` defined?
type: Comment

http://stackoverflow.com/comment/82155892
comment on: http://stackoverflow.com/a/47598672
score: 0
type: AnswerComment
has text: @ArgusMalware Which specific part is not and how do you decide what's "Pythonic" and what's not?
type: Comment

http://stackoverflow.com/comment/82385816
comment on: http://stackoverflow.com/a/47705931
has text: Thank you. It did work. I also tried Cartopy and works fine aswell.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82102660
score: 0
has text: Yes, `(?! \d)` or `(?!\s*\d)` if there should be no digits at all.
comment on: http://stackoverflow.com/q/47569622
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82112704
type: Comment
comment on: http://stackoverflow.com/a/47577661
has text: Sorry I am not very familiar with `multiprocessing `
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82293500
comment on: http://stackoverflow.com/a/47666967
score: 0
type: Comment
has text: the above code will return TypeError: Object of type 'Page' is not JSON serializable
type: AnswerComment

http://stackoverflow.com/q/47670635
has comment: http://stackoverflow.com/comment/82322641
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82306833
has body: right now I'm trying to do two things that involve removing sprites from groups. I want to accomplish two things: First, I have bullets and powerups. Once my bullet collides with my powerup, I want those specific bullets and powerups to be removed. Second, if my powerups are not hit after a certain amount of time, then I want them to be removed. Problem with Goal 1: Once of my bullets collides with a powerup, all my bullets freeze. Problem with Goal 2: All of my powerups are removed, rather than one powerup at a time. Here is my Bullet Class: class Bullet(Image): def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)): super().__init__(screen_size, width, height, filename, color = (255, 0, 0)) def checkCollision(self, powerup): return pygame.sprite.collide_mask(self, powerup) def removeBullet(self, powerup): if self.checkCollision(powerup): self.kill() def update(self, powerup): self.rect.centerx += 3 self.removeBullet(powerup) Here is my PowerUp Class class PowerUp(Image): def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)): super().__init__(screen_size, width, height, filename, color = (255, 0 , 0)) _centerx = random.randint(20, 1100) # &lt;-- local variable _centerx (don't need it in other methods) _centery = random.randint(20, 700) # &lt;-- local variable _centery (don't need it in other methods) self.radius = 10 self.rect = pygame.Rect(_centerx-self.radius, _centery-self.radius, self.radius*2, self.radius*2) def update(self): pass And here is where I run everything: class GameScreen(SceneBase): def __init__(self): SceneBase.__init__(self) self.my_font = pygame.font.SysFont("Arial", 50) self.bullets_group = pygame.sprite.Group() self.powerup_group = pygame.sprite.Group() self.player_paddle = classes.PlayerPaddle(screen_size, 20, 100, "naruto.png", self.bullets_group) self.ai_paddle = classes.AIPaddle(screen_size, 20, 100, "naruto.png") self.pong = classes.Pong(screen_size, 20, 20, "pokeball.png") self.now1 = pygame…
has comment: http://stackoverflow.com/comment/82306286
has comment: http://stackoverflow.com/comment/82321832
has comment: http://stackoverflow.com/comment/82323784
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82322489
has comment: http://stackoverflow.com/comment/82322008
has comment: http://stackoverflow.com/comment/82322294
has answer: http://stackoverflow.com/a/47673236
has comment: http://stackoverflow.com/comment/82311630
has comment: http://stackoverflow.com/comment/82310302
score: 0
has comment: http://stackoverflow.com/comment/82322597
has comment: http://stackoverflow.com/comment/82306058
has comment: http://stackoverflow.com/comment/82322824
has comment: http://stackoverflow.com/comment/82305075
answer count: 1
has comment: http://stackoverflow.com/comment/82305571
has comment: http://stackoverflow.com/comment/82323159
type: Question
has title: Having Trouble Removing Singular Sprites from Groups
has comment: http://stackoverflow.com/comment/82310022

http://stackoverflow.com/comment/83540762
type: Comment
comment on: http://stackoverflow.com/q/47603473
type: QuestionComment
score: 0
has text: My version of google-auth is 1.3.0 and I am using [this code](https://pastebin.com/yDstN38r), which is based on yours. Everything works fine.

http://stackoverflow.com/q/47645298
score: 3
has answer: http://stackoverflow.com/a/47645553
tagged with: python
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47645553
has body: I have a placeholder which shape is [None, dimension], "None" means batch size. I want to get the real shape of "None". I try two methods when I build model: First, x.get_shape() and get shape as [Dimension(None), Dimension(128)] Second, x.shape and get shape as [Dimension(None), Dimension(128)] And what I want is the real shape, for example, when the batch size is 100 in this round, I would like to get [Dimension(100), Dimension(128)]. How do I get the dynamic input shape?
has title: How to get real shape of None (dynamic input shape) in TensorFlow?
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/47564932
has body: I make a simple scraper for a company's stock price history. The problem I have is when I use matplotlib to make graph, most of the x-axis labels (date in this case) are missing. How can I force pandas/matplotlib to display all labels? import pandas as pd import urllib.request from bs4 import BeautifulSoup import matplotlib.pyplot as plt #open url and make soup quote_url = "http://www.nasdaq.com/symbol/atnx/historical" page = urllib.request.urlopen(quote_url) soup = BeautifulSoup(page, 'html.parser') #grab all the stock price data (except volume) for the last 2 weeks trs = soup.find('div', attrs={'id': 'historicalContainer'})\ .find('tbody').find_all('tr') temp_list = list() for tr in trs: for td in tr: if td.string.strip(): temp_list.append(td.string.strip()) list_of_list = [temp_list[i:i+5] for i in range(0, len(temp_list), 6)] #only take data from the last 2 weeks for the sake of simplicity list_of_list = list_of_list[:14] data_dict = {sublist[0]: [float(n.replace(',', '')) for n in sublist[1:len(sublist)]] for sublist in list_of_list} #create a pandas DataFrame for stock prices df = pd.DataFrame(data_dict) df.rename({0: 'Open', 1: 'High', 2: 'Low', 3: 'Close/Last'}, inplace=True) #Transpose dataframe df= df.T #plot with matplotlib (most x labels are missing here) df.plot() plt.show() Thanks.
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/35663705
type: Question
type: UnansweredQuestion
has title: how to show all the x-axis label with panda/matplotlib
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47566994
has comment: http://stackoverflow.com/comment/82098251
score: 0
tagged with: pandas
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82090820
has comment: http://stackoverflow.com/comment/82098255
answer count: 1

python-aiofiles
tag name: python-aiofiles
tags question: http://stackoverflow.com/q/47611139
type: Tag

http://stackoverflow.com/a/47681103
type: Answer
has comment: http://stackoverflow.com/comment/82713261
has comment: http://stackoverflow.com/comment/82713976
downvote count: 0
has comment: http://stackoverflow.com/comment/82708430
upvote count: 1
answers question: http://stackoverflow.com/q/47680803
has comment: http://stackoverflow.com/comment/82526568
has comment: http://stackoverflow.com/comment/82708422
has comment: http://stackoverflow.com/comment/82708483
has comment: http://stackoverflow.com/comment/82713318
has comment: http://stackoverflow.com/comment/82526166
has comment: http://stackoverflow.com/comment/82708387
has body: IIUC: mask = (df['Column 1'] == 'a') &amp; (df['Column 2'] == 'b') &amp; (df['Column 3'] == '1') &amp; (df['Column 4'].isin(['2','5'])) df['new_value'] = np.where(mask,'OK','NOT OK') Output: Column 1 Column 2 Column 3 Column 4 "New_name" new_value 0 a b 1 2 "OK" OK 1 a b 1 5 "OK" OK 2 c d e f "NOT OK" NOT OK
has comment: http://stackoverflow.com/comment/82713248
has comment: http://stackoverflow.com/comment/82708363
has comment: http://stackoverflow.com/comment/82371058
has comment: http://stackoverflow.com/comment/82708501
score: 1
has comment: http://stackoverflow.com/comment/82708489

http://stackoverflow.com/comment/82072715
comment on: http://stackoverflow.com/q/47557395
score: 0
type: QuestionComment
has text: No message appears where? Do you mean "the message is not sent"?
type: Comment

http://stackoverflow.com/a/47576699
upvote count: 1
has body: SOLVED! I do not know why but after a re-run of all the cells of the jupyter notebook, the graph apperead correctly.
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/122127463
answers question: http://stackoverflow.com/q/47560074
score: 0

http://stackoverflow.com/a/47642546
has body: After form validation, save your form without committing, then set your foreign key and save. if userinfo_form.is_valid() and seller_event_form.is_valid(): userinfo_form.save() new_seller_event = seller_event_form.save(commit=False) new_seller_event.user = user new_seller_event.save() return redirect('/home')
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82245261
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47642400
answers question: http://stackoverflow.com/q/47642400

http://stackoverflow.com/q/47689237
has answer: http://stackoverflow.com/a/47689264
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: datetime
tagged with: dataframe
tagged with: merge
accepted answer: http://stackoverflow.com/a/47689264
type: Question
has body: I have a dataframe that looks like this: df Name year week date 0 Adam 2016 16 2016-04-24 1 Mary 2016 17 2016-05-01 2 Jane 2016 20 2016-05-22 3 Joe 2016 17 2016-05-01 4 Arthur 2017 44 2017-11-05 5 Liz 2017 41 2017-10-15 6 Janice 2016 47 2016-11-27 And I want to create column season so df['season'] that attributes a season MAM or OND depending on the value in week. The result should look like this: df_final Name year week date season 0 Adam 2016 16 2016-04-24 MAM 1 Mary 2016 17 2016-05-01 MAM 2 Jane 2016 20 2016-05-22 MAM 3 Joe 2016 17 2016-05-01 MAM 4 Arthur 2017 44 2017-11-05 OND 5 Liz 2017 41 2017-10-15 OND 6 Janice 2016 47 2016-11-27 OND In essence, values of week that are below 40 should be paired with MAM and values above 40 should be OND. So far I have this: condition =df.week &lt; 40 df['season'] = df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: 'OND') But it is clunky and does not produce the final response. Thank you.
answer count: 1
downvote count: 0
has title: How to apply values in column based on condition in row values in python
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47624840
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47623723
has body: Using the concept of None forcing numpy to not broadcast an object into an array, something brought to my attention by Paul Panzer, I created a function which will transform the last axis into a poly1d object: def array_to_poly(arr): return np.apply_along_axis(lambda poly: [None, np.poly1d(poly)], -1, arr)[..., 1] However, if we're okay with abusing more than one system in a single function, we can make it apply over arbitrary axes: def array_to_poly(arr, axis=-1): temp_arr = np.apply_along_axis(lambda poly: [None, np.poly1d(poly)], axis, arr) n = temp_arr.ndim s = [slice(None) if i != axis%n else 1 for i in range(n)] return temp_arr[s] Testing it with arr = np.arange(1, 25).reshape(2,3,4), we obtain: In [ ]: array_to_poly(arr, 0) Out[ ]: array([[poly1d([ 1, 13]), poly1d([ 2, 14]), poly1d([ 3, 15]), poly1d([ 4, 16])], [poly1d([ 5, 17]), poly1d([ 6, 18]), poly1d([ 7, 19]), poly1d([ 8, 20])], [poly1d([ 9, 21]), poly1d([10, 22]), poly1d([11, 23]), poly1d([12, 24])]], dtype=object) In [ ]: array_to_poly(arr, 1) Out[ ]: array([[poly1d([1, 5, 9]), poly1d([ 2, 6, 10]), poly1d([ 3, 7, 11]), poly1d([ 4, 8, 12])], [poly1d([13, 17, 21]), poly1d([14, 18, 22]), poly1d([15, 19, 23]), poly1d([16, 20, 24])]], dtype=object) In [ ]: array_to_poly(arr, 2) Out[ ]: array([[poly1d([1, 2, 3, 4]), poly1d([5, 6, 7, 8]), poly1d([ 9, 10, 11, 12])], [poly1d([13, 14, 15, 16]), poly1d([17, 18, 19, 20]), poly1d([21, 22, 23, 24])]], dtype=object) as expected.
answers question: http://stackoverflow.com/q/47623723
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/82082579
type: Comment
score: 2
has text: @sasha You were of course right to demand more reproducible code in the question, but rather than asking for that you came off as angry and dismissive, which is irritating and just results in a waste of both our time before we get to the bottom of the issue. The OS is Windows, by the way.
type: QuestionComment
comment on: http://stackoverflow.com/q/47551850

http://stackoverflow.com/q/47628807
accepted answer: http://stackoverflow.com/a/47628916
has answer: http://stackoverflow.com/a/47628916
tagged with: python
has answer: http://stackoverflow.com/a/47629290
answer count: 4
has title: How to separate a list into two different lists ?(Python2.7)
has answer: http://stackoverflow.com/a/47629258
type: Question
tagged with: python-2.7
score: 0
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/47628830
downvote count: 2
favorite count: 0
has body: My current data is in the format of : [ 1982, 1, 108108, 5568], [ 1982, 2, 64488, 2433], ..., [ 2007, 498, 4341, 395], [ 2007, 499, 4328, 274], [ 2007, 500, 4323, -118]] I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list. How would I do this?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47628830

http://stackoverflow.com/q/47548076
has comment: http://stackoverflow.com/comment/82052741
has comment: http://stackoverflow.com/comment/82053137
has answer: http://stackoverflow.com/a/47548545
has comment: http://stackoverflow.com/comment/82053284
accepted answer: http://stackoverflow.com/a/47548545
tagged with: python
has comment: http://stackoverflow.com/comment/82053196
has comment: http://stackoverflow.com/comment/82053015
has comment: http://stackoverflow.com/comment/82053140
has comment: http://stackoverflow.com/comment/82053227
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Django: Update model fields using ajax call from template
tagged with: django
has comment: http://stackoverflow.com/comment/82053153
favorite count: 0
has comment: http://stackoverflow.com/comment/82052993
type: Question
tagged with: ajax
type: AnsweredQuestion
has body: I have a model: class ok(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have model form. class okForm(ModelForm): class Meta: model = ok fields='__all__' I am getting first 3 fields: name, project, story user manual entry. Now I want to populate the last two fields with respect to third field using AJAX call from views function that will query to mysql database. I have a fucntion in views.py def get(self, request): name = request.GET.get('name') project = request.GET.get('project') story = request.GET.get('story') if name and project and story: try: obj = ok.objects.get(name=name, project=project, story=story) return JsonResponse(data={ 'depends_on': ok_obj.depends_on, 'rfc': ok_obj.rfc}, status=200) except ok.DoesNotExist: pass return JsonResponse(data={'error': 'bad request'}, status=400) How i will make the ajax call with the third value the user just filled, as he has not submitted the form yet . Kindly help.

http://stackoverflow.com/comment/109072707
score: 0
type: Comment
has text: @ev-kounis well, no I couldn't. The whole point of using a single iteration of `for` is to get a key, as dictionaries are not indexed and the goal is not to create any lists. the `break` basically makes the `next()` unnecessary, but otherwise I'm doing what you did.
type: AnswerComment
comment on: http://stackoverflow.com/a/47695089

http://stackoverflow.com/q/47564583
has comment: http://stackoverflow.com/comment/82087769
tagged with: list
answer count: 1
has title: Multiplying csv value - TypeError: can't multiply sequence by non-int of type 'float'
has comment: http://stackoverflow.com/comment/82108714
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82087708
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47564893
has comment: http://stackoverflow.com/comment/82087790
upvote count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47564893
has body: So, part of the code I am writing for my uni work requires me to multiply ranking points on a csv list by the difficulty of the tournament. I have tried everything that I know but I keep getting TypeError: can't multiply sequence by non-int of type 'float' This is what I have at the moment: import csv class Opener: with open("DADSA 17-18 COURSEWORK A RANKING POINTS.csv", "r") as csv_file3: next(csv_file3) rp = csv.reader(csv_file3) ranking_points = [] for rowrp in rp: if len(rowrp) != 0: ranking_points += [rowrp] List with the ranking points(left) Download csv file here tourn=input("What is this tournament: ").upper() def tournament(tourn): rp0 = Opener.ranking_points[0][0] multiply = 0 for line in rp0: if tourn == "TAC1": multiply = 2.7 rp0 *= multiply elif tourn == "TAE21": multiply = 2.3 rp0 *= multiply elif tourn == "TAW11": multiply = 3.1 rp0 *= multiply elif tourn == "TBS2": multiply = 3.25 rp0 *= multiply return rp0 tournament(tourn) TAC1, TAE21, TAW11 and TBS2, are the name of the difficulty levels. I hope one of you can help me with this, I've tried a few things that I found here but at the end it all comes down to the same error. EDIT: The error that I put initially was from a previous run where I tried something else. The full error from this code looks like this: Traceback (most recent call last): File "D:/Transferencias/DADSA/Tournament.py", line 62, in tournament(tourn) File "D:/Transferencias/DADSA/Tournament.py", line 50, in tournament rp0 *= multiply TypeError: can't multiply sequence by non-int of type 'float'
tagged with: arrays
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82087476
has comment: http://stackoverflow.com/comment/82087734
has comment: http://stackoverflow.com/comment/82087400
type: AnsweredQuestion

http://stackoverflow.com/a/47621240
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47621187
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47621187
type: Answer
has body: First filter only necessary columns by drop or filter and then count with value_counts and then if necessary replace NaNs to 0 by fillna: df1 = df.drop('Lane', 1).apply(lambda x: x.value_counts()).T.fillna(0).astype(int) Or: df1 = df.filter(like='Prop').apply(lambda x: x.value_counts()).T.fillna(0).astype(int) print (df1) FAIL PASS WARN PropA 1 2 1 PropB 2 2 0 PropC 0 2 2 And last: df1.plot.bar()

http://stackoverflow.com/comment/82264533
comment on: http://stackoverflow.com/a/47550915
type: Comment
has text: Most of the times, python errors really directly tell you the problem. In this case, either `x` or `y` or both are empty. I hope you don't expect me to know what you did for that to happen.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82179221
score: 0
has text: @RottenCandy and both can be done without using `eval` :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47610320
type: Comment

http://stackoverflow.com/comment/82247260
has text: I’ve already finished with that part of code, and as well I’ve added while loop thing so now it works fine. Just didn’t know, as you said, that ‘Yes’ doesn’t work with ‘upper() function.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47624629

http://stackoverflow.com/q/47612502
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47612531
has title: Check if multiple strings exists in list using Python
score: 7
tagged with: python
has comment: http://stackoverflow.com/comment/82183282
accepted answer: http://stackoverflow.com/a/47612588
has answer: http://stackoverflow.com/a/47612588
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47612531
downvote count: 0
upvote count: 7
has body: How can i test if multiple strings exist in another list? Below is a code example that I started with but doesn't work properly. It should return true if even part of the string is found in the list. I marked in the comments what the result should return. as you can see they all fail though. def all_exist(avalue, bvalue): if avalue == []: return True else: print (all(x in avalue for x in bvalue)) items = ['greg','krista','marie'] all_exist(['greg', 'krista'], items) # true all_exist(['gre', 'kris'], items) # true all_exist(['gre', 'purple'], items) # false Would it be better to convert the second list to a single string and then just test if strings in list exist in it?
favorite count: 0
has comment: http://stackoverflow.com/comment/82183329

http://stackoverflow.com/comment/82077876
score: 0
has text: @Daniel I get '2' (basically i get an output) thats not true when using the import statement .I get nothing in that case
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47559939

http://stackoverflow.com/comment/82043220
score: 0
comment on: http://stackoverflow.com/q/47542260
type: QuestionComment
has text: Ah, I see.. My issue with installing mod_wsgi through pip was that I was constantly receiving the `Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-LhKUr6/mod-wsgi/` error so I ended up installing `libapache2-mod-wsgi`. I will update my python version and try to work out that error issue when I get back from class. Thank you lots for the help so far!
type: Comment

http://stackoverflow.com/q/47678422
favorite count: 0
has comment: http://stackoverflow.com/comment/82316261
type: Question
has comment: http://stackoverflow.com/comment/82316013
tagged with: shortcut
accepted answer: http://stackoverflow.com/a/47679850
has answer: http://stackoverflow.com/a/47679850
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82316046
score: 1
has title: FileNotFoundError for shortcut files
answer count: 1
downvote count: 0
tagged with: file
upvote count: 1
has body: I'm trying the practice project, Deleting Unneeded files (Chapter: Organising files, Page: 213) from the book Automate the boring task with python. The full problem statement is, It’s not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you’re trying to free up room on your computer, you’ll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them. Write a program that walks through a folder tree and searches for excep- tionally large files or folders—say, ones that have a file size of more than 100MB. (Remember, to get a file’s size, you can use os.path.getsize() from the os module.) Print these files with their absolute path to the screen. Here's my code, #!/usr/bin/python # A program to walk a path and print all the files name with size above 100MB import os pathInput = os.path.abspath(input('Enter the path for the directory to search ')) for folder, subFolders, files in os.walk(pathInput): for file in files: file = os.path.join(folder, file) if int(os.path.getsize(file)) &gt; 100000000: print('File located, Name: {fileName}, Location: {path}'.format(fileName=file, path=folder)) However for some files I get FileNotFoundError. So, when trying this #!/usr/bin/python # A program to walk a path and print all the files name with size above 100MB import os pathInput = os.path.abspath(input('Enter the path for the directory to search ')) for folder, subFolders, files in os.walk(pathInput): for file in files: file = os.path.join(folder, file) try: if int(os.path.getsize(file)) &gt; 100000000: print('File {fileName} located at {path}'.format(fileName=file, path=folder)) except FileNotFoundError: print('FileNotFoundError: {}'.format(file)) I found that the files which are shortcuts with size zero bytes causes the error. So, how should I overcome this error? Is there any function in python is check if the file is shortcut?

http://stackoverflow.com/q/47662978
has comment: http://stackoverflow.com/comment/82285633
has title: PiCamera pictures inconsistent
has body: I am working with a Raspberry pi with a camera module (Raspberry pi Camera) mounted on a drone and programmed to take pictures after a fixed interval. However, the images seem to be a bit inconsistent as seen below . Images 4 and 8 appear to have slightly more 'colored' as compared to other images and appear to have more saturation. However, as the default saturation is 0 and my code is not changing that, I believe it is something else. My python script is as below def calibrate(t): with picamera.PiCamera() as camera: time.sleep(t) camera.shutter_speed = camera.exposure_speed ss=camera.shutter_speed camera.still_stats = 'true' camera.exposure_mode = 'off' g = camera.awb_gains camera.awb_mode = 'off' camera.awb_gains = g camera.close() return ss,g def capture(ss,g,stream): with picamera.PiCamera() as camera: camera.resolution = (3280,2464) camera.shutter_speed = ss camera.still_stats camera.exposure_mode = 'off' camera.awb_mode = 'off' camera.awb_gains = g camera.still_stats = 'true' camera.capture(stream,format='jpeg') camera.close() I call the calibrate function before taking any pictures that calibrate the camera. After calibrating, I take the pictures and get this problem. Does anyone know how to solve this?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82285652
tagged with: raspberry-pi
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47663197
score: 3
upvote count: 3

http://stackoverflow.com/comment/82313009
score: 0
comment on: http://stackoverflow.com/q/47676972
type: Comment
has text: Chage `surname` function to be `surname(first_name)` and call it with `return surname(first_name)`
type: QuestionComment

http://stackoverflow.com/comment/82146825
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47586162
has text: please try to give a more in depth example, create a simple, example html file and try your code against that, show what code your using, what output you would expect and what your actually getting
score: 0

http://stackoverflow.com/a/47684423
has comment: http://stackoverflow.com/comment/82361347
score: 0
answers question: http://stackoverflow.com/q/47683727
type: Answer
has body: ffill fills rows with values from the previous row if they weren't NaN, bfill fills rows with the values from the NEXT row if they weren't NaN. In both cases, if you have NaNs on the first and/or last row, they won't get filled. Try doing both one after the other. If any columns have entirely NaN values then you will need to fill again with axis=1, (although I get a NotImplementedError when I try to do this with inplace=True on python 3.6, which is super annoying, pandas!).

http://stackoverflow.com/comment/82330213
comment on: http://stackoverflow.com/a/47685169
score: 0
type: Comment
type: AnswerComment
has text: @ Gabrieal A - Yes, I already did try converting all the values in the column to Python `datetime` using `to_pydatetime()`. However, this function cannot convert `NaT` values successfully.

http://stackoverflow.com/a/47683444
has body: You could do something like this : a = [[1, 3, 3], [7, 2, 6], [4, 2, 8]] min_no=min([i[1] for i in a]) max_no=max([i[2] for i in a]) for item in a: if min_no and max_no in item: print(item) output: [4, 2, 8]
answers question: http://stackoverflow.com/q/47672176
type: Answer
score: 0

http://stackoverflow.com/comment/82258209
score: 0
comment on: http://stackoverflow.com/q/47644824
type: Comment
has text: No, `dressing table` is a child of bedroom items (to quote)
type: QuestionComment

wagtail
tags question: http://stackoverflow.com/q/47637504
tag name: wagtail
tags question: http://stackoverflow.com/q/47623026
tags question: http://stackoverflow.com/q/47622238
tags question: http://stackoverflow.com/q/47636246
tags question: http://stackoverflow.com/q/47613627
tags question: http://stackoverflow.com/q/47618971
type: Tag

http://stackoverflow.com/comment/82066181
type: AnswerComment
comment on: http://stackoverflow.com/a/47549412
has text: It sounds like you want CSV style output too?
type: Comment
score: 0

http://stackoverflow.com/comment/82283086
comment on: http://stackoverflow.com/q/47661778
score: 0
type: QuestionComment
has text: can you post an example of your desired data set?
type: Comment

http://stackoverflow.com/comment/82188336
type: QuestionComment
comment on: http://stackoverflow.com/q/47585662
has text: The last line of the code: df=dataset.groupby(['ID']).apply(yearfilt).sort_values(["ID"]).reset_index(drop=True)
type: Comment
score: 0

http://stackoverflow.com/a/47584955
upvote count: 1
score: 1
has body: I think you need to check each element and change the plot order. import numpy as np import matplotlib.pyplot as plt N = 3 price1 = [28688, 28241, 30091] price2 =[27285, 29924, 35291] ind = np.arange(N) width = 0.2 bar_handlers_a = [] bar_handlers_b = [] for i, p1, p2 in zip(ind, price1, price2): if p1 &lt; p2: b1 = plt.bar(i, p2, width, color='red') a1 = plt.bar(i, p1, width, color='black') else: a1 = plt.bar(i, p1, width, color='black') b1 = plt.bar(i, p2, width, color='red') bar_handlers_a.append(a1) bar_handlers_b.append(b1) plt.show()
answers question: http://stackoverflow.com/q/47584805
downvote count: 0
type: Answer

http://stackoverflow.com/a/47638482
answers question: http://stackoverflow.com/q/47637989
has comment: http://stackoverflow.com/comment/82236017
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92532618
type: Answer
has comment: http://stackoverflow.com/comment/82236114
has comment: http://stackoverflow.com/comment/82236202
has body: I believe your code is working. See this example: import numpy as np import matplotlib.pyplot as plt from sklearn import datasets iris = datasets.load_iris().data X = iris[:,0] Y = iris[:,1] Z = iris[:,2] fig = plt.figure("Color MAP 2D+") contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr") plt.xlabel("X") plt.ylabel("Y") plt.title("Color MAP 2D+") #Legend def fmt(x, pos): a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) import matplotlib.ticker as ticker plt.colorbar(contour, format=ticker.FuncFormatter(fmt)) plt.show() Output:
score: 0

http://stackoverflow.com/comment/82280843
has text: Please add it to the question and mention in topic or in tag it's issue related to macOS. It will allow easier searching for similar problem solution in future.
comment on: http://stackoverflow.com/q/47657349
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/57722843
has body: The error message no display name and no $DISPLAY environment variable says it: it is unknown where to display the graphics. If the $DISPLAY variable was set, it got lost due to the sudo. You can try to preserve it by means of the -E (preserve environment) option: sudo -E python3 SpaceWars.py But the question remains whether you really have to execute it as the superuser.
accepted answer of: http://stackoverflow.com/q/47671547
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47671547
type: Answer

http://stackoverflow.com/a/47564153
has comment: http://stackoverflow.com/comment/82086375
has comment: http://stackoverflow.com/comment/82087443
answers question: http://stackoverflow.com/q/47564103
type: Answer
has comment: http://stackoverflow.com/comment/82086390
accepted answer of: http://stackoverflow.com/q/47564103
score: 0
has comment: http://stackoverflow.com/comment/82087026
has body: You can perform a groupby on a column(s) and still access that column - df1.groupby(['BNF Chapter','Name'])['BNF Chapter'].sum()
has comment: http://stackoverflow.com/comment/82086686
has comment: http://stackoverflow.com/comment/82086799
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82086923
has comment: http://stackoverflow.com/comment/82086813

http://stackoverflow.com/comment/82304749
type: Comment
comment on: http://stackoverflow.com/a/47653065
type: AnswerComment
has text: It was the only solution I could think of.
score: 0

http://stackoverflow.com/comment/82357460
score: 0
comment on: http://stackoverflow.com/a/47682175
type: Comment
has text: @ShubhamSrivastava You're welcome. Could you mark it as an answer if it solves your question? Thanks ^_^
type: AnswerComment

http://stackoverflow.com/comment/82174848
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47605047
has text: @furas I followed that exactly but I still get issue https://pastebin.com/EZfz4Pn6

http://stackoverflow.com/a/47594915
has comment: http://stackoverflow.com/comment/82147074
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47594473
has body: So you need to do something like the following: hasUpper = False hasLower = False hasDigit = False etc etc Then, go through the 'password' one character at a time: ie. string[1], string[2], string[3] Run your boolean result on it (isupper, islower, etc) when true, change your hasUpper, hasLower, hasDigit to True Then, once gone through the whole string, check your boolean results with your requirements. ie: if requirements are upper, lower, and digit. if hasUpper = True and hasLower = True and hasDigit = True: then it's a good password, etc. Make sense?
has comment: http://stackoverflow.com/comment/97118864

http://stackoverflow.com/q/47623021
type: Question
has answer: http://stackoverflow.com/a/47623544
has title: Adding attributes to a relationship in Django Rest Framework w/ JSON API Format
score: 0
tagged with: python
type: UnansweredQuestion
tagged with: django-rest-framework
answer count: 1
has body: I'm able to return the following response from my api sans the bold text. { "data": { "type": "users", "id": "2", "attributes": { "email": "test@test.com", "name": "first last", }, "relationships": { "businesses": { "data": { "type": "Business", "id": "1" "attributes": { "name": "the spot:, "address": "foo", } } }, I'm using Django Rest Framework JSON Api to format the response to JSON Api spec and I'm wondering what I need to do to get attributes added to the response in the relationship object. It would seem that the business serializer is the issue however their documentation isn't all that clear on how to get a response formatted like this as it instead shows how to get just the primary key of the business returned. Any ideas? My serializer looks like this: from rest_framework import serializers from rest_framework_json_api import serializers as srs from rest_framework_json_api.relations import ResourceRelatedField, SerializerMethodResourceRelatedField from businesses.serializers import BusinessSerializer from businesses.models import Business from . import models class UserSerializer(serializers.ModelSerializer): token = srs.SerializerMethodField() # necessary for M2M fields &amp; reverse FK fields businesses = ResourceRelatedField(read_only=True, allow_null=True) review_user = ResourceRelatedField(read_only=True, allow_null=True, many=True) booking_user = ResourceRelatedField(read_only=True, allow_null=True, many=True) #businesses = serializers.PrimaryKeyRelatedField(queryset=Business.objects.all(), required=False) #businesses = BusinessSerializer(read_only=True) """Meta class tells Django what fields we want to take from the model""" class Meta: # links the serializer to the model class model = models.User # this is a tuple fields = ('id', 'email', 'password', 'name', 'phone', 'location', 'token', 'has_business', 'is_active', 'businesses') extra_kwargs = {'password': {'write_only': True}}
tagged with: json-api

http://stackoverflow.com/comment/82261764
type: Comment
comment on: http://stackoverflow.com/q/47651288
score: 0
has text: @Tom Wojcik: <class 'pandas.core.frame.DataFrame'> RangeIndex: 534 entries, 0 to 533 Data columns (total 3 columns): workyear 534 non-null int64 gender 534 non-null int64 Wage 534 non-null float64 dtypes: float64(1), int64(2) memory usage: 12.6 KB
type: QuestionComment

http://stackoverflow.com/comment/82061691
type: QuestionComment
has text: Are you trying to show file name under the mouse pointer from *windows explorer*?
comment on: http://stackoverflow.com/q/47544449
score: 0
type: Comment

http://stackoverflow.com/comment/82228368
score: 2
comment on: http://stackoverflow.com/q/47634922
type: Comment
type: QuestionComment
has text: Alternatively don't print while processing. Do the testing work, adding results to a dict - then print them at the end of the process. This also makes re-formatting them easier in future if you need a different output structure (e.g. html table)

http://stackoverflow.com/a/47674970
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47671985
has comment: http://stackoverflow.com/comment/82309723
score: 1
type: Answer
has body: Something like this, perhaps. This is limited to 2-byte UTF-8 characters. import re j = u'{"something":"text \\u00ce\\u00b2 text..."}' def decodeu (match): u = '%c%c' % (int(match.group(1), 16), int(match.group(2), 16)) return repr(u.decode('utf-8'))[2:8] j = re.sub(r'\\u00([cd][0-9a-f])\\u00([89ab][0-9a-f])',decodeu, j) print(j) returns {"something":"text \u03b2 text..."} for your sample. At this point, you can import it as regular JSON and get the final string you want. result = json.loads(j)
answers question: http://stackoverflow.com/q/47671985

http://stackoverflow.com/q/47574518
has comment: http://stackoverflow.com/comment/82105923
answer count: 3
has answer: http://stackoverflow.com/a/47574685
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82105847
has answer: http://stackoverflow.com/a/47574646
type: Question
has title: Python: Is there a more efficient way to convert int value of months?
accepted answer: http://stackoverflow.com/a/47574685
has body: I have a list of integers [1, 2...40, 41...] that represent months of a few years. i.e. 1 is January of year 1, 13 is January of year 2, and so on. When trying to convert into just the month integer (all Januarys to 1, etc.) I'm using month_int % 12 but it turns December into 0. I wrote the following small block to catch the Decembers but was wondering if there's a more efficient way? for month_int in month_list: if not(bool(month_int % 12)): # Dec exception here else: # work as normal Basically, I want to change lists like this: [1, 2...12, 13, 14, 15...] [1, 2...12, 1, 2, 3...]
upvote count: 1
has answer: http://stackoverflow.com/a/47574584
possible better answer: http://stackoverflow.com/a/47574584
downvote count: 0
has comment: http://stackoverflow.com/comment/82105987
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/a/47602390
has comment: http://stackoverflow.com/comment/82163722
has comment: http://stackoverflow.com/comment/82168664
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47602282
has comment: http://stackoverflow.com/comment/82163980
has comment: http://stackoverflow.com/comment/82169015
answers question: http://stackoverflow.com/q/47602282
has comment: http://stackoverflow.com/comment/82164012
upvote count: 2
has body: Your string is UTF-8 encoded, and the URL encoded string reflects this. 0xC3A8 is the UTF-8 encoding of the Unicode value U+00E8, which is described as "LATIN SMALL LETTER E WITH GRAVE". In order to get the string you are after, you need to let Python know which codepage you're using, like this: my_text=bytes("City of Liège",'cp1252')
type: Answer
has comment: http://stackoverflow.com/comment/82192403

http://stackoverflow.com/comment/82159780
has text: Yes, because the two different tables have something in common which is their ID. Without their ID, how can you match the Courses and their respective time?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47600399
score: 0

http://stackoverflow.com/q/47688824
has answer: http://stackoverflow.com/a/47698312
has comment: http://stackoverflow.com/comment/82336875
has comment: http://stackoverflow.com/comment/82343674
upvote count: 4
has title: Why is matrix subtraction much slower than dot product in numpy?
answer count: 3
has comment: http://stackoverflow.com/comment/82337077
has comment: http://stackoverflow.com/comment/82336841
downvote count: 0
has answer: http://stackoverflow.com/a/47689033
favorite count: 0
has answer: http://stackoverflow.com/a/47690361
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82337109
has body: Let's say we have a vector and a matrix: X = np.random.random((1, 384)).astype('float32') Y = np.random.random((500000, 384)).astype('float32') Why is np.dot(X, Y.T) much faster than X - Y? In [8]: %timeit np.dot(X, Y.T) 10 loops, best of 3: 42.4 ms per loop In [9]: %timeit X - Y 1 loop, best of 3: 501 ms per loop What can I do to make subtraction like this as faster as dot product?
type: UnansweredQuestion
tagged with: python
score: 4

http://stackoverflow.com/comment/82198497
comment on: http://stackoverflow.com/a/47620155
type: AnswerComment
has text: @RoseAnn Done, but nothing I would recommend.
score: 0
type: Comment

http://stackoverflow.com/q/47681704
has title: Python Global Variable Issue Being Set
duplicate of: http://stackoverflow.com/q/15595393
has body: The global variable does not 'save' after the function is done being executed. You can run the code below and see the debug output. Main file: from GlobalTest import * def init(): #call that function, should set Mode2D to True set2DMode(True) #define it as a global global Mode2D #see what the value is set to now, which is not what I set it to for an unknown reason print("Mode:",Mode2D) init() GlobalTest: Mode2D = False def set2DMode(mode): #define it as global so it uses the one above global Mode2D #set the GLOBAL variable to the argument Mode2D = mode #output of what it thinks it is, which is as expected print("local var mode =",mode) print("Mode2D =", Mode2D) What I expect: local var mode = True Mode2D = True Mode: True Result I get: local var mode = True Mode2D = True Mode: False
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82322522
answer count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/47660938
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82322527
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/15595393
tagged with: python
linked to: http://stackoverflow.com/q/1977362

http://stackoverflow.com/a/47634401
score: 0
has comment: http://stackoverflow.com/comment/82339566
type: Answer
has body: Did you install the right module or have you tried updating it? I found a 3.3.1 version on https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv opencv_python‑3.3.1+contrib‑cp36‑cp36m‑win_amd64.whl.
answers question: http://stackoverflow.com/q/47632758

http://stackoverflow.com/comment/82106131
type: Comment
comment on: http://stackoverflow.com/q/47574478
type: QuestionComment
has text: can be a lot more than 1000.
score: 0

http://stackoverflow.com/a/47598284
score: 5
upvote count: 5
type: Answer
has body: Use str.format(). Preferably, be explicit about passing arguments to it. But as a stopgap measure, you can use locals() to pass a dict of local (function-defined) variables to the formatting function: foo = 'bar' print('Foo is actually {foo}'.format(**locals())) You can of course copy globals() to a local dict, and merge locals() to it, and use it to more closely emulate the f-string approach.
has comment: http://stackoverflow.com/comment/96442960
answers question: http://stackoverflow.com/q/47597831
has comment: http://stackoverflow.com/comment/96464255
downvote count: 0
has comment: http://stackoverflow.com/comment/96342666

http://stackoverflow.com/comment/82084128
has text: Okay, I got it. How do I access widget names on different tabs?
type: Comment
comment on: http://stackoverflow.com/a/47559208
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82312858
has text: Thank you, so I use this in my python file but how do I retrieve that data in my javascript file?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47676949
type: AnswerComment

http://stackoverflow.com/a/55284674
type: Answer
score: 0
has body: I had luck doing this: import pandas as pd df = pd.DataFrame(['01/01/2019',None], columns=['datetime_field']) df['datetime_field'] = pd.to_datetime(df['datetime_field']) df['datetime_field'] = pd.to_datetime(df['datetime_field'], errors='coerce').where(df['datetime_field'].notnull(), 0.0) Originally the nulls in this field are NaT. pandas where docs
answers question: http://stackoverflow.com/q/47685033

http://stackoverflow.com/q/47696719
downvote count: 2
favorite count: 0
type: Question
has title: How to use an object of a function inside a class from another script in python?
answer count: 2
has answer: http://stackoverflow.com/a/47696791
has answer: http://stackoverflow.com/a/47696839
upvote count: 0
type: UnansweredQuestion
score: -2
tagged with: python
has body: I am trying to run the below script for generating an email notification: class ecom_common_functions_class(sendmailobject): def __init__(self): count = 0 def ecom_send_mail_without_attachement(self,email_sender_id,email_reciever_id,mail_body,mail_subj,server): print "INSIDE MAIL SENT FUNCTION" msg = MIMEMultipart() print "in function email_reciever_id =", email_reciever_id msg['From'] = email_sender_id msg['To'] = email_reciever_id msg['Subject'] = mail_subj body = mail_body msg.attach(MIMEText(body, 'html')) part = MIMEBase('application', 'octet-stream') encoders.encode_base64(part) server = smtplib.SMTP('localhost') text = msg.as_string() server.sendmail(email_sender_id, email_reciever_id, text) server.quit() When I import this function in another script I get this error: Traceback (most recent call last): File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_validation_negative.py", line 10, in &lt;module&gt; import ecom_nis_common_functions File "/ecom_data/US_full/binaries/NIS/aneesha/ecom_nis_common_functions.py", line 32, in &lt;module&gt; class ecom_common_functions_class(sendmailobject): NameError: name 'sendmailobject' is not defined The result must be printed as a message in an email.
has comment: http://stackoverflow.com/comment/82353144

http://stackoverflow.com/a/47689114
answers question: http://stackoverflow.com/q/47688907
has body: &gt;&gt;&gt; txt = "Hello, goodbye Fred" &gt;&gt;&gt; txt.replace(',', ' ').split() ['Hello', 'goodbye', 'Fred']
type: Answer
has comment: http://stackoverflow.com/comment/82338231
score: 0

http://stackoverflow.com/comment/82060823
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47544256
has text: Images are immutable, once created they don't change. You replace them with new images. (And volumes are the correct answer for your development workflow.)
score: 1

http://stackoverflow.com/q/47605720
favorite count: 0
type: Question
has title: Perform a function at a regular time-based interval with python
tagged with: datetime
answer count: 1
has body: I'm currently trying to retrieve the contents of a webpage (JSON) that updates very regularly. Ideally, I would like to download the data from this URL every 10 minutes and save it, appending it to a growing data structure of updates. Is there a way to repeatedly run a python function at a user-defined interval (10 minutes)? In my case, I'm able to download a url using the below code, but wish to add data to it every 10 minutes. with urllib.request.urlopen(URL) as url: data = json.loads(url.read().decode()) print(data)
score: -1
linked to: http://stackoverflow.com/q/510348
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47605754
has comment: http://stackoverflow.com/comment/82169936
upvote count: 0
duplicate of: http://stackoverflow.com/q/510348
tagged with: python
type: UnansweredQuestion
downvote count: 1

http://stackoverflow.com/q/47585991
downvote count: 3
has answer: http://stackoverflow.com/a/47586070
favorite count: 0
type: Question
answer count: 2
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82129717
tagged with: function
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/986006
has answer: http://stackoverflow.com/a/47586073
has title: Why is my function paramter returning an error of not being defined
has comment: http://stackoverflow.com/comment/82129953
has body: I'm new to functions, so I'm not quite sure how or why this is happening and I do not know how t fix it. Can someone explain why this error keeps occuring? def loan_payment(l): loan = float(input("Please enter how much you expend monthly on loan payments:")) return loan def insurance_cost(i): insurance = float(input("Please enter how much you expend monthly on insurance:")) return insurance def gas_cost(g): gas = float(input("Please enter how much you expend monthly on gas:")) return gas def maitanence_cost(m): maitanence = float(input("Please enter how much you expend monthly on maintanence:")) return maitanence def monthly_cost(l, i, g, m): monthly_expenses = float(l + i + g + m) print("You expend $"+format(monthly_expenses, '.2f')+" in a month.") return float(monthly_expenses) def yearly_cost(monthly_cost): yearly_expenses = 12 * monthly_cost print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".") return yearly_expenses def main(): loan_payment(l) insurance_cost(i) gas_cost(g) maitanence_cost(m) monthly_cost(l, i, g, m) yearly_cost(monthly_cost) main() This code returns the error: line 24, in main loan_payment(l) NameError: name 'l' is not defined
has comment: http://stackoverflow.com/comment/82129797

http://stackoverflow.com/a/47659939
has comment: http://stackoverflow.com/comment/82462210
has comment: http://stackoverflow.com/comment/82359414
has comment: http://stackoverflow.com/comment/82385163
score: 0
answers question: http://stackoverflow.com/q/47653048
has comment: http://stackoverflow.com/comment/82396810
type: Answer
has body: If you want to use queue.Queue.join, then you must also use queue.Queue.task_done. You can read the linked documentation or see the following copied from information available online: Queue.task_done() Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. Queue.join() Blocks until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. To test your problem, an example implementation was created to find out what was going on. It is slightly different from how your program works but demonstrates a method to solving your problem: #! /usr/bin/env python3 import abc import csv import pathlib import queue import sys import threading import time def main(): source_path = pathlib.Path(r'C:\path\to\file.csv') data_source = CSVDataSource(source_path) data_source.start() processor = StoppableThread(target=consumer, args=[data_source]) processor.start() time.sleep(0.1) data_source.stop() def consumer(data_source): while data_source.empty: time.sleep(0.001) while not data_source.empty: task = data_source.get_from_queue(True, 0.1) print(*task.data, sep=', ', flush=True) task.done() class StopThread(StopIteration): pass threading.SystemExit = SystemExit, StopThread class StoppableThread(threading.Thread): def _bootstrap(self, stop=False): # noinspection PyProtectedMember if threading._…
has comment: http://stackoverflow.com/comment/82472002

http://stackoverflow.com/q/47541183
tagged with: numpy
has title: Using .net API with python packages
linked to: http://stackoverflow.com/q/7367976
answer count: 0
tagged with: hardware
has comment: http://stackoverflow.com/comment/82039943
type: UnansweredQuestion
score: 1
downvote count: 0
tagged with: .net
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82040784
tagged with: c#
has comment: http://stackoverflow.com/comment/82040759
has body: I am interested to control a number of instruments which has an API written in C# .NET. Based on my experience, if I use IronPython then I can't use python packages like Numpy and Scipy. However, I wanted to see if there is another way to call the .net libraries and be able to use python to implement my control and data analysis algorithms?
tagged with: python
type: Question

http://stackoverflow.com/comment/82765909
has text: I have some raw bytes, and they are either HTTP request or response, I want to parse them both.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47687312
type: Comment

http://stackoverflow.com/comment/82210028
score: 0
type: AnswerComment
has text: I tried using textwrap.wrap() but that did not fulfill the requirement of not splitting words, if a word makes the line length more than 16, that word should be put on the next line.
type: Comment
comment on: http://stackoverflow.com/a/47626051

http://stackoverflow.com/comment/82282478
comment on: http://stackoverflow.com/q/47661559
type: Comment
score: 0
has text: Reading template file is just a piece of my project. I just want to make sure the function works properly so I can continue.
type: QuestionComment

http://stackoverflow.com/comment/82285611
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47663138
has text: The second line would replace the value of graph[1] to 5

http://stackoverflow.com/comment/82056415
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47549303
has text: I got a `TypeError: '<' not supported between instances of 'str' and 'NoneType'` in cases where no character after the number was present. I'd suggest changing it to `return int(n), s if s else ''` in the comp function. Also, maybe an improvement maybe not, the regex can be added to the signature of the comp function, avoiding clutter in the global namespace, i.e. `def comp(x, p=re.compile(r"(\d+)(.*)")):`

http://stackoverflow.com/comment/82093906
type: AnswerComment
has text: see https://docs.djangoproject.com/en/1.11/topics/http/urls/#reversing-namespaced-urls
score: 1
comment on: http://stackoverflow.com/a/47568178
type: Comment

http://stackoverflow.com/q/47573519
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/82112813
has title: dask read_sql error when querying from MYSQL
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: mysql
type: Question
tagged with: dask
has comment: http://stackoverflow.com/comment/82108317
has comment: http://stackoverflow.com/comment/82108387
has body: I am using python 2.7 with dask and trying to query a db table from a remote machine to a dask dataframe I have a multiple column index in the table, and I try to read it using the following script ddf = dd.read_sql_table("table name", "mysql://user:pass@ip:port/Dbname",spesific column name).head() And getting the following error start = asanyarray(start) * 1.0 TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32') I got the sqlalchemy uri as explained here i'm not sure what's the problem, when I try to query by another column as the index, and only use the ddf head(), i don't get an error, and when I try to compute the whole ddf i get the same error, i assume it's an issue regarding the column not being of unique values, I don't have a single column index, but multiple column, what is the solution to read the entire table here? Thanks. full traceback &gt; Traceback (most recent call last): File "path", line 28, in &lt;module&gt; &gt; ddf = dd.read_sql_table("tablename", "mysql://user:pass@ip:port/dbname","indexcolumn") File "file", line &gt; 123, in read_sql_table &gt; divisions = np.linspace(mini, maxi, npartitions + 1).tolist() File &gt; "/home/user/.local/lib/python2.7/site-packages/numpy/core/function_base.py", &gt; line 108, in linspace &gt; start = asanyarray(start) * 1.0 TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('S32') &gt; dtype('S32') dtype('S32')
accepted answer: http://stackoverflow.com/a/47583816
has comment: http://stackoverflow.com/comment/82106762
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47583816
has comment: http://stackoverflow.com/comment/82114999
has comment: http://stackoverflow.com/comment/82104404

http://stackoverflow.com/comment/82122309
comment on: http://stackoverflow.com/q/47579112
score: 1
type: Comment
type: QuestionComment
has text: There are two options: if you know if a string that *cannot* appear in any input file, you can simply write that to the output stream between files. Otherwise, a safer idea is to write the file size to the stream *before* the file, so that a consumer knows that after reading a file size, the next X bytes are all part of the same file. After reading that many bytes, the next input should be another file size. Basically, you need some sort of protocol for encoding multiple files into one stream that both `script1.py` and `script2.py` will agree on.

http://stackoverflow.com/comment/82239831
score: 1
type: Comment
type: AnswerComment
has text: Wow what a silly mistake. Thank you @pycoder
comment on: http://stackoverflow.com/a/47640580

http://stackoverflow.com/comment/82264529
has text: Can you be more specific about what you want? You've defined it by exclusion - "outside the protocol". That leaves ... an infinite number of other possibilities. Can you just edit your question to say what you want to do (instead of what you don't)?
type: Comment
comment on: http://stackoverflow.com/q/47650933
type: QuestionComment
score: 0

http://stackoverflow.com/a/47625978
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/82214104
upvote count: 6
has comment: http://stackoverflow.com/comment/82242803
answers question: http://stackoverflow.com/q/47619836
has body: I think I can explain the problem in your code. The OS error appears to be: " ERROR_DS_RIDMGR_DISABLED 8263 (0x2047) The directory service detected the subsystem that allocates relative identifiers is disabled. This can occur as a protective mechanism when the system determines a significant portion of relative identifiers (RIDs) have been exhausted. " via https://msdn.microsoft.com/en-us/library/windows/desktop/ms681390 I think you exhausted a significant portion of the RIDs at this step in your code: dataset['description'] = dataset['description'].apply(lambda x: list(set([lemmatizer.lemmatize(item,tag) for item in x]))) You're passing a lemmatizer in your lambda, but lambdas are anonymous, so it looks like you might be making 2.2 million copies of that lemmatizer at runtime. You should try changing the low_memory flag to true whenever you have a memory issue. Response to comment- I checked the Pandas documentation, and you can define a function outside of dataset['description'].apply(), and then reference that function in the call to dataset['description'].apply(). Here is how I would write said function. def lemmatize_descriptions(x): return list(set([lemmatizer.lemmatize(item,tag) for item in x])) Then, the call to apply() would be- dataset['description'] = dataset['description'].apply(lemmatize_descriptions) Here is the documentation.
accepted answer of: http://stackoverflow.com/q/47619836
type: Answer
has comment: http://stackoverflow.com/comment/82214277
type: AcceptedAnswer

http://stackoverflow.com/q/47657406
has comment: http://stackoverflow.com/comment/82392624
score: 0
has comment: http://stackoverflow.com/comment/82314214
has comment: http://stackoverflow.com/comment/82335941
has comment: http://stackoverflow.com/comment/82380676
has comment: http://stackoverflow.com/comment/82356553
has answer: http://stackoverflow.com/a/47729617
has comment: http://stackoverflow.com/comment/82397569
has comment: http://stackoverflow.com/comment/82354533
answer count: 1
has comment: http://stackoverflow.com/comment/82392553
type: Question
has comment: http://stackoverflow.com/comment/82302901
has comment: http://stackoverflow.com/comment/82356097
has comment: http://stackoverflow.com/comment/82354179
has title: Unable to fetch data by checking if one list is equal to other list in django
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82356305
has comment: http://stackoverflow.com/comment/82412308
has comment: http://stackoverflow.com/comment/82374664
tagged with: django
has comment: http://stackoverflow.com/comment/82276010
tagged with: python
has comment: http://stackoverflow.com/comment/82355435
has body: I am new to Django and I am trying to fetch records from the table UserBookmark where tag is equal to category. My code is as follows: views.py: def home(request): category=Category.objects.values_list('category',flat = True).filter(user=request.user.pk) category = list(category) print category bookmarks = UserBookmark.objects.filter(tag__name__in = category) print bookmarks return render(request,'home.html',{'bookmarks':bookmarks}) models.py: class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) def __str__(self): return '%s %s'%(self.user,self.category) class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) But when I print bookmarks in views.py , I get an empty set.I tried printing category as well , it gives : u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"] And when I try this in shell: UserBookmark.objects.filter(tag__name__in = [u'Data Science', u'Python', u'Android', u'Data Analytics']) I do get a resultset &lt;QuerySet [&lt;UserBookmark: 24 user12 https://github.com/shreyag12?tab=stars&gt;, &lt;UserBookmark: 24 user12 https://github.com/swapnil?tab=stars&gt;, &lt;UserBookmark: 26 user13 https://github.com/retme7/My-Slides&gt;, &lt;UserBookmark: 26 user13 https://github.com/retme7/My-Slides&gt;, &lt;UserBookmark: 26 user13 https://github.com/retme7/My-Slides&gt;, &lt;UserBookmark: 27 user14 https://github.com/sunny2krGupta/Bigquery-series&gt;, &lt;UserBookmark: 28 user14 https://github.com/ctfs/write-ups-2017&gt;]&gt; Can someone guide me in this?
has comment: http://stackoverflow.com/comment/82275659

http://stackoverflow.com/a/47683913
accepted answer of: http://stackoverflow.com/q/47683644
score: 0
has comment: http://stackoverflow.com/comment/82401158
answers question: http://stackoverflow.com/q/47683644
type: AcceptedAnswer
has body: Select all columns of a dataframe as a StructType from pyspark.sql.functions import struct, lit commonA = dfA.select("time", struct(*[c for c in df.columns]).alias("dfA")) commonB = dfB.select("time", struct(*[c for c in df.columns]).alias("dfB")) but this cannot be unioned as described. You could: commonA_ = commonA.select("time", "dfA", lit(None).cast(dfB.schema).alias("dfB")) commonB_ = commonB.select("time", lit(None).cast(dfA.schema).alias("dfA"), "dfB") commonA_.union(commonB_) but it sounds you are looking for something more like outer join dfA.alias("A").join(dfB.alias("B"), ["time"], "fullouter")
type: Answer

http://stackoverflow.com/a/53735000
has body: Mypy is correct in flagging your function calls. The following code illustrates why: def func(str_arg='x', float_arg=3.0): # type: (str, float) -> None print(str_arg, float_arg) kwargs1 = {'float_arg': 8.0} kwargs2 = {'str_arg': 13.0} # whoops func(float_arg=5.0) # prints "x 5.0" -- good func(**kwargs1) # prints "x 13.0" -- good but flagged by Mypy func(**kwargs2) # prints "13.0 3.0" -- bad In this example, kwargs1 and kwargs2 are both of type Dict[str, float]. The type checker does not consider the content of the keys, only their types, so the second and third calls to func look identical to Mypy. They must either both be errors or both be acceptable, and they can't both be acceptable since the third call violates the type system. The only way that the type checker can be sure that you're not passing incorrect types in the dict is if all of the arguments that haven't been explicitly passed share the type of the dict's values. Note, however, that mypy will not protect you from errors caused by respecifying a keyword argument in a dict: # This works fine: func('x', **kwargs1) # This is technically type safe and accepted by mypy, but at runtime raises # `TypeError: func() got multiple values for argument 'str_arg'`: func('x', **kwargs2) There is some further discussion of this issue here.
type: Answer
score: 12
upvote count: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47632128
answers question: http://stackoverflow.com/q/47632128

http://stackoverflow.com/q/47616292
tagged with: self
answer count: 5
has answer: http://stackoverflow.com/a/75432204
type: UnansweredQuestion
has title: Calling python class method which has no argument
has answer: http://stackoverflow.com/a/64151733
has comment: http://stackoverflow.com/comment/82190923
tagged with: python
tagged with: parameter-passing
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47616371
has answer: http://stackoverflow.com/a/72208276
downvote count: 0
has body: I am new to python (coming from the c++ world) and was experimenting with class methods. I created a method without any argument (purposefully avoided self argument in this case). Then I tried to call it class car: def car_method(): print("Inside Car method") obj = car_method() obj.car_method() <---- this creates error: TypeError: car_method() takes 0 positional arguments but 1 was given I think this error is because, In Python, every class method, when called is always passed at least one argument which is that object's reference. am I correct? Then to experiment further, I wrote obj.car_method <----- assuming I am not passing any argument to it but the function printed nothing. Then I tried to print the type of it using print(obj.car_method) which resulted in bound method car.car_method of <__main__.car object at 0x005D2290> Can anyone explain what is going on here? How do I 'call' the car_method? If there is no way to call the car_method, why does python let me define the method without any argument? I am trying to get a good grasp on the basics here. Can I even call car_method as a class method? or it is just a method defined inside a class?
tagged with: class-method
has answer: http://stackoverflow.com/a/47616352
linked to: http://stackoverflow.com/q/12179271
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47574255
favorite count: 0
tagged with: google-oauth
has answer: http://stackoverflow.com/a/75538903
type: Question
tagged with: google-sheets
has body: So I'm running this code from the tutorial but can't even get through the authorization process. import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/oauth.json', scope) gc = gspread.authorize(credentials) table = gc.openall() After n minutes of waiting when I interrupt the process, I see that it hangs on File "/usr/lib/python3.5/http/client.py", line 1252, in connect super().connect() File "/usr/lib/python3.5/http/client.py", line 849, in connect (self.host,self.port), self.timeout, self.source_address) File "/usr/lib/python3.5/socket.py", line 702, in create_connection sock.connect(sa) KeyboardInterrupt executing this method gspread.authorize(credentials). Do you have any idea what could be the problem? I tried with multiple oauth jsons so I guess it's not a problem on Google's side. I tried reading the json and passing args on my own with the same result. I created json files from two different Google accounts, one of which is in the company domain, with the same result. I'm running the code on Ubuntu 16.04, PyCharm 2017.2.4, with Python 3.5 and gspread 0.6.2. Edit: The exact same problem occurs on Jupyter Notebook.
tagged with: python
type: UnansweredQuestion
tagged with: gspread
has answer: http://stackoverflow.com/a/75299967
tagged with: http://stackoverflow.com/tag/json
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/67159193
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/78450537
has title: Gspread stuck on authorization

http://stackoverflow.com/q/47561142
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47561552
tagged with: windows
tagged with: wifi
has body: I am trying to connect to a romba robot via wifi. I have successfully been able to use the below code to open the cmd and connect to the wifi and send its password. This connects the bot and the computer successfully. My problem is when I try to send additional information. I am only attempting to pass one character at a time. I am using the subprocess and pipe functionality to send data, but when I try to use this a second time, it gives me the error "Cannot send input after starting communication" Can someone please point out what I am doing wrong? #Connects the the desired WiFi network. def connect_to_network(name): global Network #global Putty Network = Popen('netsh wlan connect ' + str(name), shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE) password = "password" Network.communicate(input=password.encode('utf-8')) Network.stdin.close() #Putty = Application(backend="uia").start('putty.exe -raw 192.168.1.1') #Sends out character to BOT via WiFi. def WiFi_Send(action): global Network #global Putty clear_output() print("Sending: " + str(action)) #PACKET TO SEND packet = "" if(action == "SCAN"): packet = "S" elif(action == "MOVE FORWARD"): packet = "F" elif(action == "TURN LEFT"): packet = "L" elif(action == "TURN RIGHT"): packet = "R" Network.communicate(input=packet.encode('utf-8')) Network.stdin.close() output: Sending: SCAN --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-2-c2f5d752b649&gt; in &lt;module&gt;() 341 # call in value. (Waits for it to start) 342 if __name__ == "__main__": --&gt;343 main() &lt;ipython-input-2-c2f5d752b649&gt; in main() 326 buttonFlag = 0 327 actionComplete = True --&gt; 328 WiFi_Send(action) 329 break 330 elif(B_button): &lt;ipython-input-2-c2f5d752b649&gt; in WiFi_Send(action) 172 packet = "R" 173 --&gt; 174 Network.communicate(input=packet.encode('utf-8')) 175 Network.stdin.close() 176 ~\Anaconda3\lib\subprocess.py in communicate(self, input…
score: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47561552
type: Question
upvote count: 2
has title: Python wifi subprocess & communication errors
tagged with: python
answer count: 1
tagged with: putty
tagged with: subprocess

http://stackoverflow.com/q/47666825
has comment: http://stackoverflow.com/comment/82326398
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82323462
linked to: http://stackoverflow.com/q/43118879
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/82323690
has comment: http://stackoverflow.com/comment/82323216
has comment: http://stackoverflow.com/comment/82335203
tagged with: python
has body: In the Google App Engine app.yaml file, you specify a version property (though the current preference instead of app.yaml: "...instead, use a command-line flag (--version) to specify your version ID"). In my case, I use this for different environments. (See note at bottom) As documented in app.yaml, unique version values produce unique URLs: Note: Version names should begin with a letter, to distinguish them from numeric instances which are always specified by a number. This avoids the ambiguity with URLs like 123.my-service.appspot.com... I use two versions, the first as my "QA environment" , the second as my "Production environment": dev 1 I want my code to set a variable is_prod, and I want the value to be a boolean True if the version value is equal to 'dev'. How can I do that? *Note, as @Dan Cornilescu says in the comments, using-versions-for-environments may be a bad idea, per posts like this and this
has comment: http://stackoverflow.com/comment/82312732
linked to: http://stackoverflow.com/q/40192557
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43218971
has answer: http://stackoverflow.com/a/47666848
has title: How to tell which version of Google App Engine is running
answer count: 1
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82096154
has text: You could always base64 encode your image, send that to the server and then decode it. It's how I usually handle image transfers over HTTP
type: Comment
comment on: http://stackoverflow.com/q/47569320
type: QuestionComment
score: 0

http://stackoverflow.com/q/47587329
tagged with: jupyter-notebook
type: Question
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
has body: I am very new to coding and using the terminal and everything of the sorts. I want to use jupyter notebook but when I run it it gives me this Kernel Error: Traceback (most recent call last): File "C:\Users\saiya\Anaconda3\lib\site-packages\notebook\base\handlers.py", line 516, in wrapper result = yield gen.maybe_future(method(self, *args, **kwargs)) File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "&lt;string&gt;", line 4, in raise_exc_info File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\saiya\Anaconda3\lib\site-packages\notebook\services\sessions\handlers.py", line 75, in post type=mtype)) File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "&lt;string&gt;", line 4, in raise_exc_info File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\saiya\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 79, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "&lt;string&gt;", line 4, in raise_exc_info File "C:\Users\saiya\Anaconda3\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\saiya\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 92, in sta…
tagged with: terminal
has answer: http://stackoverflow.com/a/55957551
tagged with: anaconda
score: 1
has title: Kernel Error with Jupyter Notebook (Anaconda) Setup, New to computers
tagged with: python
tagged with: kernel

http://stackoverflow.com/comment/82041355
score: 0
type: Comment
has text: `data_file1.isnull().sum(0)` <- per column; `data_file1.isnull().sum().sum()` <-- df wide NaNs.
type: QuestionComment
comment on: http://stackoverflow.com/q/47542073

http://stackoverflow.com/comment/82070299
score: 0
comment on: http://stackoverflow.com/q/47555140
type: Comment
has text: Thankyou, I have edited the post to include, the actual code. If there is anything else that I need to include, please say.
type: QuestionComment

http://stackoverflow.com/a/47594148
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47588167
has body: ITransport will notify its IProtocol of the loss-of-connection event by calling connectionLost on the IProtocol provider. Therefore, if you want to react to that event, you should implement connectionLost on your protocol (ClientTelnetProtocol in this case, it appears?) and put your application logic in that method. This method is called as soon as the ITransport implementation knows the connection has been lost so it should serve your needs (note that it is not an interrupt because Twisted is a (largely) single-threaded cooperative multi-tasking system; so if you have application code that blocks (for example, clientsocket.connect) Twisted won't call any of your callbacks until that completes and the reactor regains control. But as soon as it is given the chance, it will dispatch events (such as connection lost) to handlers (such as connectionLost). I don't understand why your sample code uses the socket module directly to create and then discard a connection to the destination address. My guess is that you're trying to determine if the server is accepting connections or not. In this case, you may want to use the ClientFactory method clientConnectionFailed to detect that the connection attempted by reactor.connectTCP has failed rather than using the socket module and checking for an exception. You could also use Twisted's endpoint abstraction to get this notification as a Deferred callback instead. You may also be interested in Tubes which provides an even higher-level abstraction over data flow.
downvote count: 0
has comment: http://stackoverflow.com/comment/82158099

http://stackoverflow.com/comment/82049292
type: QuestionComment
has text: Assuming that the td's without links in them are always the ones holding description, they should be pretty easy to get at: xpath('//td[not(a)]')
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47544194

http://stackoverflow.com/comment/82333960
comment on: http://stackoverflow.com/q/47680573
type: Comment
type: QuestionComment
has text: What version of `rasterio` are you using? Not that this seems particularly likely to be the problem, but `rasterio.plot.show` only began using the extent of the raster in 0.32.
score: 0

http://stackoverflow.com/comment/82291958
comment on: http://stackoverflow.com/q/47666302
type: Comment
type: QuestionComment
score: 0
has text: Does your url work if you put it into the browser? I'm guessing yes, but just want to check.

http://stackoverflow.com/a/47588776
score: -3
has body: You can use: print(dictionary[IntTensor.data[0]]) The key you're using is an object of type autograd.Variable. .data gives the tensor and the index 0 can be used to access the element.
downvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47588682
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47588682

http://stackoverflow.com/comment/82137400
comment on: http://stackoverflow.com/q/47590051
type: Comment
type: QuestionComment
score: 0
has text: What have you tried that didn't work ?

http://stackoverflow.com/a/47545241
accepted answer of: http://stackoverflow.com/q/47545052
has comment: http://stackoverflow.com/comment/82047680
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47545052
has body: A full implementation of what you want can be found here: series_set = df.apply(frozenset, axis=1) new_df = series_set.apply(lambda a: series_set.apply(lambda b: jaccard(a,b)))
has comment: http://stackoverflow.com/comment/82047532
has comment: http://stackoverflow.com/comment/82047586
has comment: http://stackoverflow.com/comment/82047644
has comment: http://stackoverflow.com/comment/82047553
downvote count: 0
has comment: http://stackoverflow.com/comment/82047795
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82047399
type: Answer

http://stackoverflow.com/q/47593834
answer count: 0
upvote count: 3
score: 3
downvote count: 0
has body: I am unable to get WinRM session in a python script. Client - 2012 R2 Client is a Domain member. user01 is a non domain account and member of Local administrators group. I have tried setting winrm basic or kerberos to false. I even tried with local administrator account but still same error. Both ntlm and ssl were not working. After setting LocalAccountTokenFilterPolicy registry to 1 this works: p = Protocol( endpoint='https://X.X.X.X:5986/wsman', transport='ntlm', username='user01', password='admin@123', server_cert_validation='ignore') p.open_shell() SSL is not working: p = Protocol( endpoint='https://X.X.X.X:5986/wsman', transport='ssl', username='user01', password='admin@123', server_cert_validation='ignore') p.open_shell() Error: InvalidCredentialsError("the specified credentials were rejected by the server") winrm.exceptions.InvalidCredentialsError: the specified credentials were rejected by the server
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: InvalidCredentialsError("the specified credentials were rejected by the server")
tagged with: python
tagged with: winrm

http://stackoverflow.com/comment/82122826
has text: Using `-e` seems to only create an "egg-info" file in the `site-packages` dir, it doesn't actually install the whole package (apparently). So, it doesn't seem like there's any package to which I can symlink?
type: Comment
comment on: http://stackoverflow.com/a/47565333
score: 0
type: AnswerComment

http://stackoverflow.com/a/47598598
answers question: http://stackoverflow.com/q/47598311
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/82155932
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47598311
has body: If your values are ordered, like in the example data, this is possible in logarithmic time using bisection: &gt;&gt;&gt; vals = [210418, 211120, 211822, 212523, 213500] &gt;&gt;&gt; target = 210944 &gt;&gt;&gt; from bisect import bisect_left &gt;&gt;&gt; i = bisect_left(vals, target) &gt;&gt;&gt; if i == 0: ... raise Exception ... &gt;&gt;&gt; vals[i-1] 210418 If they are not ordered, consider numpy: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array(vals) &gt;&gt;&gt; a[a&lt;target].max() 210418
has comment: http://stackoverflow.com/comment/82155520

bluez
tags question: http://stackoverflow.com/q/47668125
tag name: bluez
type: Tag

http://stackoverflow.com/comment/82218392
score: 0
type: Comment
has text: I tried. It take about 1.5 sec and it's too much
type: QuestionComment
comment on: http://stackoverflow.com/q/47630287

http://stackoverflow.com/comment/82321832
type: QuestionComment
has text: Hi, I still don't understand how to fix the collision between my powerup and my bullets. First, my bullets aren't moving towards the right of the screen, despite me updating it. Also, whenever the bullet collides with the ramen, both are supposed to disappear.
score: 0
comment on: http://stackoverflow.com/q/47670635
type: Comment

fluentd
tag name: fluentd
type: Tag
tags question: http://stackoverflow.com/q/47694878

http://stackoverflow.com/comment/82089191
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47565589
has text: Thanks! I was hoping I could accept both `str` and `int` inputs, is that possible?
type: Comment

http://stackoverflow.com/q/47548953
tagged with: dictionary
upvote count: 6
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47549240
has answer: http://stackoverflow.com/a/70524457
has answer: http://stackoverflow.com/a/58143440
has comment: http://stackoverflow.com/comment/82054391
downvote count: 3
has body: I am working in Python project and I have a problem seem as what I explain below but with other data. For example, if I have this dict: fruitsCount= {"apple": 24, "orange": 20, "banana":18, "grape":13, "kiwi": 13} how can I return the keys with maximum values ? what if I want to return three largest ? I used heapq.nlargest(3, fruitCount.values) but I don't know how I return them with their keys Note: fruitsCount is a dict returned after using Counter() from another dict. Output: should be same fruitsCount dictionary with n largest fruitsCount.values
has comment: http://stackoverflow.com/comment/82054501
accepted answer: http://stackoverflow.com/a/47549005
favorite count: 0
possible better answer: http://stackoverflow.com/a/47549240
type: Question
has answer: http://stackoverflow.com/a/47549005
score: 3
has title: Find n largest values from dictionary
tagged with: python

http://stackoverflow.com/q/47686116
has comment: http://stackoverflow.com/comment/82332065
has answer: http://stackoverflow.com/a/47686495
accepted answer: http://stackoverflow.com/a/47686495
tagged with: python
has title: Trouble removing hidden parts of a string
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82331924
answer count: 2
has answer: http://stackoverflow.com/a/47686670
possible better answer: http://stackoverflow.com/a/47686670
score: 1
upvote count: 1
has body: I'm trying to use a scraped string with BeautifulSoup in a simple calculation. The interpreter gives a base 10 error, indicating that there's hidden characters in the string. This turned out to be true, because the console outputs the raw string including hidden data as: 2.177 ['\n\n2.177'] 2.177 is the number I'm trying to work with here. ['\n\n2.177'] is a hidden part of the string. Since it won't cast to int because of the hidden values however I can't make any calculations on it. I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters. Mine are sadly not special. Does anyone know how to remove this part of the string?
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/q/47567263
has answer: http://stackoverflow.com/a/55862183
upvote count: 2
has comment: http://stackoverflow.com/comment/82130772
tagged with: http-redirect
downvote count: 0
tagged with: flask
tagged with: unit-testing
has title: How to avoid "ClientRedirectError: loop detected" error during testing Flask application (and how is it triggered)?
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82131098
has comment: http://stackoverflow.com/comment/82126374
answer count: 1
tagged with: python
has body: Environment: Python 3.6.1 Flask 0.12.2 Werkzeug 0.14.1 While writing tests for my Flask application, I have discovered the following peculiarity: if in tests for Flask application you will be redirected to the same url two times 'in a row' ClientRedirectError: loop detected will be thrown, even if it stops redirecting after the second redirect (i.e. loop is not, actually, happening). Consider the following, simplified, example: app.py from flask import ( Flask, redirect, url_for, session ) app = Flask(__name__) app.secret_key = 'improper secret key' @app.route('/') def index(): if not session.get('test', False): session['test'] = True return redirect(url_for('index')) else: return "Hello" @app.route('/redirection/') def redirection(): # do something — login user, for example return redirect(url_for('index')) test_redirect.py from unittest import TestCase from app import app class RedirectTestCase(TestCase): def setUp(self): self.test_client = app.test_client() def testLoop(self): response = self.test_client.get('/redirection/', follow_redirects=True) self.assertTrue('Hello'.encode('ascii') in response.data) Now, if I will run the test — it'll throw a ClientRedirectError: loop detected (even though, it could be seen from the code that second redirect will happen only once). If I just run the app and go to the /redirection/ — it takes me to the index (i.e. /) with no problem, and no looping is happening. The reason I need if not session.get('test', False): in index(), is because in my app I'm using it to set some things in session, in case user accessing / for the first time. As suggested by comment in code, in my 'real' app redirection() is a function that logs user in. My questions are: Is there a 'right' way to overcome throwing of ClientRedirectError: loop detected in similar cases (i.e. is it possible to make the test run &amp; pass)? Is there a better/'more correct' way to setup things in session for the 'first-time' user? Can mentioned behaviour be considered a…
favorite count: 0
type: Question
tagged with: flask-testing
accepted answer: http://stackoverflow.com/a/55862183

http://stackoverflow.com/comment/82186595
has text: Not quite right. If you close the file, it only results in an `ValueError`. You need to exit the function/program once the control is returned from `startQuiz()`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47613677
type: Comment

http://stackoverflow.com/comment/82251501
has text: Thank you! Your example works, and should do exactly what I need. For simplicity reasons, would it be better to put the ItemWidget class under TestMainWindow, and if I did so, would creating a method such as addItemWidget work in that instance? I just want to understand that a little more
comment on: http://stackoverflow.com/a/47646332
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82041965
has text: See here: https://stackoverflow.com/questions/8282231/i-have-python-on-my-ubuntu-system-but-gcc-cant-find-python-h
comment on: http://stackoverflow.com/q/47542282
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82189116
has text: Have you startup the server? Are there any errors in the log?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47615323
type: Comment

http://stackoverflow.com/q/47684408
tagged with: wordpress
has answer: http://stackoverflow.com/a/47684579
favorite count: 0
type: Question
tagged with: vps
tagged with: server
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: ubuntu
has title: Simple script running on server and app communicating with it
has answer: http://stackoverflow.com/a/47684462
answer count: 2
has body: new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the request and how can the page/application receive the data back(like download link,or info like JSON). A simple information would suffice,i don't need a thorough explanation,mostly names like protocols,etc.. maybe some sample code for Hello World. I should add that my website runs with Wordpress and i am not looking to change that yet.I want to create a web app within wordpress,with the app written in Python.
downvote count: 3

http://stackoverflow.com/a/47696199
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47695939
has body: savetxt's default format for each field is '%.18e', which is a floating point format. Add the fmt argument to change the format, e.g. np.savetxt('filename', X, fmt='%s', delimiter=' ', header='Some Header')
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47695939

http://stackoverflow.com/comment/82045214
has text: You opened the file in text mode, so end-of-line conversions were performed. Use `'wb'` to write in binary mode instead.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47544053

http://stackoverflow.com/a/47553863
upvote count: 7
answers question: http://stackoverflow.com/q/47553832
type: Answer
accepted answer of: http://stackoverflow.com/q/47553832
has body: C.layers.Dense(hidden_layers_dim) returns a function which is being called with the argument h. You could also write it as: fun = C.layers.Dense(hidden_layers_dim) h = fun(h)
score: 7
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47554066
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47552045
has body: Alternate way to explode array without converting to rdd, from pyspark.sql import functions as F udf1 = F.udf(lambda x : x.split()[0]) df.select('index',F.explode('result').alias('id'),udf1(F.col('id')).alias('idtype')).show() +-----+-------------+------+ |index| id|idtype| +-----+-------------+------+ | 1|AA 1234 ZXYV| AA| | 1| BB A 890| BB| | 1| CC B 321| CC| | 2|AA 1234 LMNO| AA| | 2| BB D 123| BB| | 2| CC E 321| CC| | 3|AA 1234 ZXYV| AA| | 3| CC B 321| CC| +-----+-------------+------+ df1.groupby('index').pivot('idtype').agg(F.first('id')).join(df,'index').show()
score: 7
type: Answer

http://stackoverflow.com/comment/82240299
score: 0
comment on: http://stackoverflow.com/q/47640913
has text: Yes in modelPRank function where I call Prank.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82248884
has text: You didn't import `linalg.linalg`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47645024
type: Comment
score: 0

http://stackoverflow.com/comment/82203381
type: AnswerComment
score: 0
type: Comment
has text: curious - what would you then use other than python?
comment on: http://stackoverflow.com/a/47622586

http://stackoverflow.com/q/47617624
linked to: http://stackoverflow.com/q/519107
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64625750
possible better answer: http://stackoverflow.com/a/64625750
answer count: 2
tagged with: tagging
has body: I'm looking for a django app that provides a form-filed with taggit integration and a front end JS tagging library as mentioned here: jQuery autocomplete tagging plug-in like StackOverflow&#39;s input tags? Do I have to implement this myself or is there an existing django app that integrates django-taggit with a front-end tagging library. Ideally I would want auto-suggest and auto-complete. Admin integration would be nice. This will be useful for others too since every body wants SO like tagging or more advanced tagging.
tagged with: django-taggit
tagged with: django-tagging
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47617887
accepted answer: http://stackoverflow.com/a/47617887
upvote count: 1
downvote count: 1
tagged with: python
has title: Django taggit integration with frontend (auto-complete and auto-suggest)

http://stackoverflow.com/a/47637717
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82234309
answers question: http://stackoverflow.com/q/47635397
type: Answer
has comment: http://stackoverflow.com/comment/82234338
has body: Or we can using replace :-) ary=np.concatenate(df1.iloc[:,:2].values) mapdf=pd.DataFrame({'data':pd.Series(ary).astype('category').cat.codes.add(1),'maper':ary}).set_index('maper') df1'node1','node2'=df1'node1','node2'.replace(mapdf.data.to_dict()) df1 Out[1631]: node1 node2 weight 0 1 3 1 1 1 4 2 2 2 4 1 3 3 5 1

http://stackoverflow.com/comment/82131495
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47586948
has text: @COLDSPEED yes, you are definitely right! Thanks!
score: 0

http://stackoverflow.com/comment/82042013
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47542260
has text: I am using `version 4.3` of `libapache2-mod-wsgi` and my server MPM is `prefork` @GrahamDumpleton

http://stackoverflow.com/a/47683603
answers question: http://stackoverflow.com/q/47637578
type: Answer
has comment: http://stackoverflow.com/comment/137540422
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/102686503
has body: I've implemented my own solution for the problem. There's much room for improvements. E.g. randomly sorted coulomb matrix and bag of bonds are still not implemented. import numpy as np def get_coulombmatrix(molecule, largest_mol_size=None): """ This function generates a coulomb matrix for the given molecule if largest_mol size is provided matrix will have dimension lm x lm. Padding is provided for the bottom and right _| """ numberAtoms = len(molecule.atoms) if largest_mol_size == None or largest_mol_size == 0: largest_mol_size = numberAtoms cij = np.zeros((largest_mol_size, largest_mol_size)) xyzmatrix = [[atom.position.x, atom.position.y, atom.position.z] for atom in molecule.atoms] chargearray = [atom.atomic_number for atom in molecule.atoms] for i in range(numberAtoms): for j in range(numberAtoms): if i == j: cij[i][j] = 0.5 * chargearray[i] ** 2.4 # Diagonal term described by Potential energy of isolated atom else: dist = np.linalg.norm(np.array(xyzmatrix[i]) - np.array(xyzmatrix[j])) cij[i][j] = chargearray[i] * chargearray[j] / dist # Pair-wise repulsion return cij

http://stackoverflow.com/a/48683630
type: Answer
has body: Other way for several adjacent float fields. Here for 3 fields starting from 'x' we obtain same result with: np.ndarray((len(data),3), float, data, offset= data.dtype.fields['x'][1], strides= (data.strides[0], np.dtype(float).itemsize))
score: 0
answers question: http://stackoverflow.com/q/47550615

http://stackoverflow.com/q/47661930
downvote count: 0
upvote count: 1
tagged with: python
tagged with: key
favorite count: 0
score: 1
tagged with: pygame
tagged with: image
has comment: http://stackoverflow.com/comment/82283426
has answer: http://stackoverflow.com/a/70008872
type: Question
has body: I'm trying to let an image (transparent image) Rotate on the keys that I press. I.E. I want to rotate my player's head up and down(he is shooting from his head), but I don't really have a decent guideline on how to code this. If anyone could help me it would be greatly appreciated. Also I wanted the head just to smoothly rotate(aim) up and down when I hold the keys down. Code below: import pygame pygame.init() white = (255,255,255) BLACK = (0,0,0) red = (255,0,0) gameDisplay = pygame.display.set_mode((640,360)) background = pygame.image.load('background.jpg').convert() player = pygame.image.load('BigShagHoofdz.png') #this must be rotateable pygame.display.set_caption('Leslie is Lauw') clock = pygame.time.Clock() gameDisplay.blit(background, [0,0]) gameDisplay.blit(player, [-1,223]) pygame.display.update() FPS = 60 direction = "Down" def head(): if direction == "Down": playerhead = player if direction == "Up": playerhead = pygame.transform.rotate(player, 60) def gameLoop(): global direction gameExit = False while gameExit==False: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.key == pygame.KEYDOWN: if event.key == pygame.K_UP: direction = "Up" elif event.key == pygame.K_DOWN: direction = "Down" clock.tick(60) pygame.quit() quit() It should only rotate up or down when I press the up or down key, maybe let it go smooth when it's held down or up.
tagged with: rotation
answer count: 2
has comment: http://stackoverflow.com/comment/82283562
has comment: http://stackoverflow.com/comment/82283799
type: UnansweredQuestion
has title: How to rotate my image using Keys in pygame?
has answer: http://stackoverflow.com/a/47662415

http://stackoverflow.com/comment/82185471
comment on: http://stackoverflow.com/a/47613423
score: 0
type: Comment
has text: You are going to have to do better than that to convince me @juanpaarrivillaga - if you need a `Person` to access a collection of `Persons`, it is surely better to give them a pointer to a collection of `Persons`... Now you have a class `Person` that must do the housekeeping for the `Persons`!?!
type: AnswerComment

http://stackoverflow.com/comment/82159496
type: Comment
type: AnswerComment
has text: oh, wow... somehow I didn't even see the semi-colons until you explicitly mentioned it... And, yes, it works perfectly when you type it in right!
comment on: http://stackoverflow.com/a/47584917
score: 1

http://stackoverflow.com/q/47603905
possible better answer: http://stackoverflow.com/a/66858582
upvote count: 7
has answer: http://stackoverflow.com/a/66858582
favorite count: 0
type: Question
has title: How to bundle cx_oracle with Pyinstaller
tagged with: pyinstaller
tagged with: oracle-database
tagged with: python
type: AnsweredQuestion
has body: My goal is to use Pyinstaller to bundle an exe file from a simple python script that uses Tkinter and cx_oracle to access a database. The python code is developed on a windows machine with Anaconda, cx_oracle package and oracle client installed. Then I need to run the exe file in many target windows machines without oracle client or Python. I am using Python 2.7 and Pyinstaller 3.1 on the development machine. I searched quite a while online but only found one tutorial on this: https://mail.python.org/pipermail/tutor/2014-December/103608.html I followed the same procedure and modified the spec file as below: # -*- mode: python -*- block_cipher = None a = Analysis(['mycode.py'], pathex=['C:\\Users\\myuser\\PycharmProjects\\mycode'], binaries=None, datas=None, hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries + [('oraociei11.dll','D:\ProgramFiles\Anaconda2\oraociei11.dll','BINARY')], a.zipfiles, a.datas, name='mycode', debug=False, strip=False, upx=True, console=True ) the bundle worked. The code runs on the original machine with oracle client installed. But on a separate machine without oracle client, it failed to run, with the below error message: Exception in Tkinter callback Traceback (most recent call last): File "lib-tk\Tkinter.py", line 1537, in call File "", line 152, in login DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "The specified module could not be found". See https://oracle.github.io/odpi/doc/installation.html#windows for help Now I am very confused what are the required steps to safely bundle an exe from a python script with cx_oracle so that it can run on a windows machine without oracle client? Or do I "have to" install oracle client on the target machine? I really hope to find a more detailed tutorial on bundling cx_oracle with pyinstaller …
answer count: 2
accepted answer: http://stackoverflow.com/a/47604770
score: 7
tagged with: cx-oracle
has answer: http://stackoverflow.com/a/47604770
downvote count: 0

http://stackoverflow.com/q/47624129
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/47624194
type: Question
has answer: http://stackoverflow.com/a/47624194
downvote count: 0
tagged with: pyspark
answer count: 1
score: 6
has body: I am trying to standardize (mean = 0, std = 1) one column ('age') in my data frame. Below is my code in Spark (Python): from pyspark.ml.feature import StandardScaler from pyspark.ml.feature import VectorAssembler from pyspark.ml import Pipeline # Make my 'age' column an assembler type: age_assembler = VectorAssembler(inputCols= ['age'], outputCol = "age_feature") # Create a scaler that takes 'age_feature' as an input column: scaler = StandardScaler(inputCol="age_feature", outputCol="age_scaled", withStd=True, withMean=True) # Creating a mini-pipeline for those 2 steps: age_pipeline = Pipeline(stages=[age_assembler, scaler]) scaled = age_pipeline.fit(sample17) sample17_scaled = scaled.transform(sample17) type(sample17_scaled) It seems to run just fine. And the very last line produces: "sample17_scaled:pyspark.sql.dataframe.DataFrame" But when I run the line below it shows that the new column age_scaled is of type 'vector': |-- age_scaled: vector (nullable = true) sample17_scaled.printSchema() How can I calcualate anything using this new column? For example, I can't calculate a mean. When I try, it says it should be 'long' and not udt. Thank you very much!
favorite count: 0
type: AnsweredQuestion
tagged with: apache-spark
tagged with: scale
has title: How to standardize ONE column in Spark using StandardScaler?
linked to: http://stackoverflow.com/q/38384347

http://stackoverflow.com/q/47614346
tagged with: key-value
has title: Nested dictionary key and values
has comment: http://stackoverflow.com/comment/82187536
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82187107
upvote count: 0
has body: mydict = {'Papa': {12: {45: {'AG'}}}} mydict['Rocks']['Big'] = 'black' &gt;&gt;&gt;print(mydict) {'Papa': {Marbles: {Small: {'blue'}}}, {'Rocks': {'Big': {'black'}} [evaluate asdf.py] Traceback (most recent call last): File "C:/Users/Justin/asdf.py", line 2, in &lt;module&gt; mydict['Rocks']['Big'] = 'black' builtins.KeyError: 'Rocks' I'm getting a key error...
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/47614429
tagged with: python
score: -2
tagged with: key
has answer: http://stackoverflow.com/a/47614429
type: AnsweredQuestion

http://stackoverflow.com/comment/82330649
type: QuestionComment
score: 0
has text: Windows doesn't care, but Python launcher does. Those are two very different things ;)
type: Comment
comment on: http://stackoverflow.com/q/47685251

http://stackoverflow.com/comment/82479994
type: QuestionComment
comment on: http://stackoverflow.com/q/47618622
score: 0
has text: @ekhumoro Thank you so much I could able to implement callback function successfully. But I have small error with pause & Restart of pool.apply_async method. please read my description and can you give me some hints now.
type: Comment

http://stackoverflow.com/comment/82306257
has text: Check this links also [click_here_1](https://stackoverflow.com/questions/47670856/connecting-to-mssql-server-2017-from-apache-http-server-via-python-script) [click_here_2](https://stackoverflow.com/questions/47672851/how-to-print-exception-raised-in-python-via-web-browser)
comment on: http://stackoverflow.com/a/47661995
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82346691
score: 1
has text: if the label are not unique we can do this [{'label':label} for label in df['label'].unique()]
type: Comment
comment on: http://stackoverflow.com/a/47693600
type: AnswerComment

http://stackoverflow.com/a/47629009
type: Answer
accepted answer of: http://stackoverflow.com/q/47603024
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47603024
has comment: http://stackoverflow.com/comment/82242129
has body: Webots needs that you call the robot.step(timeStep) function on a regular basis in order to progress on the simulation time, otherwise it will simply stop the simulation and wait until the next call to robot.step(timeStep). I would simply add a call to robot.step(timeStep) in your main loop, right before self._clock.tick(30) and uncomment the initialization of timeStep in your main program. Note that if your Webots simulation is running in real time, calling robot.step(X) will last approximately X milliseconds. So you should probably set the WorldInfo.basicTimeStep to 30 milliseconds in your world file and get rid of the call to self._clock.tick(30).
score: 1

http://stackoverflow.com/a/47606983
has body: Firstly I'm assuming your input file contains binary data and not character data (i.e. hex characters). What makes this non-trivial is that the file format is not aligned on byte boundaries (3x 12 bits then 1x 10 bits then 2x 1 bit) and so some bit twiddling is needed. If we examine the format for a single measure we have this: # 0xF4 0x1F 0x9E 0X08 0x20 0x00 # --------- --------- --------- --------- --------- ------------ # 0xF 0x4 0x1 0xF 0x9 0xE 0x0 0x8 0x2 0x0 0x0 0x0 # 1111 0100 0001 1111 1001 1110 0000 1000 0010 0000 0000 00 0 0 The alignment we want is: # x-axis y-axis z-axis light b r # -------------- -------------- -------------- ------------ - - # 1111 0100 0001 1111 1001 1110 0000 1000 0010 0000 0000 00 0 0 Therefore to get the interpretation you want we need to do some bit manipulation. The below shows how to do this long-hand (there are likely APIs to help made this simpler): MEASURE_SIZE_BYTES = 6 MEASURES_PER_PAGE = 300 PAGE_SIZE_BYTES = MEASURE_SIZE_BYTES * MEASURES_PER_PAGE def readPage(data): measures = [] for measure in xrange(0, MEASURES_PER_PAGE): i = measure * MEASURE_SIZE_BYTES xAxis = (data[i] &lt;&lt; 4) + (data[i + 1] &gt;&gt; 4) yAxis = ((data[i + 1] &amp; 0xF) &lt;&lt; 8) + (data[i + 2]) zAxis = (data[i + 3] &lt;&lt; 4) + (data[i + 4] &gt;&gt; 4) light = ((data[i + 4] &amp; 0xF) &lt;&lt; 8) + (data[i + 5] &amp; 0xFC) button = (data[i + 5] &amp; 0x2) &gt;&gt; 1 reserved = (data[i + 5] &amp; 0x1) &gt;&gt; 0 measures.append({'xAxis': hex(xAxis), 'yAxis': hex(yAxis), 'zAxis': hex(zAxis), 'light': hex(light), 'button': hex(button), 'reserved': hex(reserved)}) return measures with open("data.bin", 'rb') as f: pages = [] pageBytes = bytearray(f.read(PAGE_SIZE_BYTES)) while len(pageBytes) == PAGE_SIZE_BYTES: pages.append(readPage(pageBytes)) pageBytes = bytearray(f.read(PAGE_SIZE_BYTES)) print(pages) Produces (for a single page/measure): [[{'reserved': '0x0', 'yAxis': '0xf9e', 'light': '0x0', 'button': '0x0', 'zAxis': '0x82', 'xAxis': '0xf41'}]] …
answers question: http://stackoverflow.com/q/47605357
score: 0
has comment: http://stackoverflow.com/comment/82172954
type: Answer

http://stackoverflow.com/comment/82334605
type: Comment
has text: @ManojJadhav Well, it started executing twice before I started working on nameConfirmation() at all.
score: 0
comment on: http://stackoverflow.com/q/47687450
type: QuestionComment

http://stackoverflow.com/q/47690610
tagged with: python
type: UnansweredQuestion
tagged with: openshift
has comment: http://stackoverflow.com/comment/82346129
tagged with: openshift-origin
score: 0
tagged with: openshift-3
has comment: http://stackoverflow.com/comment/82349064
answer count: 0
has body: I have a python application that needs to be run 24/7. I have employed openshift to do this. I have managed to get the files up on openshift. However if I want to execute this application, how do I go about doing this. This particular application has an executable python file that needs to be run to run the application. Any help is greatly appreciated
has comment: http://stackoverflow.com/comment/82374652
has comment: http://stackoverflow.com/comment/82389113
has title: Openshift Python Execution
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/82389303

http://stackoverflow.com/comment/82179997
comment on: http://stackoverflow.com/a/47609561
type: AnswerComment
type: Comment
has text: @ zck We are almost done. Thank you. So: 1. How to edit that plot, I would like it to look like I'll add another picture.
score: 0

http://stackoverflow.com/q/47630127
score: 0
answer count: 1
tagged with: schedule
has answer: http://stackoverflow.com/a/47630348
has comment: http://stackoverflow.com/comment/82218906
type: Question
has body: I am writing a program that could greet users on at fixed times. And if the user didn't reply anything within a period of time, the program will send another message. Currently I use a outer function including two inner functions as I wanted to import the outer one into another main file in the future. But when I call the outer function test(), only the first inner function weekends() was executed. This is my code. import schedule import time from threading import Thread def test(): def weekends(): weekends_ans = None def weekends_check(): time.sleep(20) if weekends_ans!=None: return print('\nWhat about watching a movie?') Thread(target=weekends_check).start() weekends_ans=input('Whats your plan for weekends?') def monday(): monday_ans = None def monday_check(): time.sleep(20) if monday_ans!=None: return print('\nHave fun next week!') Thread(target=monday_check).start() monday_ans=input('Monday again.') schedule.every().friday.at('17:00').do(weekends) schedule.every().sunday.at('17:00').do(monday) while True: schedule.run_pending() time.sleep(1) test() Anyone could help?
type: UnansweredQuestion
tagged with: function
has comment: http://stackoverflow.com/comment/82224257
tagged with: python
has title: Python - Only the first inner funciton was excuted

http://stackoverflow.com/a/47601900
has body: week window is defined by: week_start, week_end tasks are defined by: task_start, task_end task has overlap with week if: task_start &lt; week_end and task_end &gt;= week_start
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82163876
answers question: http://stackoverflow.com/q/47601770
has comment: http://stackoverflow.com/comment/82163678
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/47601770
upvote count: 6

http://stackoverflow.com/comment/82881125
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47674185
type: QuestionComment
has text: @guettli maybe you could run tests with `pytest -l`, then generate two versions of the test report: one with locals, another one filter out locals port, access as you want. but unfortunately, I dont have Jenkins at hand cant test this idea.

http://stackoverflow.com/a/47611662
accepted answer of: http://stackoverflow.com/q/47611492
type: Answer
has comment: http://stackoverflow.com/comment/82182054
has comment: http://stackoverflow.com/comment/82184390
answers question: http://stackoverflow.com/q/47611492
upvote count: 1
type: AcceptedAnswer
has body: First decide what you want to do with bad lines? if you want to skip them, use additional parameter(s) while reading file using pandas: error_bad_lines=False Code becomes: &gt;&gt;&gt; df = pd.read_csv("test_data_file.csv", delimiter=":", warn_bad_lines=False, error_bad_lines=False) if you don't want to drop the 'unusual' data (usual case), read the data as rows of string &amp; process each row based on the number of separators as below: &gt;&gt;&gt; df = pd.read_csv("/home/kiran/test_data_2.csv") &gt;&gt;&gt; df["id"]= df['id:message:user'].apply(lambda x: x.split(":")[0]) &gt;&gt;&gt; df["message"]= df['id:message:user'].apply(lambda x: x.split(":")[1] if (len(x.split(":"))==3) else x.split(":")[1]+":"+x.split(":")[2]) &gt;&gt;&gt; df["user"]= df['id:message:user'].apply(lambda x: x.split(":")[-1]) &gt;&gt;&gt; df.drop('id:message:user', 1, inplace=True) &gt;&gt;&gt; df.head(5) id message user 0 1 hi admin 1 2 im fine :) user1
has comment: http://stackoverflow.com/comment/82182610
has comment: http://stackoverflow.com/comment/82196746
downvote count: 0
score: 1

http://stackoverflow.com/q/47684778
linked to: http://stackoverflow.com/q/25073064
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82329227
duplicate of: http://stackoverflow.com/q/25073064
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82329137
score: 0
has title: <generator object <genexpr> at 0x03416540>
answer count: 0
has body: I'm getting the error " at 0x03416540>" while running the following code. How do I print the list ? def add(x,y): return x+y def even(x): return x%2==0 a=[1,2,3,4] b=[17,11,11,10] result = filter(even, map(add,a,b)) print(x for x in result)

http://stackoverflow.com/comment/114036723
type: Comment
has text: Additionally, if the tools (linter, IDE etc.) complain or cannot handle our sensible choices, the problem is with the tools. Software architecture should be served by the tools not the opposite. BTW, the Python built-in libs themselves are plenty of examples of better choices, including name convention, than that *recommended* by PEP8 (which is intended for the language development, not as a sacred book for everything else).
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47562412

http://stackoverflow.com/comment/82078083
type: Comment
comment on: http://stackoverflow.com/q/47560074
has text: Maybe look through the Pandas documentation for plotting and see if your missing something? http://pandas.pydata.org/pandas-docs/stable/visualization.html
score: 1
type: QuestionComment

http://stackoverflow.com/q/47551654
type: Question
has comment: http://stackoverflow.com/comment/82061546
has comment: http://stackoverflow.com/comment/82059912
accepted answer: http://stackoverflow.com/a/47553258
score: 0
has answer: http://stackoverflow.com/a/47553258
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
has body: I have two lists looking like: L1 = 25, 34, 'ABCD', 'EFG' L2 = 12, 22, 'ABCD', 'EGH' I want to extract "ABCD" from both lists and compare them one character at a time. To extract the strings from the lists I used: string1 = [string[3] for string in L1] string2 = [string[3] for string in L2] To compare them I used: (Because I both want the character and position) if len(string1) == len(string2): for i, char in enumerate(string1): print(i) print(char) When printing I only get position 0 and for char I get the whole string (ABCD). How should I do to get each position and get each character one at a time?
has comment: http://stackoverflow.com/comment/82060201
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/82062880
tagged with: compare
has comment: http://stackoverflow.com/comment/82059881
tagged with: python
has title: How to take out strings from lists and compare them one character at a time

http://stackoverflow.com/comment/82526166
type: Comment
has text: I am having an error code on the last line. dframe_final["final'] = np.where(mask , 'ok' ,'not ok')
comment on: http://stackoverflow.com/a/47681103
type: AnswerComment
score: 0

docker
tags question: http://stackoverflow.com/q/47659088
tag name: docker
type: Tag
tags question: http://stackoverflow.com/q/47561124
tags question: http://stackoverflow.com/q/47568739
tags question: http://stackoverflow.com/q/47679962
tags question: http://stackoverflow.com/q/47544256
tags question: http://stackoverflow.com/q/47579112
tags question: http://stackoverflow.com/q/47630767
tags question: http://stackoverflow.com/q/47656242
tags question: http://stackoverflow.com/q/47634655
tags question: http://stackoverflow.com/q/47673008

http://stackoverflow.com/q/47624578
tagged with: python
tagged with: nlp
has body: I'm trying to apply lemmatization over some Spanish words in Python 3, I found a nice library "pattern" to do it in python 2. However, this one has no support for python 3 yet and cannot really find a good one. It's not enough for my work to apply a steamer such as SnowBall from nltk. Any help or advice on libraries will be greatly appreciated it.
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82215060
has comment: http://stackoverflow.com/comment/82207088
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: lemmatizer for Spanish in python 3

http://stackoverflow.com/a/47568593
accepted answer of: http://stackoverflow.com/q/47568470
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47568470
has comment: http://stackoverflow.com/comment/82095328
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82099789
has body: Following code should do its job: def add_to_dict(dictionary, word): current_dict = dictionary for i, letter in enumerate(word): if i == len(word) - 1: current_dict[letter] = word else: if not letter in current_dict: current_dict[letter] = {} current_dict = current_dict[letter] dictionary = {} add_to_dict(dictionary, "Hello") add_to_dict(dictionary, "Hella") Or you could use defaultdict: from collections import defaultdict def nested_dict(): return defaultdict(nested_dict) def add_to_dict(dictionary, word): current_dict = dictionary for i, letter in enumerate(word): if i == len(word) - 1: current_dict[letter] = word else: current_dict = current_dict[letter] def to_dict(dictionary): dictionary = dict(dictionary) for key, value in dictionary.items(): if isinstance(value, defaultdict): dictionary[key] = to_dict(value) return dictionary dictionary = defaultdict(nested_dict) add_to_dict(dictionary, "Hello") add_to_dict(dictionary, "Hella") dictionary = to_dict(dictionary)

http://stackoverflow.com/q/47692678
tagged with: apache
tagged with: django
tagged with: python
has title: Django + WSGI: When is wsgi.py called?
tagged with: settings
has body: I deployed my Django-project via Apache2 on a server. The problem I have is that I have two setting-modules: settings.py which are my local development settings and settingsprod.py which are my productive settings. I found the following line in the WSGI.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") Is this module only called when using WSGI? And if yes is this a good place to use my production settings like so? os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settingsprod") For local development I use the development server like so: python3 manage.py runserver Does this still defaults to settings.py then?
type: AnsweredQuestion
score: 0
tagged with: mod-wsgi
answer count: 1
accepted answer: http://stackoverflow.com/a/47692848
type: Question
has answer: http://stackoverflow.com/a/47692848

http://stackoverflow.com/comment/82198951
score: 0
has text: Hi, I did a rollback on your question. You are not supposed to change it to a new question after you got answers, because doing so would invalidate the answers. Please ask a new question instead and reference this one if needed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47618826

http://stackoverflow.com/comment/82289243
type: Comment
type: QuestionComment
has text: Based on `Input contains NaN, infinity or a value too large for dtype('float64')`, I'd start by printing the contents of `X_train` and `Y_train` and checking for NaN. Maybe `df_subset` contains some NaN rows that make it through `train_test_split`. The fix *may* be to call `df_subset.dropna(inplace=True)`.
comment on: http://stackoverflow.com/q/47664709
score: 0

http://stackoverflow.com/comment/122031086
score: 0
comment on: http://stackoverflow.com/a/50726290
type: Comment
type: AnswerComment
has text: This library has not received updates since 2019 (as of september 2021). But upgrading from 1.1.13 to 1.2.5 solved the issue for me, so that no longer the whole task is inside a single transaction.

http://stackoverflow.com/comment/82128736
type: QuestionComment
comment on: http://stackoverflow.com/q/47585421
score: 0
type: Comment
has text: `[int(t) for t in tokens if t.isdigit() else t]`

http://stackoverflow.com/q/47652524
has comment: http://stackoverflow.com/comment/82289970
has comment: http://stackoverflow.com/comment/82263421
has comment: http://stackoverflow.com/comment/82264210
has comment: http://stackoverflow.com/comment/82263593
has answer: http://stackoverflow.com/a/47659461
has comment: http://stackoverflow.com/comment/82266779
tagged with: python
tagged with: pymc
has title: constrained random numbers sampling using python (Monte-Carlo, Markov chains, pymc)
tagged with: mcmc
tagged with: python-3.x
score: 0
tagged with: random
has comment: http://stackoverflow.com/comment/82264902
type: UnansweredQuestion
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82263628
has comment: http://stackoverflow.com/comment/82263389
has comment: http://stackoverflow.com/comment/82264000
has body: I am trying to sample random numbers with constraints using Python and pymc library. Here mins and maxes are arrays of minimums and maximums for each of 22 variables. It works fine in this case. from pymc import * X = Uniform('X', mins, maxes) @potential def s(X=X): cons1 = X[0] &lt; 225 cons2 = X[0] &gt; 405 if cons1 or cons2: return -inf else: return 0.0 mc = MCMC([X, s]) mc.sample(10000) However when I try to add one more constraint: that sum of variables must be equal to 1000, everything breaks: from pymc import * X = Uniform('X', mins, maxes) @potential def s(X=X): cons1 = X[0] &lt; 225 cons2 = X[0] &gt; 405 cons3 = X.sum() &gt;= 1000 if cons1 or cons2 or cons3: return -inf else: return 0.0 mc = MCMC([X, s]) mc.sample(10000) Error is: 'ZeroProbability: Potential s forbids its parents' current values' Could you please recommend some solutions to this problem?
downvote count: 1
has comment: http://stackoverflow.com/comment/82264843
favorite count: 0
type: Question

http://stackoverflow.com/comment/113542211
type: AnswerComment
score: 1
has text: `parser = ConfigParser(interpolation=None)`
comment on: http://stackoverflow.com/a/55520045
type: Comment

http://stackoverflow.com/q/47591401
tagged with: arrays
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/82140267
tagged with: append
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47592773
has title: Append Javascript arrays or object like python
has answer: http://stackoverflow.com/a/47591451
possible better answer: http://stackoverflow.com/a/47591451
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82140326
has comment: http://stackoverflow.com/comment/82140295
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47592773
has body: I tried different thing like array push and the new Set() .add but i cant achieve a functionality like pythons append. any thoughts? am i missing something? ex. in py x = [1, 2, 3] x.append([4, 5]) gives you: [1, 2, 3, [4, 5]] OR if im in a for loop and i append to first item item.append(9) gives you: [[1, 9], 2, 3] the second is the one i want to use inside a 2 for-loops js ex let b = [1,2,3]; b.forEach(function (item) { item.push(9); //error }); maybe its a silly question but i am new to js sorry :S
score: -2

http://stackoverflow.com/comment/82253345
type: Comment
type: QuestionComment
has text: I recommend you should read the data structures in python.
comment on: http://stackoverflow.com/q/47647413
score: 0

http://stackoverflow.com/q/47658805
tagged with: file
has body: I want to open a file, decode the format of data (from base64 to ASCII), rewrite or save the decoded string, either back to the same file, or new one. I have it opening, reading, decoding (and printing as a test) the decoded base64 string into readable format (ASCII I believe) My goal is to now save this output to: either a "newfile.txt" document or back to the original "test.mcz" file ready for the next steps of my mission... I know there are great online base64 decoders and they do work well for what I am doing - I use them often, but my goal is to write my own program as a learning exercise more than anything (also when my internet plays up I need an offline program) Here's where I am so far (the original file is .mcz format it is a game save) # PYTHON 3 import base64 f = open('test.mcz', 'r') f_read = f.read() # print(f_read) # was just as a test new_f_read = base64.b64decode(f_read) print (new_f_read) This prints a butt-load of readable code that is what I need, but I don't want to have to just copy and paste this output from the Python shell into another editor, I want to save it to a file...for convenience. Either back into the same test.mcz (I will be re-encoding to base64 again later on anyway) or to a new file - thus leaving my original as it was. problem arises when I want to save/write this decoded output that is stored within the new_f_read variable...it's just been a headache, before I started I could visualise how it needed to be written, I got tripped up when I had to switch it all over to Python3 for some reason (Don't ask...) and I have tried so many variations from online examples - I wouldn't know where to start explaining what I've tried so far. I can't open the original file as both "r" AND "w" together so once Ive opened and decoded I cant reopen the original file as "w" because it just wipes the contents (which are still encoded anyway) - I think I need to write functions to handle: 1. Open, read, save string to a variable 2. Manipulate strin…
type: Question
tagged with: overwrite
accepted answer: http://stackoverflow.com/a/47658944
has title: Opening, edit/rewrite string, save back to a new or same file
tagged with: python
has comment: http://stackoverflow.com/comment/82276398
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47659060
possible better answer: http://stackoverflow.com/a/47659060
has answer: http://stackoverflow.com/a/47658944

restore
tag name: restore
type: Tag
tags question: http://stackoverflow.com/q/47678647

http://stackoverflow.com/a/47683347
has comment: http://stackoverflow.com/comment/82329561
has body: Adding to Alexander's comment, it's best to explicitly handle null values. One way would be to edit your function like so: import pandas as pd def dt64_to_datetime(dt64): unix_epoch = np.datetime64(0, 's') one_second = np.timedelta64(1, 's') if pd.isnull(dt64): return pd.NaT else: seconds_since_epoch = (dt64 - unix_epoch) / one_second return datetime.utcfromtimestamp(seconds_since_epoch) On my environment pd.isnull(numpy.datetime64('NaT')) returns True. Also, my environment actually can't replicate your error (it returns nan without explicitly handling nulls). So consider upgrading pandas and / or numpy.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82332024
answers question: http://stackoverflow.com/q/47683120

http://stackoverflow.com/comment/82058975
type: Comment
comment on: http://stackoverflow.com/a/47550892
type: AnswerComment
has text: Right, it makes it look much better as well. Not sure if I understand how the formatting works. Will do my best to get familiar with the document.
score: 0

http://stackoverflow.com/q/47553339
downvote count: 0
tagged with: image-processing
upvote count: 1
has title: Beier neely image morphing in python, need help regarding numpy/image array
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-imaging-library
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82089778
has body: So the basic algo or part of it is for all pixles X in an image calculate u,v,X' destinationImage(X) = SourceImage(X') my code for this part till now is: from PIL import Image, ImageDraw from math import sqrt import numpy im = Image.open('1a.png') imArray = numpy.array(im) xi = input("enter initial position of inputline, x coordinate ") yi = input("enter initial position of inputline, y coordinate ") xif = input("enter final position of inputline, x coordinate ") yif = input("enter final position of inputline, y coordinate ") xt = input("enter initial position of targetline, x coordinate ") yt = input("enter initial position of targetline, y coordinate ") xtf = input("enter final position of targetline, x coordinate ") ytf = input("enter final position of targetline, y coordinate ") P = numpy.mgrid[xi:yi] Q = numpy.mgrid[xif:yif] Po= numpy.mgrid[xt:yt] Qo= numpy.mgrid[xtf:ytf] width = im.size[0] height = im.size[1] #draw = ImageDraw.Draw(im) #draw.line((100,200, 150,200),fill=128,width=3) #im.show() vec = [xi,yi] vec1 = [xif,yif] vec2 = [xt,yt] vec3 = [xtf,ytf] perp = numpy.cross(vec,vec1) perp1 = numpy.cross(vec2,vec3) for i in range(width+1): for j in range(height+1): X=numpy.mgrid[i:j] u = numpy.dot((X-P),(Q-P))/pow((numpy.sqrt((Q-P).dot(Q-P))),2) #v = numpy.dot((X-P),(numpy.cross((Q-P)))/numpy.sqrt((Q-p).dot(Q-P))) v = numpy.dot((X-P),(perp))/numpy.sqrt((Q-p).dot(Q-P))) X1 = Po + numpy.dot(Qo-Po) + numpy.dot(v,perp1)/numpy.sqrt((Qo-Po).dot(Qo-Po)) where i am now having problem is that what should i do for the last algorithm line, destinationImage(X) = sourceImage(X') i guess some changes have to be made to create new image array and display that but how to do it?
answer count: 0
score: 1

http://stackoverflow.com/q/47620882
has answer: http://stackoverflow.com/a/47621003
tagged with: python
has body: I have a dataframe df and when I run print(df.index), I get: DatetimeIndex(['2011-08-05 00:00:00-04:00', '2011-08-05 01:00:00-04:00', '2011-08-05 02:00:00-04:00', '2011-08-05 03:00:00-04:00', '2011-08-05 04:00:00-04:00', '2011-08-05 05:00:00-04:00', '2011-08-05 06:00:00-04:00', '2011-08-05 07:00:00-04:00', '2011-08-05 08:00:00-04:00', '2011-08-05 09:00:00-04:00', ... '2017-07-30 14:00:00-04:00', '2017-07-30 15:00:00-04:00', '2017-07-30 16:00:00-04:00', '2017-07-30 17:00:00-04:00', '2017-07-30 18:00:00-04:00', '2017-07-30 19:00:00-04:00', '2017-07-30 20:00:00-04:00', '2017-07-30 21:00:00-04:00', '2017-07-30 22:00:00-04:00', '2017-07-30 23:00:00-04:00'], dtype='datetime64[ns, America/New_York]', name=u'Time', length=52488, freq=None) I am trying to modify the datetimeindex object, so that the First timestamp in the series is changed from '2011-08-05 00:00:00-04:00' to '2011-08-04 20:00:00' and Second stamp in the series would be changed from '2011-08-05 00:00:00-04:00' to '2011-08-04 21:00:00', and so on. I tried pd.to_datetime(df.index, format='%Y-%m-%d %H:%M:%S'), but it returns the same datetimeindex object as above. It is OK with me if the timestamps are converted to string, so I tried: df.index.strftime('%Y-%m-%d %H:%M:%S') But neither lines of code achieves my end goal.
type: AnsweredQuestion
tagged with: datetimeindex
has title: Adding offset to timestamp in pandas
tagged with: pandas
upvote count: 3
score: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47621003

http://stackoverflow.com/a/47600218
type: Answer
score: 3
answers question: http://stackoverflow.com/q/47598953
upvote count: 3
downvote count: 0
has body: The key to it is to use the ondrag() event handler on a turtle. A short and not so sweet solution: import turtle turtle.ondrag(turtle.goto) turtle.mainloop() which will likely crash shortly after you start dragging. A better solution with a larger turtle to drag, and that turns off the drag handler inside the drag hander to prevent events from piling up: from turtle import Turtle, Screen def dragging(x, y): yertle.ondrag(None) yertle.setheading(yertle.towards(x, y)) yertle.goto(x, y) yertle.ondrag(dragging) screen = Screen() yertle = Turtle('turtle') yertle.speed('fastest') yertle.ondrag(dragging) screen.mainloop() Note that you have to click and drag the turtle itself, not just click somewhere on the screen. If you want to get the turtle to follow the mouse without keeping the left button held down, see my answer to Move python turtle with mouse pointer.

http://stackoverflow.com/comment/82195311
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47618569
score: 0
has text: It's called "URL encoding"; you can look it up easily.

http://stackoverflow.com/q/47547283
type: Question
has body: Python suddenly stopped when matplot image was drawn. I wanna show matplot image's table in index.html.Now I wrote in views.py def past_result(request): return render(request, 'index.html', {'chart': _view_plot(request)}) def _view_plot(request): dates = [20150805,20160902,20170823] heights = [5,6,3] df = pd.DataFrame() df['DATE'] = dates df['SCORE'] = heights 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 if ax is None: size = (np.array(df.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=df.values, bbox=bbox, colLabels=df.columns) 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)]) plt.show() return ax in index.html &lt;img src="data:image/png;base64,{{ chart }}" width="700px" height="500px" alt="RESULT"/&gt; When I read past_result method,Python suddenly stopped .I do not know why.Why does such a error happen? I read this url as reference How to save the Pandas dataframe/series data as a figure? .How should I fix this? Traceback is ** First throw call stack: ( 0 CoreFoundation 0x00007fffc96b737b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00007fffde4b348d objc_exception_throw + 48 2 CoreFoundation 0x00007fffc96bc082 +[NSException raise:format:arguments:] + 98 3 Foundation 0x00007fffcb103ce0 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195 4 Foundation 0x00007fffcb08e3b3 +[NSUndoManager(NSPrivate) _endTopLevelGroupings] + 170 5 AppKit 0x00007fffc711e8bd -[NSApplication run] + 1200 6 _macosx.so 0x000000010509c8d2 init_macosx + 325…
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82053096
score: 0
answer count: 0
has title: Python suddenly stopped when matplot image was drawn
has comment: http://stackoverflow.com/comment/82051772
linked to: http://stackoverflow.com/q/19726663
has comment: http://stackoverflow.com/comment/82051214

http://stackoverflow.com/comment/82213963
score: 0
type: AnswerComment
has text: by changing this line `a = Attendee.objects.get(pk=pk) Payment.objects.filter(pk=a.payment.pk).update(registered=0)` works for me. Thank you thank you.
type: Comment
comment on: http://stackoverflow.com/a/47625924

http://stackoverflow.com/a/47599887
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82158873
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47599461
has body: You can reshape it to dimension [N,P,1] first then transpose the first and second axis: tf.transpose(tf.reshape(T, [N, P, 1]), [1,0,2]) # ^^^^ switch the two dimensions here and then transpose Example: T = tf.expand_dims([1,2,3,4,5,6], 1) sess = tf.Session() T1 = tf.transpose(tf.reshape(T, [2,3,1]), [1,0,2]) sess.run(T1) #array([[[1], # [4]], # [[2], # [5]], # [[3], # [6]]], dtype=int32)
accepted answer of: http://stackoverflow.com/q/47599461

http://stackoverflow.com/q/47626216
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/82211247
favorite count: 0
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20449427
score: 1
has body: Based on reading the 2.7 documentation, the following code should step through correctly from what I can tell. I call raw_input(text) to get an input for variable age, but it always returns You can see rated R movies. import sys age = raw_input("What is your age? ") if age &gt;= 17: print "You can see rated R movies." elif age &lt; 17 and age &gt; 12: print "You can see a rated PG-13 movies." else: print "You can only see PG movies!" Based on my logic, if the value passed to age is not greater than or equal to 17, it should move onto the next statement. That is not the result I get though. It always returns the Rated R line. For example I input 3 and it still gives me the rated R response. If I flip the > to &lt; then it always returns the "You can only see PG movies!" line. Thoughts?
has title: Why does this if and elif statement not fully execute?
has comment: http://stackoverflow.com/comment/82210209
tagged with: python
has answer: http://stackoverflow.com/a/47626755
has answer: http://stackoverflow.com/a/47626245
answer count: 2
downvote count: 0
upvote count: 1

flask-restless
type: Tag
tag name: flask-restless
tags question: http://stackoverflow.com/q/47569162

http://stackoverflow.com/comment/82322344
has text: @JokerMartini. I see you've added a small edit, but it doesn't really clarify anything. For example, what exactly do you expect to happen when dragging a selection rectangle, if it includes items that are in a mixture of states? And a similar situation can occur when making a multiple selection via ctrl-click.
score: 0
comment on: http://stackoverflow.com/a/47681015
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47689615
downvote count: 0
type: AcceptedAnswer
has body: Please try with {{}}, Add http://www.tornadoweb.org/en/stable/guide/templates.html
answers question: http://stackoverflow.com/q/47689160
type: Answer
accepted answer of: http://stackoverflow.com/q/47689160
score: 2
upvote count: 2

http://stackoverflow.com/comment/95895328
comment on: http://stackoverflow.com/a/47651070
score: 0
type: AnswerComment
type: Comment
has text: Adding encoding='bytes' as 2nd argument for load(..) resolved the UnicodeDecodeError for me in Python 3.7

http://stackoverflow.com/comment/82071261
comment on: http://stackoverflow.com/q/47556251
score: 1
type: QuestionComment
type: Comment
has text: Do you think [this](https://stackoverflow.com/a/26605026/4819376) can help you?

http://stackoverflow.com/q/47558374
score: 0
has comment: http://stackoverflow.com/comment/82075362
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47559030
type: Question
possible better answer: http://stackoverflow.com/a/47558555
answer count: 2
has comment: http://stackoverflow.com/comment/82075175
has answer: http://stackoverflow.com/a/47558555
has body: I'm going nuts. Whatever I do, Django adds a ' character to the start of the first field of my data. I have a df that looks like so: Year JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV \ 0 1910 6.1 7.2 8.9 9.6 14.5 17.1 17.3 16.9 15.6 12.5 6.9 1 1911 5.8 6.5 7.5 9.7 16.2 17.8 21.7 21.4 17.3 12.4 8.2 2 1912 6.0 7.5 9.1 12.5 14.4 16.0 18.4 15.0 13.7 11.6 8.4 3 1913 6.7 7.2 8.5 10.4 13.8 16.5 17.6 18.5 16.5 13.5 10.6 4 1914 5.6 8.7 8.4 13.2 13.8 17.6 18.5 19.1 17.0 12.9 9.1 5 1915 5.9 6.4 7.7 10.8 15.1 18.0 16.9 17.7 17.0 11.9 6.0 6 1916 9.2 5.7 5.5 11.1 14.1 14.5 18.3 19.2 16.0 12.9 8.8 7 1917 2.7 3.8 6.1 8.4 16.3 17.5 19.3 17.1 16.2 10.7 9.9 8 1918 6.4 8.4 8.7 10.1 16.2 16.6 18.4 18.3 14.3 11.5 8.5 ... I have a function that puts it into a model: def add_to_db(weatherstats_df): print(weatherstats_df) for row in weatherstats_df.itertuples(): # print(row) year = int(str(row.Year).strip('\'')) print(year) measurement = row.Measurement location = row.Location ikey = 0 for key, month_or_season in WeatherStatistics.MONTH_OR_SEASON: ikey += 1 value = row[ikey] if (value == "---"): value = None WeatherStatistics( year=year, measurement_type=measurement, location=location, month_or_season=key, value=value, ).save() The model looks like this: year = models.IntegerField( default=0, validators=[MaxValueValidator(9999), MinValueValidator(0)], ) Every time I run this, no matter how I try to strip the ' from the year, I still get an error like this: could not convert string to float: "'1910" I must be doing something dumb, but I can't figure out where I went wrong? Environment: Request Method: GET Request URL: http://127.0.0.1:8000/weatherstats/wales Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weatherstats'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sess…
has comment: http://stackoverflow.com/comment/82074630
tagged with: django
accepted answer: http://stackoverflow.com/a/47559030
has title: Django keeps adding ' character to first cell of my data so it can't store it in the model
type: AnsweredQuestion

http://stackoverflow.com/comment/82154486
comment on: http://stackoverflow.com/a/47598041
type: Comment
type: AnswerComment
has text: Thank you 13ros27 - i will look into this method ... Do you know if it will lineup the rows when there is a missing header? most of the headers are the same but some of the account have one more or less so i would have blanks ... Just need them to lineup in the right rows.
score: 0

function
tags question: http://stackoverflow.com/q/47585991
type: Tag
tags question: http://stackoverflow.com/q/47658626
tag name: function
tags question: http://stackoverflow.com/q/47627403
tags question: http://stackoverflow.com/q/47618379
tags question: http://stackoverflow.com/q/47671795
tags question: http://stackoverflow.com/q/47615999
tags question: http://stackoverflow.com/q/47672679
tags question: http://stackoverflow.com/q/47685425
tags question: http://stackoverflow.com/q/47571842
tags question: http://stackoverflow.com/q/47643961
tags question: http://stackoverflow.com/q/47614135
tags question: http://stackoverflow.com/q/47607071
tags question: http://stackoverflow.com/q/47577301
tags question: http://stackoverflow.com/q/47607515
tags question: http://stackoverflow.com/q/47604094
tags question: http://stackoverflow.com/q/47684222
tags question: http://stackoverflow.com/q/47666884
tags question: http://stackoverflow.com/q/47543233
tags question: http://stackoverflow.com/q/47620697
tags question: http://stackoverflow.com/q/47649044
tags question: http://stackoverflow.com/q/47647797
tags question: http://stackoverflow.com/q/47667363
tags question: http://stackoverflow.com/q/47680233
tags question: http://stackoverflow.com/q/47661778
tags question: http://stackoverflow.com/q/47613070
tags question: http://stackoverflow.com/q/47623450
tags question: http://stackoverflow.com/q/47555265
tags question: http://stackoverflow.com/q/47633807
tags question: http://stackoverflow.com/q/47655075
tags question: http://stackoverflow.com/q/47687912
tags question: http://stackoverflow.com/q/47616073
tags question: http://stackoverflow.com/q/47585503
tags question: http://stackoverflow.com/q/47581591
tags question: http://stackoverflow.com/q/47543631
tags question: http://stackoverflow.com/q/47683498
tags question: http://stackoverflow.com/q/47580866
tags question: http://stackoverflow.com/q/47668186
tags question: http://stackoverflow.com/q/47630127
tags question: http://stackoverflow.com/q/47585050
tags question: http://stackoverflow.com/q/47569284
tags question: http://stackoverflow.com/q/47585074
tags question: http://stackoverflow.com/q/47596122
tags question: http://stackoverflow.com/q/47661633

http://stackoverflow.com/comment/82040222
type: Comment
has text: @O.rka `dt.strptime("2/3/13", '%d/%m/%y').date()`
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47541445

http://stackoverflow.com/comment/82302029
type: Comment
type: QuestionComment
has text: https://docs.djangoproject.com/en/2.0/ref/models/expressions/#using-f-with-annotations
comment on: http://stackoverflow.com/q/47671551
score: 1

http://stackoverflow.com/q/47614010
favorite count: 0
has answer: http://stackoverflow.com/a/47614478
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/82186981
has comment: http://stackoverflow.com/comment/82186750
tagged with: find
has title: python string find function doesn't give position from text returned by beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82187286
has comment: http://stackoverflow.com/comment/82186968
tagged with: python
has comment: http://stackoverflow.com/comment/82187170
score: 2
has comment: http://stackoverflow.com/comment/82187043
has body: I am trying to scrape a section of 10-K filings. I am having a problem to identify the postion of 'item 7(a).' from text returned by beautifulsoup inspite of having the word in it. But the following code is working for a string I made that contains 'item 7(a).' import urllib2 import re import bs4 as bs url=https://www.sec.gov/Archives/edgar/data/1580608/000158060817000015/santander201610-k.htm' html = urllib2.urlopen(url).read().decode('utf8') soup = bs.BeautifulSoup(html,'lxml') text = soup.get_text() text = text.encode('utf-8') text = text.lower() print type(text) print len(text) text1 = "hf dfbd item 7. abcd sfjsdf sdbfjkds item 7(a). adfbdf item 8. skjfbdk item 7. sdfkba ootgf sffdfd item 7(a). sfbdskf sfdf item 8. sdfbksdf " print text.find('item 7(a)') print text1.find('item 7(a)') Output: &lt;type 'str'&gt; 592214 -1 37
upvote count: 2
has comment: http://stackoverflow.com/comment/82187287
has comment: http://stackoverflow.com/comment/82187110
has comment: http://stackoverflow.com/comment/82187294
has comment: http://stackoverflow.com/comment/82187080
answer count: 1
downvote count: 0
tagged with: string

http://stackoverflow.com/comment/82154788
type: QuestionComment
has text: What do you mean by "invert"?
comment on: http://stackoverflow.com/q/47598315
score: 0
type: Comment

http://stackoverflow.com/q/47616887
has title: Mutability in a dictionary
has comment: http://stackoverflow.com/comment/82192089
has comment: http://stackoverflow.com/comment/82192100
has comment: http://stackoverflow.com/comment/82192208
tagged with: mutability
upvote count: 0
has answer: http://stackoverflow.com/a/47617277
answer count: 3
has answer: http://stackoverflow.com/a/47617030
has comment: http://stackoverflow.com/comment/82192320
tagged with: python
has answer: http://stackoverflow.com/a/47616941
has comment: http://stackoverflow.com/comment/82192134
has comment: http://stackoverflow.com/comment/82192062
has comment: http://stackoverflow.com/comment/82191962
favorite count: 0
type: Question
downvote count: 2
has comment: http://stackoverflow.com/comment/82192067
has comment: http://stackoverflow.com/comment/82192167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82192367
score: -2
has body: &gt;&gt;&gt; mydict = {1: {45: 'ades', 54:'adee'}, 2: {68: 'gdes'}} &gt;&gt;&gt; curr_value = mydict[1][45] &gt;&gt;&gt; mydict[1][45] = 'zzzz' &gt;&gt;&gt; print (curr_value) ades # Expected value: zzzz How come my curr_value is not mutating from mydict? I did not clone curr_value or anything.
has comment: http://stackoverflow.com/comment/82192081

http://stackoverflow.com/comment/82245575
type: AnswerComment
comment on: http://stackoverflow.com/a/47643326
has text: Thanks, @AntonvBR. That is helpful to see how my code could have been rewritten. I do understand, but it will take a while for me to absorb this concept. I really appreciate your answer!.
type: Comment
score: 0

http://stackoverflow.com/comment/82313989
has text: @chilun please update your question with these cases. I can think of ways to do it in python on the top of my head and not PySpark. Maybe someone else can get to it before me
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47673889
type: QuestionComment

http://stackoverflow.com/q/47597904
has title: the pyspark code must call persist to make it run
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/82164371
answer count: 0
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/82219246
score: 1
downvote count: 0
has body: The code works well by calling a persist beforehand under all Spark versions Without calling persist, it works well under Spark 2.2.0 but doesn't work under Spark 2.1.1 and Spark 2.1.2 It really looks like a bug in Spark. Does anyone know which solved Spark isssues are related? =================================================================== from __future__ import absolute_import, division, print_function import pyspark.sql.types as T import pyspark.sql.functions as F # 2.1.1, 2.1.2 doesn't work # 2.2.0 works print(spark.version) df = spark.createDataFrame( [{'name': 'a', 'scores': ['1', '2']}, {'name': 'b', 'scores': None}], T.StructType( [T.StructField('name', T.StringType(), True), T.StructField('scores', T.ArrayType(T.StringType()), True)] ) ) print(df.collect()) df.printSchema() def loop_array(l): for e in l: pass return "pass" # should work with persist # tmp = df.filter(F.col('scores').isNotNull()).withColumn( # 'new_col', # F.udf(loop_array)('scores') # ).persist() # won't work tmp = df.filter(F.col('scores').isNotNull()).withColumn( 'new_col', F.udf(loop_array)('scores') ) print(tmp.collect()) tmp.filter(F.col('new_col').isNotNull()).count() ====================================================================== --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-9-572fb022ddab&gt; in &lt;module&gt;() ----&gt; 1 tmp.filter(F.col('new_col').isNotNull()).count() /databricks/spark/python/pyspark/sql/dataframe.py in count(self) 378 2 379 """ --&gt; 380 return int(self._jdf.count()) 381 382 @ignore_unicode_prefix /databricks/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args) 1131 answer = self.gateway_client.send_command(command) 1132 return_value = get_return_value( -&gt; 1133 answer, self.gateway_client, self.target_id, self.name) 1134 1135 for temp_arg in temp_args: /databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw) 61 def d…
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82064703
has text: @avi The code you've presented already does what you've said, `print value in ("abc ver 1","abc ver 1.1")` where `value` is `"abc"` *does* return `False`. `"abc" in ("abc ver1")` returns `True` because it's the same as `"abc" in "abc ver1"` which is clearly true
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47553821

datetime
tags question: http://stackoverflow.com/q/47572283
tags question: http://stackoverflow.com/q/47595779
tags question: http://stackoverflow.com/q/47603148
tags question: http://stackoverflow.com/q/47571534
tags question: http://stackoverflow.com/q/47565631
tags question: http://stackoverflow.com/q/47663406
tags question: http://stackoverflow.com/q/47661164
tags question: http://stackoverflow.com/q/47672643
tag name: datetime
tags question: http://stackoverflow.com/q/47556976
tags question: http://stackoverflow.com/q/47543762
tags question: http://stackoverflow.com/q/47641938
tags question: http://stackoverflow.com/q/47661041
tags question: http://stackoverflow.com/q/47605720
tags question: http://stackoverflow.com/q/47554283
tags question: http://stackoverflow.com/q/47667149
tags question: http://stackoverflow.com/q/47681620
tags question: http://stackoverflow.com/q/47578810
tags question: http://stackoverflow.com/q/47560533
tags question: http://stackoverflow.com/q/47604425
tags question: http://stackoverflow.com/q/47540863
tags question: http://stackoverflow.com/q/47683063
tags question: http://stackoverflow.com/q/47547403
tags question: http://stackoverflow.com/q/47689237
tags question: http://stackoverflow.com/q/47683120
tags question: http://stackoverflow.com/q/47562634
tags question: http://stackoverflow.com/q/47631556
type: Tag
tags question: http://stackoverflow.com/q/47625375
tags question: http://stackoverflow.com/q/47545090
tags question: http://stackoverflow.com/q/47543061
tags question: http://stackoverflow.com/q/47626749
tags question: http://stackoverflow.com/q/47685174
tags question: http://stackoverflow.com/q/47696946
tags question: http://stackoverflow.com/q/47599080
tags question: http://stackoverflow.com/q/47541415
tags question: http://stackoverflow.com/q/47649776
tags question: http://stackoverflow.com/q/47613830
tags question: http://stackoverflow.com/q/47628325
tags question: http://stackoverflow.com/q/47664732
tags question: http://stackoverflow.com/q/47640887
tags question: http://stackoverflow.com/q/47557109
tags question: http://stackoverflow.com/q/47574551
tags question: http://stackoverflow.com/q/47685557
tags question: http://stackoverflow.com/q/47584961
tags question: http://stackoverflow.com/q/47691205
tags question: http://stackoverflow.com/q/47563103
tags question: http://stackoverflow.com/q/47626038
tags question: http://stackoverflow.com/q/47613827
tags question: http://stackoverflow.com/q/47556851
tags question: http://stackoverflow.com/q/47591429
tags question: http://stackoverflow.com/q/47629177
tags question: http://stackoverflow.com/q/47685507
tags question: http://stackoverflow.com/q/47600508

http://stackoverflow.com/comment/82231142
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47636448
has text: `run` returns the output. You could try to print it.

http://stackoverflow.com/comment/82075312
comment on: http://stackoverflow.com/q/47558622
score: 0
has text: @agtoever no, as OP is not using pygame
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47575201
answer count: 2
has comment: http://stackoverflow.com/comment/82108202
accepted answer: http://stackoverflow.com/a/47678481
has comment: http://stackoverflow.com/comment/82138183
has title: python script throwing an error that i can deal with
type: Question
has comment: http://stackoverflow.com/comment/82107613
possible better answer: http://stackoverflow.com/a/47575915
has body: I have created the above script to remove unwanted genes from a database. It does work quite well if you only use it once but I re-run it, it giving me an error message such as: shutil.Error: Destination path 'path/rejected_database_genes/gene_A.fa' already exists And obviously it stops. I think that the problem arises when there are two or more genes in the file that needs to be removed. Kind regards, and thanks for your help. import glob, sys, os, shutil from Bio import SeqIO, SearchIO from Bio.SeqRecord import SeqRecord import argparse def help_function(): print 'Hi' parser = argparse.ArgumentParser() parser.add_argument('-input_file', '-i',type=str,help='path_to_data') opts = parser.parse_args() def check_file_exists(filepath, file_description): if not os.path.exists(filepath): print("The " + file_description + " (" + filepath + ") does not exist") sys.exit(1) else: print file_description + " detected" def remove_empty_files(alleles_files,destination): input_handle=open(alleles_files, 'r') gene_records=list(SeqIO.parse(input_handle, 'fasta')) for gene_record in gene_records: #filename=gene_record.id[0] #count=0 if len(gene_record.seq)&lt;5 or 'N'in gene_record.seq: print gene_record.id elif '-' in gene_record.seq: print gene_record.id #count+=1 shutil.move(alleles_files, destination) def main(): destination=opts.input_file + '/rejected_database_genes' if os.path.exists(destination): print 'Folder already exits' else: os.makedirs(destination) print 'Folder has been created' files=glob.glob(opts.input_file+'/*.fa') #print files #sys.exit() for f in files: #print f #sys.exit() alleles_files=glob.glob(f)[0] #print alleles_files #sys.exit() remove_empty_files(alleles_files,destination) print 'Files have been removed' main()
has answer: http://stackoverflow.com/a/47575915
tagged with: python
has answer: http://stackoverflow.com/a/47678481
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82336875
type: QuestionComment
comment on: http://stackoverflow.com/q/47688824
type: Comment
has text: numpy broadcasting for subtraction may result in more time
score: 0

http://stackoverflow.com/q/47564997
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/74900395
tagged with: dependencies
favorite count: 0
type: Question
tagged with: raspberry-pi
type: UnansweredQuestion
tagged with: cross-compiling
has body: I have just cross-compiled Python 3.6 from a Fedora 26 64 bit to a Raspberry Pi 3, and everything went fine until the last part where it checks for pip and setuptools: Requirement already up-to-date: setuptools in /usr/lib/python3.6/site-packages Requirement already up-to-date: pip in /usr/lib/python3.6/site-packages And just before that there's a lot of gibberish that goes like: if test "xupgrade" != "xno" ; then \ case upgrade in \ upgrade) ensurepip="--altinstall --upgrade" ;; \ install|*) ensurepip="--altinstall" ;; \ esac; \ _PYTHON_PROJECT_BASE=/home/ariel/Descargas/Python-3.6.3 _PYTHON_HOST_PLATFORM=linux-arm PYTHONPATH=/home/ariel/Descargas/Python-3.6.3/build/lib.linux-arm-3.6:./Lib _PYTHON_SYSCONFIGDATA_NAME=_sysconfigdata_m_linux_arm-linux-gnueabihf python3.6 -m ensurepip \ $ensurepip --root=/ ; \ fi Apparently, it's checking for availability on my local machine, due to --root=/. If I navigate to the site-packages path under the altinstall target I only see a README.txt file. What can I do to get pip and setuptools built along Python 3.6? Edit: This is a follow-up question for my question about how to cross-compile Python 3.6 for a Raspberry Pi 3.
has title: Cross compiled Python 3.6 missing pip, setuptools and other core packages
tagged with: python
upvote count: 4
score: 4

http://stackoverflow.com/q/47676989
tagged with: beautifulsoup
has body: I am trying to convert HTML table to json using beautifulsoup() function python, i was able to convert some other tables to json but this is of different kind. I am trying to achieve something like this: [{ "name": "abc", "age": "21", "sex": "m", "loction": "us", "language": "en" }, { "name": "xyz", "age": "25", "sex": "f", "loction": "us", "language": "en" }] Table is : name age sex location language abc 21 m us en xyz 25 f us en Some help is appreciated
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47677283
downvote count: 0
tagged with: python
has title: convert HTML to json in python using BeautifulSoup
answer count: 2
has answer: http://stackoverflow.com/a/66270285
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47587760
has body: In this code, I am trying to compare the value of a set that has been looped each time to a value passed (in this case a) in a parameter. What's interesting though is that it shows when I use a for each loop that each element is an integer. How do I get a integer to integer comparison without a console error? def remove(s,a,b): c=set() c=s for element in c: element=int(element) if(element&lt;a or element&gt;b): c.discard(element) return c def main(): remove({3, 17, -1, 4, 9, 2, 14}, 1, 10) main() Output: if(element&lt;=a or element&gt;=b): TypeError: '&gt;=' not supported between instances of 'int' and 'set'
score: 0
has answer: http://stackoverflow.com/a/47587896
answer count: 3
has answer: http://stackoverflow.com/a/47587872
tagged with: types
tagged with: set
has answer: http://stackoverflow.com/a/47589254
type: Question
has comment: http://stackoverflow.com/comment/82133509
type: UnansweredQuestion
tagged with: python
tagged with: comparison
has title: How do you change a specific element of a set?
tagged with: integer

http://stackoverflow.com/a/49938770
upvote count: 25
has comment: http://stackoverflow.com/comment/101122711
has comment: http://stackoverflow.com/comment/115477337
score: 24
downvote count: 1
has comment: http://stackoverflow.com/comment/103424082
type: Answer
answers question: http://stackoverflow.com/q/47663809
has body: This has been settled in 988251 In short; use the python ast library's literal_eval() function. import ast my_string = "{'key':'val','key2':2}" my_dict = ast.literal_eval(my_string)

http://stackoverflow.com/comment/82088859
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47556302
has text: @MartijnPieters, I added a screenshot when I debug, as you can see, i remove backslashes because they appear at the beginning.
type: Comment

http://stackoverflow.com/comment/82140484
has text: if my number is 19.89 it prints my number as 19
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47590349

http://stackoverflow.com/q/47654302
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Adding Yogaglo as supported youtube-dl site
favorite count: 0
type: Question
has body: I would like to add Yogaglo support for youtube-dl. I've followed guidance on Github . And have drafted the following: # coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class YogagloIE(InfoExtractor): _SIGNIN_URL = 'https://www.yogaglo.com/login' _PASSWORD_URL = 'https://www.yogaglo.com/login/password' _USER_URL = 'https://www.yogaglo.com/login/user' _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide yogaglo.com account credentials.' _NETRC_MACHINE = 'yogaglo' def _real_initialize(self): self._login() _VALID_URL = r'https?://(?:www\.)?yogaglo\.com/class/(?P&lt;id&gt;[0-9]+)' _TEST = { 'url': 'https://www.yogaglo.com/class/7206', 'md5': 'TODO: md5 sum of the first 10241 bytes of the video file (use --test)', 'info_dict': { 'id': '7206', 'ext': 'mp4', 'title': 'Have a Great Day!' # TODO more properties, either as: # * A value # * MD5 checksum; start the string with md5: # * A regular expression; start the string with re: # * Any Python type (for example int or float) } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) title = self._html_search_regex(r'&lt;h1&gt;(.+?)&lt;/h1&gt;', webpage, 'title') return { 'id': video_id, 'title': title, 'description': self._og_search_description(webpage), 'uploader': self._search_regex(r'&lt;div[^&gt;]+id="uploader"[^&gt;]*&gt;([^&lt;]+)&lt;', webpage, 'uploader', fatal=False), # TODO more properties (see youtube_dl/extractor/common.py) } I've added yogagloIE to the list of extractors and when I run it I get an error that the URL is not supported. This is really a first draft and any guidance on hoe to improve it and make it work is recommended.
type: UnansweredQuestion
tagged with: python
tagged with: youtube-dl
has answer: http://stackoverflow.com/a/47654795

http://stackoverflow.com/a/47673411
score: 2
has comment: http://stackoverflow.com/comment/138303082
downvote count: 0
has comment: http://stackoverflow.com/comment/82320502
upvote count: 2
type: Answer
has body: Anaconda places it's binaries in it's own install directory. As mentioned in the Anaconda documentation the defaults for these are as follows: Windows 10: C:\Users\&lt;your-username&gt;\Anaconda3\ macOS: /Users/&lt;your-username&gt;/anaconda3 Linux: /home/&lt;your-username&gt;/anaconda3 When installing Anaconda it should prompt you: Do you wish the installer to prepend the Anaconda&lt;2 or 3>install location to PATH in your /home//.bashrc? If you choose not to do this then the path to the Anaconda binaries will not be added to your PATH environment variable in your shell. Therefor you will either need to call the activate script using the full path to your install directory (in macOS), like: /Users/&lt;your-username&gt;/anaconda3/bin/activate root Alternatively, you should manually add the Anaconda binary path to your PATH environment file in your ~/.bashrc file. Instructions on how do do this can be found in the Anaconda documentation, here: Should I add Anaconda to the macOS or Linux PATH?
answers question: http://stackoverflow.com/q/47664482

http://stackoverflow.com/q/47560292
tagged with: regex
has comment: http://stackoverflow.com/comment/82078441
has title: Convert string enclosed in %% to lower case in python
has body: I have pyspark dataframe in which one of the fields has values enclosed within %%..%%. The contents enclosed are not consisted in terms of case. I want to convert them into lower case. Below is a snapshot of the dataframe. The text in the column looks like this https://www.xxxxxxxx.co.nz/Activities|http://www.xxxxxxxx.co.nz/things-to-do/search?location=%%t.Trip_Intrip_1_dest_City_1%% https://images.trvl-media.com/media/content/expus/email/2016/us/banner/images/image_stor-34461_09_600x250.jpg|%%mis_lx_Offers_mod_Images.LargeImageURL%% I want to convert the above text to the following format: https://www.xxxxxxxx.co.nz/Activities|http://www.xxxxxxxx.co.nz/things-to-do/search?location=%%t.trip_intrip_1_dest_city_1%% https://images.trvl-media.com/media/content/expus/email/2016/us/banner/images/image_stor-34461_09_600x250.jpg|%%mis_lx_offers_mod_images.largeimageurl%% Only the string enclosed with %% are to be convert to lowercase
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82078483
accepted answer: http://stackoverflow.com/a/47560459
has answer: http://stackoverflow.com/a/47560459
has comment: http://stackoverflow.com/comment/82078374
tagged with: apache-spark-sql
type: Question
has answer: http://stackoverflow.com/a/47569026
possible better answer: http://stackoverflow.com/a/47560582
has comment: http://stackoverflow.com/comment/82078432
has answer: http://stackoverflow.com/a/47560582
tagged with: python

http://stackoverflow.com/comment/82186210
has text: @yklsga Thanks for pointing it out. Moving `searchfile.close()` inside the for loop will take care of that
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47613677

http://stackoverflow.com/a/47673249
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82308331
score: 13
accepted answer of: http://stackoverflow.com/q/47671732
has comment: http://stackoverflow.com/comment/82307942
type: Answer
has comment: http://stackoverflow.com/comment/82394797
upvote count: 13
answers question: http://stackoverflow.com/q/47671732
has body: If you want the number of images to be a sequence (like a movie with frames), you need to put pixels AND channels as features: input_shape = (225,3072) #a 3D input where the batch size 7338 wasn't informed If you want more processing before throwing 3072 features into an LSTM, you can combine or interleave 2D convolutions and LSTMs for a more refined model (not necessarily better, though, each application has its particular behavior). You can also try to use the new ConvLSTM2D, which will take the five dimensional input: input_shape=(225,32,32,3) #a 5D input where the batch size 7338 wasn't informed I'd probably create a convolutional net with several TimeDistributed(Conv2D(...)) and TimeDistributed(MaxPooling2D(...)) before adding a TimeDistributed(Flatten()) and finally the LSTM(). This will very probably improve both your image understanding and the performance of the LSTM.

http://stackoverflow.com/q/47683265
has body: PYTHON 3: Hi, so I have this piece of code for money in range(0, 2501, 500): print("{} Euro".format(money), end='') throws = 0 d = trump.possession(board) while False in d.values(): prevLoc = piece.location piece.move(trump.throw()) throws += 1 if piece.location &lt; prevLoc: money += 200 if board.names[piece.location] in d and d[board.names[piece.location]] == False and money &gt;= board.values[piece.location]: money -= board.values[piece.location] d[board.names[piece.location]] = True return throws and this code takes 0 money to start with, runs the code, looks for amount of throws required to buy the entire board, does the same with 500 starting money, 1000 and so forth my question is, how can i take the average of the throws to buy the entire board for each starting value? the way my code is now it returns the amount of throws for all the starting values, but simulated once, so it may not be accurate. I searched a lot, and tried some things but i had problems with this one because I want to like run it, say for example, 2000 times, and get the average for each starting value for the money. anyone got any tips for this? been struggling on it for a while.. i tried making a for loop from 0 to 2000 and then inside of that another for loop that prints 0-2500 and then uses the code below in a function, appends the return value of throws into a list and sums it up and devides it by 2000, it did not turn out so good...
has title: How can I average multiple outputs independently in python
accepted answer: http://stackoverflow.com/a/47683652
type: Question
tagged with: average
has answer: http://stackoverflow.com/a/47683652
score: 0
tagged with: list
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82325993
answer count: 1
has comment: http://stackoverflow.com/comment/82326215
has comment: http://stackoverflow.com/comment/82326238
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82326181
tagged with: python

http://stackoverflow.com/q/47664981
type: Question
has answer: http://stackoverflow.com/a/47665098
score: 5
has body: I have a csv file1 which is like FLAGSTAFF AZ 50244.67 5.02 KA1_Podium_Garage_S FLAGSTAFF AZ 33752.13 3.38 KA1_Podium_Garage_S FLAGSTAFF AZ 11965.5 1.2 KA1_Podium_Garage_S FLAGSTAFF AZ 3966.48 0.4 KA1_Podium_Garage_S SEATTLE WA 12646.9 1.26 KA1_Podium_Garage_S SEATTLE WA 225053.92 22.51 KA1_Podium_Garage_S SEATTLE WA 23974.3 2.4 KA1_Podium_Garage_S SEATTLE WA 7036.4 0.7 KA1_Podium_Garage_S SEATTLE WA 3021.93 0.3 KA1_Podium_Garage_S I have a csv file 2 which is like , Alabama AL 1 Alaska AK 2 Arizona AZ 4 Arkansas AR 5 California CA 6 Colorado CO 8 Connecticut CT 9 SEATTLE WA 53 Now i have to append the third column value from csv file2 to csv file1, by comparing second column For example it should look like, AZ code is 4 WA code is 53 wherever AZ,WA is there in my csv file1 , the code should get appended into a column My output should look like, FLAGSTAFF AZ 50244.67 5.02 KA1_Podium_Garage_S 4 FLAGSTAFF AZ 33752.13 3.38 KA1_Podium_Garage_S 4 FLAGSTAFF AZ 11965.5 1.2 KA1_Podium_Garage_S 4 FLAGSTAFF AZ 3966.48 0.4 KA1_Podium_Garage_S 4 SEATTLE WA 12646.9 1.26 KA1_Podium_Garage_S 53 SEATTLE WA 225053.92 22.51 KA1_Podium_Garage_S 53 SEATTLE WA 23974.3 2.4 KA1_Podium_Garage_S 53 SEATTLE WA 7036.4 0.7 KA1_Podium_Garage_S 53 SEATTLE WA 3021.93 0.3 KA1_Podium_Garage_S 53 Here is the code which i tried, with open("/home/sumit/Desktop/CSV_FILE1.csv", "r") as f: first = {rows[1]: rows[0:] for rows in list(csv.reader(f))} # compare second csv and append Code with open("CSVFILE2.csv", "r") as f1: for row in csv.reader(f1): if row[1] in first: first[row[1]].append(row[2]) # convert dict back to list merged = [(k,) + tuple(v) for k, v in first.items()] # write list to output csv with open("output.csv", "w") as f1: csv.writer(f1).writerows(merged) Output am getting like, AZ FLAGSTAFF AZ 44230.4 4.42 KA1_Podium_Garage_S 4 WA SEATTLE WA 45329.3 4.53 KA1_Podium_Garage_S 53
upvote count: 5
answer count: 1
downvote count: 0
tagged with: python
has title: How to compare two csv files?
accepted answer: http://stackoverflow.com/a/47665098
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82289402
has comment: http://stackoverflow.com/comment/82289376
favorite count: 0

http://stackoverflow.com/q/47687633
upvote count: 1
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47687634
has body: I have written a cython code to help bridge the gap between a 3rdparty library and python. I also written some of my code in cython to improve its performance. Can I convert both of my above use cases into raw python? example of use case one def f(double x): return x**2-x def integrate_f(double a, double b, int N): cdef int i cdef double s, dx s = 0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s * dx example of use case 2 from libc.stdlib cimport atoi cdef parse_charptr_to_py_int(char* s): assert s is not NULL, "byte string value is NULL" return atoi(s) # note: atoi() has no error detection!
has title: Can I convert my Cython code to Python?
favorite count: 0
score: 1
answer count: 1
downvote count: 0
tagged with: cython

http://stackoverflow.com/q/47598233
tagged with: pandas
answer count: 1
tagged with: multi-index
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47598398
has body: I have a multi-index dataframe where I'd like to add a "three" index with 6 values, 2 for a, b and c in columns X and Y. import pandas as pd, numpy as np np.arrays = [["one", "one", "one", "two", "two", "two"], ["a", "b", "c", "a", "b", "c"]] df = pd.DataFrame(np.random.randn(6,2), index = pd.MultiIndex.from_tuples(list(zip(*np.arrays))), columns = ["X", "Y"]) df = round(abs(df), 3) df X Y one a 1.521 0.048 b 1.595 1.783 c 0.286 1.042 two a 1.480 1.071 b 0.807 1.058 c 1.730 1.233 What I'd like is: X Y one a 1.521 0.048 b 1.595 1.783 c 0.286 1.042 two a 1.480 1.071 b 0.807 1.058 c 1.730 1.233 three a 1.2 5.5 b 4.2 2.2 c 7.8 3.4 Also, how do I delete an index? I tried the following code, but it gave an AttributeError: delitem del df.loc["one"] Any help would be awesome.
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has title: How to add/delete an index in a multi index dataframe Python
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47598398
downvote count: 0

http://stackoverflow.com/q/47584017
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47584100
possible better answer: http://stackoverflow.com/a/47584322
tagged with: python
has title: Pandas combination of unique indices in two series
has answer: http://stackoverflow.com/a/47584100
has answer: http://stackoverflow.com/a/47584322
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 2
downvote count: 0
has body: I have the following two Pandas series: d1 = pd.Series(index=['a','b','c','d'],data=[100,200,300,400]) d1.index.name='letter' d1.name='value' d2 = pd.Series(index=[1,2,3], data=[.75,.5,.25]) d2.index.name='number' d2.name='pct' print d1 print d2 letter a 100 b 200 c 300 d 400 Name: value, dtype: int64 number 1 0.75 2 0.50 3 0.25 Name: pct, dtype: float64 I want to multiply each combination of rows from the two series. The resulting series will be a multiindex series for each of the 12 combinations of [a,b,c,d] and [1,2,3]. The values will be the product of each of these combinations. I can achieve this by creating a dataframe with a multiindex and then joining each of the two series. What is the better way to do this? d3 = pd.DataFrame(index=pd.MultiIndex.from_product([d1.index, d2.index],names=['letter','number'])).join(d1).join(d2) print d3.value*d3.pct letter number a 1 75.0 2 50.0 3 25.0 b 1 150.0 2 100.0 3 50.0 c 1 225.0 2 150.0 3 75.0 d 1 300.0 2 200.0 3 100.0 dtype: float64

http://stackoverflow.com/comment/82278156
comment on: http://stackoverflow.com/a/47654028
type: AnswerComment
has text: list is like below a = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foobar': 3, 'bar': 5}, {'name':x','bar': 33, 'foo': 10}] i don't want to merge dictionaries, here there are two dictionaries have same name equal x so i will only save one in new list new_lst = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foobar': 3, 'bar': 5}]
score: 0
type: Comment

request
tags question: http://stackoverflow.com/q/47542456
tag name: request
tags question: http://stackoverflow.com/q/47665944
tags question: http://stackoverflow.com/q/47612518
type: Tag
tags question: http://stackoverflow.com/q/47626744
tags question: http://stackoverflow.com/q/47570285
tags question: http://stackoverflow.com/q/47603949
tags question: http://stackoverflow.com/q/47658584

http://stackoverflow.com/a/47604591
has body: It may not be sufficient, to reach your goal, but one obvious improvement is to avoid recalculating the simulation for the same values, in case it is not a lose. Removing all print output will speed things up too. def search(seq, grid): if len(seq) &lt;= 2: return seq[0] p = len(seq)//2 sim_result = simulation(grid, seq[p]) if sim_result == 'lose': return search(seq[p: len(seq)-1], grid) elif sim_result == 'win': return search(seq[0: p], grid) You will probably have to look at how the simulation is run to improve further.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47604564
score: 2
type: Answer

http://stackoverflow.com/q/47662341
tagged with: recurrent-neural-network
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47663179
has answer: http://stackoverflow.com/a/47663179
answer count: 1
tagged with: tensorflow
tagged with: lstm
type: AnsweredQuestion
score: 0
has body: I am trying to build an LSTM model that I downloaded from Github, using Tensorflow and Python 3.6. The link for the model is https://github.com/adeshpande3/LSTM-Sentiment-Analysis. When the following command is executed lstmCell = tf.contrib.rnn.BasicLSTMCell(lstmUnits) I am receiving the error NotFoundError: D:\Anaconda3\lib\site-packages\tensorflow\contrib\rnn\python\ops_lstm_ops.dll not found As you may have notices, the path has no non-ASCII codes!! Any suggestion?
has title: Tensorflow _lstm_ops.dll not found
tagged with: python

spacy
tags question: http://stackoverflow.com/q/47549856
tags question: http://stackoverflow.com/q/47633449
tags question: http://stackoverflow.com/q/47638877
tags question: http://stackoverflow.com/q/47599425
tags question: http://stackoverflow.com/q/47580326
tag name: spacy
tags question: http://stackoverflow.com/q/47603200
tags question: http://stackoverflow.com/q/47626464
tags question: http://stackoverflow.com/q/47649396
tags question: http://stackoverflow.com/q/47682966
tags question: http://stackoverflow.com/q/47595011
type: Tag
tags question: http://stackoverflow.com/q/47654298

http://stackoverflow.com/a/47626300
has comment: http://stackoverflow.com/comment/102944439
score: 0
has body: There is no direct way to stop an playing audio in pydub at this time since it can either use pyaudio or ffplay in the backend (depending on what's installed and accessible). See details on backend code here However, you can hit Ctrl + c to break the play and wrap around play method in try - except block. It will generate KeyboardInterrupt exception that you can process it according your needs. Here is a working sample that's tested on windows. from pydub import AudioSegment from pydub.playback import play song = AudioSegment.from_wav("audio.wav") while True: try: play(song) except KeyboardInterrupt: print "Stopping playing" break #to exit out of loop, back to main program
has comment: http://stackoverflow.com/comment/103046788
answers question: http://stackoverflow.com/q/47596007
has comment: http://stackoverflow.com/comment/103147284
type: Answer

http://stackoverflow.com/comment/136122305
score: 1
type: Comment
has text: @Tashus It seems there is hope. With Pandas 2.1.1 I get this warning: "FutureWarning: The provided callable <function nanstd at ...> is currently using SeriesGroupBy.std. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "std" instead."
type: AnswerComment
comment on: http://stackoverflow.com/a/47699378

http://stackoverflow.com/comment/82075556
has text: Please provide full error message (as given by the compiler), with relevant line numbers and so on. That will make it easier for StackOverflow users to help you. Also, in some cases inspecting that line on your own will help you realize the problem immediately.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47558842

http://stackoverflow.com/a/47552359
score: -1
answers question: http://stackoverflow.com/q/47550922
upvote count: 0
has body: I suppose there's no way to do that. You can only verify input parameters in a function. Just verify a and b internal operator.eq.
downvote count: 1
type: Answer

http://stackoverflow.com/q/47623582
has comment: http://stackoverflow.com/comment/82207260
linked to: http://stackoverflow.com/q/20908754
tagged with: python
has comment: http://stackoverflow.com/comment/82205748
score: 2
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/60553318
has comment: http://stackoverflow.com/comment/82208352
has title: efficiently calculate list of 3d rotation matrices in numpy or scipy
tagged with: scientific-computing
has comment: http://stackoverflow.com/comment/110238451
tagged with: matrix
has comment: http://stackoverflow.com/comment/82208310
has answer: http://stackoverflow.com/a/60553318
has comment: http://stackoverflow.com/comment/110405957
downvote count: 0
has comment: http://stackoverflow.com/comment/82208522
has comment: http://stackoverflow.com/comment/82205311
has comment: http://stackoverflow.com/comment/82208367
has comment: http://stackoverflow.com/comment/110200665
tagged with: scipy
has comment: http://stackoverflow.com/comment/82205672
has comment: http://stackoverflow.com/comment/82207261
has comment: http://stackoverflow.com/comment/82205054
favorite count: 0
has comment: http://stackoverflow.com/comment/82205200
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47630443
has comment: http://stackoverflow.com/comment/82208644
upvote count: 2
has answer: http://stackoverflow.com/a/47630443
has body: I have a list of N unit-normalized 3D vectors p stored in a numpy ndarray with shape (N, 3). I have another such list, q. I want to calculate an ndarray U of shape (N, 3, 3) storing the rotation matrices that rotate each point in p to the corresponding point q. The list of rotation matrices U should satisfy: np.all(np.einsum('ijk,ik-&gt;ij', U, p) == q) On a point-by-point basis, the problem reduces to being able to compute a rotation matrix for a rotation of some angle about some axis. Code solving the single-point case appears below: def rotation_matrix(angle, direction): direction = np.atleast_1d(direction).astype('f4') sina = np.sin(angle) cosa = np.cos(angle) direction = direction/np.sqrt(np.sum(direction*direction)) R = np.diag([cosa, cosa, cosa]) R += np.outer(direction, direction) * (1.0 - cosa) direction *= sina R += np.array(((0.0, -direction[2], direction[1]), (direction[2], 0.0, -direction[0]), (-direction[1], direction[0], 0.0))) return R What I need is a function that behaves exactly as the above function, but instead of accepting a single angle and a single direction, it accepts an angles array of shape (npts, ) and a directions array of shape (npts, 3). The code below is only partially finished - the problem is that neither np.diag nor np.outer accept an axis argument def rotation_matrices(angles, directions): directions = np.atleast_2d(directions) angles = np.atleast_1d(angles) npts = directions.shape[0] directions = directions/np.sqrt(np.sum(directions*directions, axis=1)).reshape((npts, 1)) sina = np.sin(angles) cosa = np.cos(angles) # Lines below require extension to 2d case - np.diag and np.outer do not support axis arguments R = np.diag([cosa, cosa, cosa]) R += np.outer(directions, directions) * (1.0 - cosa) directions *= sina R += np.array(((0.0, -directions[2], directions[1]), (directions[2], 0.0, -directions[0]), (-directions[1], directions[0], 0.0))) return R Does either numpy or scipy have a compact vectorized function computing the approp…

pyopenssl
tag name: pyopenssl
type: Tag
tags question: http://stackoverflow.com/q/47661377

http://stackoverflow.com/comment/82113488
comment on: http://stackoverflow.com/q/47576339
has text: `tkinter` is wrapper for language `tcl` and its graphics module `tk`. `tkinter` doesn't display windows/widgets directly but it executes `tcl/tk` commands to do it
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82317835
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47678507
has text: @Divakar Little thin areas that are not a major colour but appear near a major colour in the image.

http://stackoverflow.com/comment/82317803
score: 0
comment on: http://stackoverflow.com/q/47679190
type: Comment
type: QuestionComment
has text: @mu無 oops, its just an example used to give context to my question

http://stackoverflow.com/a/47673903
type: Answer
has body: #ifdef _DEBUG #define _DEBUG_WAS_DEFINED 1 #undef _DEBUG #endif #include &lt;Python.h&gt; #ifdef _DEBUG_WAS_DEFINED 1 #define _DEBUG 1 #endif That solved the Debugging errors for me (I still can't debug in the python script but I don't need to). It is important to give the name of the python module without .py.
has comment: http://stackoverflow.com/comment/82453668
accepted answer of: http://stackoverflow.com/q/47653159
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/47653159

http://stackoverflow.com/a/47613875
answers question: http://stackoverflow.com/q/47613852
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: You can just do: def sort_students_by_id(student_list): return sorted(student_list, key=lambda s: int(s.split(',')[-1])) # ['Jake,1', 'John,4', 'Alex,10'] print(sort_students_by_id(student_list))

http://stackoverflow.com/a/47592539
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/82142665
type: Answer
has comment: http://stackoverflow.com/comment/82142175
has comment: http://stackoverflow.com/comment/82142383
answers question: http://stackoverflow.com/q/47592490
has body: Updated answer Assuming your csv file is formatted like this (with no column headings): 1E+08,1E+028 2E+08,4E+028 3E+08,9E+028 You can plot the values using the dataframe itself, without creating any lists. In the code below, I've named the columns of the dataframe 'a' and 'b', but you can call them whatever you want as long as you're consistent: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('SDISKSTATS_timeMassDisk.csv', delimiter=',', header=None, names=['a', 'b']) plt.plot(df['a'], df['b'], label='csv') plt.xlabel('x') plt.ylabel('y') plt.title('pls let this work') plt.legend() plt.show()

http://stackoverflow.com/comment/82327535
score: 0
type: QuestionComment
type: Comment
has text: @Jean-FrançoisFabre made the change and fixed the typo. It's quit_time
comment on: http://stackoverflow.com/q/47683896

http://stackoverflow.com/comment/82347241
has text: Thank you but for some reason, it's easier for me to comprehend while loops than for loops, but I'll learn more about now
type: Comment
comment on: http://stackoverflow.com/a/47693977
score: 0
type: AnswerComment

http://stackoverflow.com/q/47641889
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47641975
score: 0
tagged with: python
has title: django creating generic class to validate User authentication
tagged with: generics
accepted answer: http://stackoverflow.com/a/47641993
tagged with: constructor
has body: I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class. The Base Class class CustomView(View): def __init__(self, request): if not request.user.is_authenticated: redirect('register.registerForm') The sub class class DashboardPage(CustomView): def get(self, request): user_object = User.objects.get(username=request.user) all_files = user_object.files_set.all() return render(request, 'dashboard/dashboard.html', {'all_files': all_files}) I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication. I am getting the below error: TypeError at /dashboard/ __init__() missing 1 required positional argument: 'request' Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 1.11.7 Exception Type: TypeError Exception Value: __init__() missing 1 required positional argument: 'request' Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62 Python Executable: C:\Program Files (x86)\Python36-32\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\Varun\\Desktop\\newsite', 'C:\\Program Files (x86)\\Python36-32\\python36.zip', 'C:\\Program Files (x86)\\Python36-32\\DLLs', 'C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\Program Files (x86)\\Python36-32', 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages', 'C:\\Program Files ' '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg', 'C:\\Program Files ' '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg'] Server time: Mon, 4 Dec 2017 20:43:12 +0000
answer count: 2
has answer: http://stackoverflow.com/a/47641975
has answer: http://stackoverflow.com/a/47641993
tagged with: authentication
tagged with: django
type: Question

http://stackoverflow.com/comment/82504942
type: AnswerComment
has text: yes, sorry for that. I think you can use the code above if you pass create_using = nx.DiGraph() https://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html#networkx.convert.from_numpy_matrix
comment on: http://stackoverflow.com/a/47680447
type: Comment
score: 0

http://stackoverflow.com/q/47551596
has comment: http://stackoverflow.com/comment/82060022
favorite count: 0
type: Question
tagged with: numpy
has title: Vector quantization(convector float vector into short vector)
answer count: 0
tagged with: vector
type: UnansweredQuestion
has body: I want to quantize a float vector into short one. I did research online and found many vector quantization algorithms, such as LBG. However, I still do not understand how to map a float vector space into short vector space. So I did further research, one article I found did the exact thing what I want. ﻿import numpy as np from sklearn.preprocessing import normalize def get_median_values_for_bins(bins): median_values = {} for binidx in range(1, bins.shape[0]): binval = bins[binidx] binval_prev = bins[binidx - 1] median_values[binidx] = binval_prev median_values[bins.shape[0]] = bins[bins.shape[0]-1] return median_values def get_quantized_features(features, quantization_factor=30): normalized_features = normalize(features, axis=1) offset = np.abs(np.min(normalized_features)) offset_features = normalized_features + offset # Making all feature values positive # Let's proceed to quantize these positive feature values min_val = np.min(offset_features) max_val = np.max(offset_features) bins = np.linspace(start=min_val, stop=max_val, num=quantization_factor) median_values = get_median_values_for_bins(bins) original_quantized_features = np.digitize(offset_features, bins) quantized_features = np.apply_along_axis(lambda row: map(lambda x: median_values[x], row), 1, original_quantized_features) quantized_features = np.floor(quantization_factor*quantized_features) return quantized_features quantization_factor = 5000 # Adjust this depending on accuracy of quantized features. quantized_features = get_quantized_features(features, quantization_factor)
has comment: http://stackoverflow.com/comment/82059950
downvote count: 0
upvote count: 1
tagged with: scikit-learn
tagged with: python
tagged with: data-science
score: 1

http://stackoverflow.com/a/47697000
downvote count: 0
has body: First join columns and then use to_datetime: s = df['date'] + ' ' + df['time'].astype(str) df['datetime'] = pd.to_datetime(s, format='%d%m%Y %H%M%S') print (df) date time value datetime 0 02112017 143335 1.79 2017-11-02 14:33:35 1 03112017 153540 0.86 2017-11-03 15:35:40 2 04112017 164015 2.79 2017-11-04 16:40:15 3 05112017 135150 3.50 2017-11-05 13:51:50
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82359692
accepted answer of: http://stackoverflow.com/q/47696946
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82360647
type: Answer
answers question: http://stackoverflow.com/q/47696946

http://stackoverflow.com/comment/82096395
type: QuestionComment
has text: Cope the array ONCE (what you did on line 2), that will copy the entire array, i.e. all values, all of which you can change at will.
comment on: http://stackoverflow.com/q/47569461
score: 0
type: Comment

http://stackoverflow.com/q/47670008
tagged with: argparse
score: 1
has title: Python argparser mutually exclusive with same argument in multiple groups
upvote count: 1
possible better answer: http://stackoverflow.com/a/47670820
has answer: http://stackoverflow.com/a/47681518
favorite count: 0
accepted answer: http://stackoverflow.com/a/47681518
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47670820
tagged with: python
has body: I use argparser as a generic way to provide inputs on multiple different files, that are used to generate at the end a json, and sent to a database. Have that said, I want to use multiple mutually exclusive groups, with the option to a flag being part of multiple different groups (as in the example below). parser = argparser.argumentParser group1 = parser.add_mutually_exclusive_group() group2 = parser.add_mutually_exclusive_group(required=True) group3 = parser.add_mutually_exclusive_group() group1.add_argument('-a', type=int) group1.add_argument('-d', type=int) group2.add_argument('-z', type=int) group2.add_argument('-x', type=int) group3.add_argument('-a', type=int) group3.add_argument('-z', type=int) it means that -d and -z can go together (but -z or -x are mandatory), giving me the option to have -a -d -x OR -z -d for some reason, the argparser thinks each one of the -a or -z flags are conflicting, so i have added the conflict_handler to 'resolve', but seems to have no effect
type: AnsweredQuestion

http://stackoverflow.com/comment/82041252
comment on: http://stackoverflow.com/q/47541888
type: Comment
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ It's also in the title but I take your point :) I did like your numpy trick however.

http://stackoverflow.com/q/47690983
tagged with: sql-server
score: 0
has answer: http://stackoverflow.com/a/47691144
answer count: 3
has title: Python - Fill a table MSSQL with data from Excel
tagged with: excel
has answer: http://stackoverflow.com/a/48132790
type: Question
has comment: http://stackoverflow.com/comment/82340981
has body: I have an xlsx file with 4 column and 68k+ lines. And i want to put all data in a table in MSSQL server. I made this. def jb_treat_attributes(dicoval): conn = pymssql.connect(dicoval['MSSQL_erver'],dicoval['MSSQL_Login'],dicoval['MSSQL_Password'],dicoval['MSSQL_Database_DELTA']) cursor = conn.cursor() cursor.execute('TRUNCATE TABLE delta.Attribute') for row in load_workbook(dicoval['path_root']+'Delta/attributes/excel.xlsx').worksheets[0].iter_rows(): row = [cell.value.strip() if cell.value is not None else '' for cell in row] cursor.execute("INSERT INTO delta.Attribute VALUES (%s,%s,%s,%s)",(row[0],row[1],row[2],row[3])) conn.commit() conn.close() And it's working, but with 340s of execution time. Does it exist a way to do it faster ?
has answer: http://stackoverflow.com/a/47691136
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82349133
has text: Yes got it, need to pop obj_def instead of definition. Works now. So if a related name field is specified, a source attribute is required! thanks for the help. :)
type: Comment
comment on: http://stackoverflow.com/a/47694816
type: AnswerComment
score: 0

http://stackoverflow.com/q/47559470
has answer: http://stackoverflow.com/a/47559601
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47560735
type: Question
has answer: http://stackoverflow.com/a/47560735
has body: I am learning Python and I have the following doubt about the NumPy library: I have the following 2x2 matrix: a = np.array([[2,4],[5,1]]) This matrix gives the following output: [[2 4] [5 1]] Nevertheless, I would like to reorder the elements to obtain: [[5 1] [2 4]]
tagged with: python
linked to: http://stackoverflow.com/q/6771428
has title: Ordering the elements in a matrix with Numpy
tagged with: numpy
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47559601
tagged with: arrays
upvote count: 1

http://stackoverflow.com/q/47620836
has comment: http://stackoverflow.com/comment/82201840
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47620937
has answer: http://stackoverflow.com/a/47623211
answer count: 3
has comment: http://stackoverflow.com/comment/82199878
possible better answer: http://stackoverflow.com/a/47620979
has answer: http://stackoverflow.com/a/47620937
score: 0
has comment: http://stackoverflow.com/comment/82199592
has answer: http://stackoverflow.com/a/47620979
has comment: http://stackoverflow.com/comment/82199685
has comment: http://stackoverflow.com/comment/82201447
type: Question
tagged with: python-3.x
has title: Trying to add my first score counter (Python) (Beginner)
has body: This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out. Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.) Here is the code: import random import time def game(): user_wins = 0 user_loses = 0 while True: try: number = int(input('Choose a number between 1 and 10: ')) if 0 &lt;= number &lt;= 10: print('Rolling the dices {} time(s)!'.format(number)) break else: print("That's not quite what we were looking for.") continue except ValueError: print("That's not quite what we were looking for.") user_number = random.randint(1, 50) computer_number = random.randint(1, 50) time.sleep(1) print("You've rolled {}".format(user_number)) time.sleep(1) print('Bob rolled {}'.format(computer_number)) if computer_number &gt; user_number: time.sleep(0.5) print('Bob Won') user_loses += 1 elif computer_number &lt; user_number: time.sleep(0.5) print("You've Won!") user_wins += 1 elif computer_number == user_number: time.sleep(0.5) print('Seems like we have a little situation') print("\nWins: {} \nLosses: {}".format(user_wins, user_loses)) time.sleep(0.5) play_again = input(str("Would you like to play again (y/n)? ")) if play_again == 'y': print("Ready?\n") game() else: print("\nThank you for playing.") game() I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
tagged with: python

http://stackoverflow.com/comment/82040667
has text: @AntonioLópezRuiz you can using cold’s method. Assign the label ,the different from us is how to get the matrix
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47541336
type: Comment

http://stackoverflow.com/a/47684167
accepted answer of: http://stackoverflow.com/q/47683705
answers question: http://stackoverflow.com/q/47683705
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: del df gc.collect() Erase reference, and garbage colector. Edit, this erase your dataframe from memory, you can not close the file, take the info and dont use ram.
score: 1

http://stackoverflow.com/q/47602645
duplicate of: http://stackoverflow.com/q/2295290
has body: I am trying to create a list of functions. For example, if I have a function which takes in two arguments f(x,y) I want to create a list of functions f(x) like [f(x,0), f(x,1), f(x,2), f(x,3)]. Here is a contrived example: Given f(x,i) = x ** i. Make a list [f(x,0), f(x,1), f(x,2), f(x,3)] where the functions in the list accept only one argument. So if the list is named 'a', a function can be called as a[index](x) Here are my attempts at coding this problem. n = 4 def func_creator_1(n): func_list = list() for i in range(n): def func(x): return x ** i func_list.append(func) return func_list f_list_1 = func_creator_1(n) def func_creator_2(i): def func(x): return x ** i return func f_list_2 = [func_creator_2(i) for i in range(n)] def func_creator_3(n): def func_outer(i): def func(x): return x ** i return func func_list = [func_outer(i) for i in range(n)] return func_list f_list_3 = func_creator_3(n) def func_creator_4(n): def func_x_i(x,i): return x ** i return [lambda x: func_x_i(x,i) for i in range(n)] f_list_4 = func_creator_4(n) def func_creator_5(n): return [lambda x: x**i for i in list(range(n))] f_list_5 = func_creator_5(n) Next I assign the variable x to 2 and I print the output. n is already assigned to 4 so that it could be used by the list comprehension below method 2. x = 2 print('function\tmethod 1\tmethod 2\tmethod 3\tmethod 4\tmethod 5') print('-'*90) for c, f_tuple in enumerate(zip(f_list_1, f_list_2, f_list_3, f_list_4, f_list_5)): f1, f2, f3, f4, f5 = f_tuple print('{}^{}:\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n'.format( x, c, f1(x), f2(x), f3(x), f4(x), f5(x))) And here is the output: function method 1 method 2 method 3 method 4 method 5 2^0: 8 1 1 8 8 2^1: 8 2 2 8 8 2^2: 8 4 4 8 8 2^3: 8 8 8 8 8 Except the format looks better on the console... Anyway, in my opinion method 1 is the most readable and is representative of how I would code this, but it fails. I'm a python beginner, but my guess is that when the function in the list is created the variable 'i' i…
has comment: http://stackoverflow.com/comment/82164276
type: Question
has comment: http://stackoverflow.com/comment/82164515
tagged with: for-loop
answer count: 0
tagged with: overwrite
tagged with: dynamic-function
has comment: http://stackoverflow.com/comment/82164270
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82164407
has comment: http://stackoverflow.com/comment/82182636
has comment: http://stackoverflow.com/comment/82164518
has comment: http://stackoverflow.com/comment/82164288
linked to: http://stackoverflow.com/q/2295290
score: 0
has comment: http://stackoverflow.com/comment/82182718
tagged with: list
has comment: http://stackoverflow.com/comment/82164497
has title: Python - Create list of functions in for loop
tagged with: python

http://stackoverflow.com/a/47624121
score: -1
has comment: http://stackoverflow.com/comment/82206441
has comment: http://stackoverflow.com/comment/82206136
has comment: http://stackoverflow.com/comment/82206406
has comment: http://stackoverflow.com/comment/82222930
answers question: http://stackoverflow.com/q/47624036
type: AcceptedAnswer
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/82289257
accepted answer of: http://stackoverflow.com/q/47624036
has body: Edit: This solution reads the file many times but does not rely on a library and is platform independent. Please give more detail! Here is a solution you could use. Of course there are alternatives but I don't know the exact use case. I think you want to reload the file once it is modified. def fileWatcher(): global comandos, comandosText while True: f = open('comandos.json') content = f.read() f.close() if content != comandosText: print("File was modified! Reloading it...") comandos = json.loads(content) comandosText = content time.sleep(0.5) #Adjust this to get the best performance Then later in your main code... import time import threading import json threading.Thread(target=fileWatcher).start() This starts the file watcher asynchronously in the background and updates comandos once you updated the file. This code should run out of the box.
type: Answer

http://stackoverflow.com/comment/96719396
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47580796
has text: @georgexsh could you share your example test in a gist or pastebin to see if I can reproduce/compare with my situation? Specifically the issue for me occurs when there still are running tasks on the pool, I would like all of them to stop immediately and the program to exit
type: Comment

http://stackoverflow.com/q/47575203
accepted answer: http://stackoverflow.com/a/47575273
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47575273
has body: I would like to count the number of uppercase words in a pandas dataframe. I have a dataframe with a column in which there are lists of words in each cell. How can I do it ?
tagged with: python
has title: Pandas: Count number of uppercase words
type: AnsweredQuestion
score: 2
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47606951
type: AcceptedAnswer
downvote count: 0
has body: Here is the answer to do what you are trying to do. I have modified your app code to: import flask import time from flask import request from jinja2 import Environment from jinja2.loaders import FileSystemLoader app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): result = None if request.method == 'POST': counter = int(request.form.get('counter', 0)) def inner(): for x in range(counter):# eg: 100 should input value from browser time.sleep(1) yield '%s&lt;br/&gt;\n' % x result = inner env = Environment(loader=FileSystemLoader('templates')) tmpl = env.get_template('result.html') return flask.Response(tmpl.generate(result=result if result is None else result())) app.run(debug=True) Here I have modified the index view to handle both GET and POST methods. If a simple GET requests comes it returns the template with result=None and if method is POST it returns=result()(I have assigned result=inner in POST block). The logic to handle None or a value is handled in the template. And your template needs to be changed to: &lt;html&gt; {% block body %} &lt;body&gt; {% if result%} {% for line in result %} {{ line }} {% endfor %} {% else %} &lt;form method="post"&gt; &lt;input type="text" placeholder="Enter a number" name="counter"&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; {% endif %} &lt;/body&gt; {% endblock %} &lt;/html&gt; I have added the if-else condition as you are using the same template and even the URL doesn't change. You can follow Flask Quickstart Tutorial to learn more
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47606587
score: 2
answers question: http://stackoverflow.com/q/47606587

http://stackoverflow.com/comment/82236221
type: QuestionComment
has text: Thanks. I assume `np_pred_boxes.shape` is something like (m, n, 3) or (m, n, 4). Is that correct?
comment on: http://stackoverflow.com/q/47638689
score: 0
type: Comment

http://stackoverflow.com/q/47641314
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82244954
tagged with: tweepy
tagged with: telegram-bot
has body: I am trying to create a telegram bot that streams requested tweets to a user, group or channel. Thus far i have been able to stream the tweets to my computer successfully, however, when i try to send the tweets to my telegram bot i only receive a single tweet. I am able to view the tweet-stream on my computer but i can't get telegram to forward each tweet, besisdes the first one as a message. please have a look at my code, any help would be greatly appreaciated updater = Updater(token=TOKEN) jB = updater.job_queue dispatcher = updater.dispatcher class Listener(StreamListener): def on_data(self, data): # use json to load data all_data = json.loads(data) tweet = all_data["text"] username = all_data["user"]["screen_name"] tweet_stream = {"name":username, "twit":tweet} print(tweet_data) #remove retweets from the tweets if not all_data["retweeted"] and 'RT @' not in all_data["text"]: print((username, tweet)) def bot_message(bot, job): bot.send_message(chat_id=job.context, text=(username, tweet)) def bot_timer(bot, update, job_queue): bot.send_message(chat_id=update.message.chat_id, text='Tweet will be sent every 5 seconds') job_queue.run_repeating(bot_message, 5, context=update.message.chat_id) bot_handler=CommandHandler('tweets',bot_timer,pass_job_queue=True) updater.dispatcher.add_handler(bot_handler) # *** need to apply the error codes for the error function def on_error(self, status): print(status, "this is an error") return True # List of followers to track followers =[ "759251", "1333467482", "2592325530", "759252279862104064", "1051053836", "884936655437791232", "862007728956485632","869908314292924416" ] twitterStream = Stream(auth, Listener()) twitterStream.filter(follow=followers, async=True) # telegram to send message logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) updater.start_polling(timeout=5)
has title: Telegram bot only sends one message from twitter stream
score: 1
tagged with: twitter-streaming-api
favorite count: 0
type: Question
tagged with: python-telegram-bot
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82242104

http://stackoverflow.com/a/47643690
score: 3
has comment: http://stackoverflow.com/comment/82246574
answers question: http://stackoverflow.com/q/47643264
type: Answer
has comment: http://stackoverflow.com/comment/82246603
has comment: http://stackoverflow.com/comment/82246157
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47643264
has body: One option would be to calculate the ranks by dropping the duplicates first: temp = df'HP', 'unit'.drop_duplicates() temp.assign(rank=temp['HP'].rank(method='min', ascending=False)).merge(df) Out[48]: HP unit rank N-D 0 24 UD 1.0 C1 1 24 UD 1.0 C2 2 24 UD 1.0 C3 3 7 UC 2.0 Q1 4 7 UC 2.0 Q2 5 7 UC 2.0 Q3 6 7 UA 2.0 D1 7 7 UA 2.0 D2 8 7 UA 2.0 D3 9 5 UB 4.0 E1 10 5 UB 4.0 E2 11 5 UB 4.0 E3 Added (antonvbr) a slight modification to assign directly: df['rank']= (df'HP', 'unit'.drop_duplicates()['HP'] .rank(method='min', ascending=False) .reindex(range(len(df)),method='pad'))

http://stackoverflow.com/comment/82278238
has text: You're not using OrderedDict at all. You just have a string literal that looks like code using OrderedDict (and doing it all wrong, trying to call OrderedDict on a list of keys and not even trying to use the constructed OrderedDict).
comment on: http://stackoverflow.com/q/47659689
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47568569
tagged with: python
tagged with: jupyter
has answer: http://stackoverflow.com/a/58240595
has title: Read/Write access issue Python on Jupyter Server
type: Question
has body: I am working on a Jupyter notebook server remotely and when I create a file using: file = open("test.txt","w") file.write("test") file.close() Everything works as expected and the file test.txt is written to the working directory. My problem arises wh trying to use the the Pandas to_hfs command: data.to_hdf('raw_data.h5','raw_data_santodomingo',mode='w',format='f',data_columns=True) I get the following error: Opening raw_data.h5 in read-only mode --------------------------------------------------------------------------- OSError Traceback (most recent call last) /opt/conda/lib/python3.6/site-packages/pandas/io/pytables.py in open(self, mode, **kwargs) 586 try: --&gt; 587 self._handle = tables.open_file(self._path, self._mode, **kwargs) 588 except (IOError) as e: # pragma: no cover /opt/conda/lib/python3.6/site-packages/tables/file.py in open_file(filename, mode, title, root_uep, filters, **kwargs) 319 # Finally, create the File instance, and return it --&gt; 320 return File(filename, mode, title, root_uep, filters, **kwargs) 321 /opt/conda/lib/python3.6/site-packages/tables/file.py in __init__(self, filename, mode, title, root_uep, filters, **kwargs) 783 # Now, it is time to initialize the File extension --&gt; 784 self._g_new(filename, mode, **params) 785 tables/hdf5extension.pyx in tables.hdf5extension.File._g_new() /opt/conda/lib/python3.6/site-packages/tables/utils.py in check_file_access(filename, mode) 178 raise IOError("directory ``%s`` exists but it can not be " --&gt; 179 "written" % (parentname,)) 180 elif mode == 'a': OSError: directory ``.`` exists but it can not be written During handling of the above exception, another exception occurred: OSError Traceback (most recent call last) &lt;ipython-input-182-479f2e98ea81&gt; in &lt;module&gt;() ----&gt; 1 pre_clean_data.to_hdf('raw_data.h5','raw_data_santodomingo',mode='w',format='f',data_columns=True) /opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in to_hdf(self, path_or_buf, key, **kwargs) 11…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82265712
answer count: 1
has comment: http://stackoverflow.com/comment/82266043
has comment: http://stackoverflow.com/comment/82497067
has comment: http://stackoverflow.com/comment/82268062
has comment: http://stackoverflow.com/comment/82477643
has comment: http://stackoverflow.com/comment/82271739
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/82265304
tagged with: file-permissions

http://stackoverflow.com/comment/82271661
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47656015
type: Comment
has text: It only goes into the debugger when it encounters and error. You can just add "raise" in your source code if you want it to start the debugger at at that point

http://stackoverflow.com/comment/82151760
score: 0
has text: did you run it in console/terminal/cmd.exe to see error message in console ? It could give more useful information.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47584350

http://stackoverflow.com/comment/82212680
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47627417
has text: @jamadagni I only looked at the [source code for tuple and that doesn't define an `__init__`](https://github.com/python/cpython/blob/master/Objects/tupleobject.c#L840). That means it inherits it from `object`. But it does have a `__new__` method (a few lines later, it's called `tp_new`).
type: Comment

http://stackoverflow.com/q/47647365
tagged with: folium
has comment: http://stackoverflow.com/comment/82253733
score: 0
answer count: 0
has body: I want to learn folium with the following documation https://python-visualization.github.io/folium/index.html But when I use pip install found that only have version 0.5.0 in Windows command Does someone know about this question? I want the latest version because I got a problem with its function markers m = folium.Map( location=[45.372, -121.6972], zoom_start=12, tiles='Stamen Terrain' ) tooltip = 'Click me!' folium.Marker([45.3288, -121.6625], popup='Mt. Hood Meadows', tooltip=tooltip).add_to(m) folium.Marker([45.3311, -121.7113], popup='Timberline Lodge', tooltip=tooltip).add_to(m) m
has comment: http://stackoverflow.com/comment/82253798
has comment: http://stackoverflow.com/comment/82253431
has comment: http://stackoverflow.com/comment/82253538
has comment: http://stackoverflow.com/comment/82254633
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82254822
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82254013
has comment: http://stackoverflow.com/comment/82253706
has title: How to install folium 0.5.0+115.g53bf936 in python 3.6.3
tagged with: python
has comment: http://stackoverflow.com/comment/82253294

http://stackoverflow.com/comment/82226847
type: Comment
type: QuestionComment
has text: Delete `while upper >=2:`, it is unnecessary. `for num in range(2, upper + 1):` is doing the job.
comment on: http://stackoverflow.com/q/47634410
score: 0

http://stackoverflow.com/a/47601703
has body: As far as I'm aware (current release of numba: 0.36), you cannot use jitclass with ahead-of-time compilation (AOT). It is unclear from your question how much compilation time is spent in your code. One minute seems extreme, but I've typically only used a few jitclasses at a time. I have used dozens of inter-dependent functions spread across many modules and have never seen compilation times more than a handful of seconds. If you could compare the time it takes to execute your code for the first time vs subsequent times, that should be the compilation time assuming the runtime is deterministic. Your best option if the start up cost of doing just-in-time compilation is not practical is probably to use Cython to write C-extensions. The downside is that you won't be able to use them from numba code in nopython mode. There many be some better way of organizing your datastructures that might help, but it's hard to tell without seeing the code.
answers question: http://stackoverflow.com/q/47597264
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82230505
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47597264

http://stackoverflow.com/comment/82319430
type: Comment
has text: Additional: `pk` means primary key.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47680111

http://stackoverflow.com/q/47630462
tagged with: conda
score: 0
tagged with: anaconda
answer count: 0
has comment: http://stackoverflow.com/comment/82221326
has comment: http://stackoverflow.com/comment/82225825
has comment: http://stackoverflow.com/comment/82220882
has comment: http://stackoverflow.com/comment/82222418
has body: I've created a concoct_env to run python 2.7.6. The default python on my system is python 3.4.6. So I activate the concoct environment. user1@workmachine:~/anaconda3/envs/concoct_env$ source activate concoct_env I check which python version that will be called, looks fine. (concoct_env) user1@workmachine:~/anaconda3/envs/concoct_env$ which python /home/user1/anaconda3/envs/concoct_env/bin/python But when I call python or check the python version, it shows the default python installed on my system. (concoct_env) user1@workmachine:~/anaconda3/envs/concoct_env$ python --version Python 3.4.6 (concoct_env) user1@workmachine:~/anaconda3/envs/concoct_env$ python Python 3.4.6 (default, Mar 22 2017, 12:26:13) [GCC] on linux Is there something I'm missing in the PATH parameters in my bashrc? Thanks in advance for nay help. Edited to add: How I create the test environment conda create -n concoct_env python=2.7.6 How my bashrc file looks like: export PATH=/home/user1/anaconda3/bin:$PATH Location of python 2.7.6 in conda environment (same as indicated in "which python" Python 2.7.6 |Continuum Analytics, Inc.| (default, May 27 2014, 14:50:58) &gt;&gt;&gt; os.path.dirname(sys.executable) '/home/user1/anaconda3/envs/concoct_env/bin'
has title: Calling python in conda environment (2.7.6) activate defaults to python in system (3.4.6)
type: Question
has comment: http://stackoverflow.com/comment/82220589
has comment: http://stackoverflow.com/comment/82221633
has comment: http://stackoverflow.com/comment/82220143
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1270537
tagged with: python
has comment: http://stackoverflow.com/comment/82219770

http://stackoverflow.com/comment/118755326
comment on: http://stackoverflow.com/a/47582228
type: AnswerComment
has text: The width of the axis and labels is not computed by any Python code, it is only computed in the browser, in JavaScript code. So the first option is not possible in principle, except in the Bokeh server case (and even then, only retro-actively after the fact). A fixed size with clipping could be possible, but no one has ever asked for that as a feature, so it's never been considered. Please feel free to open a [github issue](https://github.com/bokeh/bokeh/issues) to propose it.
score: 1
type: Comment

http://stackoverflow.com/comment/82233239
type: Comment
has text: @mesboomin please test it is working fine .please let me know if any thing is required from my side
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47636071

http://stackoverflow.com/comment/82176501
has text: You're missing some model definitions above, and your .get is missing a named parameter (like `platforms=platform.list)`. That said, you should in general think of what the sql is doing. If you had all of this right, you're where clause is asking your sql engine to match two lists exactly. I don't think that's what you are after. Moreover, I don't know why you need to go get "Upload" because you already (I think?) have all the "Uploads" (again, guessing because I haven't seen any models) in platform.list. So in the template it would be platform.list.0.field (or whatever).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47609001
type: Comment

http://stackoverflow.com/comment/115547692
type: AnswerComment
score: 0
type: Comment
has text: That did it for me! Thanks for you solution!
comment on: http://stackoverflow.com/a/47560616

http://stackoverflow.com/a/47614040
answers question: http://stackoverflow.com/q/47614013
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47614013
type: AcceptedAnswer
has body: Very popular mistake var = Widget(...).grid() It assigns to var value returned by grid() - None - so later you get None.bind() You have to do it in two lines var = Widget(...) var.grid() After that bind() will work correctly. BTW: bind() executes function with argument event which you have to receive. import tkinter as tk # --- functions --- def press_space(event): #print(event) #print( dir(event) ) print('Hello world') # --- main --- root = tk.Tk() txt = tk.Text(root) txt.grid() txt.bind('&lt;space&gt;', press_space) root.mainloop()

http://stackoverflow.com/a/47613455
answers question: http://stackoverflow.com/q/47613323
downvote count: 1
type: Answer
has body: Easy to understand version: original = (([75, 0], [100, 0], [100, 370]), ([75, 0], [100, 370], [75, 370])) final = [] for each_tuple in original: final_child_list = [] for each_list in each_tuple: final_child_list.extend(each_list) final.append(final_child_list) You'll get: &gt;&gt;&gt; final [[75, 0, 100, 0, 100, 370], [75, 0, 100, 370, 75, 370]] # if you prefer the inside element to be tuples &gt;&gt;&gt; [tuple(x) for x in final] [(75, 0, 100, 0, 100, 370), (75, 0, 100, 370, 75, 370)] There might be shorter versions using list comprehension, but less readability.
score: 0
upvote count: 1

http://stackoverflow.com/comment/82293664
comment on: http://stackoverflow.com/q/47666565
score: 0
has text: @llimllib [avoiding dots](https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82109154
type: QuestionComment
has text: I see your point. This might help you https://stackoverflow.com/a/36829884/6102131 (edit: linking to the answer instead)
comment on: http://stackoverflow.com/q/47575934
score: 1
type: Comment

http://stackoverflow.com/comment/82166137
comment on: http://stackoverflow.com/a/47601270
score: 0
type: Comment
type: AnswerComment
has text: yeah, group by B and C

http://stackoverflow.com/a/47609385
score: 2
downvote count: 0
upvote count: 2
has body: Use side='left' or side='right' for your buttons since you want them to go left-to-right within their containing frame. button1 = tki.Button(btn_frm_r,text='Bottom button 1').pack(side="left") button2 = tki.Button(btn_frm_c,text='Bottom button 2').pack(side="left") button3 = tki.Button(btn_frm_l,text='Bottom button 3').pack(side="left") By the way, if you're going to do tki.Button(...).pack(...), there's no point in assigning it to a variable. The variable will always have the value None. A full explanation of the pack algorithm is here: http://tcl.tk/man/tcl8.5/TkCmd/pack.htm#M26
type: Answer
answers question: http://stackoverflow.com/q/47609256

http://stackoverflow.com/comment/82122565
comment on: http://stackoverflow.com/q/47582434
score: 0
has text: Because they have a different library for DB2 support: https://pypi.python.org/pypi/ibm_db/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82073104
score: 0
comment on: http://stackoverflow.com/q/47557740
type: Comment
type: QuestionComment
has text: Pure code-writing requests are off-topic on Stack Overflow -- we expect questions here to relate to *specific* programming problems -- but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better.

http://stackoverflow.com/a/47591877
has comment: http://stackoverflow.com/comment/82164416
has comment: http://stackoverflow.com/comment/82206796
answers question: http://stackoverflow.com/q/47581326
has body: A million is small for the answer I give below. Expecting only that you have to be able to run the solution in the interview, without a pause, then The following works in less than two seconds and gives the required result: from collections import Counter def triple_counter(s): c = Counter(s[n-3: n] for n in range(3, len(s))) for tri, n in c.most_common(): if n &gt; 1: print('%s - %i times.' % (tri, n)) else: break if __name__ == '__main__': import random s = ''.join(random.choice('0123456789') for _ in range(1_000_000)) triple_counter(s) Hopefully the interviewer would be looking for use of the standard libraries collections.Counter class. Parallel execution version I wrote a blog post on this with more explanation.
has comment: http://stackoverflow.com/comment/82148115
downvote count: 0
has comment: http://stackoverflow.com/comment/82213696
upvote count: 15
has comment: http://stackoverflow.com/comment/82204749
has comment: http://stackoverflow.com/comment/82147109
type: Answer
has comment: http://stackoverflow.com/comment/82148628
score: 15

http://stackoverflow.com/comment/82193220
has text: What is the value of `api_base`? Enabling logging might reveal something: https://stackoverflow.com/a/24588289/21945. (not sure if that will work in Lambda).
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47615802
type: Comment

http://stackoverflow.com/a/47682068
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47681818
has body: it's due to the cycle, this should fix it: def discount(self, current_price, days): for day in range(days): yield current_price current_price = current_price * 0.9 def run(self): initial = self.get_item_price() for price in self.discount(initial, 10): print(price)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82167384
score: 0
has text: I could manually check all diagonals but the 2D array won’t always be the same size
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47604046

http://stackoverflow.com/a/68233594
type: Answer
score: 0
has body: You can use CSS selectors to grab those links. soup.select_one('.yuRUbf a')['href'] Code and example in the online IDE: from bs4 import BeautifulSoup import requests headers = { 'User-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)" "Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } html = requests.get('https://www.google.com/search?q=turtles', headers=headers) soup = BeautifulSoup(html.text, 'html.parser') # iterates over organic results container for result in soup.select('.tF2Cxc'): # extracts url from "result" container url = result.select_one('.yuRUbf a')['href'] print(url) ------------ ''' https://en.wikipedia.org/wiki/Turtle https://www.worldwildlife.org/species/sea-turtle https://www.britannica.com/animal/turtle-reptile https://www.britannica.com/story/whats-the-difference-between-a-turtle-and-a-tortoise https://www.fisheries.noaa.gov/sea-turtles https://www.fisheries.noaa.gov/species/green-turtle https://turtlesurvival.org/ https://www.outdooralabama.com/reptiles/turtles https://www.rewild.org/lost-species/lost-turtles ''' Alternatively, you can do the same thing using Google Search Engine Results API from SerpApi. It's a paid API with a free trial of 5,000 searches and the main difference here is that all you have to do is to navigate through structured JSON rather than figuring out why stuff doesn't work. Code to integrate: from serpapi import GoogleSearch params = { "api_key": "YOUR_API_KEY", "engine": "google", "q": "turtle", } search = GoogleSearch(params) results = search.get_dict() for result in results['organic_results']: print(result['link']) -------------- ''' https://en.wikipedia.org/wiki/Turtle https://www.britannica.com/animal/turtle-reptile https://www.britannica.com/story/whats-the-difference-between-a-turtle-and-a-tortoise https://turtlesurvival.org/ https://www.worldwildlife.org/species/sea-turtle https://www.conserveturtles.org/ ''' Disclaimer, I work for SerpApi.
answers question: http://stackoverflow.com/q/47618469

http://stackoverflow.com/comment/116656212
score: 0
type: Comment
type: QuestionComment
has text: @Karl, Hi did you ever find a solution for this. I need to do the same.
comment on: http://stackoverflow.com/q/47559623

http://stackoverflow.com/q/47671985
has comment: http://stackoverflow.com/comment/82303202
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47681161
has title: JSON contains incorrect UTF-8 \u00ce\u00b2 instead of Unicode \u03b2, how to fix in Python?
has comment: http://stackoverflow.com/comment/82371278
answer count: 2
has comment: http://stackoverflow.com/comment/82303509
score: 1
downvote count: 0
upvote count: 1
has body: First note that symbol β (Greek beta) have hex representation in UTF-8: CE B2 I have legacy source code in Python 2.7 that uses json strings: u'{"something":"text \\u00ce\\u00b2 text..."}' I then it calls json.loads(string) or json.loads(string, 'utf-8'), but the result is Unicode string with UTF-8 characters: u'text \xce\xb2 text' What I want is normal Python Unicode (UTF-16?) string: u'text β text' If I call: text = text.decode('unicode_escape') before json.loads, then I got correct Unicode β symbol, but it also breaks json by also replacing all new lines - \n The question is, how to convert only "\\u00ce\\00b2" part without affecting other json special characters? (I am new to Python, and it is not my source code, so I have no idea how this is supposed to work. I suspect that the code only works with ASCII characters)
tagged with: string
tagged with: unicode
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47674970
has comment: http://stackoverflow.com/comment/82379930
has answer: http://stackoverflow.com/a/47674970
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82303319
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/82305708
possible better answer: http://stackoverflow.com/a/47681161
has comment: http://stackoverflow.com/comment/82303376

http://stackoverflow.com/q/47640407
has body: I have two Python lists of numbers. list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563] list2 = [2,5,14,3] ##these numbers specify desired chunk sizes I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2. As a result, I would like to have this: a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1 b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1 c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1 d_list = [154,122,563] ##next 3 numbers from list1 Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1, the second chunk should have the next 5 elements, and so on. How can I do this?
has answer: http://stackoverflow.com/a/47640597
has answer: http://stackoverflow.com/a/58566401
score: 1
tagged with: python
has title: How to Split or break a Python list into Unequal chunks, with specified chunk sizes
answer count: 3
has answer: http://stackoverflow.com/a/47640651
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47613962
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47613957
downvote count: 0
answers question: http://stackoverflow.com/q/47613957
score: 3
has body: You can use dictionary comprehension: def run(domain, **kwargs): options = {'opt1': 'abc', 'opt2': 'def'} options = {a:kwargs.get(a, b) for a, b in options.items()}
type: Answer

http://stackoverflow.com/comment/82161679
comment on: http://stackoverflow.com/q/47601487
type: Comment
has text: What is ID, Name, Cost and Date1? Do they change on these loops?
score: 1
type: QuestionComment

http://stackoverflow.com/comment/82084887
score: 0
type: Comment
type: AnswerComment
has text: @ytutow That is horrible.
comment on: http://stackoverflow.com/a/47563443

http://stackoverflow.com/comment/82155459
score: 0
comment on: http://stackoverflow.com/q/47598578
type: Comment
type: QuestionComment
has text: Why are people down voting this question? I couldn't find this through a search.

http://stackoverflow.com/comment/82244725
comment on: http://stackoverflow.com/q/47642991
type: Comment
has text: You're not calling the lambda function (and also the lambda is pointless - you could just call `BasicLSTMCell` directly).
score: 1
type: QuestionComment

http://stackoverflow.com/comment/82243979
type: QuestionComment
comment on: http://stackoverflow.com/q/47642568
score: 1
type: Comment
has text: Or `lambda t: t[0] * 2` depending on the call

equation
tags question: http://stackoverflow.com/q/47612058
tag name: equation
type: Tag

http://stackoverflow.com/q/47606652
has title: How to standardize matrix row-wise (axis=1)?
tagged with: standardized
type: Question
accepted answer: http://stackoverflow.com/a/47606695
linked to: http://stackoverflow.com/q/12525722
has comment: http://stackoverflow.com/comment/82171737
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47606695
tagged with: matrix
answer count: 1
has body: For a two-dimensional array, I'm trying to make a standardize-function, which should work row-wise and column-wise. I'm not sure what to do when an argument is given with axis=1 (row-wise). def standardize(x, axis=None): if axis == 0: return (x - x.mean(axis)) / x.std(axis) else: ????? I tried to change axis to axis = 1 in this part: (x - x.mean(axis)) / x.std(axis) But then I got the following error: ValueError: operands could not be broadcast together with shapes (4,3) (4,) Can someone explain to me what to do as I'm still a beginner?

http://stackoverflow.com/comment/82110552
has text: @goodvibration Comented all code, it works if just have the function declared and calling it, how can I debug this?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47576697

http://stackoverflow.com/comment/82058628
has text: Also doing `..+'\n', end='')` does not make sense. Simplify it as above.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47550892

http://stackoverflow.com/q/47574478
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82106765
downvote count: 1
favorite count: 0
type: Question
has title: How to reduce computation when making combination of feature vectors?
tagged with: feature-selection
type: UnansweredQuestion
tagged with: feature-extraction
has body: I have two classes of feature vectors, lets call them A and B (each of dimension d). Now I can take one vector from class A and one vector from class B, perform a linear operation on them to get a resultant vector also of dimension d. (Note: The linear operation is not important here, you can assume it to be simple vector addition). Lets call the class of resultant vector as C. Clearly computing resultant class C, is O(n^2) task. Now, I need to find similarity between a query vector (q) and a subset of vectors in class C (The subset is formed based on a criterion on the vectors in class C). If a vector 'x' in this subset is similar to the vector 'q' above a threshold, the output will be original vectors from classes A and B, whose combination made the vector 'x'. What is the fastest way to do this if I am ready to compromise a little on accuracy of both, finding the subset of class C based on the criterion as well as, of finding the similarity of query vector. I have thought of precomputing the class C, but even thousand feature vectors in each class will result in a million combination. I think some clustering might help but I am unable to reach a concrete solution.
has comment: http://stackoverflow.com/comment/82106131
has comment: http://stackoverflow.com/comment/82107263
tagged with: python
tagged with: data-science
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82106075

http://stackoverflow.com/q/47549799
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82056671
has title: How to pass a list of files as a parameter in Python?
tagged with: python
tagged with: pyenchant
tagged with: parameters
type: Question
tagged with: list
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82074806
type: UnansweredQuestion
score: 1
has body: I'm working with the pyenchant spelling corrector and I'm trying to pass multiple files as a parameter in order to create a personal dictionary. I have 82 additional text files stored in a folder and I would like to pass them to the function without typing every single file name. Is that possible with Python? I've already tried creating a list of all the text files and then passing the list, but that didn't work. Here is my code: import enchant import os allfiles = os.listdir("dicts") dictpwl = enchant.DictWithPWL("de_DE", allfiles) This yields the following error: AttributeError: 'list' object has no attribute '_request_dict_data' Any suggestions on how to pass my text files in a different way? Thanks in advance!

http://stackoverflow.com/a/47695027
has body: This: 1,2 == 1,2 is evaluated as a three element tuple that contains 1, 2 == 1 and 2 respectively. You need to use a couple of parentheses here: (1, 2) == (1, 2) This is stated in the Language Reference: Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
accepted answer of: http://stackoverflow.com/q/47694844
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47694844
type: AcceptedAnswer

http://stackoverflow.com/a/47663138
has body: Here is the code that will read from input file and builds adjacency matrix f = open("graph.txt", 'r') graph = {} n = 0 for i in f.readlines(): nodes = i.split(" ") n1 = int(nodes[0]) n2 = int(nodes[1]) if n &lt; n1 and n1 &gt; n2: n = n1 if n &lt; n2 and n2 &gt; n1: n = n2 if n1 not in list(graph): graph[n1] = [] adjacencyList = graph[n1] adjacencyList.append(n2) graph[n1] = adjacencyList adjacencyMatrix = [] for i in range(1,n+1): row = [] for j in range(1,n+1): if i in list(graph) and j in graph[i]: row.append(1) else: row.append(0) adjacencyMatrix.append(row) for i in range(n): row = "" for j in range(n): row += str(adjacencyMatrix[i][j])+" " print(row)
has comment: http://stackoverflow.com/comment/82285498
answers question: http://stackoverflow.com/q/47663030
has comment: http://stackoverflow.com/comment/82294385
has comment: http://stackoverflow.com/comment/82285592
has comment: http://stackoverflow.com/comment/82288239
has comment: http://stackoverflow.com/comment/82287222
type: Answer
has comment: http://stackoverflow.com/comment/82286344
score: 0
has comment: http://stackoverflow.com/comment/82285611
has comment: http://stackoverflow.com/comment/82295844
has comment: http://stackoverflow.com/comment/82287203
has comment: http://stackoverflow.com/comment/82287171
has comment: http://stackoverflow.com/comment/82286459
has comment: http://stackoverflow.com/comment/82286885

http://stackoverflow.com/a/47591883
score: 1
downvote count: 0
upvote count: 1
type: Answer
has body: If you already have the binary downloaded on the folder why you need to run pip install commit That would download and install it again right? Just run pip install . on the folder where you downloaded the package.
answers question: http://stackoverflow.com/q/47591513
has comment: http://stackoverflow.com/comment/82196565

http://stackoverflow.com/q/47565987
has comment: http://stackoverflow.com/comment/82108184
tagged with: python-3.x
has body: Say in Tkinter you have a listbox of a certain size within a window. Then let's say you add a string to that listbox that is larger than that size. If you highlight this element and drag to the side the listbox will automatically "scroll" itself so that you can see the full element. Is there anyway to disable this short of running a thread that repeatedly attempts to set the scroll to 0? import tkinter root = tkinter.Tk() listbox = tkinter.Listbox(root) listbox.insert("end", "Minimal, Complete, and Verifiable example") listbox.pack() root.mainloop() quit()
has comment: http://stackoverflow.com/comment/82106207
type: Question
has comment: http://stackoverflow.com/comment/82107808
accepted answer: http://stackoverflow.com/a/47575656
has comment: http://stackoverflow.com/comment/82090999
tagged with: python
has answer: http://stackoverflow.com/a/47575656
has comment: http://stackoverflow.com/comment/82106805
tagged with: tkinter
type: AnsweredQuestion
tagged with: listbox
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has title: How can I disable horizontal scrolling in a Tkinter listbox? (Python 3)

http://stackoverflow.com/q/47613138
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47613180
favorite count: 0
type: Question
has title: Remove common dictionary elements that are in 2 lists
has answer: http://stackoverflow.com/a/47613234
type: UnansweredQuestion
has body: I am trying to 'minus' out the common elements within 2 lists, however the elements within the 2 lists are dictionary. Example: list_dict_01 = [{'aaa':123}, {'bbb':234}, {'ccc':234}, {'ddd':456}] list_dict_02 = [{'bbb':234}, {'ddd':456}] res = list(set(list_dict_01)^set(list_dict_02)) # Expected output : `[{'aaa':123}, {'ccc':234}]` However as I execute the code, I got the following errors: # Error: unhashable type: 'dict' # Traceback (most recent call last): # File "&lt;maya console&gt;", line 4, in &lt;module&gt; # TypeError: unhashable type: 'dict' # What other ways can I do to achieve the result I wanted?
has comment: http://stackoverflow.com/comment/82184616
tagged with: python
has comment: http://stackoverflow.com/comment/82184556
answer count: 2
score: 1

http://stackoverflow.com/a/47580848
has body: To answer your question on count of occurrences: What I would do is: #This represents all early, ontime, and late arrivals. If you want to grab per stopnum then you need to groupby first (see below) #Define a specific stop num and store as stop_num = the number early, ontime, late = df_arrivals[df_arrivals.stop_number == stop_num].OnTimeStatus.value_counts()[-1], df_arrivals.OnTimeStatus.value_counts()[0], df_arrivals.OnTimeStatus.value_counts()[1] total_stops = len(df_stops[df_stops.StopNumber == stop_num]) EarlyPercent= early/total_stops OntimePercent= ontime/total_stops LatePercent= late/total_stops Now keep in mind that this is only per one stop num. I actually don't think there is a way to avoid iterations in this case without overly complex code (chaining, etc...). df_stops['PercentEarly'] = '' df_stops['PercentOntime'] = '' df_stops['PercentLate'] = '' for stop_num in df_arrivals.stop_number.tolist(): early, ontime, late = df_arrivals[df_arrivals.stop_number == stop_num].OnTimeStatus.value_counts()[-1], df_arrivals.OnTimeStatus.value_counts()[0], df_arrivals.OnTimeStatus.value_counts()[1] total_stops = len(df_stops[df_stops.StopNumber == stop_num]) EarlyPercent= early/total_stops OntimePercent= ontime/total_stops LatePercent= late/total_stops df_stops.loc[df_stops.StopNumber == stop_num, 'PercentEarly'] =EarlyPercent df_stops.loc[df_stops.StopNumber == stop_num, 'PercentOnTime'] = OntimePercent df_stops.loc[df_stops.StopNumber == stop_num, 'PercentLate'] =LatePercent
answers question: http://stackoverflow.com/q/47562671
type: Answer
score: 0

http://stackoverflow.com/comment/82156846
type: Comment
comment on: http://stackoverflow.com/a/47599093
type: AnswerComment
score: 0
has text: @ArthurSpoon `numpy` requires compiled code and is not native to Python so not all Python installs have it...

http://stackoverflow.com/comment/82096799
has text: re.escape and \b - lack of experience! From the 24 or so sample records I have it looks like they all start with letters and no spaces etc but lots of other whitespace stuff occurs later in the line.
score: 0
comment on: http://stackoverflow.com/q/47569622
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47590092
tagged with: django-admin
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82138332
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82140664
score: 0
has title: Django url resolver
has comment: http://stackoverflow.com/comment/82137728
answer count: 0
tagged with: django-urls
linked to: http://stackoverflow.com/q/38390177
tagged with: django-forms
has comment: http://stackoverflow.com/comment/82137346
has comment: http://stackoverflow.com/comment/82142030
type: Question
has body: On this line in the template: {% url object|smart_admin_urlname:'change' object.pk %} I got: Exception Value: Reverse for 'exercises_exercise_change' with arguments '(3,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] exercises/admin.py from django.contrib.admin import site, ModelAdmin class ExerciseAdmin(ModelAdmin): actions = ['apply_tag', 'show', 'hide'] list_filter = ['exercise_set', 'visible', 'exercise_set'] list_display = ['short_title', 'visible', 'exercise_set'] # ommited custom functions and irrelavent parameters class PythonExerciseAdmin(ExerciseAdmin): form = PythonExerciseAdminForm class SqlExerciseAdmin(ExerciseAdmin): form = SqlExerciseAdminForm site.register(PythonExercise, PythonExerciseAdmin) site.register(SqlExercise, SqlExerciseAdmin) The working url in administration site should look like: http://127.0.0.1/admin/exercises/pythonexercise/3/ http://127.0.0.1/admin/exercises/sqlexercise/4/ I'm not sure where to look, or change to fix this bug. Thank you @Sandeep Balagopal! Why didn't I think of grep -rl "smart_admin_urlname" . silly me. common/templatetags/common_tags.py @register.filter def smart_admin_urlname(obj, view_name): return u'admin:{0}_{1}_{2}'.format(obj._meta.app_label, obj._meta.model_name, view_name) exercises/models.py class Exercise(Model): # ommited custom parameters and functions class PythonExercise(Exercise): exercise_type = Constant.PYTHON # ommited custom parameters class SqlExercise(Exercise): exercise_type = Constant.SQL Adding the following line fixed the link, but this is not what I want to do...it makes the admin site show the Exercise class. site.register(Exercise, ExerciseAdmin) Tried, but did not make any difference: exercises/forms.py def get_admin_form(exercise_model=PythonExercise,exercise_type=Constant.PYTHON): class ExerciseAdminForm(ModelForm): class Meta: model = exercise_model fields = '__all__' def __init__(self, *args,**kwargs): super(ExerciseAdminForm, self).__init__(*args,**kwargs) self.fiel…
has comment: http://stackoverflow.com/comment/82137608

http://stackoverflow.com/q/47675504
has body: I have a PySpark program in which there is a SQL query like this: id = 'abc1' info = sqlc.sql("SELECT * from df WHERE isn = 'id'") This query does not work. I am returned with a blank set of values. However, if I hardcode the value, it works. info = sqlc.sql("SELECT * from df WHERE isn = 'abc1'") I have tried str(id) just to be sure. How can I resolve this?
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47675610
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: python
has title: Spark Sql query works with hardcoded value but not with variable
type: AnsweredQuestion
tagged with: apache-spark
score: 0
has answer: http://stackoverflow.com/a/47675610
answer count: 1

http://stackoverflow.com/comment/82153343
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47597289
has text: @WillemVanOnsem, I don`t fully understand how to implement this binary tree. Can you explain this point in more detail?

http://stackoverflow.com/q/47658521
favorite count: 0
type: Question
has body: I am working on a project that's implemented by c++ and i want to use some algorithms from sklearn library. can i do something like that? i know sklearn library is for python. And if it's not possible can i call a function from python script? Thanks in advance.
tagged with: call
tagged with: python
has comment: http://stackoverflow.com/comment/82275790
has comment: http://stackoverflow.com/comment/82275762
tagged with: c++
score: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
has title: Can i call a function from python script in c++ file?
downvote count: 1

http://stackoverflow.com/comment/82191563
comment on: http://stackoverflow.com/q/47616200
score: 0
has text: Maybe duplicated question https://stackoverflow.com/questions/47616114/how-to-loop-over-the-elementary-arithmetic-symbols
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47637675
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82240234
downvote count: 0
has comment: http://stackoverflow.com/comment/82237344
upvote count: 1
has comment: http://stackoverflow.com/comment/82241384
has body: I'm making a tkinter app in python in which I use two modules: os and vlc. The problem is the following: When I'm running the tkinter app and using that part of the application which needs os and vlc, the windows cmd and the vlc window pop up for a few seconds and then both of them disappear. How could I eliminate the appearing of these two windows? EDIT: import vlc import os class PageOne(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.image_label = Label(self, text='your stream pics', font=controller.title_font) self.image_label.grid(row=0) print(self.framer) def framer(self, stream_url): full_path = self.create_folder() req_value = self.create_vlc_command(full_path + '\\', stream_url) print(req_value) os.system(req_value) function inside PageOne class that uses vlc module: def create_vlc_command(self, full_path, stream_url): pre_sc_path = '--scene-path=' file_name = pre_fn + self.get_date_time() vid_settings = ("--rate=1 --video-filter=scene " "--vout=dummy --run-time=3 " "--scene-format=png --scene-ratio=24 " "--scene-prefix=") + file_name scene_path = pre_sc_path + full_path req_value = ("vlc {arg_name} {vid_settings} {scene_path} " "{quit}").format(arg_name=stream_url, vid_settings=vid_settings, scene_path=scene_path, quit='vlc://quit') print('req_value: ', req_value) print('scene_path', scene_path) return req_value Thanks
has comment: http://stackoverflow.com/comment/82239848
favorite count: 0
type: Question
has title: vlc and cmd window appear when running tkinter app
has comment: http://stackoverflow.com/comment/82240807
has comment: http://stackoverflow.com/comment/82240707
has comment: http://stackoverflow.com/comment/82240448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82241746
has comment: http://stackoverflow.com/comment/82233846
tagged with: python
has comment: http://stackoverflow.com/comment/82233532
has comment: http://stackoverflow.com/comment/82242799
tagged with: tkinter

http://stackoverflow.com/comment/82311228
score: 0
comment on: http://stackoverflow.com/a/47658012
type: AnswerComment
has text: It turns out, when I delect `code = base64.b64encode(code)`. Then `zlib.inflate` will do the job. Thanks @Mark Adler
type: Comment

http://stackoverflow.com/q/47600619
favorite count: 0
type: Question
tagged with: testing
type: UnansweredQuestion
has body: I have a number of tests, scattered among different test modules and classes. I need to start up/tear down a docker container before/after running the tests, but neither setUpClass() nor setUpModule() seems appropriate. How do I specify set-up and tear-down methods for multiple modules?
tagged with: python
has title: set-up and tear-down method for multiple test modules
has answer: http://stackoverflow.com/a/47600900
downvote count: 0
tagged with: automated-tests
score: 1
upvote count: 1
tagged with: python-unittest
answer count: 1

http://stackoverflow.com/comment/82179138
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47610308
type: Comment
has text: It seems to be a network connection error. Does the error occur in exactly the same place (at 5%) when you try again?

http://stackoverflow.com/comment/82107378
comment on: http://stackoverflow.com/q/47572872
type: Comment
type: QuestionComment
has text: To EL3PHANTEN: I tryed but still error 73.
score: 0

http://stackoverflow.com/q/47680901
type: AnsweredQuestion
tagged with: list
score: -5
has title: why this code doesn't work i am using python3?
has answer: http://stackoverflow.com/a/47681117
has body: I wanna delete the values of the list lists = [12,15,15,15,3,15,1,6,4,7,888,56248] while len(lists) is True: lists.pop() print(lists) But i got this output : [12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]
tagged with: python
has comment: http://stackoverflow.com/comment/82321636
possible better answer: http://stackoverflow.com/a/47681004
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47681117
answer count: 2
has answer: http://stackoverflow.com/a/47681004
has comment: http://stackoverflow.com/comment/82321214
has comment: http://stackoverflow.com/comment/82321293
has comment: http://stackoverflow.com/comment/82320990
has comment: http://stackoverflow.com/comment/82321176
has comment: http://stackoverflow.com/comment/82321247
linked to: http://stackoverflow.com/q/6260089
upvote count: 1
linked to: http://stackoverflow.com/q/5205575
has comment: http://stackoverflow.com/comment/82321433
downvote count: 6

http://stackoverflow.com/comment/82331002
type: QuestionComment
score: 0
has text: No duplicate column names. However, there are column names with the name df['BASAL_AREA_1']. That shouldn't be a problem though
comment on: http://stackoverflow.com/q/47685399
type: Comment

http://stackoverflow.com/a/47607468
type: Answer
answers question: http://stackoverflow.com/q/47600280
has body: Your algorithm runs in O(n2) time: The find() call will take O(n) time The replace() call will create a complete new string which takes O(n) time The outer loop executes O(n) times As others have stated, this can be solved by counting inversions using merge sort, but in this answer I try to stay close to your algorithm, keeping the outer loop and result += index_of_letter, but changing the way index_of_letter is calculated. The improvement can be done as follows: preprocess the word_1 string and note the first position of each distinct letter in word_1 in a dict keyed by these letters. Link each letter with its next occurrence. I think it is most efficient to create one list for this, having the size of word_1, where at each index you store the index of the next occurrence of the same letter. This way you have a linked list for each distinct letter. This preprocessing can be done in O(n) time, and with it you can replace the find call with a O(1) lookup. Every time you do this, you remove the matched letter from the linked list, i.e. the index in the dict moves to the index of the next occurrence. The previous change will give the absolute index, not taking into account the removals of letters that you have in your algorithm, so this will give wrong results. To solve that, you can build a binary tree (also preprocessing), where each node represents an index in word_1, and which gives the actual number of non-deleted letters preceding a given index (including itself as well if not deleted yet). The nodes in the binary tree never get deleted (that might be an idea for a variant solution), but the counts get adjusted to reflect a deletion of a character. At most O(logn) nodes need to get a decremented value upon such a deletion. But apart from that no string would be rebuilt like with replace. This binary tree could be represented as a list, corresponding to nodes in in-order sequence. The values in the list would be the numbers of non-deleted letters preceding that no…
has comment: http://stackoverflow.com/comment/82175973
has comment: http://stackoverflow.com/comment/82207781
has comment: http://stackoverflow.com/comment/82177381
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47600280
has comment: http://stackoverflow.com/comment/82178492

http://stackoverflow.com/a/47655115
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47643678
has body: In the fit function I had to add if done: next_state = None
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47643678

http://stackoverflow.com/q/47644517
has title: Coffee Roasters- 'Saving' a dictionary to a .txt file
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82247775
has comment: http://stackoverflow.com/comment/82247806
has body: Part of this homework problem I am working on is to save a file to an existing .txt-file which is coffee.txt. In the problem it says: To save the dictionary data to coffee.txt: Create a new temp.txt file, in which you write every element in the dictionary. Delete coffee.txt Rename temp.txt to coffee.txt Below is my save function: As stated my main problem is with saving (I can't use modules and I need to save the dictionary in the format like: key value or Sumatran 30 tempfile = open('temp.txt', 'w') for k, v in coffee_dict.items(): dict_content = k + '' + v + '\n' tempfile.write(str(dict_content)) coffee = open('coffee.txt', 'w') tempfile = coffee print('Your file has been saved.') Any ideas in what is going on? Also keep getting error: must be str, not int.
type: Question
has comment: http://stackoverflow.com/comment/82247783
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82291267
tagged with: python
has comment: http://stackoverflow.com/comment/82249795

http://stackoverflow.com/comment/82121589
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47581808
has text: Code snippets are for runnable HTML+CSS+JS, not just code formatting. For that use the {} button at the top after highlighting the code.

http://stackoverflow.com/a/47545619
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82048073
has comment: http://stackoverflow.com/comment/82073993
has body: The most efficient way is to hash T-I[i] for each i and check each element as you see it def sum2(I,T): h = {} for itm in I: if itm in h: return True h[T-itm] = 1 return False
has comment: http://stackoverflow.com/comment/82049136
answers question: http://stackoverflow.com/q/47545339
has comment: http://stackoverflow.com/comment/82073781
type: Answer
has comment: http://stackoverflow.com/comment/82071700
has comment: http://stackoverflow.com/comment/82048242
has comment: http://stackoverflow.com/comment/82048189
upvote count: 2

http://stackoverflow.com/comment/82346848
has text: use `include` instead of `extend`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47693834
type: QuestionComment

http://stackoverflow.com/q/47571412
type: AnsweredQuestion
score: 0
has title: Python adding more value than expected
tagged with: python
linked to: http://stackoverflow.com/q/588004
has body: I was preparing a code for my friend and I stumbled upon this interesting bug/feature. See the source and output below and can someone explain to me, why does it add more than 0.001 to the current_time var? Source: import time current_time = 0.000 check = input("Ready to go?") while True: current_time = current_time+0.001 print(str(current_time)+" s") time.sleep(0.001) Output: Ready to go? 0.001 s 0.002 s 0.003 s 0.004 s 0.005 s 0.006 s 0.007 s 0.008 s 0.009000000000000001 s 0.010000000000000002 s 0.011000000000000003 s 0.012000000000000004 s Thanks in advance!
favorite count: 0
accepted answer: http://stackoverflow.com/a/47571575
type: Question
tagged with: python-3.x
tagged with: timer
has answer: http://stackoverflow.com/a/47571575
duplicate of: http://stackoverflow.com/q/588004
answer count: 1
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/82164099
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47602526
has text: https://pandas.pydata.org/pandas-docs/stable/advanced.html

http://stackoverflow.com/a/47660778
has body: Use .reshape and pass -1 as the second argument: &gt;&gt;&gt; a = np.array([1,2,3,4,5]) &gt;&gt;&gt; a = a.reshape(1, -1) &gt;&gt;&gt; a[0,2] 3 Note, if you are expecting any type of ndarray, then this might not be what you want: &gt;&gt;&gt; arr = np.array([[1,2],[3,4]]) &gt;&gt;&gt; arr array([[1, 2], [3, 4]]) &gt;&gt;&gt; arr.reshape(1, -1) array([[1, 2, 3, 4]]) So you may need to add a conditional check: &gt;&gt;&gt; if a.ndim &lt; 2: ... a = a.reshape(1, -1) ... &gt;&gt;&gt; a array([[1, 2, 3, 4, 5]])
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47660726

http://stackoverflow.com/comment/82162820
type: QuestionComment
score: 0
has text: Your second codefragment is not even JSON.
type: Comment
comment on: http://stackoverflow.com/q/47602020

http://stackoverflow.com/comment/82243318
type: QuestionComment
comment on: http://stackoverflow.com/q/47642211
has text: @roganjosh edited my question. thanks !
score: 0
type: Comment

http://stackoverflow.com/comment/82270518
comment on: http://stackoverflow.com/q/47656127
type: Comment
score: 0
type: QuestionComment
has text: @MuhammadShoaib yes, it was imported (just edited the question to show it)

http://stackoverflow.com/q/47643785
has comment: http://stackoverflow.com/comment/82246362
has comment: http://stackoverflow.com/comment/82246669
has answer: http://stackoverflow.com/a/47643890
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/82246462
has comment: http://stackoverflow.com/comment/82246289
score: 1
has comment: http://stackoverflow.com/comment/82246631
answer count: 1
downvote count: 0
tagged with: floating-point
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82246812
has comment: http://stackoverflow.com/comment/82246440
has body: I have a column with float values such as 600.0750, 600.2274, 600.3798, 600.5322.I rounded the values to 3 decimal places and then applied the diff() function to that column which gave me values 0.1524,0.1524 and 0.1524.To remove the duplicates from the output, I applied drop_duplicates. I was expecting to see only 0.1524 but in actual I got 0.1524,0.1524,0.1524. So I store the output values in another dataframe df_diff and I do df_diff.iloc[2] which gives me 0.15239999999994325 and for df_diff.iloc[3] I get 0.15240000000005693. I go back and do the same for original df and I get 600.07500000000005. So even when I am rounding, the values are not getting rounded. What can I do to fix this? Thanks
has title: pandas dataframe float point issues
accepted answer: http://stackoverflow.com/a/47643890
tagged with: python

http://stackoverflow.com/comment/82243434
has text: what exactly do you want to detect? Could you give the expected answer for your example and explain it?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47642388

http://stackoverflow.com/comment/82263271
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47652148
has text: tried it already can't even get that working; even remove the last incomplete user section.
type: Comment

http://stackoverflow.com/a/47635513
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/105558801
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82229531
has comment: http://stackoverflow.com/comment/82229930
has body: You need to merge both list and send it in response from django.db.models import F def multi_autocomplete(request): if request.is_ajax(): query = request.GET.get("term", "") companies = Company.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label') treatments = Treatment.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label') results = list(companies) + list(treatments) data = json.dumps(results) else: data = 'fail' return HttpResponse(data, 'application/json') Your autocomplete handler will look like. $("#input_element_id").autocomplete({ source: "{% url 'url name' %}", response: function(event, ui) { if (!ui.content.length) { var noResult = { value: "", label: "No data found" }; ui.content.push(noResult); } }, select: function (e, ui) { if (ui.item.value) { //do stuff after user selected option from autocomplete } } }); Update Check this JsFiddle i think this will help.
type: Answer
accepted answer of: http://stackoverflow.com/q/47632093
answers question: http://stackoverflow.com/q/47632093
downvote count: 0

http://stackoverflow.com/a/73735490
has body: I had the same problem. This is the way I did it and now have the correct shape: from sklearn.metrics.pairwise import euclidean_distances def gauss_kernel(x1, x2, gamma): sigma = math.sqrt(gamma) return np.exp(-euclidean_distances(x1, x2)2/(2*sigma2))
type: Answer
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/130207436
answers question: http://stackoverflow.com/q/47564504
downvote count: 1

http://stackoverflow.com/comment/82278932
score: 0
comment on: http://stackoverflow.com/q/47660041
has text: Any specific reason to use `pickle` over `json.dump`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47564798
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47563095
answers question: http://stackoverflow.com/q/47563095
has body: It seems to me that the problem is the headers, it seems to be very sensitive to at least the Content-Type header, it seems it's used internally on the server to decode the incoming URL or something like that. Try downloading the request like this (this is what the internal js is doing) yield Request('https://www.boozebud.com/a/producturl/p/%C3%A0bloc/superprestigenaturalblondebeer', headers={"Content-Type": "application/json; charset=UTF-8"})
type: Answer
upvote count: 2

qfilesystemmodel
tag name: qfilesystemmodel
type: Tag
tags question: http://stackoverflow.com/q/47546742

http://stackoverflow.com/q/47682830
type: Question
accepted answer: http://stackoverflow.com/a/76076555
has comment: http://stackoverflow.com/comment/82327399
has answer: http://stackoverflow.com/a/76076555
has comment: http://stackoverflow.com/comment/95076050
has body: I would like to extract the bounding box of a SVG drawing. Since Python is already available on the system and also used to perform other tasks, I don't want to use JavaScript or any other language. My understanding is if the bounding box of a single element can be calculated (but I don't know how). The bounding box of the whole drawing is just the minimum and maximum x,y values a of all elements, hence probably the bounding boxes of all elements need to be calculated. I am a Python beginner, but svgwrite is probably not the right module and so far I was scared by the installation of rsvg on a Windows system.
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/75825777
linked to: http://stackoverflow.com/q/35260742
has comment: http://stackoverflow.com/comment/127125957
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/svg
answer count: 2
score: 5
has title: Get bounding box of SVG drawing
possible better answer: http://stackoverflow.com/a/75825777
downvote count: 0
tagged with: bounding-box
has comment: http://stackoverflow.com/comment/82325151
favorite count: 0

http://stackoverflow.com/comment/82324823
type: Comment
type: QuestionComment
has text: BTW: instead of `for n in range(numPlayers): self.team1players[n].displayCircle()` you can do `for player in self.team1players: players.displayCircle()` - it is more readable.
score: 0
comment on: http://stackoverflow.com/q/47682662

http://stackoverflow.com/q/47693496
type: Question
has comment: http://stackoverflow.com/comment/82346873
answer count: 0
has title: How to create a pandas column with a time based constraint on another column?
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82347936
has comment: http://stackoverflow.com/comment/82347029
tagged with: pandas
has comment: http://stackoverflow.com/comment/82347563
tagged with: dataframe
tagged with: python
has body: I have a dataframe which looks like below, there are only 2 categories A and B. Each name can be associated with either of them in each row. When the name appears again, I need other 2 columns which indicate the count of category A and category B for that name in last 5 transactions of that name. If there are less than 5 transactions before that, then the output should be "-1". So, I have clubbed the dataframe on names by sorting on names and then on Date Due, but not sure how to proceed further. Document Number Date Due Name Category 21175370 9/20/17 Max A 20762835 8/20/17 Max A 21134931 8/25/17 Emily B 20784776 8/19/17 John A 20874477 8/4/17 Doe B 20874568 8/4/17 Doe B 20874575 8/4/17 Doe B 19784032 5/9/17 Doe B 19980723 5/25/17 Doe B 20833755 9/16/17 Doe A The output would look like this: Document Number Date Due Name Category Category_A_Count Category_B_Count 21175370 9/20/17 Max A -1 -1 20762835 8/20/17 Max A -1 -1 21134931 8/25/17 Emily B -1 -1 20784776 8/19/17 Doe A -1 -1 20874477 8/4/17 Doe B -1 -1 20874568 8/4/17 Doe B -1 -1 20874575 8/4/17 Doe B -1 -1 19784032 5/9/17 Doe B -1 -1 19980723 5/25/17 Doe B 1 4 20833755 9/16/17 Doe A 0 5 I have tried something by changing the pandas dataframe to list, this does the work, but how can i do it in pandas? : vendorList = list(vendorLast5["Name"]) cat = list(vendorLast5["Category"]) print type(vendorList) catA = [-1, -1, -1, -1] catB = [-1, -1, -1, -1] for i in range(0, len(vendorList)): if(i &gt; 4): countA = 0 countB = 0 for j in range(i-5, i): if(vendorList[j] != vendorList[i]): countA = -1 countB = -1 break if(cat[j] == "A"): countA = countA+1 else: countB=countB+1 catA.append(countA) catB.append(countB)

http://stackoverflow.com/q/47636049
upvote count: 1
tagged with: data-science
favorite count: 0
type: AnsweredQuestion
has body: I am attempting to filter some time series data without any luck in pandas.. Any tips for what I am doing wrong is greatly appreciated.. First I am attempting to filter just for the month of July 2013 and then filter the data again for taking hourly averages of the dataset samples. Ultimately what I am wanting to do is filter the data as described above in addition for Weekdays, OR individual weekdays Mondays, Tuesdays, Wednesday, etc. with the CustomBusinessDay function. I am getting tripped up where the code is commented out for the CustomBusinessDay import pandas as pd import numpy as np from pandas.tseries.offsets import CustomBusinessDay time = pd.date_range('6/28/2013', periods=2000, freq='45min') data = pd.Series(np.random.randint(100, size=2000), index=time) print(data) ##weekmask = 'Mon Tue Wed Thu Fri' df = data.truncate(before='7/1/2013', after='7/31/2013') df = df.groupby(df.index.hour).mean() print(df) ##df = CustomBusinessDay(weekmask=weekmask) ##df = pd.bdate_range(start=None, end=None, periods=None, freq='B') ## ##print(df)
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/47639942
tagged with: python
has comment: http://stackoverflow.com/comment/82231629
type: Question
has comment: http://stackoverflow.com/comment/82230842
has title: Python pandas CustomBusinessDay
tagged with: python-3.x
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47639942

http://stackoverflow.com/a/47633939
accepted answer of: http://stackoverflow.com/q/47630640
has body: Problem is because you use while inside for. Object inside for should make only small step and external while should execute for many times. You need some method to check if all objects are moved to destination and repeat again for loop. I use how_many_moved to check if all enemies are in destination. It could be something like this # value bigger than 0 to start `while` loop how_many_moved = 1 while how_many_moved &gt; 0: how_many_moved = 0 ### every enemy makes only small step ### for enemy in self.enemies: if enemy.waypoints_reached &lt; len(config.WAYPOINTS): # count how many was moved how_many_moved += 1 # Move enemy enemy.move() # Paint game + new enemy location self.paint(self.screen) # Update Screen afer every enemy made small step pygame.display.update()
answers question: http://stackoverflow.com/q/47630640
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82228872
score: 1
type: Answer

http://stackoverflow.com/comment/82089090
comment on: http://stackoverflow.com/a/47565532
has text: thanks for pointing that out, modify the answer to handle end of string
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47580135
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82120233
tagged with: django
has body: I'm new to django and have been going through tutorials on udemy and on the django website. I'm using a virtual environment and Bash on Ubuntu Windows. My issue is that when I update code in any views.py / urls.py files for my project it doesn't "compile" in the .pyc files. So say I add a home page to my urls list I get an error that the page was not found. Once I go back and delete the .pyc files though I can access a home page (or what ever page) I've added. My work around at the moment is that I wrote a python script to delete the .pyc files. EDIT: I've noticed that this issue occurs when I have two django projects in the same root folder. I made a another user account in the terminal and tried to have two django files in the same root folder and this issue occurred. Is this improper directory set up for django projects? |-- home `-- hlat |-- djangoproject1 |-- djangoproject2
has comment: http://stackoverflow.com/comment/82792953
has comment: http://stackoverflow.com/comment/82119327
has comment: http://stackoverflow.com/comment/83175341
has comment: http://stackoverflow.com/comment/82119750
has comment: http://stackoverflow.com/comment/82118400
tagged with: python
has title: urls.pyc and views.pyc files do not auto update
has comment: http://stackoverflow.com/comment/82119694
has comment: http://stackoverflow.com/comment/82119180
has comment: http://stackoverflow.com/comment/82120481
type: Question
has comment: http://stackoverflow.com/comment/82119252
score: 0
linked to: http://stackoverflow.com/q/6954603

http://stackoverflow.com/q/47648276
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47648955
has comment: http://stackoverflow.com/comment/82255198
score: 3
has comment: http://stackoverflow.com/comment/82254931
tagged with: http://stackoverflow.com/tag/html
has title: Django form is not displaying
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82255152
upvote count: 3
downvote count: 0
has body: I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes: tag of index.html: Login Register {% block login_content %} {% endblock %} {% block register_content %} {% endblock %} login.html which goes into the {% block login_content %} {% extends 'index.html' %} {% block login_content %} {% csrf_token %} Username: Password: Login {% endblock %} register.html that goes into the {% block register_content %} {% extends 'index.html' %} {% block register_content %} {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} {% endblock %} On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does not appear at all. When i inspect the console of my UI, the html does not even pick up the following line from the register.html: Here is the login.js which is responsible for the UI interactivity: $(function() { $('#login-form-link').click(function(e) { $("#login-form").delay(100).fadeIn(100); $("#register-form").fadeOut(100); $('#register-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); $('#register-form-link').click(function(e) { $("#register-form").delay(100).fadeIn(100); $("#login-form").fadeOut(100); $('#login-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); }); EDIT: Here is my views.py: def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('homepage')) # main page if login is successful else: return HttpResponse("ACCOUNT NOT ACTIVE") else: print('Someone tried to log in and failed') print('Username: {}, password, {}'.format(username, password)) return HttpResponse('Invalid login details supplied') else: return render(request, 'authentication/login.html', {}) def register(request):…
tagged with: django
tagged with: javascript
answer count: 1

http://stackoverflow.com/a/47666123
has body: Is the spelling in your question correct? get_flourescence_timeStamps with the capital 'S' is not a function. Neither is get_fourescence_timeStamps with a missing l. Here's where that function is called inside of get_running_speed: https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/core/brain_observatory_nwb_data_set.py#L807 It looks like it's spelled correctly. Here's the definition of get_fluorescence_timestamps: https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/core/brain_observatory_nwb_data_set.py#L256 Could you post a small code snippet that reproduces your error?
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82295183
answers question: http://stackoverflow.com/q/47645674
score: 1
has comment: http://stackoverflow.com/comment/82313222
upvote count: 1
has comment: http://stackoverflow.com/comment/82295602

http://stackoverflow.com/comment/82133097
score: 0
comment on: http://stackoverflow.com/a/47587872
type: Comment
type: AnswerComment
has text: So you took the parameter b and made it to a set? and compared set to set?

http://stackoverflow.com/comment/82348763
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47694637
has text: Hi Jmons, ok I got the diff between filter and get, but the thing is that the attribute in questiion is body so a.body and that a.body is a dict coresponding to what I wrote in my post : ['{ "1)Long descriptive text":Score, "2)Long descriptive text":Score, "3)Long descriptive text":Score, "4)Long descriptive text":Score }'] with score beiing an integer and I need to extract that valeu

http://stackoverflow.com/comment/82272994
type: Comment
has text: @EdmundDipple tried running 'GIT_SSH_COMMAND="ssh -v" git clone <your repo>' on the remote machine but it complained that GIT_SSH_COMMAND is not recognized, am I missing something?
type: QuestionComment
comment on: http://stackoverflow.com/q/47657170
score: 0

http://stackoverflow.com/a/47650314
type: Answer
answers question: http://stackoverflow.com/q/47649263
has body: Try sending your last GET request using the response variable. After all, it's the one who made the login and holds the cookies (if there are any). You've used a new requests object for your last request thus ignoring the login you just made.
score: 0
has comment: http://stackoverflow.com/comment/82276900

http://stackoverflow.com/comment/82364585
has text: I was cleaning up the code a bit, i changed it from quit() to sys.exit() and it works perfectly fine now.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47588079
score: 0

http://stackoverflow.com/q/47541693
answer count: 3
has answer: http://stackoverflow.com/a/47541719
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47541721
upvote count: 1
has answer: http://stackoverflow.com/a/47541975
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47541719
has comment: http://stackoverflow.com/comment/82040728
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82040701
has title: Error while getting input added into list
has comment: http://stackoverflow.com/comment/82040634
possible better answer: http://stackoverflow.com/a/47541721
tagged with: python
has comment: http://stackoverflow.com/comment/82040777
has comment: http://stackoverflow.com/comment/82066197
type: AnsweredQuestion
has body: I am attempting to create a program that asks for the user to enter his/her name and records the input into a list (Was working towards dictionary but seems like I made a boo boo!) but it is returning with "TypeError: can only concatenate list (not "str") to list". The following is the code.Thanks in advance. namedic = [] while True: print ("Please, enter your name:") name = input() if len(name) &gt; 3: print ("Welcome") else: print ("Ew, your name have less than 4 letters! Gross! Try a new one") continue namedic = namedic + name print ("Ah, your name have at least 4 words, good name.") for name in namedic: print (name)

http://stackoverflow.com/a/47683496
answers question: http://stackoverflow.com/q/47682906
has body: The problem is that when you change the attribute, you use self, which refers to this instance. But since you create a new PopupColor object, each time you open the popup, you need to treat color as a shared variable. So you could change color like this: PopupColor.color = colorpicker.color That way you treat the attribute color as shared with all PopupColor objects.
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47682906
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/78199421
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47576975
has body: Here's how you can do it: import numpy as np from astropy.modeling import models, fitting ####### Reading data ####### data_LARS02 =np.loadtxt('/Users/a/data.asc') r_l02 = data[:,0] flux_l02 = data[:,1] flux_err_l02 = data[:,2] #assuming your data has errors at this column ####### Initiate the model and fitter ####### sers_l02_init = models.Sersic1D(amplitude=5e40, r_eff=1, n=2) fit_sers_l02 = fitting.LevMarLSQFitter(calc_uncertainties=True) ####### Fitting the data ####### Sers_l02 = fit_sers_l02(sers_l02_init,r_l02,flux_l02,weights=1/(flux_err_l02**2)) ####### Plotting the result ####### plt.figure() plt.errorbar(r_l02, flux_l02, yerr=flux_err_l02, fmt='ko', label='Data') plt.plot(r_l02, sers_l02_init(r_l02), 'b-', label='Initial Model') plt.plot(r_l02, Sers_l02(r_l02), 'k-', label='Fitted Model') plt.xlabel('Radius') plt.ylabel('Flux') plt.legend() For more details, you can refer to their website: https://docs.astropy.org/en/stable/modeling/example-fitting-line.html#fit-using-uncertainties
type: Answer

http://stackoverflow.com/comment/82351627
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47696061
has text: Use python to execute bash commands?

http://stackoverflow.com/q/47642801
accepted answer: http://stackoverflow.com/a/47651313
tagged with: python
has answer: http://stackoverflow.com/a/47651313
has body: I have the following script that works in jupyter notebook when run through a single cell, but fails when running through 2 cells as done below: Is there any way to make this kind of arrangement work in notebook? cell 1: class Plotting(object): def __init__(self, run, hist): self.running = run self.histogram = hist def start_plot(self): if self.running: self.run_fig, self.run_ax = plt.subplots(1,2) if self.histogram: self.hist_fig, self.hist_ax = plt.subplots(1,2) def create_plots(self, iwindow, run_series, hist_series): if self.running: self.run_ax[iwindow].plot(run_series) if self.histogram: self.hist_ax[iwindow].hist(hist_series, histtype='step') plot = Plotting(run =1, hist =1) plot.start_plot() cell 2: for iwindow in np.arange(2): r = np.random.rand(20) h = np.random.rand(50) plot.create_plots(iwindow, r, h)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82255683
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/82244320
tagged with: jupyter-notebook
type: Question
has title: plotting in ipython notebook in 2 steps
score: 0
tagged with: subplot

http://stackoverflow.com/comment/82079929
comment on: http://stackoverflow.com/a/47560511
type: Comment
has text: Have rectified using `top.after()` Bryan.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82278326
has text: It's `np.array` not `np.ndarray`
type: QuestionComment
comment on: http://stackoverflow.com/q/47658848
score: 0
type: Comment

http://stackoverflow.com/a/47644700
has comment: http://stackoverflow.com/comment/82248373
has comment: http://stackoverflow.com/comment/82289269
has comment: http://stackoverflow.com/comment/82252750
score: 2
has body: I'd recommend creating processes manually (rather than as part of a pool), and sending the return values to the main process through a multiprocessing.Queue. These queues can share almost any Python object in a safe and relatively efficient way. Here's an example, using the jobs you've posted. def jobA(num, q): q.put(num * 2) def jobB(num, q): q.put(num ^ 3) import multiprocessing as mp q = mp.Queue() jobs = (jobA, jobB) args = ((10, q), (2, q)) for job, arg in zip(jobs, args): mp.Process(target=job, args=arg).start() for i in range(len(jobs)): print('Result of job {} is: {}'.format(i, q.get())) This prints out: Result of job 0 is: 20 Result of job 1 is: 1 But you can of course do whatever further processing you'd like using these values.
has comment: http://stackoverflow.com/comment/82273872
has comment: http://stackoverflow.com/comment/82248178
has comment: http://stackoverflow.com/comment/82252294
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47644554
has comment: http://stackoverflow.com/comment/82271963
has comment: http://stackoverflow.com/comment/82289325

http://stackoverflow.com/q/47545946
has answer: http://stackoverflow.com/a/47546086
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47546086
answer count: 1
has title: cp949 codec can't encode character error in python
type: Question
has body: I am using the code below to parse the XML format wikipedia training data into a pure text file: from __future__ import print_function import logging import os.path import six import sys from gensim.corpora import WikiCorpus if __name__ == '__main__': program = os.path.basename(sys.argv[0]) logger = logging.getLogger(program) logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s') logging.root.setLevel(level=logging.INFO) logger.info("running %s" % ' '.join(sys.argv)) # check and process input arguments if len(sys.argv) != 3: print("Using: python process_wiki.py enwiki.xxx.xml.bz2 wiki.en.text") sys.exit(1) inp, outp = sys.argv[1:3] space = " " i = 0 output = open(outp, 'w') wiki = WikiCorpus(inp, lemmatize=False, dictionary={}) for text in wiki.get_texts(): if six.PY3: output.write(bytes(' '.join(text), 'utf-8').decode('utf-8') + '\n') # ###another method### # output.write( # space.join(map(lambda x:x.decode("utf-8"), text)) + '\n') else: output.write(space.join(text) + "\n") i = i + 1 if (i % 10000 == 0): logger.info("Saved " + str(i) + " articles") output.close() logger.info("Finished Saved " + str(i) + " articles") when I run this code, it gives me a following error message: File "wiki_parser.py", line 42, in &lt;module&gt; output.write(bytes(' '.join(text), 'utf-8').decode('utf-8') + '\n') UnicodeEncodeError: 'cp949' codec can't encode character '\u1f00' in position 1537: illegal multibyte sequence When I searched this error online, most answers told me to add 'utf-8' as the encoding which is already there. What could be the possible issue with the code?

http://stackoverflow.com/comment/82141875
score: 0
comment on: http://stackoverflow.com/a/47580750
type: AnswerComment
has text: By the way, **7** - you won't problems with `flask app context` ))) You can send all the necessary request data from endpoint/view/Resource. Anyway, divide application(`flask`, `celery` and your own business logic) is a good way. Tests will be small and supportable(as and your application). If you have a time I recommend make changes in your project(or part of project/ just for fun). You will be surprised at how much easier it is to work. Good luck ;)
type: Comment

http://stackoverflow.com/comment/82183505
comment on: http://stackoverflow.com/a/47611908
type: Comment
score: 0
type: AnswerComment
has text: Shouldn't it be ''' instead of ''? Also, I get this error now cur.execute(q) sqlite3.OperationalError: no such column: Room.Locations

http://stackoverflow.com/comment/82045385
type: QuestionComment
comment on: http://stackoverflow.com/q/47544192
score: 1
type: Comment
has text: Your tests should not depend on one another or on the order they run. This is bad practice and now you're seeing why...

http://stackoverflow.com/a/47586457
has body: All of the answers so far are very memory intensive, or quite finite. I would consider the itertools.count generator and printing the results immediately. This will use very little memory, and is by far the most 'infinite' of the solutions posted so far. from itertools import count for c in count(): print(c, end="")
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47586275
answers question: http://stackoverflow.com/q/47586275
type: Answer

http://stackoverflow.com/q/47640787
tagged with: android
tagged with: adb
tagged with: python
has title: How to Run Code on Android Generated by AndoirdViewClient?
type: AnsweredQuestion
score: 0
answer count: 1
has body: Through the CulebraTester application on my device, I generated some python to simply open the settings application. When I went to run the script, I was greeted with pkg_resources.DistributionNotFound: The 'androidviewclient&lt;12.4.0' distribution was not found and is required by the application So then I realized that I didn't have the environment variable set, so I downloaded the project from Github and ran the command export ANDROID_VIEW_CLIENT_HOME=/path/to/androidviewclient/ I'm confident I did this correctly because I can cd to $ANDROID_VIEW_CLIENT_HOME and view the contents. Now when I go back to run the script this same error appears, so I commented out pkg_resources.require('androidviewclient>=12.4.0') and was then presented with this error ImportError: No module named com.dtmilano.android.viewclient Right now I'm clueless about what to do, I tried googling, but I've found nothing to fix the problem. Some-what related I saw a video on youtube where curl was used to run javascript generated by CulebraTester so maybe the same can be done with Python?
type: Question
accepted answer: http://stackoverflow.com/a/47641924
tagged with: androidviewclient
has answer: http://stackoverflow.com/a/47641924

http://stackoverflow.com/comment/82260761
type: Comment
comment on: http://stackoverflow.com/a/47651149
type: AnswerComment
has text: Very nice solution.
score: 1

http://stackoverflow.com/q/47682159
score: 0
has comment: http://stackoverflow.com/comment/82325137
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82323628
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82325480
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82325006
tagged with: mechanize-python
has title: Python Web scraper for dynamically populating drop down list (using mechanize and beautifulsoup(
tagged with: python
has comment: http://stackoverflow.com/comment/82325393
linked to: http://stackoverflow.com/q/30607410
has body: i am newbie to python. I am using python 2.7 and trying to scrape the website and collect the data . I am having issue in selection of drop down list and getting new response form with updated list of items. These are the steps : I am opening a xyz.com website Its UI appears as in the attached image link There are 5 drop down menus displayed in the initial form we open. They are : State District Sub District Village Year Cycle And only State and Year cycle are initially populated. And rest of the drop down menus are dependent on one another in a sequential order. Eg : When state is selected --> It populates District in a dynamic manner. And when District is selected --> It populates Sub District and similarly Village is populated with the selection of Sub district. And this dynamic update is happening because of javascript. So far am able to get to the stage of collecting list of states (Used beautifulsoup and mechanize). And initially am just choosing one state and submitting the form as : def select_form(form): return form.attrs.get('action', None) == '/PublicReports/NutrientStatusFarmerWise' br = mechanize.Browser() br.open(url) br.response() br.select_form(predicate=select_form) br.form.set_all_readonly(False) br.form['State_Code'] = ['29'] response = br.submit() print response.read() And when i print the response.read i dont see newly populated district names. I dont know what am missing here. As in the similar manner, i need to collect district names to populate subdistrict and so on with the rest of items. Any clues and hints would be of great help PS : I have read the old post and used it as reference : Web Scraper for dynamic forms in python form with drop down options Thank you !

http://stackoverflow.com/comment/82241766
type: AnswerComment
has text: it works only because lines are equal :( ; must be tuned.
comment on: http://stackoverflow.com/a/47641624
score: 1
type: Comment

http://stackoverflow.com/comment/82071462
type: QuestionComment
has text: check the [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) documentation, especially the `format` parameter. To look what format you need, check the [`strptime` documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)
comment on: http://stackoverflow.com/q/47556851
score: 0
type: Comment

http://stackoverflow.com/comment/82112582
score: 0
has text: What makes you think that `Pool` doesn't wait?
comment on: http://stackoverflow.com/q/47577391
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47611399
upvote count: 5
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82181957
tagged with: python
has comment: http://stackoverflow.com/comment/82181249
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82182870
has body: I'm trying to create a stacked bar chart in MatPlotLib with two distinct x-labels on top and bottom. The upper one is supposed to have a bounding box with the same width as the bars themselves. Plot that's not quite right This is how I create the labels: plt.tick_params(axis="both", left=False, bottom=False, labelleft=False) plt.xticks(ind, diagram.keys()) ax.set_frame_on(False) for label, x in zip([q[1] for q in diagram.values()], ind): ax.text( x, 1.05, '{:4.0%}'.format(label), ha="center", va="center", bbox={"facecolor": "blue", "pad": 3} ) diagram is a dictionary like {bottom-label: [[contents], top-label]} So I guess my question boils down to: How do I manipulate the bounding boxs of the text objects? Thanks a lot! As per request, a runnable example: import matplotlib.pyplot as plt import numpy as np def stacked_bar_chart( diagram, title="example question", img_name="test_image", width=0.7, clusters=None, show_axes=True, show_legend=True, show_score=True): """ Builds one or multiple scaled stacked bar charts for grade distributions. saves image as png. :param show_score: whether the score should be shown on top :param show_legend: whether the legend should be shown :param show_axes: whether question name should be shown on bottom :param clusters: indices of clusters to be displayed. :param width: the width of the bars as fraction of available space :param title: diagram title :param img_name: output path :param diagram: dictionary: {x-label: [[grade distribution], score]} :return: nothing. """ grades = { "sehr gut": "#357100", "gut": "#7fb96a", "befriedigend": "#fdd902", "ausreichend": "#f18d04", "mangelhaft": "#e3540e", "ungenügend": "#882d23" } # select clusters if clusters is not None: diagram = {i: diagram[i] for i in clusters} # normalize score distribution =&gt; sum of votes = 1.0 normalized = [] for question in diagram.values(): s = sum(question[0]) normalized.append([x / s for x in question[0]]) # transpose dict values (score distributions) to list of l…
accepted answer: http://stackoverflow.com/a/47613833
linked to: http://stackoverflow.com/q/40796117
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47613833
has comment: http://stackoverflow.com/comment/82186084
favorite count: 0
type: Question
score: 5
has title: Matplotlib: how to specify width of x-label bounding box
has comment: http://stackoverflow.com/comment/82182167

aes
tag name: aes
tags question: http://stackoverflow.com/q/47544115
type: Tag

http://stackoverflow.com/comment/82204369
type: Comment
type: QuestionComment
has text: Do you need these users in the code after? Or could you use celery?
score: 0
comment on: http://stackoverflow.com/q/47623219

http://stackoverflow.com/comment/82312280
has text: Oh no, it makes no difference what the start_line number is, or what the sample data is. It does the same thing no matter what file I feed it or what line I start at, I have already thrown quite a few different files at it, it does the same thing... Which print statement did you mean? The only one there prints the current line number which is an int...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47673406
score: 0

http://stackoverflow.com/comment/82323897
type: Comment
type: QuestionComment
has text: `global` declarations go inside each function that wants to use the global, not at global scope. (`global` at global scope should really be a SyntaxError, but it's not.)
comment on: http://stackoverflow.com/q/47682356
score: 0

http://stackoverflow.com/q/47689407
tagged with: python
has title: two different csv file data manipulation using pandas
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
tagged with: merge
accepted answer: http://stackoverflow.com/a/47689593
type: Question
has body: I have two data frame df1 and df2 df1 has following data (N Rows) Time(s) sv-01 sv-02 sv-03 Val1 val2 val3 1339.4 1 4 12 1.6 0.6 1.3 1340.4 1 12 4 -0.5 0.5 1.4 1341.4 1 6 8 0.4 5 1.6 1342.4 2 5 14 1.2 3.9 11 ...... ..... .... ... .. df2 has following data which has more rows than df1 Time(msec) channel svid value-1 value-2 valu-03 1000 1 2 0 5 1 1000 2 5 1 4 2 1000 3 2 3 4 7 ..... ..................................... 1339400 1 1 1.6 0.4 5.3 1339400 2 12 0.5 1.8 -4.4 1339400 3 4 -0.20 1.6 -7.9 1340400 1 1 0.3 0.3 1.5 1340400 2 6 2.3 -4.3 1.0 1340400 3 4 2.0 1.1 -0.45 1341400 1 1 2 2.1 0 1341400 2 8 3.4 -0.3 1 1341400 3 6 0 4.1 2.3 .... .... .. ... ... ... What I am trying to achieve is 1.first multiplying Time(s) column by 1000 so that it matches with df2 millisecond column. 2.In df1 sv 01,02 and 03 are in independent column but those sv are present in same column under svid. So goal is when time of df1(after changing) is matching with time of df2 copy next three consecutive lines i.e copy all matched lines of that time instant. Basically I want to iterate the time of df1 in df2 time column and if there is a match copy three next rows and copy to a new df. I have seen examples using pandas merge function but in my case both have different header. Thanks.
tagged with: numpy
has answer: http://stackoverflow.com/a/47689593

http://stackoverflow.com/q/47562490
tagged with: scipy
possible better answer: http://stackoverflow.com/a/79495896
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82083780
has comment: http://stackoverflow.com/comment/82087600
has answer: http://stackoverflow.com/a/79495896
has answer: http://stackoverflow.com/a/47565200
tagged with: python
has title: Numerically stable evaluation of log of integral of a function with extremely small values
tagged with: numerical-integration
accepted answer: http://stackoverflow.com/a/47565200
has body: If I have a random number Z that is defined as the sum of two other random numbers, X and Y, then the probability distribution of Z is the convolution of the probability distributions for X and Y. Convolution is basically to an integral of the product of the distribution functions. Often there is no analytic solution to the integral in the convolution, so it must be calculated with a basic quadrature algorithm. In pseudocode: prob_z(z) = integrate(lambda t: prob_x(t) * prob_y(z-t), -inf, inf) For a concrete example, the sum Z of a normally distributed variable X and a log normally distributed variable Y can be calculated with the following Python/Scipy code: from scipy.integrate import quad from scipy.stats import norm, lognorm from scipy import log prob_x = lambda x: norm.pdf(x, 0, 1) # N(mu=0, sigma=1) prob_y = lambda y: lognorm.pdf(y, 0.1, scale=10) # LogN(mu=log(10), sigma=0.1) def prob_z(z): return quad(lambda t: prob_x(t)*prob_y(z-t), -inf, inf) Now I want to calculate the log probability. The naive solution is to simple do: def log_prob_z(z): return log(prob_z(z)) However, this is numerically unstable. After about 39 standard deviations, probability distributions are numerically 0.0, so even if the log probability has some finite value, it can't be calculated outside this by simply taking the log of the probability. Compare norm.pdf(39, 1, 0) which is 0.0 to norm.logpdf(39, 1, 0) which is about -761. Clearly, Scipy doesn't compute logpdf as log(pdf)—it finds some other way—because otherwise it would return -inf, an inferior response. In the same way, I want to find another way for my problem. (You may wonder why I care about the log likehood of values so far from the mean. The answer is parameter fitting. Fitting algorithms can get closer when the log likelihood is some hugely negative number, but nothing can be done when it is -inf or nan.) The question is: does anyone know how I can rearrange log(quad(...)) so I don't compute quad(...) and thereby avoiding …
tagged with: statistics
type: AnsweredQuestion
answer count: 2
tagged with: numerical-stability
has comment: http://stackoverflow.com/comment/82083894
score: 7
has comment: http://stackoverflow.com/comment/82083641
downvote count: 0
has comment: http://stackoverflow.com/comment/82127848
has comment: http://stackoverflow.com/comment/82083102
upvote count: 7
has comment: http://stackoverflow.com/comment/82088413
has comment: http://stackoverflow.com/comment/82083943

http://stackoverflow.com/a/47615749
type: AcceptedAnswer
has body: Based on this you could write (dashPer represents a chosen amount of characters): '-'.join(text[i:i+dashPer] for i in range(0, len(text), dashPer)) as in just replace: text = str(number) + ": " + str(''.join(random.sample(chars*6, 16))) with: dashPer = 5 text = str(''.join(random.sample(chars*6, 16))) text = '' + '-'.join(text[i:i+dashPer] for i in range(0, len(text), dashPer)) text = str(number) + ": " + text
has comment: http://stackoverflow.com/comment/82220166
type: Answer
accepted answer of: http://stackoverflow.com/q/47615403
downvote count: 0
answers question: http://stackoverflow.com/q/47615403
upvote count: 1
score: 1

http://stackoverflow.com/q/47591359
has comment: http://stackoverflow.com/comment/82225201
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/40703086
tagged with: glcm
has answer: http://stackoverflow.com/a/48665283
answer count: 1
has comment: http://stackoverflow.com/comment/82219587
tagged with: mask
has comment: http://stackoverflow.com/comment/82219182
has comment: http://stackoverflow.com/comment/82141135
favorite count: 0
has comment: http://stackoverflow.com/comment/82222851
has comment: http://stackoverflow.com/comment/82222598
type: Question
tagged with: opencv
score: 3
has body: I have the following code in which I am trying to get a portion of a image corresponding to a mask I am given. Then I would like to apply the skimage.feature.glcm on that portion. But I get the error: glcm = greycomatrix(mancha, [2], [0], levels=None, symmetric = True, normed = True) File "D:\WinPython-64bit-2.7.13.1ZeroNew\python-2.7.13.amd64\lib\site-packages\skimage\feature\texture.py", line 101, in greycomatrix assert_nD(image, 2) File "D:\WinPython-64bit-2.7.13.1ZeroNew\python-2.7.13.amd64\lib\site-packages\skimage\_shared\utils.py", line 178, in assert_nD raise ValueError(msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim]))) ValueError: The parameter `image` must be a 2-dimensional array The code is: mask = cv2.imread(pathMask, 0) cruda = cv2.imread(pathCruda, 0) imaskc = mask &gt; 0 mancha = cruda[imaskc] glcm = greycomatrix(mancha, [2], [0], levels=None, symmetric = True, normed = True) energy = greycoprops(glcm, 'energy') homogeneity = greycoprops(glcm, 'homogeneity') I have also tried unsuccesfully with: labeled_image, nb_labels = ndimage.label(mascara) blobs = ndimage.find_objects(labeled_image) glcm = greycomatrix(cruda[blobs[0]] Any ideas how to get this done? Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82226773
has comment: http://stackoverflow.com/comment/82219766
tagged with: scikit-image
has comment: http://stackoverflow.com/comment/82141920
tagged with: python
has comment: http://stackoverflow.com/comment/82162015
has title: Calculating the co-occurrence matrix of part of an image from a mask
has comment: http://stackoverflow.com/comment/82223713

http://stackoverflow.com/comment/82248707
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47645024
has text: You haven't clearly indicated which directory you added to the PYTHONPATH - the `linalg` directory, or the `python2.7` directory (or both? or something else?).
score: 0

http://stackoverflow.com/a/47560787
has comment: http://stackoverflow.com/comment/88381349
type: Answer
has comment: http://stackoverflow.com/comment/88339782
score: 0
has body: Since the class tag is unique to the 'data-o' items that you want, you may want to use the syntax {'class': 'class_name'} to get only those &lt;td&gt; tags that contain class='bc bs oi' first, then print the 'data-o' item for each of those items. import urllib.request from bs4 import BeautifulSoup x = urllib.request.urlopen('https://www.oddschecker.com/football/champions- league/bayern-munich-v-paris-st-germain/winner') soup = BeautifulSoup(x.read(), 'html.parser') alltd = soup.find_all('td', {'class': 'bc bs oi'}) for item in alltd: print item['data-o'] output: 6/4 17/11 13/8 23/10 or if you just want the list: print [str(item['data-o']) for item in alltd] ['6/4', '17/11', '13/8', '23/10'] Hope this helps.
answers question: http://stackoverflow.com/q/47560523
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47560523

http://stackoverflow.com/a/59278515
downvote count: 1
type: Answer
has body: I had similar issues when I tried to load config from a python script that was not on the project root directory. and what I figured out was that: logging.config.fileConfig is dependent on configparser and have issues with initializing with absolute path. Try relative path. Replace fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") with some thing like: ## get path tree from project root and replace children from root with ".." path_rslv = path.split(path.dirname(path.abspath(__file__)))[1:] fileName = path.join(*[".." for dotdot in range(len(path_rslv)], "logging.config")
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/47636747

http://stackoverflow.com/comment/82380425
comment on: http://stackoverflow.com/a/47656596
type: Comment
score: 0
type: AnswerComment
has text: no, no - it did not `connect` to .200 - it was the *local* addr (from `getsockname()`) being .200, i.e. as if the client was talking to .200 and not .100 before -- but it turned out that this was caused by some mess going on when my change was merged into the baseline; now that the merge is ok, this problem doesn't show anymore! I consider this solved now :)

http://stackoverflow.com/q/47556787
has comment: http://stackoverflow.com/comment/82073475
has answer: http://stackoverflow.com/a/47557952
has comment: http://stackoverflow.com/comment/82071033
score: 0
answer count: 1
tagged with: selenium
has body: In a jenkins environment I want to use selenium, but what I get is an error (when trying to import the webdriver): + python -c 'from selenium import webdriver' Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/jenkins/04/workspace/platform.alex-test/venv/lib/python2.6/site-packages/selenium/webdriver/__init__.py", line 18, in &lt;module&gt; from .firefox.webdriver import WebDriver as Firefox # noqa File "/jenkins/04/workspace/platform.alex-test/venv/lib/python2.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 34, in &lt;module&gt; from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver File "/jenkins/04/workspace/platform.alex-test/venv/lib/python2.6/site-packages/selenium/webdriver/remote/webdriver.py", line 991 return {k: size[k] for k in ('width', 'height')} Any idea what could go on? Version python: 2.6.6 Version selenum: 3.7.0 Here is the complete code I execute in jenkins: virtualenv venv . venv/bin/activate pip install selenium which python python -c "import selenium; print selenium.__version__" pip freeze python -c "from selenium import webdriver" According to the documentation selenium 3.7.0 is compatible with python 2.6...
has title: Why do I get syntax error when using selenium in jenkins?
type: Question
tagged with: jenkins
has comment: http://stackoverflow.com/comment/82071062
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82228582
type: Comment
score: 0
type: AnswerComment
has text: @srig They are working with indices not elements in the lists.
comment on: http://stackoverflow.com/a/47634665

http://stackoverflow.com/q/47659726
has comment: http://stackoverflow.com/comment/82278266
duplicate of: http://stackoverflow.com/q/13293810
duplicate of: http://stackoverflow.com/q/47027754
type: AnsweredQuestion
score: 0
tagged with: pandas
upvote count: 1
tagged with: leading-zero
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47659803
tagged with: text-files
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/13250046
duplicate of: http://stackoverflow.com/q/16929056
has comment: http://stackoverflow.com/comment/82278295
duplicate of: http://stackoverflow.com/q/22360140
linked to: http://stackoverflow.com/q/13293810
has body: I have this txt file: Tu 11:44:00 119 52913161 DETECTOR STATE 0001 Tu 11:44:00 119 52913161 DETECTOR STATE 1100 Tu 11:44:02 119 52913161 DETECTOR STATE 0000 Tu 11:44:02 119 52913161 DETECTOR STATE 1110 Tu 11:44:04 119 52913161 DETECTOR STATE 0000 Tu 11:44:04 119 52913161 DETECTOR STATE 0011 Which I open in Python (Jupyter Notebook) using this code: import pandas as pd data= pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None) data.columns = ["day", "time", "street", "sensor", "type", "state", "bits"] I get this output: day time street sensor type state bits 0 Tu 11:44:00 119 52913161 DETECTOR STATE 1 1 Tu 11:44:00 119 52913161 DETECTOR STATE 1100 2 Tu 11:44:02 119 52913161 DETECTOR STATE 0 3 Tu 11:44:02 119 52913161 DETECTOR STATE 1110 4 Tu 11:44:04 119 52913161 DETECTOR STATE 0 5 Tu 11:44:04 119 52913161 DETECTOR STATE 11 How can keep the leading zeros? I've tried the following options: data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, dtype={'column': object}) data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None).astype(str) data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, converters={'ColName': str}) None of the above options work. I've updated pandas to the latest version. Any idea?
has title: Python: Keeping leading zeros when open txt with pandas
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47659803

http://stackoverflow.com/comment/82309875
type: AnswerComment
comment on: http://stackoverflow.com/a/47671583
type: Comment
has text: Thank you Sandeep. But I cannot have it work automatically without calling it from the view, correct ?
score: 0

http://stackoverflow.com/q/47586754
has body: I am trying to create a Python 64 bit installer using PyInstaller. While creating an .exe I am getting an error message like: wx_python is not loading In short, the module named wx.lib.pubsub in wx_python is not loading. But its working when I run it in the Python IDE (Python 2.7). What could be the problem? How can it be solved?
answer count: 0
downvote count: 0
has title: wx_python is not loading while creating Installer using PyInstaller
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7

http://stackoverflow.com/a/47729846
answers question: http://stackoverflow.com/q/47630356
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47630356
type: AcceptedAnswer
downvote count: 0
score: 6
has body: You can do it like below class SpeciesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Species fields = ( 'url', 'id', 'canonical_name', 'slug', 'species', 'genus', 'subfamily', 'family', 'order','class', 'phylum', 'ncbi_id', 'ncbi_taxonomy', ) read_only_fields = ('slug',) extra_kwargs = { 'url': {'lookup_field': 'slug'} } SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name") As explained in below answer https://stackoverflow.com/a/47717441/2830850
type: Answer

http://stackoverflow.com/q/47644293
tagged with: regex
favorite count: 0
has answer: http://stackoverflow.com/a/47644546
type: Question
possible better answer: http://stackoverflow.com/a/47644546
has body: I'm reading in some data in the form a list of items, space separated. Each item has a name, which may be one or more words, and a quantity which can either be a single integer or a fraction of integers. Ex. '12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank' I want this split into the following list: ['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank'] Here is my Python regex: import re re.findall(r'\d+(/\d+)?\D+', "12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank") This produces the following result, which is obviously not right: ['', '/5', '', '/18'] What is the proper regex here?
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/47644316
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Python 3 regex to split list of items?
score: 1
has answer: http://stackoverflow.com/a/47644316

http://stackoverflow.com/comment/82107253
type: Comment
type: QuestionComment
has text: @MattR this is yet another story; it inserts a third list. Don't confuse OP even more.
score: 0
comment on: http://stackoverflow.com/q/47575111

http://stackoverflow.com/a/47585782
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47585503
has body: The problem is with the expression t &gt;= start or t &lt;= end. Firstly what are start an end? You describe in the situation two time periods, but you are only passing into the function arguments for one potential time period? Lets assume start=100 and end =700. If t is before the start, say t=5. Well t is still less than 700, so this statement will be true. Or if t is after the end, say t=705, then t is still larger than 100, so again this expression will evaluate to true (which is why ac_on is always False). Basically no matter what the value of t this statement will always be true. I think what you want is t &gt;= start and t &lt;= end. Although I am still slightly confused by the two time periods you have described, maybe pass in 4 arguments, start1, end1, start2 and end2, then use: if (t &gt;= start1 and t &lt;= end1) or (t &gt;= start2 and t &lt;= end2):

http://stackoverflow.com/comment/82265107
has text: 1. Check if all elements have the same length. 2. Delete whichever elements you want to delete.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47653487
score: 3

http://stackoverflow.com/comment/82322667
has text: This is not exactly the answer of my question, but it really made my life a lot easier. Thank you.
comment on: http://stackoverflow.com/a/47681264
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82317728
comment on: http://stackoverflow.com/q/47678333
type: Comment
score: 0
has text: This seems to work.
type: QuestionComment

http://stackoverflow.com/comment/82338656
score: 0
comment on: http://stackoverflow.com/q/47689601
type: Comment
has text: it would be easier to diagnose if you would cut and paste the code or commands you and the actual crash msg
type: QuestionComment

http://stackoverflow.com/comment/82257967
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47648164
has text: FYI: Your solution will work if `mat` is C-contiguous. It will not work with, for example, `mat = np.random.randint(1, 10, size=(5, 5)).T`, because `mat.ravel()` will be a copy.
score: 0

http://stackoverflow.com/a/47620940
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47620444
has comment: http://stackoverflow.com/comment/82200084
type: Answer
has comment: http://stackoverflow.com/comment/82201578
has body: Let's consider a single line in your file: line = "01-01-1989-06:30:00| Stefan Reinartz; 1.1.1989; 06:30; +01; Engelskirchen,Germany; 50n59; 7e24; M;" If you want to get rid of the first 21 characters of a line, then you can simply use what is referred to as slicing as follows: &gt;&gt;&gt; print(line[21:]) Stefan Reinartz; 1.1.1989; 06:30; +01; Engelskirchen,Germany; 50n59; 7e24; M; (Have a look at this site for more details about retrieving substrings via slicing.) Now, if you need to extract parts of such a line, then you can indeed make use of regular expressions. To get the parts of the date, as you mentioned, you can use, e.g., a pattern with named groups as follows: import re p = r"[^\;]+; (?P&lt;day&gt;[0-9]+)\.(?P&lt;month&gt;[0-9]+)\.(?P&lt;year&gt;[0-9]+)" m = re.match(p, line) The matched groups may then be accessed like this: &gt;&gt;&gt; m.group("day") '1' &gt;&gt;&gt; m.group("month") '1' &gt;&gt;&gt; m.group("year") '1989' (You can, of course, get the date more easily by extracting it right from the beginning of a line, but this is just an example that demonstrates the use of named group.)
accepted answer of: http://stackoverflow.com/q/47620444
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82271288
has text: can you check if you have a migration folder in your application directory?
score: 1
comment on: http://stackoverflow.com/q/47656071
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47584413
score: 0
has body: I'm currently working with some people to develop an application that will display a "sound library" when the user selects an option on their voip phone. The idea is that the phone system will pass a url with a device id in it, and that will open the django app to the users' library. I was told to remove login/user authentication in order to make the process easier for the user. My question is, is there a way to create a user field and save the model for future retrieval via the url request alone? Do I need to pass the device id to some hidden form first and redirect to the main page, and query the users' objects via the device id? I know there are security concerns but was wondering if it's even possible, any help is appreciated!
answer count: 1
tagged with: url
tagged with: authentication
has title: Django create user account via URL
tagged with: django
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47584549
tagged with: python

http://stackoverflow.com/comment/82235163
has text: As this is more of a mathematical problem than a computing problem, I thought it would be more appropriate here, but if you believe this question deserves to be on stackoverflow, I'll post it there after I let it here a few. :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47638458
score: 0

http://stackoverflow.com/comment/82256022
has text: Why not just pass the `tower` array into your function? It looks like you're passing the whole array in there any way. If you want to not include element 0, you can pass in `tower[1:]` Inside the function you can loop over the array with `for i in tower` or something.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47648838
score: 1

http://stackoverflow.com/comment/82269474
type: QuestionComment
score: 0
has text: Data is tuple. You need to do sth for every item in that tuple! `G = tuple([num - 5.4 for i in Data])`
comment on: http://stackoverflow.com/q/47655676
type: Comment

http://stackoverflow.com/comment/82130747
has text: what is the command you entered?
comment on: http://stackoverflow.com/q/47586526
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82135434
type: AnswerComment
has text: Honestly, a ring/circular buffer, in C or C++. I'm sure this is doable in python somehow, but for anything dealing with actual bytes, standard in, or raw buffers...I'd go with C or C++. Maybe this will help? https://codereview.stackexchange.com/questions/85068/efficient-ring-buffer-fifo
comment on: http://stackoverflow.com/a/47588710
score: 1
type: Comment

http://stackoverflow.com/q/47617611
upvote count: 1
has body: I have a list of short strings, and a list of multiple long strings. I would like to iterate through the short strings list and find which of the short strings is in all the items of a certain list. for example: short_str_list = ["aga", "ttt", "aca"] seq_list = ["atcgcgtacat", "acatcgggattt", "tttacagtgtgtggg"] the result should be: "aca" Can someone help me with the python script for it?
favorite count: 0
type: Question
tagged with: python-3.x
score: 1
has answer: http://stackoverflow.com/a/47617792
possible better answer: http://stackoverflow.com/a/47617792
tagged with: python
has answer: http://stackoverflow.com/a/47618317
accepted answer: http://stackoverflow.com/a/47618317
linked to: http://stackoverflow.com/q/3437059
tagged with: substring
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/108959412
answer count: 2
downvote count: 0
has title: How to find an item in a list that exists as a sub-string in all the items of a list python

pyqt5
tags question: http://stackoverflow.com/q/47660050
tags question: http://stackoverflow.com/q/47556122
tags question: http://stackoverflow.com/q/47600467
type: Tag
tags question: http://stackoverflow.com/q/47622714
tags question: http://stackoverflow.com/q/47661854
tags question: http://stackoverflow.com/q/47621972
tags question: http://stackoverflow.com/q/47679599
tags question: http://stackoverflow.com/q/47544669
tags question: http://stackoverflow.com/q/47572366
tags question: http://stackoverflow.com/q/47583630
tags question: http://stackoverflow.com/q/47663812
tags question: http://stackoverflow.com/q/47670661
tags question: http://stackoverflow.com/q/47560399
tags question: http://stackoverflow.com/q/47599170
tags question: http://stackoverflow.com/q/47557240
tags question: http://stackoverflow.com/q/47685405
tags question: http://stackoverflow.com/q/47692960
tags question: http://stackoverflow.com/q/47647857
tags question: http://stackoverflow.com/q/47584350
tags question: http://stackoverflow.com/q/47644274
tags question: http://stackoverflow.com/q/47575981
tags question: http://stackoverflow.com/q/47620300
tags question: http://stackoverflow.com/q/47545128
tag name: pyqt5
tags question: http://stackoverflow.com/q/47604561
tags question: http://stackoverflow.com/q/47621360
tags question: http://stackoverflow.com/q/47613823
tags question: http://stackoverflow.com/q/47621042
tags question: http://stackoverflow.com/q/47621172
tags question: http://stackoverflow.com/q/47654327
tags question: http://stackoverflow.com/q/47640724
tags question: http://stackoverflow.com/q/47666922
tags question: http://stackoverflow.com/q/47584343
tags question: http://stackoverflow.com/q/47546162

http://stackoverflow.com/comment/82061264
comment on: http://stackoverflow.com/a/47551485
score: 0
type: AnswerComment
has text: Are you sure they match the skills in skillsdata.csv?
type: Comment

http://stackoverflow.com/a/47676878
has body: You need to use relative paths. More info: difference between relative and absolute.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47676822

http://stackoverflow.com/a/47561893
type: Answer
answers question: http://stackoverflow.com/q/47561843
score: 4
type: AcceptedAnswer
downvote count: 0
has body: Use .sort_index(axis=1): result = df1.merge(df2, how='outer').sort_index(axis=1)
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47561843

http://stackoverflow.com/comment/82327668
has text: This is exactly what I was trying to do, thanks for the clear explanation. Thank you especially for sharing info on the list comprehension. It's another thing I'm working to get confident in at the moment so very useful to see that example.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47683552
type: Comment

http://stackoverflow.com/comment/82117365
type: QuestionComment
comment on: http://stackoverflow.com/q/47580006
has text: The format `{China:1339190000:9596960.00}` that you are requesting is incorrect. The format is {key: item}.
score: 0
type: Comment

http://stackoverflow.com/q/47552309
tagged with: dataframe
tagged with: python
score: 1
has body: I am trying to replace some values in a spark dataframe by using a UDF, but keep on getting the same error. While debugging I found out it doesn't really depend on the dataframe I am using, nor the function that I write. Here is a MWE that features a simple lambda function that I can't get to execute properly. This should basically modify all the values in the first column by concatenating the value with itself. l = [('Alice', 1)] df = sqlContext.createDataFrame(l) df.show() #+-----+---+ #| _1| _2| #+-----+---+ #|Alice| 1| #+-----+---+ df = df.withColumn("_1", udf(lambda x : lit(x+x), StringType())(df["_1"])) df.show() #Alice should now become AliceAlice This is the error that I get, mentioning a rather cryptic "AttributeError: 'NoneType' object has no attribute '_jvm". File "/cdh/opt/cloudera/parcels/CDH-5.11.1-1.cdh5.11.1.p0.4/lib/spark/python/pyspark/worker.py", line 111, in main process() File "/cdh/opt/cloudera/parcels/CDH-5.11.1-1.cdh5.11.1.p0.4/lib/spark/python/pyspark/worker.py", line 106, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/cdh/opt/cloudera/parcels/CDH-5.11.1-1.cdh5.11.1.p0.4/lib/spark/python/pyspark/serializers.py", line 263, in dump_stream vs = list(itertools.islice(iterator, batch)) File "/cdh/opt/cloudera/parcels/CDH-5.11.1-1.cdh5.11.1.p0.4/lib/spark/python/pyspark/sql/functions.py", line 1566, in &lt;lambda&gt; func = lambda _, it: map(lambda x: returnType.toInternal(f(*x)), it) File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "/cdh/opt/cloudera/parcels/CDH-5.11.1-1.cdh5.11.1.p0.4/lib/spark/python/pyspark/sql/functions.py", line 39, in _ jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col) AttributeError: 'NoneType' object has no attribute '_jvm' I am sure I am getting confused with the syntax and can't get types right (thanks duck typing!), but every example of withColumn and lambda functions that I found seems to be similar to this one.
favorite count: 0
type: Question
has title: withColumn with UDF yields AttributeError: 'NoneType' object has no attribute '_jvm'
downvote count: 0
tagged with: pyspark
upvote count: 1
tagged with: lambda
accepted answer: http://stackoverflow.com/a/47552629
linked to: http://stackoverflow.com/q/58483412
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47552629
tagged with: user-defined-functions
answer count: 1

http://stackoverflow.com/a/47653452
downvote count: 1
has comment: http://stackoverflow.com/comment/102603706
has comment: http://stackoverflow.com/comment/106715211
score: 18
type: Answer
has comment: http://stackoverflow.com/comment/110796622
upvote count: 19
has comment: http://stackoverflow.com/comment/111185159
answers question: http://stackoverflow.com/q/47629570
has comment: http://stackoverflow.com/comment/106973032
has body: This error occurs because your virtual environment has broken symlinks. Here is a nice solution taken from tevino's fix_virtualenv gist: #!/usr/bin/env bash ENV_PATH="$(dirname "$(dirname "$(which pip)")")" SYSTEM_VIRTUALENV="$(which -a virtualenv|tail -1)" BAD_ENV_PATHS="/usr/local" echo "Ensure the root of the broken virtualenv:" echo " $ENV_PATH" if -z "$ENV_PATH" || "$ENV_PATH" = *"$BAD_ENV_PATHS"* ; then echo "The root path above doesn't seems to be a valid one." echo "Please make sure you ACTIVATED the broken virtualenv." echo "‼️ Exiting for your safety... (thanks @laymonk for reporting this)" exit 1 fi read -p "‼️ Press Enter if you are not sure (y/N) " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]]; then echo "♻️ Removing old symbolic links......" find "$ENV_PATH" -type l -delete -print echo " Creating new symbolic links......" $SYSTEM_VIRTUALENV "$ENV_PATH" echo " Done!" fi Also, here is a similar question: Broken references in Virtualenvs.

http://stackoverflow.com/comment/82066060
type: AnswerComment
comment on: http://stackoverflow.com/a/47554247
has text: Oh, this was actually easy if one knows about that. Thank you! Could not find that in the docs.
type: Comment
score: 0

http://stackoverflow.com/q/47629186
has body: I have a trained network with input: input = tf.placeholder(dtype=tf.float32, shape=(None, width, height, channels), name='input') In practice, I want to be able to make predictions with variable batch_size (with maximum batch size batch_max, say 100), i.e., imgs = get_batch(batch_size=1) session.run([output], feed_dict={'input:0': imgs}) imgs = get_batch(batch_size=100) session.run([output], feed_dict={'input:0': imgs}) Now I observed the following behaviour: imgs_batch1 = get_batch(batch_size=1) imgs_batch100 = get_batch(batch_size=100) session.run([output], feed_dict={'input:0': imgs_batch1}) session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s session.run([output], feed_dict={'input:0': imgs_batch1}) session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.5s session.run([output], feed_dict={'input:0': imgs_batch100}) # takes 1.0s Otherwise said, changing the batch size slows down the evaluation. The first evaluation of a batch size is significantly slower than direct following evaluations of same batch size. That sounds reasonable I can find logical reasons why that would be the case. But given that I know the maximum batch size that will ever be sent as input, is there not a smarter way to achieve this without the slowing down as soon as there is a batch of size 1 being sent? Thanks
has answer: http://stackoverflow.com/a/47629621
has title: Tensorflow evaluate network with different batch size
score: 0
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47613964
favorite count: 0
type: Question
has body: I'm trying to deploy a Django app on Heroku. As recommended for security, I don't want to commit and push my secret key from the settings.py file, so I put the key in a separate file and imported it into settings.py. I put my file containing the secret key into .gitignore so that it doesn't get committed. Now the problem is when I'm pushing to Heroku, I get a ModuleNotFoundError - which makes sense because this file was never committed. Is there a workaround or best practice to use secret keys without exposing them?
tagged with: django
tagged with: python
tagged with: git
tagged with: heroku
type: AnsweredQuestion
has title: Best practice to deploy and reference files in gitignore
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47614109
accepted answer: http://stackoverflow.com/a/47614109

http://stackoverflow.com/q/47686795
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47695657
tagged with: python-3.6
type: AnsweredQuestion
tagged with: jsonstore
accepted answer: http://stackoverflow.com/a/47695657
tagged with: http://stackoverflow.com/tag/json
tagged with: kivy
has title: How can I use individual json storage keys for use as the text on a button with kivy?
has body: I am trying to take text input, save it to a jsonstore, then use each individual key in the jsonstore as the text on a button. I've read all the relevant documentation that I can think of, I've tried searching google, and I've tried searching on here. I've tried indexing the keys, but that isn't supported. I really just can't figure it out. It's the last main feature that I need to have everything running. Here is my python script for the part I am talking about. class ScreenSix(Screen): def Create_ShopList(self): store = JsonStore('user_meals.json') ingredients = store.get(self._name.text)['ingredients'] return ingredients def Meal_Options(self): store = JsonStore('users_meals.json') meals = store.keys() return meals Here is the relevant part of my kv file. &lt;ScreenSix&gt;: name: 'shoplist' id: shoplist FloatLayout: canvas: Rectangle: pos: self.pos size: self.size source: '20.png' Label: text: 'Create Shopping List' font_size: 60 pos_hint: {'center_x':.5,'center_y':.8} color: 0,0,0,1 Label: text: 'Which meals would you like to add?' font_size: 40 pos_hint: {'center_x':.5,'center_y':.7} color: 0,0,0,1 Button: text: 'Menu' font_size: 36 size_hint: .2,.1 pos_hint: {'left':1,'y':0} on_release: app.root.current='menu' Button: text: 'Quit' font_size: 36 size_hint: .2,.1 pos_hint: {'right':1,'y':0} on_release: app.root.current='open' Button: text: '' font_size: 36 size_hint: .2,.1 pos_hint: {'center_x':.18,'center_y':.6} on_release: root.Create_ShopList() Button: text: '' font_size: 36 size_hint: .2,.1 pos_hint: {'center_x':.39,'center_y':.6} Button: text: '' font_size: 36 size_hint: .2,.1 pos_hint: {'center_x':.6,'center_y':.6} Button: text: '' font_size: 36 size_hint: .2,.1 pos_hint: {'center_x':.81,'center_y':.6} I want to get the buttons text to be the names which are saved as the keys in my json storage. The last few buttons are the buttons I want the meal names to be on, and I'm using the first one as a test button while I try to figure it out. I'm worried that I …
type: Question

http://stackoverflow.com/comment/82043493
has text: @SamuelN: it's not clear to me whether you're interested in how the official Python executable is built, or how third-party modules are built. If you clarify that, I can expand my answer
type: AnswerComment
comment on: http://stackoverflow.com/a/47543074
type: Comment
score: 0

http://stackoverflow.com/q/47610110
has title: Summing differences across "i"
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82179095
has body: I am trying to sum the difference across "i" according to the following formula: where f is a 15x1 array of zeros and ones, which looks like: [[1] [0] [0] [0] [0] [0] [0] [0] [0] [1] [1] [0] [0] [0] [0]] and M is a 8 x 15 matrix also of zeros and ones, the first row of which is: [0 0 1 1 1 1 0 1 0 0 0 1 1 0 0] "f" is inside a while loop and changes with each iteration, so I need to do this lots of times. I want to implement the above formula, so that each element in f is subtracted from the corresponding element of M(C, i), and then absolute values are taken, and those values are summed. From calculating by hand this value should be 10, so it is clear my current approach is wrong (this returns 117): (np.sum(abs(f - M[C,]))) I might be missing something obvious here, can anyone advise? When I try to loop in range(0,15), I am also off.
has answer: http://stackoverflow.com/a/47610441
accepted answer: http://stackoverflow.com/a/47610441
possible better answer: http://stackoverflow.com/a/47610462
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/47610462

http://stackoverflow.com/q/47607278
has answer: http://stackoverflow.com/a/47608515
has answer: http://stackoverflow.com/a/47607868
answer count: 3
has comment: http://stackoverflow.com/comment/82172974
has answer: http://stackoverflow.com/a/47607516
has title: python script to get all .mp3 files in mulitiple subfolders and move to one folder on a pc?
has comment: http://stackoverflow.com/comment/82173135
type: Question
has comment: http://stackoverflow.com/comment/82173088
accepted answer: http://stackoverflow.com/a/47607868
has body: Does anyone have a smooth python script to gather and move files with a certain extension from many subfolders to one folder on a PC?
possible better answer: http://stackoverflow.com/a/47608515
tagged with: python
type: AnsweredQuestion
score: 0

group-by
tags question: http://stackoverflow.com/q/47575064
tags question: http://stackoverflow.com/q/47551251
tags question: http://stackoverflow.com/q/47638212
tags question: http://stackoverflow.com/q/47610875
tag name: group-by
tags question: http://stackoverflow.com/q/47584238
type: Tag
tags question: http://stackoverflow.com/q/47657932

http://stackoverflow.com/q/47580615
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47583436
accepted answer: http://stackoverflow.com/a/47583436
tagged with: slice
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82119583
tagged with: tensor
has body: Given a network with two or more placeholders of varying dimensionality e.g. x1 = tf.placeholder(tf.int32, [None, seq_len]) x2 = tf.placeholder(tf.int32, [None, seq_len]) xn = tf.placeholder(tf.int32, [None, None, seq_len] The first dimension in each placeholder corresponds to the minibatch size. seq_len is the length of the inputs. The second dimension is like a list of inputs that I need to process together with x1 and x2 for each index in the minibatch. How can I group these tensors to operate on them by batch index? For example x1 = [[1, 2, 3], [4, 5, 6]] x2 = [[7, 8, 9], [8, 7, 6]] xn = [[[1, 5, 2], [7, 2, 8], [3, 2, 5]], [[8, 9, 8]]] I need to keep x1[0] i.e. [1, 2, 3], x2[0] i.e. [7, 8, 9], and xn[0] i.e. [[1, 5, 2], [7, 2, 8], [3, 2, 5]] together, because I need to perform matrix operations between x1[i] and each element in xn[i] for all i. Notice that the dimensionality of xn is jagged.
has comment: http://stackoverflow.com/comment/82118459
tagged with: python
has comment: http://stackoverflow.com/comment/82118502
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82120184
has title: Tensorflow - Grouping placeholders by batch index
tagged with: deep-learning
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47686294
type: Question
has comment: http://stackoverflow.com/comment/82363241
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/82336726
type: UnansweredQuestion
has body: I want to call av_find_input_format function (from dll coded in C) from Python. The function define as follows: AVInputFormat *av_find_input_format(const char *short_name); In order to call it successfully, I must define a structure AVInputFormat as its return value. The AVInputFormat structure is defined in C as follow: typedef struct AVInputFormat { const char *name; const char *long_name; int flags; const char *extensions; const struct AVCodecTag * const *codec_tag; const AVClass *priv_class; ///&lt; AVClass for the private context const char *mime_type; struct AVInputFormat *next; int raw_codec_id; int priv_data_size; int (*read_probe)(AVProbeData *); int (*read_header)(struct AVFormatContext *); int (*read_packet)(struct AVFormatContext *, AVPacket *pkt); int (*read_close)(struct AVFormatContext *); int (*read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags); int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit); int (*read_play)(struct AVFormatContext *); int (*read_pause)(struct AVFormatContext *); int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); int (*create_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); int (*free_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); } AVInputFormat; What should I do? Additional explanation, now my Python as follows: import ctypes class AVInputFormat(ctypes.Structure): pass AVInputFormat._fields_ = [("name", ctypes.c_char_p), ("long_name", ctypes.c_char_p), ('flags', ctypes.c_int), ('extensions', ctypes.c_char_p), ('codec_tag', ctypes.POINTER(AVCodecTag)), ('priv_class', ctypes.POINTER(AVClass)), ('next', ctypes.POINTER(AVInputFormat)), ('raw_codec_id', ctypes.c_int), ('priv_data_size', ctypes.c_int), ('read_prob…
has comment: http://stackoverflow.com/comment/82339286
has comment: http://stackoverflow.com/comment/82339630
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/82339256
answer count: 0
has comment: http://stackoverflow.com/comment/82372872
score: 1
tagged with: libavcodec
has comment: http://stackoverflow.com/comment/82333050
downvote count: 0
upvote count: 1
has title: How to define a structure with a function pointer by using ctypes?
has comment: http://stackoverflow.com/comment/82333777
favorite count: 0

http://stackoverflow.com/a/47686962
score: 0
has comment: http://stackoverflow.com/comment/82333760
accepted answer of: http://stackoverflow.com/q/47686674
has comment: http://stackoverflow.com/comment/82333744
answers question: http://stackoverflow.com/q/47686674
type: AcceptedAnswer
type: Answer
has body: Let's try this: df.text.str.split('v', expand=True)\ .apply(lambda x: x.str.extract('(\w+)', expand=False))\ .apply(lambda x: ' v '.join(x), 1) Output: 0 cans v macroni 1 chocolate v chocolate 2 Chocolate v sauce
has comment: http://stackoverflow.com/comment/82333778

http://stackoverflow.com/a/47692144
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47692037
has comment: http://stackoverflow.com/comment/82344176
has comment: http://stackoverflow.com/comment/82344367
downvote count: 0
upvote count: 1
has body: You must call the method you've defined into the class to happen. class example_class: def __init__(self, variable): self.thing = 'variable' self.example_method() def example_method(self): self.thing = 'changed text' def different_method(self): In this way, when you get/create an instance of the class "example_class", the method "example_method" will be called in the constructor. You could also do something like: if __name__ == '__main__': my_class = example_class() my_class.example_method()
has comment: http://stackoverflow.com/comment/82347399
has comment: http://stackoverflow.com/comment/82347542

http://stackoverflow.com/comment/82233380
type: Comment
comment on: http://stackoverflow.com/a/47637129
type: AnswerComment
score: 0
has text: The docs I linked to show how you can do this. You can use string interpolation if the value is in the form data, or you can override `get_success_message`.

http://stackoverflow.com/comment/82133777
comment on: http://stackoverflow.com/q/47588243
has text: What is you rexpected output for a sequence that contains other chars?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82240662
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47617605
has text: Does anybody know any sample code which works with tensorflow and unicode data? something that I can make use of it to solve my problem? I want to know if tensorflow can save unicode vocabulary.

http://stackoverflow.com/q/47559510
linked to: http://stackoverflow.com/q/42856255
has title: numpy genfromtext or numpy loadtxt " ValueError: could not convert string to float" or "too many values to unpack", tried almost everything
downvote count: 1
has comment: http://stackoverflow.com/comment/82077468
has comment: http://stackoverflow.com/comment/82077074
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82076741
upvote count: 2
has body: I have a very frustrating problem trying to solve for many hours now. I really maxed out all topics here on google with relevant questions and answers. What I would like to do: I have big datasets (50-70k columns in CSV) of photometry data that I would like to load in, then work with them as floats and plot them eventually with some fittings and calculations. an example of the data: Time(s),AnalogIn-1,AnalogIn-2 0.00E+00,3.96E-02,3.33E-02 0.00E+00,4.10E-02,3.33E-02 So each column has many numbers with scientific notation. In my code I first used the following to load the text: time, dat1, dat2= np.loadtxt(path, skiprows=1, unpack=True, delimiter=",") And it's been dropping "ValueError: could not convert string to float:" It works fine if I go to for e.g Excel, convert the whole CSV sheet from 'General' to 'Numbers. I tried literally everything discussed here, first starting with skipping headers and first rows, both with np.loadtxt, np.genfromtxt or with pandas loader. Also tried to change datatypes, fixing converters, re-mapping whatever what was loaded to floats. This helped, but only for certain rows and error popped in soon at random rows or popped back 'Too many values to unpack'. - I tried skip blank, nan also. I suspect the problem still somewhere in the conversion, that the scientific notation is indeed a string and it has "E" "+" and "-" chars in "random" order. I still believe I'm missing something very easy solution to this, as my CSV is really standard data.
has comment: http://stackoverflow.com/comment/82076913
has comment: http://stackoverflow.com/comment/82079259
tagged with: python
has answer: http://stackoverflow.com/a/47561983
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82076842
answer count: 2
has comment: http://stackoverflow.com/comment/82077076
has comment: http://stackoverflow.com/comment/82076780
tagged with: http://stackoverflow.com/tag/csv
score: 1
accepted answer: http://stackoverflow.com/a/47561983
has answer: http://stackoverflow.com/a/47561042
possible better answer: http://stackoverflow.com/a/47561042

http://stackoverflow.com/comment/82284995
comment on: http://stackoverflow.com/a/47662677
type: Comment
score: 0
has text: I don't want those vertical lines.
type: AnswerComment

http://stackoverflow.com/q/47600467
tagged with: python
has comment: http://stackoverflow.com/comment/82159655
tagged with: qt-slot
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47600783
accepted answer: http://stackoverflow.com/a/47600783
tagged with: qt-signals
answer count: 1
tagged with: pyqt5
type: Question
has title: Automatically create QStackedWidget pages based on Tuple
has comment: http://stackoverflow.com/comment/82159602
has body: I'm fairly new to python, and I feel this is an advanced question, with that in mind it might be out of the scope of Stack Exchange. Please bear with me. I have a QTreeWidget and QStackedWidget. I have populated the QTreeWidget using a tuple TreeList = ({ 'Header1': (( 'Item11', 'Item12', )), 'Header2': (( 'Item21', 'Item22' )) }) for key, value in TreeList.items(): root = QTreeWidgetItem(self.QTreeWidget, [key]) for val in value: root.addChild(QTreeWidgetItem([val])) I would like to use this same tuple to populate a QStackedWidget with pages that correspond with the QTreeWidget and establish signals and slots with in the same loop. I have tried using: for key in TreeList['Item1']: page = QWidget() page.setObjectName(key) self.QStackedWidget.addWidget(page) print(self.QStackedWidget) but all of the objects point to the same hex value, which I assume means they are not unique. Perhaps I need to increment the index? In either case I have not been able to figure out how to generate the signals and slots while doing this, since they are being dynamically created and I need unique but predictable names. The idea is that by simply adding a new category or item to the tuple, the QTreeView, QStackedWidget, and signals / slots are all generated at runtime without having to modify any source code beyond the tuple. What would be the best way to accomplish this? Sorry if this is too much, but I figured it might be a good question in case anyone else attempts the same thing at a later time. EDIT: I'm using Python 3.6 and PyQt5
tagged with: qstackedwidget

http://stackoverflow.com/comment/82319655
type: Comment
type: QuestionComment
score: 0
has text: @SLaks Are you saying I should point to the Angular JS code I wrote at every backend HTML template?
comment on: http://stackoverflow.com/q/47680153

http://stackoverflow.com/comment/82328039
type: QuestionComment
has text: So do you think I should remove the for loop in general?
score: 0
comment on: http://stackoverflow.com/q/47684058
type: Comment

http://stackoverflow.com/comment/82326620
type: QuestionComment
has text: That said, this question would be greatly improved by showing the code for your actual attempts that fail, and what errors they fail with. See the docs on building a [mcve].
comment on: http://stackoverflow.com/q/47683531
score: 1
type: Comment

http://stackoverflow.com/comment/82163678
type: Comment
comment on: http://stackoverflow.com/a/47601900
has text: Thank you for the help. I only need to add this logic to my query: `week_tasks = Task.object.exclude(owner=request.user, start_date__gt=end_week).exclude(end_date__lt=start_week)`
score: 0
type: AnswerComment

http://stackoverflow.com/a/47574956
type: Answer
answers question: http://stackoverflow.com/q/47574801
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47574801
has body: A generator is a way for Python to keep from storing everything in memory. The expression ([sum(i)] for i in new_list) is a formula for generating the items in a list. To keep from storing that list in memory, it just stores the function it would need to execute, which has less of a memory footprint. To turn a generator into a list, you can just do list([sum(i)] for i in new_list), or in this case ([[sum(i)] for i in new_list])

http://stackoverflow.com/comment/82631371
has text: @Maxim would love it if you can add that approach to your answer or describe the approach
score: 0
comment on: http://stackoverflow.com/a/47758616
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82117930
type: AnswerComment
has text: Hi I find the file but the 191 line is not the one you said and I didn't find from_pandas_adjacency in the file, I only find from_pandas_dataframe
comment on: http://stackoverflow.com/a/47569594
type: Comment
score: 0

http://stackoverflow.com/comment/82120027
type: QuestionComment
has text: Yeah, but I feel like I've tried it before. The only difference I can think of right now was to add anaconda/bin to path and export it in ~/.bashrc, because it kept resetting when I was exporting it in terminal. I'm sorry, I'm quite new in Linux, and don't know if that matters or not.
score: 0
comment on: http://stackoverflow.com/q/47541000
type: Comment

pyvisa
tags question: http://stackoverflow.com/q/47551983
type: Tag
tag name: pyvisa

http://stackoverflow.com/q/47557558
has comment: http://stackoverflow.com/comment/82076873
has body: I am training a LSTM model to predict the next number of a integer sequence. My input is of the form Id Sequence 3 1,3,13,87,1053,28576,2141733,508147108,402135275365,1073376057490373,9700385489355970183,298434346895322960005291,31479360095907908092817694945,11474377948948020660089085281068730 7 1,2,1,5,5,1,11,16,7,1,23,44,30,9,1,47,112,104,48,11,1,95,272,320,200,70,13,1,191,640,912,720,340,96,15,1,383,1472,2464,2352,1400,532,126,17,1,767,3328,6400,7168,5152,2464,784,160,19,1,1535,7424 8 1,2,4,5,8,10,16,20,32,40,64,80,128,160,256,320,512,640,1024,1280,2048,2560,4096,5120,8192,10240,16384,20480,32768,40960,65536,81920,131072,163840,262144,327680,524288,655360,1048576,1310720,2097152 11 1,8,25,83,274,2275,132224,1060067,3312425,10997342,36304451,301432950,17519415551,140456757358,438889687625,1457125820233,4810267148324,39939263006825,2321287521544174,18610239435360217 13 111,112,211,134,321,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 15 1,1,1,1,1,1,1,1,1,5,1,1,1,1,5,5,1,1,1,1,11,5,5,11,5,1,1,1,1,5,23,5,23,5,5,1,1,1,1,21,5,39,5,5,39,5,21,5,1,1,1,1,5,1,17,1,17,1,1,5,1,1,1,1,31,5,5,29,1,1,29,1,5 and my code is as follows: def parse_fake(train): final_set = [] for i in range(len(train)): x = [] x1 = list(np.array(train.iloc[i].split(","), dtype = np.float)) prefix = x1[:-1] suffix = x1[-1] x = [0,prefix,suffix] final_set.append(x) return final_set dataset = pd.read_csv('G:/Python/integer_sequencing/sample.csv', index_col = 'Id') train_data= parse_fake(dataset.Sequence) df = pd.DataFrame(train_data, columns=['sid', 'prefix', 'suffix']) df['suffix'].fillna(0, inplace=True) #df.to_csv('testcsv.csv') #print(df) maxlen = int(round(df.prefix.apply(len).min())) X_train, X_test, y_train, y_test = skcv.train_test_split(df['prefix'].values, df['suffix'].values, test_size=.1) X_train = pad_sequences(X_train, dtype='float', maxlen=maxlen) X_test = pad_seque…
tagged with: keras
type: Question
has comment: http://stackoverflow.com/comment/82241327
has title: NaN loss for LSTM model for integer sequence learning
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82077636
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/82076722
answer count: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/82073444

http://stackoverflow.com/a/47615966
has body: Hangman Try this code, is not refinished, but it works. Maybe it can give you some ideas. To work, you got to be connected, otherwise put the file with words on the computer. from urllib.request import urlopen from random import choice w0 = urlopen("https://raw.githubusercontent.com/Xethron/Hangman/master/words.txt") w = [str(x).replace("b'", "").replace("\\n", "") for x in w0] word = choice(w) word = word.replace("'", "") strips = list("_" * len(word)) chosen = [] def guess(): y = input("Guess a letter: ") if y in chosen: print("You have choose this letter yet, retry...") guess() chosen.append(y) if y in word: if "_" not in strips: print("GREAT, YOU WIN!") print() print() pass print("Great the letter is in the word") indexes = [x for x, y2 in enumerate(word) if y == y2] for ind in indexes: strips[ind] = y for ch in strips: print("[" + ch + "]", end='') print("You`ve choosen: ", "".join(chosen)) print() print() guess() else: print("This letter is not in the word, try again") print("".join(strips)) print("You`ve choosen: ", "".join(chosen)) def start(): for ch in range(len(word)): guess() print("Game over " * 5) print("The word was " + word) print("\n" * 5) print("HANGMAN - Giovanni Gianni Gatto") print("print start() to restart") print() start()
answers question: http://stackoverflow.com/q/47578003
type: Answer
score: 0

http://stackoverflow.com/comment/82308040
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47660220
has text: hi user3419537 i correct the code but it still have "stopped working error"

http://stackoverflow.com/comment/82040510
type: Comment
type: QuestionComment
has text: The standard format *is* now `%d %H:%M` (depending on what range of data you show). There is nothing "chopped off". The linked question shows how to change that format to any other format.
comment on: http://stackoverflow.com/q/47541367
score: 0

http://stackoverflow.com/comment/82150649
type: QuestionComment
has text: Thank you. I tried to provide some implementations. It is also showing my latest status for the idea.
comment on: http://stackoverflow.com/q/47583819
score: 1
type: Comment

http://stackoverflow.com/q/47629563
score: 1
has answer: http://stackoverflow.com/a/47629813
has title: Pandas : Replace values multiple times until the end
favorite count: 0
has answer: http://stackoverflow.com/a/47629629
tagged with: series
type: Question
tagged with: python
has body: I have a pandas df like this: import pandas as pd df = pd.DataFrame({'sales':[114,114,114,113,12,10,8500,8666]}) It is cumulative data from sales. There is a bug in the data : Some observations are wrong. (No value can be greater than the previous one : i.e., 8500 and 8666 are not correct) I want to replace these values with the previous one. I tried this df['above'] = df.sales.shift(1) df.loc[df.above &lt; df.sales, 'sales'] = df.above But this code works only one time, how to extend this code to replace all values until the end of the series (with the previous one) ? The desired result should looks like :
tagged with: replace
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47629813
downvote count: 0
tagged with: shift
linked to: http://stackoverflow.com/q/13842088
accepted answer: http://stackoverflow.com/a/47629629
upvote count: 1

http://stackoverflow.com/comment/82320317
score: 0
type: Comment
type: AnswerComment
has text: thanks, swear I'd tried this.. I thought it wouldn't remain as a local variable if you are using a variable from outside the function
comment on: http://stackoverflow.com/a/47680265

http://stackoverflow.com/comment/82318659
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47678775
type: QuestionComment
has text: Meaning, make sure your cell is literally `March` or whatever month, and not say ` March` or `March ` (there are spaces either before or after "March" which can throw off the matching in Python).

http://stackoverflow.com/comment/82127548
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47584902
has text: I was thinking we don't need a 3rd answer on this, but then I learned something! :)

http://stackoverflow.com/comment/82119709
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47578855
has text: @glibdud : Thank you for referring to the duplicate question. I got my answer there.

http://stackoverflow.com/comment/82085775
score: 0
comment on: http://stackoverflow.com/q/47563870
type: QuestionComment
has text: What do you mean it programmatically changes back to read access? Do you mean the permissions are changed somewhere?
type: Comment

wrapper
tag name: wrapper
tags question: http://stackoverflow.com/q/47627187
type: Tag
tags question: http://stackoverflow.com/q/47564621

http://stackoverflow.com/a/47616922
has comment: http://stackoverflow.com/comment/82192787
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82192882
answers question: http://stackoverflow.com/q/47616586
has comment: http://stackoverflow.com/comment/82192814
accepted answer of: http://stackoverflow.com/q/47616586
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82192227
downvote count: 0
has body: It seems your running directory is the outermost my-project. Try to change your WSGI application path like gunicorn myproject.myproject.wsgi:application --log-file - and see if the error changes. I think putting your project in the root directory (i.e. removing the first myproject directory and putting your manage.py in my-project directory) is a requirement for Heroku and will fix your problem.

http://stackoverflow.com/a/47664145
has comment: http://stackoverflow.com/comment/82288110
answers question: http://stackoverflow.com/q/47664026
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82289651
has body: Here is Solution f = open("test.txt","r") x = [] y = [] for i in f.readlines(): split_values = i.split("][") s1 = split_values[0].replace('[','') s2 = split_values[1].replace(']','') s1_split = s1.split(",") s2_split = s2.split(",") s1_split = map(int, s1_split) s2_split = map(int, s2_split) x.append(s1_split) y.append(s2_split) print(x) print(y)
accepted answer of: http://stackoverflow.com/q/47664026
type: Answer

http://stackoverflow.com/q/47589232
tagged with: pysftp
has comment: http://stackoverflow.com/comment/82137938
has comment: http://stackoverflow.com/comment/82136001
has title: tkinter GUI will not open when pysftp imported
tagged with: python
has answer: http://stackoverflow.com/a/47589310
has body: I'm working on a Programm where the User can insert data via a tkinter GUI, than they are saved in a JSON and after this uploaded to a server via sftp. When i start the file in pycharm all worked as designed. But when i try it via doubleclick on the .py file, only the command line opens for a second, but not the GUI. I did some testing and found out, that this only happened, when i import pysftp. Here the simple program i used for testing, which worked fine: from tkinter import * root = Tk() mainframe = Frame(root) mainframe.pack() mainframe.grid() root.mainloop() But if i do this: from tkinter import * import pysftp root = Tk() mainframe = Frame(root) mainframe.pack() mainframe.grid() root.mainloop() than the above mentioned happened. I use Python 3.6 and the latest pysftp version. Have anyone an Idea why this is happening? Thanks
type: Question
score: 0
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
tagged with: user-interface
has comment: http://stackoverflow.com/comment/82135788
linked to: http://stackoverflow.com/q/34739315

http://stackoverflow.com/comment/82166408
score: 0
has text: Yes, I read this page but I did not see anything about a difference at this level between PyQt and PySide
comment on: http://stackoverflow.com/q/47602743
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47663163
score: 0
has comment: http://stackoverflow.com/comment/82285856
has body: I'm guessing you're attempting to solve some graph problem. Read all the lines and create a square matrix with rows=columns=max number in the list Then depending on whether the graph is directional or not you should fill in the locations in the matrix with a 1. For example Matrix = [[0 for x in range(n)] for y in range(n)] where n is the maximum number of nodes in the graph. Then your first line should be assigned to Matrix[0][1] = 1 Matrix[1][0] = 1 //this line if graph is not directional
type: Answer
has comment: http://stackoverflow.com/comment/82286045
answers question: http://stackoverflow.com/q/47663030

http://stackoverflow.com/comment/82179449
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47602346
type: Comment
has text: Sincere apologies, I have corrected the codes now. if you run them you should be able to reproduce the error.

http://stackoverflow.com/q/47685291
downvote count: 0
upvote count: 1
answer count: 1
has body: Lets say I have a cluster with 3 instances, and when it was created I wanted 3 instances. I can use a scaling policy to manipulate it between 0-3 but obviously it hits the limit of the MAX capacity. I can update this on the front end but don't see an API call for it. How do I set the max capacity of an autoscaling group? Ideally there is a way to do this without creating a new one then deleting the old one. If that is the only way, do I need to make the cluster "aware" of the new scaling group?
has title: How can I set the MAX capacity of an autoscaling group with boto3?
accepted answer: http://stackoverflow.com/a/47685368
tagged with: amazon-web-services
favorite count: 0
type: Question
tagged with: boto
score: 1
has answer: http://stackoverflow.com/a/47685368
tagged with: python
tagged with: boto3
type: AnsweredQuestion

http://stackoverflow.com/comment/82139403
comment on: http://stackoverflow.com/q/47575496
score: 0
has text: Data set is too big but they are unit three vectors like (0.49766603112220764, -0.8000770807266235, 0.3349705636501312) attached to a 2d grid points.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82146432
has text: As also suggested by your upper comment, the problem is indeed, that `data` is already a selection of previously bigger-`data`. Thank you for the thorough derivation!
type: AnswerComment
comment on: http://stackoverflow.com/a/47580269
score: 0
type: Comment

http://stackoverflow.com/a/47615374
score: 0
answers question: http://stackoverflow.com/q/47615342
type: Answer
has body: You could do something like this: names = {'fire': 'John Smith', 'water': 'Steve Doe', 'earth': 'Bob Smith'} names_ab = {} for element, name in names.items(): first_name, last_name = name.split() names_ab[element] = '{}. {}'.format(first_name[0], last_name) print(names_ab) Which outputs: {'fire': 'J. Smith', 'water': 'S. Doe', 'earth': 'B. Smith'} If you need it to work for more names, you could use something like this: for element, name in names.items(): *first_names, last_name = name.split() names_ab[element] = '{}. {}'.format('. '.join(n[0] for n in first_names), last_name)

http://stackoverflow.com/comment/124093362
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/64787186
has text: in version 4.7 - don't work again(((( Fixed with add 'replace'
type: Comment

http://stackoverflow.com/comment/82072384
score: 0
type: Comment
type: QuestionComment
has text: because i have for e in elements, and each of the elements are classes that include property called object. I saved the id in that property, and now im trying to make them move.
comment on: http://stackoverflow.com/q/47556992

http://stackoverflow.com/a/47601719
answers question: http://stackoverflow.com/q/47599425
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You can use regex: import re # ... cleaned = [token.lemma_... clean_regex = re.compile('&lt;.*?&gt;') cleantext = re.sub(clean_regex, '', ' '.join(cleaned)) cleaned_text.append(cleantext) Note: if your text contains any '&lt;' characters (other than the &lt;br /&gt; tags), this method will not work Hope this helps!
accepted answer of: http://stackoverflow.com/q/47599425
type: Answer

http://stackoverflow.com/q/47592152
has title: How do I make an Excel RefreshAll wait to close until it finishes refreshing (python)?
tagged with: excel
has body: I've found this link but I couldn't resolve my problem I have an excel that doesn't have a pivot table, so the command "table.BackgroundQuery = False" in the code below is never excecuted. How can I solve the problem regarding my question in a Excel file without a Pivot table? import win32com.client fileName = "C:\\Users\Davide\Desktop\Refresh.xlsx" wb = xl.workbooks.open(fileName) xl.Visible = True #wb.RefreshAll() for sheet in wb.Sheets: print(sheet.name) for table in sheet.QueryTables: print("Found a query table on %s called %s" % (sheet.name, table.name)) table.BackgroundQuery = False if table.Refresh() == True: print("Query table %s refreshed!" % table.name) else: print("Query table %s FAILED to refresh." % table.name) for i in range(1,5): try: print("Found pivot table #%s called %s" % (i,sheet.PivotTables(i).Name)) if sheet.PivotTables(i).RefreshTable()==True: print("Refreshed pivot table %s" % sheet.PivotTables(i).Name) else: print("FAILED to refresh pivot table %s" % sheet.PivotTables(i).Name) except: print("No pivot table #%s found on sheet %s" % (i,sheet.Name)) break wb.Save() xl.Quit()
tagged with: refresh
score: 0
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/82148413
type: UnansweredQuestion
tagged with: win32com
has comment: http://stackoverflow.com/comment/85077055
has comment: http://stackoverflow.com/comment/82147248
tagged with: python

http://stackoverflow.com/a/47620197
answers question: http://stackoverflow.com/q/47620089
has body: Check if you have a module named src in the directory. This error basically means that the module is not present. Rebuild the project and it should solve your problem.
has comment: http://stackoverflow.com/comment/82198315
type: Answer
has comment: http://stackoverflow.com/comment/82200996
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/82129571
has text: @Julien &John You mean "what is the X problem" in this question, as it is a typical example of the [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).
comment on: http://stackoverflow.com/q/47585899
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/95622451
has text: I also found out that you can pass a tiemdelta to the 'widths' value of a bar and it will be the right width on the datetime axis
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47683309
type: Comment

http://stackoverflow.com/q/47662245
score: 2
upvote count: 2
has body: I am using Python and PIL to concatenate two images and trying to remove the attached boundary or seam to get a smoother and natural image without any artifacts. def merge_images(image1, image2, mask): img1 = Image.open(image1) img2 = Image.open(image2) mask = Image.open(mask).convert('RGBA') #mask.show() height = img1.size[1] + (img2.size[1]) width = img1.size[0] print(height , width) #height = img1.size[1] #width = img1.size[0]+(img2.size[0]/2) print(height - img1.size[1]) newImage = Image.new("RGB", (width, height), (0,0,0)) newImage.paste(img1, (0 , (height - img1.size[1]))) #newImage.show() print(newImage.size) #newImage.paste(img1, ((width-img1.size[0]),0)) newImage.paste(img2, (0 ,0), mask) return newImage This is referred from Blend Images This is the expected output from the above link: Expected Output I am not getting the same results and there is considerable seam in the concatenated image result. Source: The result is far off from the original. I am looking to remove the seam in the attached region and possibly the shadow at the bottom of the top image. I am guessing the problem is in the masking. Any suggestions would be very useful Edit: Missed adding the mask image Mask Image
tagged with: blending
has comment: http://stackoverflow.com/comment/82285290
downvote count: 0
has comment: http://stackoverflow.com/comment/82284399
answer count: 1
has comment: http://stackoverflow.com/comment/82286023
has answer: http://stackoverflow.com/a/47668830
favorite count: 0
has comment: http://stackoverflow.com/comment/82283874
has title: Python blending concatenated Images
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82285885
tagged with: opencv
has comment: http://stackoverflow.com/comment/82285640
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82284129
has comment: http://stackoverflow.com/comment/82285597
has comment: http://stackoverflow.com/comment/82283559
has comment: http://stackoverflow.com/comment/82283770
tagged with: python
has comment: http://stackoverflow.com/comment/82283903
has comment: http://stackoverflow.com/comment/82284119

http://stackoverflow.com/comment/82450807
has text: @teddiest Ok. I think Azure Function is a perfect option for you to loop the containers and detect the blobs which are larger than X MB.
type: Comment
comment on: http://stackoverflow.com/a/47706737
score: 0
type: AnswerComment

http://stackoverflow.com/q/47560729
has comment: http://stackoverflow.com/comment/82079855
has comment: http://stackoverflow.com/comment/82079383
tagged with: python
has answer: http://stackoverflow.com/a/47561353
has comment: http://stackoverflow.com/comment/82079532
has comment: http://stackoverflow.com/comment/82079837
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82079764
upvote count: 3
has comment: http://stackoverflow.com/comment/82079922
accepted answer: http://stackoverflow.com/a/47561353
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82079362
has title: Tkinter text integer to text index
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has body: Is there a way to get way to get an integer to a valid Tkinter text widget position. For example, 0 would get changed to '1.0' and if there were no characters on line 1, 1 would go to '2.0'. I am aware of the widget's index method however only to get the cursor position (in case this is the answer). Many thanks EDIT I believe (having now done more research on the matter) that the Tk Text widget lazy loads the text (for performance). Therefore, without you getting the entire text contents and performing string actions on that, I don't think its possible (the Tk Text only has a minor understanding of what is above and below the currently viewed text - hence why a horizontal scrollbar will constantly adjust when scrolling vertically).

http://stackoverflow.com/comment/82078161
has text: Why didn't this answer work for you? https://stackoverflow.com/a/8651412
type: Comment
comment on: http://stackoverflow.com/q/47560192
type: QuestionComment
score: 0

http://stackoverflow.com/q/47562030
has body: I am trying to crop a portion of a list of strings and print them. The data looks like the following - Books are on the table\nPick them up Pens are in the bag\nBring them Cats are roaming around Dogs are sitting Pencils, erasers, ruler cannot be found\nSearch them Laptops, headphones are lost\nSearch for them (This is just few lines from 100 lines of data in the file) I have to crop the string before the \n in line 1,2,5,6 and print them. I have to also print line 3,4 along with them. Expected output - Books are on the table Pens are in the bag Cats are roaming around Dogs are sitting Pencils erasers ruler cannot be found Laptops headphones are lost What I have tried so far - First I replace the comma with a space - a = name.replace(',',' '); Then I use regex to crop out the substring. My regex expression is - b = r'.*-\s([\w\s]+)\\n'. I am unable to print line 3 and 4 in which \n is not present. The output that I am receiving now is - Books are on the table Pens are in the bag Pencils erasers ruler cannot be found Laptops headphones are lost What should I add to my expression to print out lines 3 and 4 as well? TIA
possible better answer: http://stackoverflow.com/a/47562475
tagged with: string
accepted answer: http://stackoverflow.com/a/47562644
favorite count: 0
has comment: http://stackoverflow.com/comment/82082391
type: Question
upvote count: 2
answer count: 2
has title: Cropping out a portion of a string and printing using regex
has comment: http://stackoverflow.com/comment/82082350
has comment: http://stackoverflow.com/comment/82081850
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47562475
has answer: http://stackoverflow.com/a/47562644
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/47617045
has comment: http://stackoverflow.com/comment/82192705
has comment: http://stackoverflow.com/comment/82192658
has comment: http://stackoverflow.com/comment/82192282
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47617220
tagged with: list
has comment: http://stackoverflow.com/comment/82192348
has body: I have a list of numbers: [10,20,30] What I need is to expand it according to a predefined increment. Thus, let's call x the increment and x=2, my result should be: [10,12,14,16,18,20,22,24,.....,38] Right now I am using a for loop, but it is very slow and I am wondering if there is a faster way. EDIT: newA = [] for n in array: newA= newA+ generateNewNumbers(n, p, t) The function generates new number simply generate the new numbers to add to the list. EDIT2: To better define the problem the first array contains some timestamps: [10,20,30] I have two parameters one is the sampling rate and one is the sampling time, what I need is to expand the array adding between two timestamps the correct number of timestamps, according to the sampling rate. For example, if I have a sampling rate 3 and a sampling time 3 the result should be: [10,13,16,19,20,23,26,29,30,33,36,39]
has answer: http://stackoverflow.com/a/47618364
tagged with: loops
has answer: http://stackoverflow.com/a/47617160
possible better answer: http://stackoverflow.com/a/47617160
has answer: http://stackoverflow.com/a/47617209
answer count: 4
has comment: http://stackoverflow.com/comment/82192284
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82192317
has comment: http://stackoverflow.com/comment/82192436
has comment: http://stackoverflow.com/comment/82192337
has comment: http://stackoverflow.com/comment/82192418
has answer: http://stackoverflow.com/a/47617220
has comment: http://stackoverflow.com/comment/82193242
has title: Expand numbers in a list
tagged with: python

http://stackoverflow.com/q/47565541
has answer: http://stackoverflow.com/a/47565775
has title: Iterate through nested JSON object
type: Question
accepted answer: http://stackoverflow.com/a/47566199
has comment: http://stackoverflow.com/comment/82089356
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47566199
has answer: http://stackoverflow.com/a/47574248
has comment: http://stackoverflow.com/comment/82092879
tagged with: http://stackoverflow.com/tag/json
has body: How do I parse through JSON with unknown variables? I know "Europe" will always exist, but the city names (e.g. Germany, ...etc) will always be variable. I am trying to extract the city and hostname from each entry. { "Europe": { "Germany": [ { "hostname": "host1" } ], "Poland": [ { "hostname": "host2" } ], "Denmark": [ { "hostname": "host3" } ],
tagged with: python
has comment: http://stackoverflow.com/comment/82089749
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/82089039
answer count: 3
possible better answer: http://stackoverflow.com/a/47565775

http://stackoverflow.com/comment/82292368
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47666539
has text: Convert your `1`'s and `2`'s to strings. `0x01` has no readable character on the ASCII table.

http://stackoverflow.com/q/47552951
has answer: http://stackoverflow.com/a/47652930
accepted answer: http://stackoverflow.com/a/47652930
tagged with: python
has title: Why is a ScrolledPanel inside a Treebook not resized automatically?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82095206
has body: As I need scrollbars I changed the default Panel by a ScrolledPanel, but the content I inserted inside ScrolledPanel does not make it auto-size according to the size of the window. I then tried to create a default Panel and insert all the widgets in it through a BoxSizer and finally through another BoxSizer insert this Panel inside the ScrolledPanel, but the content continues without doing the autoresize. I also tried the opposite, that is, I created a standard Panel and inserted inside my ScrolledPanel using the BoxSizers, but also did not work. Another detail is that this ScrolledPanels must be inside a TreeBook, because I have a tree that manages the call of each ScrolledPanel. My code: import wx import wx.lib.scrolledpanel as scrolled from gettext import gettext as _ class MyMainView(wx.Frame): instance = None init = 0 def __init__(self, app): if self.init: return self.frameWidth = 850 self.frameHeight = 600 self.init = 1 no_sys_menu = wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.CAPTION | wx.CLIP_CHILDREN | wx.CLOSE_BOX wx.Frame.__init__(self, None, title=_("Title"), style=no_sys_menu) self.SetSize(wx.Size(self.frameWidth, self.frameHeight)) self.SetBackgroundColour('white') self.Centre() treeBook = Treebook(self) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(treeBook, 1, wx.ALL | wx.EXPAND, 10) self.SetSizer(sizer) self.Show() self.Layout() def __new__(self, *args, **kwargs): if self.instance is None: self.instance = wx.Frame.__new__(self) elif not self.instance: self.instance = wx.Frame.__new__(self) return self.instance class Treebook(wx.Treebook): def __init__(self, parent): wx.Treebook.__init__(self, parent, wx.ID_ANY, style=wx.BK_DEFAULT) self.AddPage(MainPanel(self), _("AppTitle")) self.AddSubPage(MenuPanel(self), _("SubNodeTitle1")) self.ExpandNode(0) class MainPanel(wx.Panel): # This Panel is OK def __init__(self, parent): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) self.font1 = wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD…
answer count: 1
tagged with: wxpython
tagged with: scroll
tagged with: panel
has comment: http://stackoverflow.com/comment/82140437
tagged with: autoresize
type: Question

http://stackoverflow.com/q/47592822
has body: Edit: I have seen a few answers to this question for people working in UNIX based systems but I am working in windows so I don't think these will work. I am trying to call R from Python via the rpy2 package, everything seemed to be working fine and then one day I started to get his error, just trying to import rpy2 packages. The code is simply: from rpy2 import robjects as r from rpy2.robjects.packages import importr from rpy2.robjects.vectors import DataFrame from rpy2.robjects import Formula from rpy2.robjects import pandas2ri And the error message I get is: Error: C stack usage 24382064 is too close to the limit Things I've tried so far are: Running the file with a random, non rpy2 related import statement, the error does not appear in this case I tried to think of a way of turning c-stack checking off from within R (i.e. using R_CStackLimit = -1) but I think this needs to be done for every R session, and as I can't connect to R at all without getting the error I can't send any commands to R. Would really appreciate some advice, I've been trying to work this out for days and got pretty much nowhere. Tim
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90443504
has title: Python, R and rpy2 c-stack too close to the limit error message
type: UnansweredQuestion
tagged with: rpy2
tagged with: python
tagged with: http://stackoverflow.com/tag/r
answer count: 0
has comment: http://stackoverflow.com/comment/82177616
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90393382

http://stackoverflow.com/q/47559084
has body: I have used the calendar.py module in Python: for day in list(calendar.monthcalendar(2017,calmonth)): print(day) to create a matrix for a month as: [0, 0, 0, 0, 0, 0, 1] [2, 3, 4, 5, 6, 7, 8] [9, 10, 11, 12, 13, 14, 15] [16, 17, 18, 19, 20, 21, 22] [23, 24, 25, 26, 27, 28, 29] [30, 31, 0, 0, 0, 0, 0] I want to transform this into a simple list like: (1,2,3,4....31) This would mean getting rid of the zeroes and transforming the matrix into a list. I have tried first turning it into an array with numpy: for day in list(calendar.monthcalendar(2017,calmonth)): print(day) dayarray = np.squeeze(np.asarray(day)) print(dayarray) But no other numpy formulas for getting rid of zeroes or transforming into a list seem to work.
tagged with: matrix
type: AnsweredQuestion
score: 0
upvote count: 1
tagged with: calendar
downvote count: 1
favorite count: 0
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47559257
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47559257
tagged with: python
accepted answer: http://stackoverflow.com/a/47559203
has answer: http://stackoverflow.com/a/47559203
has title: Creating simple list from calendar dates Python
tagged with: list

http://stackoverflow.com/comment/82331291
score: 0
has text: Thank you for this response, I have edited my answer a bit, im still testing out some stuff but of course you are correct in your analysis.
comment on: http://stackoverflow.com/a/47670308
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82117287
type: QuestionComment
comment on: http://stackoverflow.com/q/47579250
score: 0
has text: What error are you getting? Are you using `datetime.timedelta` to add/subtract days?
type: Comment

http://stackoverflow.com/comment/82250899
has text: You should write in your question that you are using the [ArcGIS API for Python](https://developers.arcgis.com/python/) rather than ArcPy then.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47586606

http://stackoverflow.com/comment/82175546
has text: Are these global variables `scores, name` a list type?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47608523
score: 0

http://stackoverflow.com/q/47560552
has body: I have googled for code to get the CPU load on RPi3. I found this code: import os def getCPUuse(): return str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()) For me it only returns an empty string. Where is the problem in this code? EDIT: I call it like this: while True: time.sleep(0.2) use = getCPUuse() print(use)
answer count: 2
tagged with: raspberry-pi
upvote count: 2
downvote count: 0
tagged with: cpu-load
has comment: http://stackoverflow.com/comment/87828370
favorite count: 0
has comment: http://stackoverflow.com/comment/82157373
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/62090128
possible better answer: http://stackoverflow.com/a/64850182
has comment: http://stackoverflow.com/comment/82161178
has answer: http://stackoverflow.com/a/62090128
has answer: http://stackoverflow.com/a/64850182
has comment: http://stackoverflow.com/comment/82159529
tagged with: python
has comment: http://stackoverflow.com/comment/82159187
has comment: http://stackoverflow.com/comment/82157146
has comment: http://stackoverflow.com/comment/82192960
type: Question
linked to: http://stackoverflow.com/q/9229333
has title: Get CPU load in python on Raspberry Pi doesn't work

http://stackoverflow.com/comment/82114768
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47578807
has text: it returns : ` File "/Users/abdul/Documents/IVirEnv/lib/python3.6/site-packages/git/cmd.py", line 418, in wait raise GitCommandError(self.args, status, errstr) git.exc.GitCommandError: Cmd('git') failed due to: exit code(128) cmdline: git clone -v https://github.com/arycloud/testing.git hjh.zip stderr: 'fatal: destination path 'hjh.zip' already exists and is not an empty directory.`

http://stackoverflow.com/comment/82084515
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47562292
has text: @PavelPereverzev I meant that this feature was added in Numpy version 1.9. You can check your version with `import numpy; print(numpy.__version__)`
score: 0

http://stackoverflow.com/a/47687054
has comment: http://stackoverflow.com/comment/82333981
accepted answer of: http://stackoverflow.com/q/47686468
has body: Let's try: df.apply(lambda x: x[:x.iloc[5]], 1) Output: 0 1 2 3 0 1.0 3.0 4.0 NaN 1 3.0 8.0 9.0 3.0 2 2.0 2.0 NaN NaN
answers question: http://stackoverflow.com/q/47686468
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82333905
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47650050
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82258553
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47651333
tagged with: user-interface
has answer: http://stackoverflow.com/a/47651333
linked to: http://stackoverflow.com/q/5104330
downvote count: 1
answer count: 1
favorite count: 0
has body: I am making a GUI which will copy folder or file from source to destination.I need to make Tree structure of Directory with checkbox to browse file.I refered this How to create a tree view with checkboxes in Python but i did't find logic to create whole folder . Please help me to solve this issue. from tkinter import tix import os i = 0 class View(object): def __init__(self, root,path): self.root = root self.path = path self.makeCheckList(self.path) def makeCheckList(self,path1): global i self.cl = tix.CheckList(self.root, browsecmd=self.selectItem) self.cl.pack(fill='both',expand="yes") self.cl.hlist.add("CL1", text=path1) self.cl.setstatus("CL1", "off") self.check(path1) self.cl.autosetmode() def selectItem(self, item): print (item, self.cl.getstatus(item)) def check(self,path1): global i self.path1 = path1 file = os.listdir(path1) for p in file: #print(p) full_path = path1 +"\\"+ p val = "CL1.Item1" if os.path.isdir(full_path) != True : self.cl.hlist.add("CL1.Item"+ str(i), text=p) self.cl.setstatus("CL1.Item"+str(i), "off") i = i + 1 self.dir(path1) def dir(self,path1): global i self.path1 = path1 file = os.listdir(path1) for folder in file: full_path = path1 +"\\"+ folder if os.path.isdir(full_path) == True : self.cl.hlist.add("CL1.Item"+str(i), text=folder) self.cl.setstatus("CL1.Item"+str(i), "off") i = i + 1 #self.dir(full_path) def main(): root = tix.Tk() root.geometry("800x400") view = View(root,"C:\\") root.update() root.mainloop() if __name__ == '__main__': main() My logic is not correct here.I want a recursive function which will create whole directory
type: Question
has title: How to create Tree Structure of Directory with check box using Tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/82258513
score: -1

http://stackoverflow.com/q/47556831
answer count: 1
has answer: http://stackoverflow.com/a/47557084
linked to: http://stackoverflow.com/q/8086412
favorite count: 0
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82071352
downvote count: 0
linked to: http://stackoverflow.com/q/5275731
linked to: http://stackoverflow.com/q/1830618
tagged with: windows
has title: Python os.st_uid only return value 0
tagged with: python
has body: I'm using windows machine and python 3. I'm trying to get the user id from windows files: import os os.stat('filepath').st_uid However this only returns st_uid = 0 which doesn't make sense. Can someone please help? If I can't use st_uid, what else I can use to obtain the file user info? Thanks! Update: Thanks for the help guys. I end up using windows security API to obtain user information: Here is the link
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82071386
type: UnansweredQuestion

http://stackoverflow.com/a/56897836
type: Answer
has body: I faced this same issue trying to save a dictionary whose values are csr_matrix. Dumped it to disk using pickle. file handler should be opened in "wb" mode. import pickle pickle.dump(csr_dict_obj, open("csr_dict.pkl","wb")) load the dict back using. csr_dict = pickle.load(open("csr_dict.pkl","rb"))
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47625864
upvote count: 1

http://stackoverflow.com/comment/82127977
has text: `len([k for k in dict1 if k in dict2])`
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47585122

http://stackoverflow.com/comment/82352476
has text: For `Element is not clickable` see this QA - https://stackoverflow.com/questions/44912203/selenium-web-driver-java-element-is-not-clickable-at-point-36-72-other-el/44916498#44916498
comment on: http://stackoverflow.com/q/47695744
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47675820
upvote count: 2
downvote count: 0
has body: (Spyder maintainer here) This is not a bug, it's the way Python works. However, the normal behavior can be improved by making our IPython consoles to load the %autoreload IPython magic. With that change, after saving a file you'll immediately get the code on it reloaded in your console. We'll do this in our 3.2.5 version (to be released on December 2017).
type: Answer
answers question: http://stackoverflow.com/q/47673851
score: 2

http://stackoverflow.com/q/47683149
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47683220
has body: I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here. So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with targetWord = ["_ " * len(answer)] answer is the word being searched for targetWord is what the user sees (e.g. app_e) However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores. The output is ["_ _ _ _ _ "] The output should be ["_ ","_ ","_ ","_ ","_ "] All help is appreciated :)
accepted answer: http://stackoverflow.com/a/47683174
answer count: 3
has comment: http://stackoverflow.com/comment/82325673
has answer: http://stackoverflow.com/a/47683174
has comment: http://stackoverflow.com/comment/82325685
has title: Adding Values to a List Separately
has comment: http://stackoverflow.com/comment/82325775
possible better answer: http://stackoverflow.com/a/47683220
has answer: http://stackoverflow.com/a/47683284
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/comment/82193723
comment on: http://stackoverflow.com/a/47617435
score: 0
type: AnswerComment
has text: @WeiErn Share some sample data! :)
type: Comment

http://stackoverflow.com/q/47648515
downvote count: 2
has body: I have crawled data online. these data are saved in a mongodb. the day is always before month and year. I just need the month and year.I want to remove the number in front of the month, the data frame are not the same,like: 20-21 May 2008, 19 March 2008, 16-17 September 2010, 5 September 2011, these data are saved as strings in python, is there any function to remove the numbers of day in python? these are about 3000 data,so I think I need a cycle to deal the problem.
has answer: http://stackoverflow.com/a/47648584
upvote count: 1
has comment: http://stackoverflow.com/comment/82255315
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47649036
accepted answer: http://stackoverflow.com/a/47648584
has comment: http://stackoverflow.com/comment/82255326
tagged with: data-conversion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82255414
has title: data conversion in python
type: Question
possible better answer: http://stackoverflow.com/a/47649036
answer count: 2
has comment: http://stackoverflow.com/comment/82255681
has comment: http://stackoverflow.com/comment/82255757

http://stackoverflow.com/comment/82154241
has text: this plot is not mine (I found it somewhere) -- this is what I want to achieve, I`m looking for such a code
type: Comment
comment on: http://stackoverflow.com/q/47597914
type: QuestionComment
score: 0

http://stackoverflow.com/a/47667459
upvote count: 2
has comment: http://stackoverflow.com/comment/82302027
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82294933
has comment: http://stackoverflow.com/comment/82294375
answers question: http://stackoverflow.com/q/47666359
has comment: http://stackoverflow.com/comment/82303854
has comment: http://stackoverflow.com/comment/82295427
type: Answer
accepted answer of: http://stackoverflow.com/q/47666359
has comment: http://stackoverflow.com/comment/82294210
score: 2
has comment: http://stackoverflow.com/comment/82295669
has body: Edit: Now also handles out of spec inputs (increments outside -1, 0, 1). Here's a slightly faster (for the time being) way (pp is me, D is @Divakar): # n = 10 # pp 0.02363790 ms # D 0.03705720 ms # n = 1000 # pp 0.03609150 ms # D 0.05877410 ms # n = 1000000 # pp 22.63471480 ms # D 36.92147740 ms Code including benchmarking: import numpy as np import types from timeit import timeit def setup_data(n, allow_out_of_spec=True): if allow_out_of_spec: data = {'y': np.cumsum(np.random.randint(0, 10, (n,)) * np.random.randint(-1, 2, (n,)))} else: data = {'y': np.cumsum(np.random.randint(-1, 2, (n,)))} return data # mine def f_pp(y, allow_out_of_spec=True): if allow_out_of_spec: d = np.sign(np.diff(y)) else: d = np.diff(y) ud = np.flatnonzero(d) uds = d[ud] chng = ud[np.r_[True, uds[1:] != uds[:-1]]] out = np.zeros(len(y), dtype=int) out[1:][chng] = d[chng] return out # @Divakar's def f_D(y): s0 = np.flatnonzero(y[1:] &gt; y[:-1])+1 s1 = np.flatnonzero(y[1:] &lt; y[:-1])+1 idx0 = np.searchsorted(s1,s0,'right') s0c = s0[np.r_[True,idx0[1:] &gt; idx0[:-1]]] idx1 = np.searchsorted(s0c,s1,'right') s1c = s1[np.r_[True,idx1[1:] &gt; idx1[:-1]]] out = np.zeros(len(y),dtype=int) out[s0c] = 1 out[s1c] = -1 return out for n in (10, 1000, 1000000): data = setup_data(n) ref = np.array(f_pp(**data)) print(f'n = {n}') for name, func in list(globals().items()): if not name.startswith('f_') or not isinstance(func, types.FunctionType): continue try: assert np.allclose(ref, func(**data)) print("{:16s}{:16.8f} ms".format(name[2:], timeit( 'f(**data)', globals={'f':func, 'data':data}, number=10)*100)) except: print("{:16s} apparently failed".format(name[2:]))
has comment: http://stackoverflow.com/comment/82295737

http://stackoverflow.com/q/47654662
has comment: http://stackoverflow.com/comment/82380552
tagged with: python
has title: Django REST Framework doesn't display value in PUT form
upvote count: 2
score: 2
has body: Yesterday I posted a question and found a solution to that problem. The solution however caused another issue. Please take a look at the question, so I don't have to duplicate the contents. In the Browsable API the value for 'class_name' is not displayed in the PUT form. The rendered HTML looks like this: Class For the other fields it displays the value properly, for example: Order Here are screenshots illustrating the problem: You can see that the value for the key "class" is there. The name of the input element as well the field name in the model is "class_name". I poked around the source code and found out that the form is rendered in the file renderers.py in the following order: In the class BrowsableAPIRenderer the method get_context creates the form and calls the method get_rendered_html_form. The method get_rendered_html_form calls the method render_form_for_serializer. The method render_form_for_serializer calls the method render of the class HTMLFormRenderer. But I still don't know where to interfere and what should I change. Also I tried to implement the method to_internal_value in the serializer, but this is only for the deserialization and has nothing to do with the form rendering. Does anyone have an idea where the problem lies and what could be done? UPDATE I have created GitHub repo with the code. You can clone it or fork it and try to help me. Many thanks!
has answer: http://stackoverflow.com/a/47717441
accepted answer: http://stackoverflow.com/a/47717441
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/47630356
tagged with: django
has comment: http://stackoverflow.com/comment/82378879
tagged with: django-rest-framework
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82387118
type: AnsweredQuestion

http://stackoverflow.com/q/47585921
has comment: http://stackoverflow.com/comment/82129551
has answer: http://stackoverflow.com/a/47586009
downvote count: 5
tagged with: python
has body: I am converting the date to Day of the month. when I am executing Ia m getting the following error. File ".\date.py", line 8, in &lt;module&gt; ans=datetime.date(year,month,date) TypeError: an integer is required (got type str) I don't understand this error. Return type is Str as expected. I have not declared as int. I am using Python3 and not getting why it is complaining about the datetype.
has comment: http://stackoverflow.com/comment/82129564
has comment: http://stackoverflow.com/comment/82129574
type: AnsweredQuestion
upvote count: 0
score: -5
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82129667
has title: strftime("%A") output is string. but assigning variable is expecting Int
has comment: http://stackoverflow.com/comment/82129659
has comment: http://stackoverflow.com/comment/82129535
has comment: http://stackoverflow.com/comment/82129563
type: Question
accepted answer: http://stackoverflow.com/a/47586009

http://stackoverflow.com/comment/82249703
comment on: http://stackoverflow.com/q/47645280
type: Comment
type: QuestionComment
has text: try `res.predict(x_test)`
score: 0

http://stackoverflow.com/q/47630203
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/82218271
has answer: http://stackoverflow.com/a/47630494
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82218205
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has body: I am trying to implement a metaclass that initializes class variables when a first its instance is being created. I want to keep a new magic method __load__ that should be called as a classmethod (like __new__). So I implemented it like this: class StaticLoad(type): __loaded_classes = set() def __call__(cls, *args, **kwargs): if cls not in cls.__loaded_classes: if hasattr(cls, '__load__'): cls.__load__() cls.__loaded_classes.add(cls) return super().__call__(*args, **kwargs) class BaseClass(metaclass=StaticLoad): s = 0 class MyClass(BaseClass): @classmethod def __load__(cls): print("Loading", cls.__name__, "...") cls.s += 1 obj1 = MyClass() obj2 = MyClass() print(MyClass.s) It works fine and gives the correct result: Loading MyClass ... 1 Now I want to implement the method __load__ as a classmethod by default like __new__ (without the need to type @classmethod above each time). I tried this: class StaticLoad(type): __loaded_classes = set() def __call__(cls, *args, **kwargs): if cls not in cls.__loaded_classes: if hasattr(cls, '__load__'): # I try to apply classmethod routine to make # cls.__load__ a classmethod classmethod(cls.__load__)() cls.__loaded_classes.add(cls) return super().__call__(*args, **kwargs) class BaseClass(metaclass=StaticLoad): s = 0 class MyClass(BaseClass): # @classmethod line was deleted def __load__(cls): print("Loading", cls.__name__, "...") cls.s += 1 obj1 = MyClass() obj2 = MyClass() print(MyClass.s) I got the error: Traceback (most recent call last): File "example.py", line 22, in &lt;module&gt; obj1 = MyClass() File "example.py", line 7, in __call__ classmethod(cls.__load__)() TypeError: 'classmethod' object is not callable It looks like classmethod routine is correctly available only inside a class definition. How should I improve my metaclass to make it work fine? I would like to keep the content of classes BaseClass and MyClass as I wrote above, placing all magic into StaticLoad.
tagged with: metaclass
score: 1
has answer: http://stackoverflow.com/a/47642846
has title: 'classmethod' object is not callable inside a metaclass's method in Python 3
tagged with: metaprogramming
has comment: http://stackoverflow.com/comment/82218399

http://stackoverflow.com/comment/82292595
comment on: http://stackoverflow.com/q/47666565
has text: In particular, look [here](https://wiki.python.org/moin/PythonSpeed/PerformanceTips)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47677014
has body: This is a new "feature" of matplotlib 2.1. The what's new page says Busy Cursor The interactive GUI backends will now change the cursor to busy when Matplotlib is rendering the canvas. There is also this issue about the undesired behaviour.
has comment: http://stackoverflow.com/comment/82313253
has comment: http://stackoverflow.com/comment/82317962
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82318677
has comment: http://stackoverflow.com/comment/82315301
answers question: http://stackoverflow.com/q/47676638
has comment: http://stackoverflow.com/comment/82315063
score: 1
type: Answer

http://stackoverflow.com/comment/82314716
type: AnswerComment
has text: If you take `k=-2`, corresponding to the case in the question where sorting is reversed you get again the oscillatory behaviour. So while this is all true from the computational point of view, the problem of the questioner is rather understanding the physics and accepting the fact that only <v|v> is an observable quantity which should have the desired waveform, not v itself.
comment on: http://stackoverflow.com/a/47677373
score: 0
type: Comment

http://stackoverflow.com/q/47623800
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: server
linked to: http://stackoverflow.com/q/44503787
tagged with: stdout
tagged with: python
tagged with: paramiko
tagged with: python-3.x
linked to: http://stackoverflow.com/q/25337320
has answer: http://stackoverflow.com/a/47771272
answer count: 2
accepted answer: http://stackoverflow.com/a/47771272
has title: Paramiko Server: Signalling the client that stdout is closed
has body: Trying to implement a test server in paramiko without having to modify the client for testing, I have stumbled across the problem how to close the stdout stream, making `stdout.read()´ not hang forever without going too low-level on the client's side. So far I have been able to communicate the completed command (simple text output to stdout) execution by: class FakeCluster(paramiko.server.ServerInterface): def check_channel_exec_request(self,channel,command): writemessage = channel.makefile("w") writemessage.write("SOME COMMAND SUBMITTED") writemessage.channel.send_exit_status(0) return True but I have not found a method to avoid the middle two lines in _,stdout,_ = ssh.exec_command("&lt;FILEPATH&gt;") stdout.channel.recv_exit_status() stdout.channel.close() print(stdout.read()) which is already a good workaround not having to call channel.exec_command diretly (found here). Not closing the stdoutstream, my output will not print and the underlying transport on the server also remains active forever. Closing the channel with stdout.channel.close() does not really have an effect and alternatively using os.close(writemessage.fileno()) (Difference explained here) does not work because the paramiko.channel.ChannelFile object used for the I/O streams "has no attribute 'fileno'". (Detailed explanation found here.) Also, closing the channel directly on the server side throws a SSHException for the client.. Solutions proposed here do always modify the client side but I know from using my client script on the actual server that it must be possible without these additional lines!
downvote count: 0
linked to: http://stackoverflow.com/q/35266753
has answer: http://stackoverflow.com/a/63308534
possible better answer: http://stackoverflow.com/a/63308534
linked to: http://stackoverflow.com/q/3562403
favorite count: 0
type: Question

http://stackoverflow.com/q/47663082
tagged with: python
upvote count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/47663599
type: AnsweredQuestion
tagged with: python-2.7
has body: I have UTC time (hours, minutes, seconds), longitude(deg E), latitude (deg N) and date. Can anyone provide me with a code to calculate solar zenith angle in Python 2.7?
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47678091
has answer: http://stackoverflow.com/a/47663599
has title: How can we compute solar position at a given place on a given day and time?
has answer: http://stackoverflow.com/a/47678091
downvote count: 2
score: 5
tagged with: astronomy

http://stackoverflow.com/comment/82224112
comment on: http://stackoverflow.com/q/47633077
type: QuestionComment
type: Comment
score: 0
has text: I'm curious why you want to do this. Are you working with some ancient ASCII-only system? Even if you can't use full Unicode, surely you can use an encoding like [Latin1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) that can handle simple accented letters.

http://stackoverflow.com/comment/82410223
has text: Thanks @PM2Ring :) yes indeed, I did some improvement on it too (like you pointed out). Appreciate your inputs.
comment on: http://stackoverflow.com/a/47703737
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47636137
type: Question
has body: What is the correct way to increment an entry in a 2d variable array? It seems like Variant A (below) should have worked, but it fails with: AttributeError: 'Tensor' object has no attribute 'assign_add' Is there any way to fix this? Variant B does work, but it performs more operations than necessary, and I'd prefer a proper assign_add as an atomic operation. Somewhat strangely, Variant C below also works, and is faster than Variant B, although seemingly it does much more (unnecessary) work. Variant A: graph = tf.get_default_graph() i = tf.Variable(5,tf.int32) j = tf.Variable(3,tf.int32) tbl = tf.Variable(np.zeros((10,10)),dtype = tf.float32) p_op = tf.assign_add(tbl[i,j],1) sess = tf.Session(graph = graph) tf.global_variables_initializer().run(session=sess) res = sess.run(p_op) Variant B: p_op = tbl[i,j].assign(tbl[i,j]+1) sess = tf.Session(graph = graph) tf.global_variables_initializer().run(session=sess) res = sess.run(p_op) Variant C: p_op = tf.scatter_add(tbl, [i], [tf.one_hot(j,10)]) sess = tf.Session(graph = graph) tf.global_variables_initializer().run(session=sess) res = sess.run(p_op)
accepted answer: http://stackoverflow.com/a/47660096
has comment: http://stackoverflow.com/comment/82230774
has answer: http://stackoverflow.com/a/47660096
has comment: http://stackoverflow.com/comment/82230952
has comment: http://stackoverflow.com/comment/82231533
tagged with: python
has comment: http://stackoverflow.com/comment/82230559
type: AnsweredQuestion
score: 0
has title: incrementing an entry in a 2d variable
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/82297786
score: 0
type: AnswerComment
has text: it is giving me a dropdown but nothing is being viewed also how do i link it to my existing code so that once I choose a particular column from the dropdown menu and after that use my text field to view the resulting rows @TarunKumar
type: Comment
comment on: http://stackoverflow.com/a/47669214

http://stackoverflow.com/comment/82116848
type: Comment
type: QuestionComment
has text: Use a parameter, which extracts the values to work on in the first line of the cost-function. But i would keep it splitted into two cost-functions.
comment on: http://stackoverflow.com/q/47579819
score: 0

http://stackoverflow.com/comment/82323733
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47681774
has text: what is `QPlotWidget`?, You could indicate in which part of the docs of pyqtgraph you mention it or how you import it.

http://stackoverflow.com/q/47607892
tagged with: django
tagged with: javascript
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82174487
answer count: 1
has body: I have a webhook. data0=[{"senderId":"smsdia","requestId":"******383233353233","report":[{"date":"2017-12-02 17:00:41","number":"12345","status":"1","desc":"DELIVERED"}],"userId":"119385","campaignName":"viaSOCKET"}] I receive the above data in a POST request to my server. Content-Type: application/x-www-form-urlencoded How do I parse it? I know that if it is a list: data1=['sree','kanth'] I can parse it with request.POST.getlist('data1[]') But I don't know how to parse when it is a list containing dict. edit1 Moreover, I get len(data1) is 2. But len(data0) is 0. edit2 using request.lib: https://requestb.in/13df2891?inspect
accepted answer: http://stackoverflow.com/a/47608142
has answer: http://stackoverflow.com/a/47608142
has comment: http://stackoverflow.com/comment/82174532
type: Question
has comment: http://stackoverflow.com/comment/82174528
has title: How to parse a javascript list containing dictionary in python django

http://stackoverflow.com/a/47578455
downvote count: 0
has comment: http://stackoverflow.com/comment/82363831
has comment: http://stackoverflow.com/comment/84621293
upvote count: 2
has body: Initially, it appeared to be a problem caused by the use of cygwin. The question at Cygwin shows UTC time instead of local time helped further isolate the problem to the value of the environment variable TZ in cygwin. The updated script: import time import datetime if __name__ == "__main__": print(datetime.datetime.now()) print(datetime.datetime.today()) print(datetime.datetime.fromtimestamp(time.time())) print(time.altzone) print(time.timezone) print(time.tzname) Output when run under a Windows CMD shell with, where TZ is not set: "D:\Program Files\Python35\python.exe" test.py 2017-11-30 09:39:47.236798 2017-11-30 09:39:47.236799 2017-11-30 09:39:47.236799 21600 25200 ('Mountain Standard Time', 'Mountain Daylight Time') Output when run under a cygwin bash shell with, where TZ is set to "America/Denver": /cygdrive/D/Program\ Files/Python35/python.exe test.py 2017-11-30 16:39:45.419884 2017-11-30 16:39:45.419884 2017-11-30 16:39:45.419884 -3600 0 ('Ame', 'ric') It's set to "America/Denver". When I executed env TZ="" /cygdrive/D/Program\ Files/Python35/python.exe test.py I got a more sensible output: 2017-11-30 09:56:08.643368 2017-11-30 09:56:08.643368 2017-11-30 09:56:08.643368 21600 25200 ('Mountain Standard Time', 'Mountain Daylight Time') When I set the environment variable TZ to "America/Denver" in the windows CMD shell, I get the same output as when run in the cygwin shell. It's not clear to me how Python uses the environment variable TZ and what the correct values are for it.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82363705
has comment: http://stackoverflow.com/comment/84627763
answers question: http://stackoverflow.com/q/47563103

http://stackoverflow.com/comment/82210595
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47626245
score: 0
has text: Yep, its correct. Mark the answer as correct, to help other people see it and to give him the deserved reputation. :)

http://stackoverflow.com/q/47555406
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82068079
score: -2
has body: I have the following code that i want to write the links in two different lines but i can't use the triple quotation (""") and i want a valid way to do that : toy_story data toy_story = media.Movie("Toy Story", "A story of a boy an his toy that come to life", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/watch?v=KYz2wyBy3kc") avatar data avatar = media.Movie("Avatar", "A marine on an alien planet", "https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg", "https://www.youtube.com/watch?v=5PSNL1qE6VY")
has comment: http://stackoverflow.com/comment/82068641
tagged with: python
has answer: http://stackoverflow.com/a/47556060
accepted answer: http://stackoverflow.com/a/47556060
has comment: http://stackoverflow.com/comment/82069837
has comment: http://stackoverflow.com/comment/82069165
type: Question
upvote count: 0
downvote count: 2
has title: how to write a link in python in two different lines?
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/82067727
has comment: http://stackoverflow.com/comment/82069008
has comment: http://stackoverflow.com/comment/82068597
favorite count: 0

http://stackoverflow.com/comment/82165432
type: Comment
comment on: http://stackoverflow.com/a/47601749
type: AnswerComment
has text: for example when I send the the encoder is in certain position I may get b '\xea' b '\x9e' b '\xe9' `b '@'` b '\x00' b '\x00' b '\xef' I am still able to convert the number into position data using the formula you provided even with the `b'@'`. I assume this is still a byte value. I guess my question is why is it sometimes providing these characters instead of a hex number?
score: 1

http://stackoverflow.com/comment/82052947
comment on: http://stackoverflow.com/q/47548177
score: 0
type: Comment
type: QuestionComment
has text: Add the code whatever you tried so that it can be understand where you got wrong.

http://stackoverflow.com/comment/82255968
has text: no you have to pass it to view
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47648747
score: 0

http://stackoverflow.com/comment/82262160
has text: Consider using a language tag if this is about a specific language
comment on: http://stackoverflow.com/q/47651993
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82200534
has text: This is not working. I feel this is not possible in Ubuntu.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47613446
type: Comment

http://stackoverflow.com/comment/82207173
has text: Thanks for your help and @furas if you can help that would be great!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47624656

http://stackoverflow.com/comment/82048288
type: AnswerComment
comment on: http://stackoverflow.com/a/47545590
has text: @miradulo I added some details about the space complexity tradeoff.
type: Comment
score: 0

http://stackoverflow.com/comment/82133772
type: AnswerComment
has text: The reason I have comparable Node-objects (dictionaries) in my data structure is that I can sort them while still knowing what their original position (worker index was). I need to keep track of the indices as I swap them, what would you suggest?
type: Comment
comment on: http://stackoverflow.com/a/47565830
score: 0

http://stackoverflow.com/comment/82064269
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47553821
has text: You can use regex for the same, but depending on the needed text, using regex might be a overkill
score: 0

http://stackoverflow.com/a/47581276
type: Answer
score: 0
has body: First of all you need to learn what return actually does. When the interpreter reaches a return statement in your code, it returns that value to wherever it was called from. For example, say I have a function sum_two_vals. This function takes two values for input a and b and returns their sum. sum_two_vals(a, b): return a + b print(sum_two_vals(4, 5)) This code is going to go the function sum_two_vals, execute whatever is in that function and then print out the result. When you return it sends whatever you are returning, back to where you called it from. Also you should note that when you return, all the subsequent code will not execute. When you return 'op' in like the third line of code (which by the way, op is completely undefined) none of the code following that return statement will execute. The problem you are given asks you to write code that takes one parameter, operator, and determine if its division or multiplication. You won't be asking for the user to input the operator value inside the function since this it is being passed in as a parameter. Here is something closer to what your code should look like: def multiply(operator): x = float(input('Enter number 1: ')) y = float(input('Enter number 2: ')) if operator == "*": return x * y elif operator == "/": return x / y else: return "invalid operator" print(multiply(input("Enter '/' or '*': "))) Read up on functions and how returns work here. Hope this helps.
answers question: http://stackoverflow.com/q/47580480
has comment: http://stackoverflow.com/comment/82120538

http://stackoverflow.com/a/71971439
has body: Or just simply: pyinstaller --onefile script.py --paths "C:\drivers\chromedriver.exe"
type: Answer
answers question: http://stackoverflow.com/q/47690548
score: 0
has comment: http://stackoverflow.com/comment/127181769

http://stackoverflow.com/comment/82043889
score: 1
type: Comment
type: AnswerComment
has text: @Brad: I suppose so, Personally I seldom ever bother because it literally usually isn't worth the trouble. Compiling regexes is usually a very insignificant part of the overall processing being done, so even if it didn't automatically cache them and it happened many times I wouldn't be too worried about it.
comment on: http://stackoverflow.com/a/47543209

http://stackoverflow.com/comment/82355750
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47697749
has text: Then why not just write a function?

lazy-evaluation
tags question: http://stackoverflow.com/q/47683660
type: Tag
tag name: lazy-evaluation

http://stackoverflow.com/q/47663498
has comment: http://stackoverflow.com/comment/82286469
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82286618
answer count: 0
type: UnansweredQuestion
has title: Guidance to set python environment on Windows
tagged with: python
has comment: http://stackoverflow.com/comment/82286323
has comment: http://stackoverflow.com/comment/82480346
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82286692
score: 1
has body: I'm trying to run my python scripts from the windows command line. Example: cygwin> PYTHONPATH=dir1:dir2 python script.py param1 param2 I already do that from Ubuntu's command line with no issues. On Windows, however, I've been unable to achieve it. On a particular script, Python claims that it can't import _AES, but pycrypto is installed, and the script runs perfectly fine from pycharm: from cygwin: $ PYTHONPATH=.:../..:/cygdrive/c/Python27/Lib/site-packages/ ./decrypt_tclaves.py Param1 Param2 Param3 Traceback (most recent call last): File "./decrypt_tclaves.py", line 29, in &lt;module&gt; from encrypted_tables import unpack_tclaves File "/cygdrive/c/Users/ItaloMunoz/Documents/Dev/Autentia6/server/autentia_db/encrypted_tables.py", line 6, in &lt;module&gt; from Crypto.Cipher import AES File "/cygdrive/c/Python27/Lib/site-packages/Crypto/Cipher/AES.py", line 50, in &lt;module&gt; from Crypto.Cipher import _AES ImportError: cannot import name _AES $ pip install pycrypto Requirement already satisfied: pycrypto in c:\python27\lib\site-packages $ echo $PATH | sed 's/:/\\\n/g' | grep -i python /cygdrive/c/Python27\ /cygdrive/c/Python27/Scripts/\ I thought of a permission issue, so I ran the command below, but the issue keeps the same: $chmod 777 -R /cygdrive/c/Python27/Lib/site-packages/ I've also tried pycharm's command line with the same bad result (again, from cygwin): $ PYTHONPATH=.:../..:/cygdrive/c/Python27/Lib/site-packages/ python "C:\\Program Files\\JetBrains\\PyCharm Community Edition 2017.1.3\\helpers\\pydev\\pydev_run_in_console.py" 52333 52334 C:/Users/ItaloMunoz/Documents/Dev/Autentia6/server/autentia_db/decrypt_tclaves.py Param1 Param2 Param3 Running C:/Users/ItaloMunoz/Documents/Dev/Autentia6/server/autentia_db/decrypt_tclaves.py PyDev console: starting. Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.3\helpers\pydev\pydev_run_in_console.py", line 78, in &lt;module&gt; globals = run_file(file, None, Non…
upvote count: 1
tagged with: windows
downvote count: 0
has comment: http://stackoverflow.com/comment/82477753

http://stackoverflow.com/q/47678013
tagged with: python
tagged with: google-cloud-dataflow
has body: I've created a Dataflow template to run with cron triggers and just after creation it runs successfully. Here's the code I'm using to create the template. But after a while (normally in the next day) it starts to throw the following exception: (4ba8b349f8644419): Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 706, in run self._load_main_session(self.local_staging_directory) File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 446, in _load_main_session pickler.load_session(session_file) File "/usr/local/lib/python2.7/dist-packages/apache_beam/internal/pickler.py", line 247, in load_session return dill.load_session(file_path) File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 363, in load_session module = unpickler.load() File "/usr/lib/python2.7/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.7/pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 423, in find_class return StockUnpickler.find_class(self, module, name) File "/usr/lib/python2.7/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named _pytest.config And then if I re-make the template and try to run our jobs again it works, until next day when the same error message returns. I've been trying to understand what's wrong but I couldn't so far. I thought on some sort of file having some time to live affecting the template or maybe my config import caused some conflict but this option doesn't quite explain why the job runs successfully at first. If you need any more information please let me know. Thanks!
has title: Apache-Beam ImportError: No module named _pytest.config
score: 2
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
answer count: 0
has comment: http://stackoverflow.com/comment/82485711
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82485878
tagged with: apache-beam

http://stackoverflow.com/q/47643978
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47644129
has title: Python: open either zipped or unzipped file using "with"
answer count: 3
tagged with: python
type: Question
score: 2
has comment: http://stackoverflow.com/comment/82246627
has answer: http://stackoverflow.com/a/47644129
upvote count: 2
accepted answer: http://stackoverflow.com/a/47644467
downvote count: 0
has answer: http://stackoverflow.com/a/61654064
has answer: http://stackoverflow.com/a/47644467
has body: I'm looking for a solution to open a file using "with". Hoever, I would like to check if the file is either gzipped or not and then either use gzip.open or just open something like: if f.endswith(".gz"): with gzip.open() as f: else: with open() as f: for line in f: Any ideas?
tagged with: with-statement

http://stackoverflow.com/q/47581582
downvote count: 0
has comment: http://stackoverflow.com/comment/82120949
possible better answer: http://stackoverflow.com/a/47583594
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47583594
type: AnsweredQuestion
score: 3
tagged with: performance
accepted answer: http://stackoverflow.com/a/47582113
has answer: http://stackoverflow.com/a/47582113
tagged with: python
has body: I need help speeding up this loop and I am not sure how to go about it import numpy as np import pandas as pd import timeit n = 1000 df = pd.DataFrame({0:np.random.rand(n),1:np.random.rand(n)}) def loop(): result = pd.DataFrame(index=df.index,columns=['result']) for i in df.index: last_index_to_consider = df.index.values[::-1][i] tdf = df.loc[:last_index_to_consider] - df.shift(-i).loc[:last_index_to_consider] tdf = tdf.apply(lambda x: x**2) tsumdf = tdf.sum(axis=1) result.loc[i,'result'] = tsumdf.mean() return result print(timeit.timeit(loop, number=10)) Is it possible to tweak the for loop to make it faster or are there options using numba or can I go ahead and use multiple threads to speed this loop up? What would be the most sensible way to get more performance than just simply evaluating this code straight away?
has title: Looking to speed up loop including pandas operations
has comment: http://stackoverflow.com/comment/82120657
answer count: 2
tagged with: for-loop
tagged with: pandas
upvote count: 3

http://stackoverflow.com/q/47655075
downvote count: 0
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/82268683
has comment: http://stackoverflow.com/comment/82268947
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82268649
accepted answer: http://stackoverflow.com/a/47655528
has title: Python threading stuck after 1 loop
has comment: http://stackoverflow.com/comment/82268830
has body: working on some threading with python 3 having two things running at the same time. Here is the script i was testing with. from threading import Thread import time as t x=1 z=1 var=0 def firstFunction(): global var while x == 1: var += 1 t.sleep(1) def secondFunction(): while z == 1: print(var) t.sleep(1) add=Thread(target=firstFunction) see=Thread(target=secondFunction) add.start() see.start() For some reason when I run it you exprect it to count up, right? but it just says 1 and doesn't end or say error, but if i try a script that has the script ask if you want to see the var it works fine. Any way i can get this to work without the asking? Here is the code with the asking. from threading import Thread import time as t x=1 z=1 var=0 def firstFunction(): global var while x == 1: var += 1 t.sleep(1) def secondFunction(): while z == 1: see1=input("See var? : ") if see1 == "y": print(var) elif seel == "n": print("ok") else: print("not option") add=Thread(target=firstFunction) see=Thread(target=secondFunction) add.start() see.start()
has answer: http://stackoverflow.com/a/47655528
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
score: 2
tagged with: function
tagged with: multithreading

http://stackoverflow.com/comment/82177994
comment on: http://stackoverflow.com/q/47609584
has text: canvas can use different coordinates then mouse.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47602302
tagged with: tensorflow
has title: unable to import module from site-package
has comment: http://stackoverflow.com/comment/82164091
tagged with: importerror
has answer: http://stackoverflow.com/a/47603158
has comment: http://stackoverflow.com/comment/82164110
tagged with: python
tagged with: module
type: Question
score: 0
has body: i am importing a module from sitepackages but showing error. i am successfully able to import a file eg. from tensorflow.contrib.rnn.python.ops import rnn_cell but when i am going to import a module from rnn_cell by from tensorflow.contrib.rnn.python.ops.rnn_cell import _norm i am getting error ImportError: cannot import name _norm P.S. the module _norm() is present there in rnn_cell file.
tagged with: python-import
has comment: http://stackoverflow.com/comment/82164814
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82164320
answer count: 1
has comment: http://stackoverflow.com/comment/82164849
has comment: http://stackoverflow.com/comment/82165193

http://stackoverflow.com/comment/82173499
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47606924
has text: Not that I use `patch` myself, but its good to know that `@patch()` will restore the scope later.
type: Comment

http://stackoverflow.com/comment/82172342
has text: thank you for informing, missed that piece of detail, I can see more clear now! :D
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47606945

http://stackoverflow.com/comment/125983274
type: Comment
comment on: http://stackoverflow.com/a/47615120
score: 0
type: AnswerComment
has text: every time this happens to me i spend 5 hours debugging and come back to this answer. Thank you! what i get for putting my working directory on dropbox.

http://stackoverflow.com/q/47685557
type: AnsweredQuestion
answer count: 3
has title: Django Timezone Awareness - Data to be stored in UTC
score: 1
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47690069
has answer: http://stackoverflow.com/a/47686488
favorite count: 0
type: Question
tagged with: postgresql
has comment: http://stackoverflow.com/comment/82339381
tagged with: timezone
has body: This is my first time developing a timezone aware web app. I'm using Django 1.11.7. I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o I'm making a booking app with start_time and end_time for each reservation. I expect the user to be able to enter dates and times as he experiences them in his timezone. On the other hand, I want these dates and times stored in a postgresql database in UTC format. If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today). Right? Django Internationalization settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_TZ = True USE_L10N = True USE_I18N = True During database creation: start_time TIMESTAMP WITH TIME ZONE NOT NULL, end_time TIMESTAMP WITH TIME ZONE NOT NULL Using Django's built in admin page feature, I enter the following information: But when I look up the results in the database, here's what I get: 2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05 The stored result changed in the opposite direction of what I was expecting. I was expecting: 2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05 If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it. Otherwise, if my expectations where right, I would appreciate any advice. Thank you.
tagged with: datetime
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/18306936
accepted answer: http://stackoverflow.com/a/47690069
has answer: http://stackoverflow.com/a/47686423
possible better answer: http://stackoverflow.com/a/47686423

http://stackoverflow.com/a/47542639
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82074656
has comment: http://stackoverflow.com/comment/82073630
downvote count: 0
has comment: http://stackoverflow.com/comment/82077426
accepted answer of: http://stackoverflow.com/q/47542549
has comment: http://stackoverflow.com/comment/82073493
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47542549
has comment: http://stackoverflow.com/comment/82074745
has body: In standard documentation see third example with module email https://docs.python.org/3.6/library/email.examples.html#email-examples # Import smtplib for the actual sending function import smtplib # And imghdr to find the types of our images import imghdr # Here are the email package modules we'll need from email.message import EmailMessage # Create the container email message. msg = EmailMessage() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = ', '.join(family) msg.preamble = 'Our family reunion' # Open the files in binary mode. Use imghdr to figure out the # MIME subtype for each specific image. for file in pngfiles: with open(file, 'rb') as fp: img_data = fp.read() msg.add_attachment(img_data, maintype='image', subtype=imghdr.what(None, img_data)) # Send the email via our own SMTP server. with smtplib.SMTP('localhost') as s: s.send_message(msg) EDIT: for other files you can get maintype, subtype import mimetypes filename = 'file.html' ctype, encoding = mimetypes.guess_type(filename) maintype, subtype = ctype.split("/", 1) print(maintype, subtype) # text html
type: Answer
has comment: http://stackoverflow.com/comment/84255556
has comment: http://stackoverflow.com/comment/82073076

http://stackoverflow.com/comment/82476192
has text: Thanks for the suggestion. I followed the lead and came to the conclusion that: 1- All missing values were going to one direction ('text > 4'). 2- Secondly, The same behavior was replicated by putting missing=0 for Dense DataFrame DMatrix conversion. Now I am searching for a way to take advantage of Xgboost Sparse data handling (with most of sparse data set as 0 initially). Any further suggestions on how to make Xgboost work in sparse format for missing values?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47720583
type: Comment

http://stackoverflow.com/a/47635950
has comment: http://stackoverflow.com/comment/82233421
upvote count: 3
has comment: http://stackoverflow.com/comment/82232472
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82231403
has body: Maybe the original issue is that the 0 and 6 were not in ${}? This works for me fine *** Variables *** @{words} 4.8 7.8 *** Test Cases *** Test1 [Tags] example Run Keyword Unless ${0} &lt; ${words[0]} &lt; ${6} Fail Test2 [Tags] example Run Keyword Unless ${0} &lt; ${words[1]} &lt; ${6} Fail Hope that helps, let me know if it is not your issue! ============================================================================== Basic ============================================================================== Test1 | PASS | ------------------------------------------------------------------------------ Test2 | FAIL | AssertionError
score: 3
has comment: http://stackoverflow.com/comment/82230855
type: Answer
answers question: http://stackoverflow.com/q/47629844
accepted answer of: http://stackoverflow.com/q/47629844

http://stackoverflow.com/q/47614753
has body: I am trying to write a list into a binary file and later load it again. I have this code: with open('W.bin', mode='wb') as file: file.write(bytearray(model.estimator.intercepts_)) file.close() Where model.estimator.intercepts_ is a list. However, I get this error: File "LM.py", line 200, in model_training file.write(bytearray(model.estimator.intercepts_)) TypeError: an integer or string of size 1 is required I don't know what's wrong with my code? Thank you
tagged with: python
accepted answer: http://stackoverflow.com/a/47614933
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47614933
has comment: http://stackoverflow.com/comment/82187975
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82187958
score: 0
answer count: 1
type: Question
has title: Issue when writing a list into a binary file

http://stackoverflow.com/a/47694114
score: 4
upvote count: 4
has body: You can use zip and *args: def add_lists(*args): return [sum(x) for x in zip(*args)] x = add_lists([1, 2],[2, 1],[3, 1]) # x is [6, 4]
has comment: http://stackoverflow.com/comment/82347469
downvote count: 0
answers question: http://stackoverflow.com/q/47694053
has comment: http://stackoverflow.com/comment/82347425
type: Answer

http://stackoverflow.com/comment/82338212
has text: You can check out https://regexr.com/ to find a lot of helpful info on regex and you can make your own patterns to try to match what you need.
score: 0
comment on: http://stackoverflow.com/q/47688358
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82185652
type: Comment
type: QuestionComment
score: 0
has text: If you did research, include some of what you learned in your question. For example, things you tried that didn't work.
comment on: http://stackoverflow.com/q/47612285

http://stackoverflow.com/a/50818292
type: AcceptedAnswer
has body: The reason why multiprocessing needs to pickle the async_runner instance is because self.runner is a bound method, meaning that it "contains" the async_runner instance. Since you're not actually using self in the run method, you can just make it a staticmethod to avoid this problem.
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/139955884
answers question: http://stackoverflow.com/q/47662040
type: Answer
has comment: http://stackoverflow.com/comment/127219878
score: 8
accepted answer of: http://stackoverflow.com/q/47662040

http://stackoverflow.com/a/47585294
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47585184
has body: You can do it just using list comprehensions: LR = [[i,sum([L[1] for L in LA if L[0]==i])] for i in set([L[0] for L in LA])] Gives the desired result. To break this down a bit set([L[0] for L in LA]) gives a set (with no repeats) of all of the ID's, then we simply itterate over that set and sum the values which also have that ID.
type: Answer

http://stackoverflow.com/q/47694476
type: UnansweredQuestion
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/82348488
has comment: http://stackoverflow.com/comment/82348199
has title: Rearranging a sublist within a list
has answer: http://stackoverflow.com/a/47695415
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47695132
type: Question
has body: I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem. A list like this: [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')] should come out like: [('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')] Best I got is: [('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')] Thank you
tagged with: tuples
answer count: 2
has comment: http://stackoverflow.com/comment/82348264

http://stackoverflow.com/q/47683063
score: 0
has comment: http://stackoverflow.com/comment/82397456
tagged with: python-dateutil
tagged with: datetime
has comment: http://stackoverflow.com/comment/82325950
has answer: http://stackoverflow.com/a/47684037
has body: I've went through a few useful discussions on the topic, but still don't understand the following: Say, I have a string "20080730 06:23:54 PDT" which I want to convert to a timezone aware datetime object. I understand, that dateutil.parser.parse() doesn't generally parse timezones like "PDT", but looks like it does parse "UTC" and "EDT" correctly. Are these exceptions? Is "EDT" an exception b/c it's my local timezone? import pytz from dateutil.parser import parse sdt="20080730 06:23:54 UTC" dt_obj = parse(sdt) dt_obj datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzutc()) sdt="20080730 06:23:54 EDT" dt_obj = parse(sdt) dt_obj datetime.datetime(2008, 7, 30, 6, 23, 54, tzinfo=tzlocal()) sdt="20080730 06:23:54 PDT" dt_obj = parse(sdt) dt_obj datetime.datetime(2008, 7, 30, 6, 23, 54)
type: Question
has comment: http://stackoverflow.com/comment/82326313
has title: converting datetime string to the correct timezone
answer count: 2
has comment: http://stackoverflow.com/comment/82398461
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82402169
has comment: http://stackoverflow.com/comment/82326001
has comment: http://stackoverflow.com/comment/82326158
tagged with: python
has answer: http://stackoverflow.com/a/47683582

http://stackoverflow.com/comment/82352581
score: 0
comment on: http://stackoverflow.com/q/47696409
has text: When calling `Runtime.exec()` the called process doesn't connect its output stream to the console of the calling Java process. You must `getInputStream()` (yes, input stream for the output) of the returned `Process` object and connect it somehow with `System.out` (maybe with own function running in a separate thread).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47644801
accepted answer of: http://stackoverflow.com/q/47644739
type: Answer
has comment: http://stackoverflow.com/comment/82248944
has comment: http://stackoverflow.com/comment/82248327
upvote count: 34
has comment: http://stackoverflow.com/comment/82248293
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/112106642
downvote count: 0
score: 34
has comment: http://stackoverflow.com/comment/82248382
answers question: http://stackoverflow.com/q/47644739
has body: Looks like SQLAlchemy supports LONGTEXT: $ python Python 2.7.13 (default, Sep 29 2017, 15:31:18) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from sqlalchemy.dialects.mysql import LONGTEXT &gt;&gt;&gt; See how to use vendor-specific types here: http://docs.sqlalchemy.org/en/latest/core/type_basics.html#vendor-specific-types For what it's worth, trying to develop a totally brand-neutral database layer is difficult, and rarely worth the effort. I worked on the Zend Framework 1.0 some years ago, and I tried to create a generic unit testing suite for all the SQL databases supported by that framework. I found that very few data types are supported in the same way across all implementations of SQL, despite them all claiming to support the ANSI/ISO SQL standard. Ultimately, you have to develop your own class hierarchy for your data layer, and implement the code slightly differently for each database-specific adapter. Update: I think the news is better than we think. I tried this test: t2 = Table('t2', metadata, Column('id', Integer, primary_key=True), Column('t1', String(64000)), Column('t2', String(16000000)), Column('t3', String(4294000000)), Column('t4', Text) ) metadata.create_all(engine) Then I checked to see what it ended up creating in the MySQL database: mysql&gt; show create table t2; CREATE TABLE `t2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `t1` mediumtext, `t2` longtext, `t3` longtext, `t4` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 So it does map SQLAlchemy's generic String data type to a more-or-less appropriate MySQL data type. It's not surprising to me that it used larger data types than we might expect. The MEDIUMTEXT supports 16MB in bytes, not in characters. Because my default character set is the multi-byte utfmb4, the max length of MEDIUMTEXT is actually much fewer than 2^24 characters. So it had to upgrade it to LONGTEXT. Of c…

http://stackoverflow.com/a/47580157
has body: Use a SEQUENCE object and NEXT VALUE FOR to control the auto-increment sequence Use a FINAL TABLE select statement to return the newly inserted values, including the auto-increment value
answers question: http://stackoverflow.com/q/47578485
type: Answer
score: 0

http://stackoverflow.com/q/47678112
possible better answer: http://stackoverflow.com/a/79160616
has title: Create a program to ask a number and print all divisors
tagged with: python
has comment: http://stackoverflow.com/comment/82315306
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
has body: Below is my code: num= int(input("Please enter number")) lista= [] for i in range(1,100): if num%i ==0: lista.append(i) print(i) But when I run the same, I get the below output: Please enter number24 99 Process finished with exit code 0 According to the above logic, my understanding is that the loop will iterate for 99 times because of the range given, and if the remainder is zero for "i", then it should be appended on the list. Not sure where and why my logic is wrong.
downvote count: 1
has answer: http://stackoverflow.com/a/79160616
has comment: http://stackoverflow.com/comment/82315479
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47678188
tagged with: conditional-statements
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/47678188

http://stackoverflow.com/comment/82713248
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47681103
has text: I created a test file with this code. import pandas as np from pandas import Series, DataFrame dframe_final = np.read_csv('G:/J/Python 2017/F_all_merged1.csv',dtype='str', usecols=['Block','Policy number','base','Plan code','Insurance type','Status','State','Issue age','Duration','Attained age','Sex','Issue year','Expiration year','Face Amount','cash value','PEV reserves','Face Amount','Final_reserves'], low_memory=False) mask = (dframe_final['Block'] == '159') & (dframe_final['Insurance type'].isin(['T','U','L'])) dframe_final['Final_reserves'] = np.where(mask,'OK','NOT OK')

http://stackoverflow.com/q/47671120
possible better answer: http://stackoverflow.com/a/54045476
type: AnsweredQuestion
has title: Django redirect from inside a view
score: 0
has body: I'm using django 1.11.8. I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored. What am I missing? class ThisCreateView(CreateView): def get_form_kwargs(self): if self.kwargs['x'] == 1: return redirect(reverse('this_app:this_list')) return kwargs
answer count: 2
accepted answer: http://stackoverflow.com/a/47671575
tagged with: http-redirect
has answer: http://stackoverflow.com/a/47671575
tagged with: django
has answer: http://stackoverflow.com/a/54045476
type: Question
tagged with: django-views
tagged with: python

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/47656023
type: Tag

http://stackoverflow.com/comment/82078777
score: 0
has text: adding sudo in front of command means that you running this command as root user. So problem is not on sudo, what does the error message says? Again same thing?
type: Comment
comment on: http://stackoverflow.com/a/47559957
type: AnswerComment

http://stackoverflow.com/a/47627266
has body: You're overwriting the file within the loop Open the file for writing before you loop and write with open('crawler_code.txt', 'w') as fx: for code in soup_obj.find('code'): codes = str(code) final_code = codes.replace('&lt;br/&gt;', '').replace('Â', '') print(final_code) fx.write(final_code)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47627193
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47627193

http://stackoverflow.com/a/67076083
score: 8
type: Answer
has body: Instead of using pysha3 (see DoesData's answer), you could also use the built-in module hashlib: import hashlib h = hashlib.sha3_512() # Python 3.6+ h.update(b"Hello World") h.hexdigest() Output: '3d58a719c6866b0214f96b0a67b37e51a91e233ce0be126a08f35fdf4c043c6126f40139bfbc338d44eb2a03de9f7bb8eff0ac260b3629811e389a5fbee8a894'
has comment: http://stackoverflow.com/comment/129131046
downvote count: 0
answers question: http://stackoverflow.com/q/47601592
upvote count: 8

http://stackoverflow.com/a/47638313
downvote count: 0
upvote count: 1
has body: Use urllib.quote (Python 2) or urllib.parse.quote (Python 3) to escape your dtmf value or anything else that might contain reserved characters.
answers question: http://stackoverflow.com/q/47638142
has comment: http://stackoverflow.com/comment/82258127
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82314071

http://stackoverflow.com/q/47564452
answer count: 1
has comment: http://stackoverflow.com/comment/82088398
has comment: http://stackoverflow.com/comment/82087597
has comment: http://stackoverflow.com/comment/82087170
type: Question
type: UnansweredQuestion
tagged with: text-to-speech
tagged with: google-text-to-speech
has title: RecursionError when using gtts on Python
tagged with: python
has comment: http://stackoverflow.com/comment/82088403
has comment: http://stackoverflow.com/comment/82114512
has comment: http://stackoverflow.com/comment/82087001
has answer: http://stackoverflow.com/a/58707422
has body: I am using the gtts(google text to speech) package to turn several Chinese Text to Speech. However, I got a lot of RecursionError: maximum recursion depth exceeded. The code is easy: from gtts import gTTS tts = gTTS(text=sentence, lang='zh') tts.save(r"E:\Project\audioData\zh%d.wav"%(1)) The full error messeage is showed as photo Error Messeage Traceback (most recent call last): File "E:\Independent Study\Project\test.py", line 3, in &lt;module&gt; tts = gTTS(text=sentence, lang='zh') File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 97, in __init__ text_parts = self._tokenize(text, self.MAX_CHARS) File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 169, in _tokenize min_parts += self._minimize(p, " ", max_size) File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 178, in _minimize return [thestring[:idx]] + self._minimize(thestring[idx:], delim, max_size) File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 178, in _minimize return [thestring[:idx]] + self._minimize(thestring[idx:], delim, max_size) File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 178, in _minimize return [thestring[:idx]] + self._minimize(thestring[idx:], delim, max_size) [Previous line repeated 983 more times] File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 176, in _minimize if self._len(thestring) &gt; max_size: File "C:\Users\Yuchen Liu\AppData\Local\Programs\Python\Python36\lib\site- packages\gtts\tts.py", line 154, in _len return len(unicode(text)) RecursionError: maximum recursion depth exceeded Please Help!
score: 0

http://stackoverflow.com/q/47675151
answer count: 1
favorite count: 0
has body: I want to add function in my python code so that whenever I call it, it will auto attach to the process that runs it using the debugger of pycharm. for example: # some code # some code # attach_here(pid) # some code # some code is there way to do that?
has title: Is there a way to programmatically attach to process with python?
type: Question
has answer: http://stackoverflow.com/a/47679823
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82309222
tagged with: pycharm
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47548638
type: Question
linked to: http://stackoverflow.com/q/22675690
has comment: http://stackoverflow.com/comment/82054028
has comment: http://stackoverflow.com/comment/82053929
type: UnansweredQuestion
has title: Zapier: How to get value from pdf file
has body: So right now i want to make a zap in zapier. Trigger when new pdf file add to specific folder in google drive, after that i want to write the code (zapier support python or javascript) to get the value from that pdf file (Ex: Birthday, address, certificate, experience, etc) and update that value into airtable. But i don't know how to write code to get the value from the pdf file ?. Can someone help me in this? . Really thanks. File: https://drive.google.com/file/d/1MKA9VLqeNcaLNxvHVyGtOG7D06pB6RcQ/view?usp=sharing (This is word file but it'll be convert to pdf through cloudconvert).
has comment: http://stackoverflow.com/comment/82054088
tagged with: python
tagged with: zapier
linked to: http://stackoverflow.com/q/28440170
linked to: http://stackoverflow.com/q/937808
score: 0
has comment: http://stackoverflow.com/comment/82054667
answer count: 0
has comment: http://stackoverflow.com/comment/82054311
tagged with: airtable
tagged with: javascript
has comment: http://stackoverflow.com/comment/82055128
has comment: http://stackoverflow.com/comment/82055244

http://stackoverflow.com/comment/82167108
has text: Code seems fine. Maybe it is my directory?
comment on: http://stackoverflow.com/q/47604044
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82214277
comment on: http://stackoverflow.com/a/47625978
type: Comment
has text: Is there any way to delete copy of data created by lambda function?
type: AnswerComment
score: 0

http://stackoverflow.com/q/47661242
has title: How to switch True to False in Python
linked to: http://stackoverflow.com/q/17168046
duplicate of: http://stackoverflow.com/q/7030831
has comment: http://stackoverflow.com/comment/82281530
favorite count: 0
has comment: http://stackoverflow.com/comment/86635726
type: Question
duplicate of: http://stackoverflow.com/q/17168046
has answer: http://stackoverflow.com/a/47661337
downvote count: 0
accepted answer: http://stackoverflow.com/a/47661300
tagged with: python
possible better answer: http://stackoverflow.com/a/47661290
has answer: http://stackoverflow.com/a/47661300
linked to: http://stackoverflow.com/q/7030831
has answer: http://stackoverflow.com/a/47661290
type: AnsweredQuestion
upvote count: 19
tagged with: boolean
score: 19
has comment: http://stackoverflow.com/comment/82285875
has body: What operation do I need to do to always get a False value to become True or to get a True value to become False? In other words, what do I do to switch the Boolean value of a given variable? new_dict = {} for i in range(1, 101): new_dict[i] = False i = 2 while i &lt; 101: for x in range(1, 101): if new_dict[x] % i == 0: a = new_dict[x] new_dict[x] = not a i += 1 for a in new_dict: print 'Light #%d --&gt; %r' % (a, new_dict[a]) The output below is only True. From this, I understand that what I did for some reason is not changing every other value to False. Why is this happening? Does anyone have any idea why? Light #1 --&gt; True Light #2 --&gt; True Light #3 --&gt; True Light #4 --&gt; True Light #5 --&gt; True Light #6 --&gt; True Light #7 --&gt; True Light #8 --&gt; True Light #9 --&gt; True Light #10 --&gt; True Light #11 --&gt; True Light #12 --&gt; True Light #13 --&gt; True Light #14 --&gt; True Light #15 --&gt; True Light #16 --&gt; True Light #17 --&gt; True Light #18 --&gt; True Light #19 --&gt; True Light #20 --&gt; True Light #21 --&gt; True Light #22 --&gt; True Light #23 --&gt; True Light #24 --&gt; True Light #25 --&gt; True Light #26 --&gt; True Light #27 --&gt; True Light #28 --&gt; True Light #29 --&gt; True Light #30 --&gt; True Light #31 --&gt; True Light #32 --&gt; True Light #33 --&gt; True Light #34 --&gt; True Light #35 --&gt; True Light #36 --&gt; True Light #37 --&gt; True Light #38 --&gt; True Light #39 --&gt; True Light #40 --&gt; True Light #41 --&gt; True Light #42 --&gt; True Light #43 --&gt; True Light #44 --&gt; True Light #45 --&gt; True Light #46 --&gt; True Light #47 --&gt; True Light #48 --&gt; True Light #49 --&gt; True Light #50 --&gt; True Light #51 --&gt; True Light #52 --&gt; True Light #53 --&gt; True Light #54 --&gt; True Light #55 --&gt; True Light #56 --&gt; True Light #57 --&gt; True Light #58 --&gt; True Light #59 --&gt; True Light #60 --&gt; True Light #61 --&gt; True Light #62 --&gt; True Light #63 --&gt; True Light …
answer count: 3

http://stackoverflow.com/a/47683851
score: 0
answers question: http://stackoverflow.com/q/47683816
has body: let's say outcomeG &lt;= 22 then your code encounters outcomeG &lt;= 25 condition first, and enters first condition, always. You have to swap your if and elif to test &lt;=22 first Of course you have to do something if outcomeG &gt; 25 else you're looping for nothing.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47683816

http://stackoverflow.com/q/47579207
tagged with: multi-index
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49618123
linked to: http://stackoverflow.com/q/18199288
has title: How to find actual row number of an index in a Multi-Index pandas Dataframe where indices are not unique
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/18199288
tagged with: dataframe
tagged with: python
has body: p is a pandas dataframe that looks in Spyder console like below: In [1]: p Out[1]: ncloc files ncloc Correlation Coefficient 1.000000 0.500000 NaN Sig. (2-tailed) NaN 0.000000 N 1600.000000 1600.000000 new_lines Correlation Coefficient 0.021537 0.021873 NaN Sig. (2-tailed) 0.242349 0.238163 N 1600.000000 1600.000000 classes Correlation Coefficient 0.978614 0.993551 NaN Sig. (2-tailed) 0.000000 0.000000 N 1600.000000 1600.000000 In Spyder data explorer, p looks like below: I can access the element corresponding to 'files' column and 'new_lines' row as: In [2]: p['files']['new_lines'] Out[2]: Correlation Coefficient 0.5 Name: files, dtype: float64 But the output is of type 'pandas.core.series.Series'. I can also access the numeric value (of type: numpy.float64) as: In [3]: p['files'][3] Out[3]: 0.5 Now, how do i find out that the actual row number of the index 'new_lines' in p is 3? I can write a for loop to find it out but there should be a very simple way to find out the row number for the index 'new_lines'. The for loop way to find this is like below: row = 'new_lines' for r_index in len(p.index): if (p.index[r_index][0] == row): break # r_index has the result So, I have my result i.e. row number in the r_index variable. How to do this operation more efficiently?
score: 2
tagged with: pandas
downvote count: 0
answer count: 1

http://stackoverflow.com/q/47647162
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82261692
accepted answer: http://stackoverflow.com/a/47652470
tagged with: javascript
tagged with: web-scraping
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/47652470
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82252997
type: Question
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82253055
has title: how to parsing json var inside script tag
has body: I'm trying to scrape the data shown in the scatter plot in https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/renal+cancer The javascript is in '&lt;script&gt; var plot = $('#scatter6001').scatterPlot({"Alive (n=651)":{"symbol":"circle","data":[{"x":0.407889650408,"y":12.811,"tooltip":"TCGA-KL-8324-01A&lt;br&gt;Female\/ Stage ii \/ Alive&lt;br&gt;FPKM: 0.4&lt;br&gt;Living days: 4676 (12.8 years)","class":"stage_ii sex_f best_low median_low"},{"x":0.587835812523,"y":8.0795,"tooltip":"TCGA-KL-8334-01A&lt;br&gt;Female\/ Stage iii \/ Alive&lt;br&gt;FPKM: 0.6&lt;br&gt;Living days: 2949 (8.1years)","class":"stage_iii sex_f best_low median_low"}'...}); My question is how to parse the information in TCGA-XX-XXXX-XXX, gender,stage, living or dead, FPKM and Living days? And how to save those information in the csv file? This is the code I have done. page = urlopen("https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/prostate+cancer#imid_3605750") content = page.read() soup = BeautifulSoup(content,'lxml') table = soup.find('div', {'id':'scatter6001'}) print(table) p = re.search(r"var plot = (.*?);",soup).group(1) print(p) The code has some error, which is Traceback (most recent call last): File "scrap2.py", line 24, in p = re.search(r"var plot = (.*?);",soup).group(1) File "C:\Python34\lib\re.py", line 170, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer How to solve this problem and scrap the data I want? Thanks

http://stackoverflow.com/comment/82236363
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47639029
has text: Works only if the set of the keys is exactly the same in both dictionaries.
type: Comment

http://stackoverflow.com/a/48623454
has body: Running Python SparkPi in YARN Cluster Mode Run the pi.py file: spark-submit --master yarn --deploy-mode cluster SPARK_HOME/lib/pi.py 10 Please refer to the following link for more information: "Running Spark Applications on YARN".
score: -2
has comment: http://stackoverflow.com/comment/84286958
type: Answer
has comment: http://stackoverflow.com/comment/84287185
has comment: http://stackoverflow.com/comment/84273544
upvote count: 0
has comment: http://stackoverflow.com/comment/84286950
downvote count: 2
answers question: http://stackoverflow.com/q/47574624
has comment: http://stackoverflow.com/comment/84357025

http://stackoverflow.com/q/47649159
has comment: http://stackoverflow.com/comment/82256913
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82256947
possible better answer: http://stackoverflow.com/a/47650321
linked to: http://stackoverflow.com/q/617787
answer count: 3
has answer: http://stackoverflow.com/a/50351843
has comment: http://stackoverflow.com/comment/82256874
downvote count: 1
favorite count: 0
type: Question
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/47649793
has title: How do I properly perform multiprocessing from PyQt?
has body: I create a button and try to run multiprocessing when I click button , but the UI is become blocked . I hope process run in backgorund . How can I fix it ? from PySide2 import QtCore,QtGui,QtWidgets import sys import multiprocessing from threading import Timer class TTT(multiprocessing.Process): def __init__(self): super(TTT, self).__init__() self.daemon = True def run(self): while True: t = Timer(5, self.doSomething) t.start() t.join() def doSomething(self): try: print('123') except Exception as e: print(e) class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) btn = QtWidgets.QPushButton('run process') btn.clicked.connect(self.create_process) self.setCentralWidget(btn) def create_process(self): QtWidgets.QMessageBox.information(self,'hhh','hhh') t = TTT() t.start() t.join() if __name__=="__main__": app=QtWidgets.QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_())
has answer: http://stackoverflow.com/a/47650321
has comment: http://stackoverflow.com/comment/82256823
has comment: http://stackoverflow.com/comment/82257466
has answer: http://stackoverflow.com/a/47649793
score: 10
tagged with: python

http://stackoverflow.com/q/47542442
has body: I read a file having the following text this is::b(test file). extra this is::another(test file). this is::a(test file) I am able to read the file and write it in another file.I want to capture the word after this is:: and before '(' i.e 'b' from the first line and 'a' from the 3rd line and store it in a list and nothing from the 2nd line since it has extra word before 'this is' I tried using the Regular expression: for item in lines: print(item) fw.write(item) found=None found=(re.search('this is::(.+?)[)]',y).group(1) where y= string read from the file y=''.join(lines) But it is capturing only 'b' and adding the new line after each line. Can someone please suggest how should I go about achieving it. Expected File: this is::b(test file). An extra line:b extra this is:another(test file). this is::a(test file). An extra line:a
has answer: http://stackoverflow.com/a/47543040
linked to: http://stackoverflow.com/q/4706499
possible better answer: http://stackoverflow.com/a/47542992
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82042920
has title: Capturing word after a particular string is present in a file and add a line if it's present
has comment: http://stackoverflow.com/comment/82070250
accepted answer: http://stackoverflow.com/a/47543040
tagged with: python
has answer: http://stackoverflow.com/a/47542992
tagged with: regex
has comment: http://stackoverflow.com/comment/82045822
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82043673
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/82311248
has text: Please look into `for` and `while` loops.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47676152

http://stackoverflow.com/comment/82308561
comment on: http://stackoverflow.com/q/47672410
type: Comment
score: 0
type: QuestionComment
has text: looks like it has been fixed https://github.com/celery/celery/pull/3958

http://stackoverflow.com/comment/82298967
comment on: http://stackoverflow.com/a/47661828
score: 0
type: AnswerComment
has text: 'labels, data = [*zip(*dict1.items())] # 'transpose' items to parallel key, value lists ^ SyntaxError: invalid syntax' It is appearing this after processing. Do you have any idea?
type: Comment

http://stackoverflow.com/comment/82070539
type: Comment
comment on: http://stackoverflow.com/a/47555693
score: 0
type: AnswerComment
has text: Actually, I made a mistake with input data - this is running 2.4 sec

http://stackoverflow.com/comment/82107902
comment on: http://stackoverflow.com/q/47575226
score: 0
type: Comment
type: QuestionComment
has text: @Jaxi Can you show a quick example?

http://stackoverflow.com/comment/98295706
score: 0
type: AnswerComment
has text: You will use datetime.strptime(date_str , '%b %d, %Y')
comment on: http://stackoverflow.com/a/47557167
type: Comment

http://stackoverflow.com/a/54504331
has body: You can just use bytes the return of read() https://docs.aws.amazon.com/rekognition/latest/dg/images-bytes.html #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) import boto3 if __name__ == "__main__": imageFile='input.jpg' client=boto3.client('rekognition') with open(imageFile, 'rb') as image: response = client.detect_labels(Image={'Bytes': image.read()}) print('Detected labels in ' + imageFile) for label in response['Labels']: print (label['Name'] + ' : ' + str(label['Confidence'])) print('Done...') [1]: https://docs.aws.amazon.com/rekognition/latest/dg/images-bytes.html
answers question: http://stackoverflow.com/q/47542341
score: 3
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47655242
has answer: http://stackoverflow.com/a/73235612
has body: Similarly to these (very useful!) two functions: "Run current cell" "Run selection or current line" Is it possible to do this with debugging? I dont want to start from the top of my large script files every time I debug. I'm using Spyder version 3.2.4
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/82269629
tagged with: debugging
has comment: http://stackoverflow.com/comment/82268678
upvote count: 8
type: UnansweredQuestion
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/108757379
has title: python spyder - debug only current cell or selection?
has answer: http://stackoverflow.com/a/47656015
has comment: http://stackoverflow.com/comment/82269798
has answer: http://stackoverflow.com/a/77402900
has answer: http://stackoverflow.com/a/77015154
tagged with: spyder
downvote count: 0

http://stackoverflow.com/q/47643805
tagged with: http://stackoverflow.com/tag/json
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: firebase-realtime-database
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: firebase
has body: I have an app that gets the updates from firebase database. Its functioning well as its updating within the REST methology, however, I am unable to save the recent values before the changes. I tried looping over everything, but it was just a mess I ve got an idea to screenshot the whole thing and then save it somewhere after it updates then psot it to the bottomest. But yeah, it's not a good practice. I'm really new at json and python syncs so I'm not really sure of what should I do. Do you have any suggestions? Here's my code by the way: @app.route("/room1") def room1(): #USE THIS LATER #%b %d, %Y %I:%M:%S %p result1date = firebase.get('/Rooms/Room1/', None) for key in result1date.keys(): key = sorted(result1date.keys())[-2] currentdate = key print currentdate result1 = firebase.get('/Rooms/Room1/' + currentdate + '/Inspection/Scan-in/Inspector/', None) result2 = firebase.get('/Rooms/Room1/' + currentdate + '/Inspection/Scan-out/Inspector/', None) print result1 print currentdate for key in result1.keys(): inspector = key timeout = result2[inspector]["Time"] # for key in result1date.keys(): # Date = key result1datetime = firebase.get('/Rooms/Room1/'+ currentdate +'/Inspection/Scan-in/Inspector/'+ inspector +'/', None) for key in result1datetime.keys(): key = sorted(result1datetime.keys())[-2] time = key print time print time ch1 = result1datetime[time]["Checklist"]["Entrance louver clean and dust-free"] # ch2 = result1datetime[time]["Checklist"]["Room plate number – clean and well-polished"] ch3 = result1datetime[time]["Checklist"]["Appearance door surface- in good condition"] # ch4 = result1datetime[time]["Checklist"]["Let the door close by itself to test the door closure – in working order"] ch5 = result1datetime[time]["Checklist"]["Eye viewer and fire escape plan in order"] ch6 = result1datetime[time]["Checklist"]["Privacy Sign or Make Up Room Sign"] # ch7 = result1datetime[time]["Checklist"]["Key card holder – in working order"] ch8 = result1datetime[time]["Chec…
has title: How to post new Json Structure On Update
score: 1

http://stackoverflow.com/q/47554689
has comment: http://stackoverflow.com/comment/82066612
tagged with: python-import
has title: How do I import module?
answer count: 1
accepted answer: http://stackoverflow.com/a/47554749
type: Question
has comment: http://stackoverflow.com/comment/82066458
tagged with: python
has comment: http://stackoverflow.com/comment/82066160
has answer: http://stackoverflow.com/a/47554749
has body: The directory structure is as follows: folder1 __init__.py file1.py folder2 file2.py If I write file2.py as follows: from folder1 import file1 I get the error No module named 'folder1'. If I write file2.py as follows: from ..folder1 import file1 I get the error ValueError: attempted relative import beyond top-level package. How can I import file1 from file2?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82129728
has text: Are you sure you are using a gray scale image? Try `img = color.rgb2gray(img)` before calling `richardson_lucy`
comment on: http://stackoverflow.com/q/47585871
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47571715
has title: Dask: create strictly increasing index
has body: As is well documented, Dask creates a strictly increasing index on a per partition basis when reset_index is called, resulting in duplicate indices over the whole set. What is the best way (e.g. computationally quickest) to create a strictly increasing index in Dask - which doesn't have to be consecutive - over the whole set? I was hoping map_partitions would pass in the partition number, but I don't think it does. Thanks. EDIT Thanks @MRocklin, I've got this far, but I need a little assistance on how to recombine my series with the original dataframe. def create_increasing_index(ddf:dd.DataFrame): mps = int(len(ddf) / ddf.npartitions + 1000) values = ddf.index.values def do(x, max_partition_size, block_id=None): length = len(x) if length == 0: raise ValueError("Does not work with empty partitions. Consider using dask.repartition.") start = block_id[0] * max_partition_size return da.arange(start, start+length, chunks=1) series = values.map_blocks(do, max_partition_size=mps, dtype=np.int64) ddf2 = dd.concat([ddf, dd.from_array(series)], axis=1) return ddf2 Where I'm getting the error "ValueError: Unable to concatenate DataFrame with unknown division specifying axis=1". Is there a better way than using dd.concat? Thanks. EDIT AGAIN Actually, for my purposes (and amounts of data that I was testing on - only a few gb) cumsum is fast enough. I'll revisit when this becomes too slow!
tagged with: python
has answer: http://stackoverflow.com/a/47573871
accepted answer: http://stackoverflow.com/a/47573871
score: 8
type: AnsweredQuestion
downvote count: 0
answer count: 1
upvote count: 8
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: dask

http://stackoverflow.com/comment/82228422
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47599297
type: Comment
has text: When I use mpl_toolbar to control two plot window under MDI subwindows sometimes it shows "already locked" any adive on this, thanks.

http://stackoverflow.com/q/47652467
accepted answer: http://stackoverflow.com/a/47652960
has answer: http://stackoverflow.com/a/47652960
type: Question
has title: Sorting 20 newsgroup dataset in python
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/82262964
tagged with: text
type: AnsweredQuestion
score: 0
has body: in the code below I tried to sort the 20 newsgroup datasets. But it provides error. The wondering part is the dimensionality of this array (11314, 130107). Anyone knows why? import numpy as np import tensorflow as tf from pprint import pprint from sklearn.datasets import fetch_20newsgroups_vectorized data_train= fetch_20newsgroups_vectorized(subset='train') temp= np.sort(data_train.data, axis=1)
answer count: 1

http://stackoverflow.com/comment/82041301
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47541316
type: Comment
has text: weird using the exact same code keeps showing me 10 figures.

http://stackoverflow.com/comment/82285481
type: Comment
has text: @YaroslavAdmin Isn't the `|` operator for shell a way of executing calls one after the other or is that a concatenation thing where it takes the output of the last command and feeds it into the next?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47662947

http://stackoverflow.com/comment/83571289
comment on: http://stackoverflow.com/q/47617849
score: 0
type: Comment
type: QuestionComment
has text: Hi sir! I also have the same problem, how did you solve this? Thanks!

http://stackoverflow.com/comment/82221164
score: 0
type: Comment
type: QuestionComment
has text: If you want to write text to the file then open it as text `open("Weather2017.csv", 'w')`.
comment on: http://stackoverflow.com/q/47631081

http://stackoverflow.com/comment/82278299
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47656189
has text: Yeap, I used this code to display `{% for i in myData %} {{ i.name }} {% endfor %}`. Finally i solved it. Thanks for your help !
type: Comment

http://stackoverflow.com/q/47670382
tagged with: python
tagged with: flask
score: 2
tagged with: flask-login
has answer: http://stackoverflow.com/a/47679437
has body: I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires). My user loader looks like this: @login_manager.user_loader def user_loader(id): user = SessionUser.find_by_session_id(id) #hits the database if user is None: flash('You have been automatically logged out') #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded session['user_id'] = None return user When the database can't find the id, I want the user to be logged out. Reasons are: there is no need to hit the SessionUser.find_by_session_id-call more than once if an id can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates. If I don't have the if user is None: code, the user loader it hit with every request. There are two problems with this: I can't flash the message "You have been automatically logged out" (because it will keep on showing) There is an unnecessary database hit. I fixed this by clearing the session-variable user_id, but this is an unwanted solution, since it users the internals of flask_login, not an API. What would be the best approach?
has title: How to logout a user from the database with flask-login
downvote count: 0
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47670530
type: UnansweredQuestion

http://stackoverflow.com/comment/133579598
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47562412
type: AnswerComment
has text: Another drawback is, that Autocompletion is not available any longer. For example accessing properties from the `__init__` method in the `__init__.py` file doesn't work - at least in VSCode. Also reimporting methods and classes leads again to circular import issues.

http://stackoverflow.com/comment/82083943
comment on: http://stackoverflow.com/q/47562490
type: Comment
type: QuestionComment
score: 1
has text: @PaulCornelius In the areas where the likelihood is too small to be represented by floating point numbers, the log likelihood can be represented accurately. I am looking for a way to calculate the log likelihood that doesn't involve just naively taking the log of the unrepresentable likelihood.

http://stackoverflow.com/comment/125612413
has text: In addition to what Robert Townley mentioned, I'd like to add that adding your app to INSTALLED_APPS also helps by making your app's templates discoverable. The default DjangoTemplates backend looks for the 'templates' folder only within the apps included in INSTALLED_APPS.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47684387
type: Comment

http://stackoverflow.com/a/47686735
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/47686690
has body: You can append string with +. print ("Right... So your name is", name + ".") Output: Right... So your name is Raven.
has comment: http://stackoverflow.com/comment/82333340
has comment: http://stackoverflow.com/comment/82333221
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47686690
has comment: http://stackoverflow.com/comment/82333360
has comment: http://stackoverflow.com/comment/82333309
score: 5

http://stackoverflow.com/q/47565825
tagged with: keras
tagged with: keras-2
has title: Error when trying to output previous to last layer in Keras
has body: I am trying to output the previous to last Dense layer in a keras model. I first load the model architecture and the weights: base_model = applications.ResNet50(weights = None, include_top = False, input_shape = (image_size[0], image_size[1], nb_channels)) top_model = Sequential() top_model.add(Flatten(input_shape=base_model.output_shape[1:])) top_model.add(Dense(1024, init = 'glorot_uniform', activation='relu', name = 'last_layer_1024')) top_model.add(Dropout(0.5)) top_model.add(Dense(nb_classes, activation = 'softmax', name = 'softmax_layer')) top_model_tensor = top_model(base_model.output) model = Model(inputs = base_model.input, outputs = top_model_tensor) model.load_weights(weights_path) Then I remove the last Dense layer by doing this: model.layers[-1].pop() #model.outputs = [model.layers[-1].layers[-1].output] #model.layers[-1].layers[-1].outbound_nodes = [] If I uncomment the commented lines, I get this error: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'flatten_1_input' with dtype float. If I keep them commented, the last dense layer is NOT effectively removed (by that I mean that when I call predict on model, I still get the output of the last dense layer). How can I solve this issue? Also, if there is a different method to get the model to output the previous to last dense layer, I can take that as an answer too (instead of trying to fix this way of doing it). Another solution that does not work is to just cut the long model after you load weights by simply doing this: short_top_model = Model(top_model.input, top_model.get_layer('last_layer_1024').output) You get the following error: RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("flatten_1_input:0", shape=(?, 1, 1, 2048), dtype=float32, device=/device:GPU:2) at layer "flatten_1_input". The following previous layers were accessed without issue: []
has answer: http://stackoverflow.com/a/47573434
tagged with: deep-learning
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47573434
possible better answer: http://stackoverflow.com/a/53664873
type: Question
has answer: http://stackoverflow.com/a/53664873
answer count: 2
tagged with: python

http://stackoverflow.com/a/47739631
has comment: http://stackoverflow.com/comment/82462727
downvote count: 0
has comment: http://stackoverflow.com/comment/82463411
accepted answer of: http://stackoverflow.com/q/47607814
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47607814
has comment: http://stackoverflow.com/comment/82462337
has comment: http://stackoverflow.com/comment/82459095
upvote count: 5
has body: Let us recap the scenario and the loss function first, so we are on the same page: Given are P sample points in N-dimensional space in the form of a PxN matrix X, so the points are the rows of this matrix. Each point in X is assigned to one out of M categories. These are given as a vector Y of length P that has integer values between 0 and M-1. The goal is to predict the classes of all points by M linear classifiers (one for each category) given in the form of a weight matrix W of shape NxM, so the classifiers are the columns of W. To predict the categories of all samples X the scalar products between all points and all weight vectors are formed. This is the same as matrix multiplying X and W yielding a score matrix Y0 that is arranged such that its rows are ordered like theh elements of Y, each row corresponds to one sample. The predicted category for each sample is simply that with the largest score. There are no bias terms so I presume there is some kind of symmetry or zero mean assumption. Now, to find a good set of weights we want a loss function that is small for good predictions and large for bad predictions and that lets us do gradient descent. One of the most straight-forward ways is to just punish for each sample i each score that is larger than the score of the correct category for that sample and let the penalty grow linearly with the difference. So if we write A[i] for the set of categories j that score more than the correct category Y0[i, j] &gt; Y0[i, Y[i]] the loss for sample i could be written as sum_{j in A[i]} (Y0[i, j] - Y0[i, Y[i]]) or equivalently if we write #A[i] for the number of elements in A[i] (sum_{j in A[i]} Y0[i, j]) - #A[i] Y0[i, Y[i]] The partial derivatives with respect to the score are thus simply | -#A[i] if j == Y[i] dloss / dY0[i, j] = { 1 if j in A[i] | 0 else which is precisely what the first four lines you say you don't understand compute. The next line applies the chain rule dloss/dW = dloss/dY0 dY0/dW. It remains to divide …
score: 5
type: Answer

http://stackoverflow.com/comment/82227412
type: Comment
score: 3
has text: Use getattr: https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it#4076099
type: QuestionComment
comment on: http://stackoverflow.com/q/47634894

http://stackoverflow.com/comment/82197984
score: 0
comment on: http://stackoverflow.com/q/47620031
type: Comment
has text: `show create table t\G`
type: QuestionComment

http://stackoverflow.com/comment/82206970
score: 0
type: Comment
type: QuestionComment
has text: `laptime` is what you are trying to accumulate? You just want a total? What is the expected result for your example data?
comment on: http://stackoverflow.com/q/47624527

http://stackoverflow.com/q/47578414
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82126841
has comment: http://stackoverflow.com/comment/82159825
downvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82118413
answer count: 1
tagged with: cluster-analysis
tagged with: machine-learning
has body: Want to calculate instagram/hotel ratio within each cluster. But the result shows I'm actually clustering very distant points together. This is not likely for DBSCAN. What's wrong? Procedure: use DBSCAN to cluster instagram posts, then use 1NN to classify hotels. import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from sklearn.cluster import DBSCAN from sklearn.neighbors import KNeighborsClassifier if __name__ == '__main__': inst = pd.read_csv('inst.csv', encoding='utf-8') ht = pd.read_csv('ht.csv', encoding='utf-8') inst = inst[(inst.lat &gt;= 48.30) &amp; (inst.lng &gt;= -139.06) &amp; (inst.lat &lt;= 60.00) &amp; (inst.lng &lt;= -114.03)] ht = ht[(ht.lat &gt;= 48.30) &amp; (ht.lng &gt;= -139.06) &amp; (ht.lat &lt;= 60.00) &amp; (ht.lng &lt;= -114.03)] # kmean = KMeans(n_clusters=50,n_jobs=-1) # kmean.fit(inst'lat', 'lng') # # ht_labels = kmean.predict(ht'lat', 'lng') # inst_labels = kmean.predict(inst'lat', 'lng') # # plt.scatter(ht.lng, ht.lat, c=ht_labels, alpha=0.5) # plt.savefig('./fig/hotel_clusters.png') # plt.clf() # # plt.scatter(inst.lng, inst.lat, c=inst_labels, alpha=0.5) # plt.savefig('./fig/instagram_posts_clusters.png') # plt.clf() dbs = DBSCAN(eps=0.05,min_samples=10,metric='haversine', n_jobs=-1) ht_labels = dbs.fit_predict(ht'lat', 'lng') inst_labels = dbs.fit_predict(inst'lat', 'lng') plt.scatter(ht.lng, ht.lat, c=ht_labels, alpha=0.5) plt.savefig('./fig/hotel_clusters1.png') plt.clf() plt.scatter(inst.lng, inst.lat, c=inst_labels, alpha=0.5) plt.savefig('./fig/instagram_posts_clusters1.png') plt.clf() knn = KNeighborsClassifier(n_neighbors=1, n_jobs=-1) knn.fit(inst'lat', 'lng', inst_labels) ht_labels = knn.predict(ht'lat', 'lng') plt.scatter(ht.lng, ht.lat, c=ht_labels, alpha=0.5) plt.savefig('./fig/hotel_clusters3.png') plt.clf() plt.scatter(inst.lng, inst.lat, c=inst_labels, alpha=0.5) plt.savefig('./fig/instagram_posts_clusters3.png') plt.clf() ht = ht[['lat',…
has title: DBSCAN clustering distant points together
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82127786
has comment: http://stackoverflow.com/comment/82171984
tagged with: dbscan
has comment: http://stackoverflow.com/comment/82114405
has comment: http://stackoverflow.com/comment/82118679
upvote count: 1
has comment: http://stackoverflow.com/comment/82127777
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47585190

http://stackoverflow.com/q/47566308
type: Question
has title: Average of a column, based on equals condition of another column
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47566419
tagged with: pandas
has body: I want the average of column 'vgain' if the value in the column 'pgain' == 4. Both vgain and pgain are of type int64, with no missing values. I tried this: df['vgain'].groupby(df['pgain'] == 4).mean() Which gave me the following output: pgain False 2.851485 True 2.060606 Name: vgain, dtype: float64 Is there a way to directly show only the value of 2.060606. Maybe with some other code? I got the value that I wanted to get, but is there a better way to do this?
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47566419
answer count: 1

http://stackoverflow.com/comment/82154884
score: 0
has text: Sure, I could refactor the menu (and I probably will -- thanks for the pointer), and I could have one function per page that just took all of the vars as inputs... but I'm not sure it answers the question of how to break up source into small consumable chunks
type: Comment
comment on: http://stackoverflow.com/q/47598177
type: QuestionComment

http://stackoverflow.com/q/47543983
has title: Converting Ipyparallel to Dask - Where is the Web UI
type: UnansweredQuestion
has body: I have set up a cluster with ipyparallel on my local machine and wish to convert it to a dask cluster. My primary motivation for this is to be able to use the web ui with dask (via bokeh) to monitor the performance. When I convert the ipyparallel cluster to a dask cluster, it does not start the bokeh web ui. Does anyone know how to launch the web UI either in the become_dask() function or after I have started dask client_ipp = ipp.Client(profile='ipp_1') dview = client_ipp[:] bview = client_ipp.load_balanced_view() e = client_ipp.become_dask() e Client Scheduler: tcp://XX.XXX.X.XX:XXXXX Cluster Workers: 8 Cores: 8 Memory: 33.60 GB If I start a cluster directly with Dask I get: from distributed import client c3 = Client() c3 Client Scheduler: tcp://XXX.X.X.X:XXXXX Dashboard: http://XXX.X.X.X:XXXXX Cluster Workers: 8 Cores: 8 Memory: 33.60 GB
has comment: http://stackoverflow.com/comment/82064046
tagged with: python
tagged with: ipython
answer count: 0
tagged with: ipython-parallel
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82115595
favorite count: 0
type: Question
tagged with: dask

http://stackoverflow.com/comment/82070476
score: 0
type: Comment
type: QuestionComment
has text: The problem is that the function is writing two times the image file from the same source base64 string. It is generating duplicates. Hopefully this makes sense.
comment on: http://stackoverflow.com/q/47556477

http://stackoverflow.com/comment/85492336
comment on: http://stackoverflow.com/a/49219529
score: 0
type: Comment
has text: Badges work with my approach which is why I put it as an answer
type: AnswerComment

http://stackoverflow.com/a/47608356
accepted answer of: http://stackoverflow.com/q/47608315
has body: If your list is already sorted, you can insert directly at the correct place: This does the insertion and keeps the list sorted in O(n). (credits to @AntonvBR for the assist in the comments) def insert_sorted(seq, elt): """inserts elt at the correct place in seq, to keep it in sorted order :param seq: A sorted list :param elt: An element comparable to the content of seq Effect: mutates the param seq. Does not return a result """ idx = 0 if not seq or elt &gt; seq[-1]: seq.append(elt) else: while elt &gt; seq[idx] and idx &lt; len(seq): idx += 1 seq.insert(idx, elt) num_list = [5, 10, 15, 20] insert_sorted(num_list, 21) num_list Edit: You could also use the module bisect, and do the same, probably more efficiently: (credits to @stefan in the comments) import bisect num_list = [5, 10, 15, 20] bisect.insort(num_list, 17)
downvote count: 0
answers question: http://stackoverflow.com/q/47608315
has comment: http://stackoverflow.com/comment/82175074
has comment: http://stackoverflow.com/comment/82175325
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82175226
has comment: http://stackoverflow.com/comment/82175372
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/82175296
type: Answer

http://stackoverflow.com/q/47697473
linked to: http://stackoverflow.com/q/3723220
favorite count: 0
type: Question
tagged with: django
tagged with: python
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/47697978
has title: Read and Write Uploaded File with Wand
has answer: http://stackoverflow.com/a/47697978
type: AnsweredQuestion
tagged with: imagemagick
tagged with: wand
has body: Here is my code: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file = request.data.get('file', None) with tempfile.TemporaryFile() as tmp: tmp.write(file.read()) all_pages = Image(file=tmp) single_image = all_pages.sequence[0] with Image(single_image) as img: img.format = 'png' img.background_color = Color('white') img.alpha_channel = 'remove' MyModel.objects.create(revision=revision, file=img) return Response(HTTP_200_OK) I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353" Obviously I am making a grave mistake since wand, with imagemagick and ghostscript installed, can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do.
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82148077
type: Comment
has text: I assume `arr` is some sample data you're using to show how to do the reshape, in which case you can do the same with `arr = np.asarray(range(0,40))[:,None]`, without the need to go list->Dataframe->numpy.array.
comment on: http://stackoverflow.com/a/47595079
type: AnswerComment
score: 1

http://stackoverflow.com/q/47577829
has comment: http://stackoverflow.com/comment/82112873
upvote count: 0
duplicate of: http://stackoverflow.com/q/15112125
type: UnansweredQuestion
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47577917
favorite count: 0
linked to: http://stackoverflow.com/q/15112125
has title: Mastermind recreation if statements stuck
tagged with: if-statement
has body: I'm recreating the Mastermind game and I'm stuck on some "if" statements i am trying make it tell the user that if the color is not the same as in guess1but is the proper color is guess2 it will print "guess 1 right color wrong position" Python V- 2.7.8 colors = ('R','B','G','P','Y','O') Color1 = random.choice(colors) Color2 = random.choice(colors) Color3 = random.choice(colors) Color4 = random.choice(colors) guess1 = raw_input("First Color: ") guess2 = raw_input("Second Color: ") guess3 = raw_input("Third Color: ") guess4 = raw_input("Fourth Color: ") guesses = (guess1,guess2,guess3,guess4) Allcolors = (Color1,Color2,Color3,Color4) if guesses == Allcolors: print "All colors are correct!" if guesses != Allcolors: #### if guess1 == Color2 or Color3 or Color4: print "Guess 1 right color wrong position" if guess1 == Color1: print "Color 1 is correct" #### if guess2 == Color2: print "Color 2 is correct" if guess3 == Color3: print "Color 3 is correct" if guess4 == Color4: print "Color 4 is correct"
tagged with: python
score: -1
type: Question

http://stackoverflow.com/comment/82247824
score: 0
has text: Did you try playing around with one of the online regex tools?
comment on: http://stackoverflow.com/q/47644570
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47650158
type: AnsweredQuestion
has title: Building Abreviations Dictionary from Text file
has comment: http://stackoverflow.com/comment/82259011
accepted answer: http://stackoverflow.com/a/47651149
possible better answer: http://stackoverflow.com/a/47651498
answer count: 3
linked to: http://stackoverflow.com/q/2082152
has answer: http://stackoverflow.com/a/47651149
score: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82260881
type: Question
tagged with: text
linked to: http://stackoverflow.com/q/5389507
has comment: http://stackoverflow.com/comment/82260090
has comment: http://stackoverflow.com/comment/82261847
has answer: http://stackoverflow.com/a/47651498
has body: I would like to build a dictionary of abreviations. I have a text file with a lot of abreviations. The text file looks like this(after import) with open('abreviations.txt') as ab: ab_words = ab.read().splitlines() An extract: 'ACE', 'Access Control Entry', 'ACK', 'Acknowledgement', 'ACORN', 'A Completely Obsessive Really Nutty person', Now I want to build the dictionnary, where I have every uneven line as a dictionary key and every even line as the dictionary value. Hence I should be able to write at the end: ab_dict['ACE'] and get the result: 'Access Control Entry' Also, How can I make it case-insensitive ? ab_dict['ace'] should yield the same result 'Access Control Entry' In fact, it would be perfect, if the output would also be lower case: 'access control entry' Here is a link to the text file: https://www.dropbox.com/s/91afgnupk686p9y/abreviations.txt?dl=0
has comment: http://stackoverflow.com/comment/82259069
has answer: http://stackoverflow.com/a/47652410
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82262877

http://stackoverflow.com/comment/82286956
score: 0
has text: Is there a limit to how deep the lists can be? If it is limited to a list or a list of lists (not a list of lists of lists, etc.), then see the comment by @juanpa.arrivillaga.
comment on: http://stackoverflow.com/q/47663745
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/111185023
has text: I has no aswcli, for example
comment on: http://stackoverflow.com/a/51136525
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/82193854
type: QuestionComment
comment on: http://stackoverflow.com/q/47616963
score: 0
has text: On which python version are you?
type: Comment

http://stackoverflow.com/comment/82259350
comment on: http://stackoverflow.com/a/47648164
has text: @PaulPanzer Great! And it's nice to avoid the footgun potential of `as_strided`.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47596154
upvote count: 1
has comment: http://stackoverflow.com/comment/82149941
downvote count: 1
has body: I'm writing a function that sums up integers from a file. Here's the code: def sum_integers_from_file(file_name): try: file = open(name) total = 0 for i in file: total += int(i) file.close() return total except: print "error" file foo.txt: 1234 The function returns 1234. why doesn't total += int(i) add up all the integers?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47596226
has title: Adding integers from a file
has answer: http://stackoverflow.com/a/47596212
has comment: http://stackoverflow.com/comment/82149971
tagged with: python
has answer: http://stackoverflow.com/a/47596226
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82149967
possible better answer: http://stackoverflow.com/a/47596212

http://stackoverflow.com/comment/82128389
has text: Can I ask you what did you try, so far?
comment on: http://stackoverflow.com/q/47585321
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47585697
downvote count: 0
has body: I would recommend you to use pyenv to manage your Python installations, but, for now, try to run: sudo pip3 install python3-weather-api
has comment: http://stackoverflow.com/comment/84129043
answers question: http://stackoverflow.com/q/47585674
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/82082949
score: 1
has text: @SpencerWieczorek note, that is technically the *bitwise* XOR, which will work differently than a boolean XOR (which doesn't actually exist in Python). It doesn't matter in this case because it is equivalent since you are using `bool` objects for both arguments, but perhaps worth noting
type: QuestionComment
comment on: http://stackoverflow.com/q/47562455
type: Comment

http://stackoverflow.com/a/47622761
answers question: http://stackoverflow.com/q/47622583
has body: You should use a context manager to open the file - notice you don't need to explicitly close it. with open("Students_1.txt" , 'w') as input_file: input_file.write("John Smith 80 90\n") input_file.write("Ryan Brown 80 60\n") input_file.write("Anna Myers 95 85\n") You can open the input file and output file in one line, like this with open("Students_1.txt" , 'r') as input_file, open("Students_2.txt" , 'w') as output_file: for line in input_file: y = line.split() first_name = y[0] last_name = y[1] math_grade = parse_to_number(y[2]) chem_grade = parse_to_number(y[3]) ave = (math_grade + chem_grade) / 2.0 print(*y, ave, file=output_file) It would be a good idea to store the paths in variables. Also break the code up into some functions.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82286702
score: 0
type: Comment
has text: As mentioned - it depends. We need to know more about the use-case before we know whether it'll be faster. It certainly *can* be though.
comment on: http://stackoverflow.com/a/47663654
type: AnswerComment

http://stackoverflow.com/comment/82300493
type: Comment
has text: Where can I get the `NetflowHeader()` and what are the usage? p.s. I am fairly new to scapy. thank you
type: AnswerComment
comment on: http://stackoverflow.com/a/47658653
score: 0

http://stackoverflow.com/comment/82182651
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47610222
has text: Thank you. I didn't know that you could use ravel as a "way of seeing the matrix" without actually storing it. Unfortunately I can only accept one question!
score: 0

http://stackoverflow.com/comment/82144082
score: 0
type: Comment
has text: this fixed it, thanks, there was an error earlier in the program where items weren't being added to the list: words
type: AnswerComment
comment on: http://stackoverflow.com/a/47574352

http://stackoverflow.com/a/47598723
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47598617
has body: Well, in the exact case you provided, it's because you're "returning" after a match. Once a function returns, no code after the return is executed meaning if you ever pass the if conditional, the method breaks out of the loop and everything, making the else unnecessary. Essentially: you don't need an else because if your conditional ever passes the code execution breaks out of method anyways.
type: Answer
score: 0

http://stackoverflow.com/q/47666699
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82292589
answer count: 2
accepted answer: http://stackoverflow.com/a/47758616
has body: BACKGROUND I have vectors with some sample data and each vector has a category name (Places,Colors,Names). ['john','jay','dan','nathan','bob'] -&gt; 'Names' ['yellow', 'red','green'] -&gt; 'Colors' ['tokyo','bejing','washington','mumbai'] -&gt; 'Places' My objective is to train a model that take a new input string and predict which category it belongs to. For example if a new input is "purple" then I should be able to predict 'Colors' as the correct category. If the new input is "Calgary" it should predict 'Places' as the correct category. APPROACH I did some research and came across Word2vec. This library has a "similarity" and "mostsimilarity" function which i can use. So one brute force approach I thought of is the following: Take new input. Calculate it's similarity with each word in each vector and take an average. So for instance for input "pink" I can calculate its similarity with words in vector "names" take a average and then do that for the other 2 vectors also. The vector that gives me the highest similarity average would be the correct vector for the input to belong to. ISSUE Given my limited knowledge in NLP and machine learning I am not sure if that is the best approach and hence I am looking for help and suggestions on better approaches to solve my problem. I am open to all suggestions and also please point out any mistakes I may have made as I am new to machine learning and NLP world.
tagged with: machine-learning
has title: Using word2vec to classify words in categories
tagged with: word2vec
has answer: http://stackoverflow.com/a/47758616
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/46724680
score: 19
possible better answer: http://stackoverflow.com/a/50335238
type: Question
upvote count: 20
has answer: http://stackoverflow.com/a/50335238
tagged with: python
tagged with: gensim
tagged with: nlp
has comment: http://stackoverflow.com/comment/82292560

http://stackoverflow.com/a/47622167
has body: I assume you want to show new number in place of old number, not below it. import tkinter as tk import random def start(): # hide button button.pack_forget() # run `add_number` first time add_number(level+2) def add_number(x): num = random.randint(1, 100) my_list.append(num) label['text'] = num if x &gt; 0: # repeat after 2000ms (2s) root.after(2000, add_number, x-1) else: # show button again after the end button.pack() # --- main --- my_list = [] level = 1 root = tk.Tk() label = tk.Label(root) label.pack() button = tk.Button(root, text="Click to start game", command=start) button.pack() root.mainloop()
answers question: http://stackoverflow.com/q/47621977
accepted answer of: http://stackoverflow.com/q/47621977
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47600141
tagged with: pygame
has answer: http://stackoverflow.com/a/47600196
favorite count: 0
linked to: http://stackoverflow.com/q/30720665
type: Question
downvote count: 2
type: UnansweredQuestion
tagged with: python
score: -2
has title: Adding a timer in pygame
answer count: 1
duplicate of: http://stackoverflow.com/q/30720665
has comment: http://stackoverflow.com/comment/82158765
upvote count: 0
has body: Would anyone know how you would code a timer to be displayed on screen in pygame, where the time is going up as the user is playing?
has comment: http://stackoverflow.com/comment/82158877

http://stackoverflow.com/q/47632664
score: 1
upvote count: 1
downvote count: 0
answer count: 1
has title: Python calendar alignment
tagged with: calendar
favorite count: 0
has answer: http://stackoverflow.com/a/47632934
type: Question
accepted answer: http://stackoverflow.com/a/47632934
tagged with: python
type: AnsweredQuestion
has body: When I run the code, the calendar day numbers do not align up with the week day they go with. I have tried justify = LEFT and RIGHT and CENTRE. None of these solve my problem even when not having the justify statement it doesn't work from tkinter import * import calendar as cl import datetime as datet year = int(datet.date.today().strftime("%Y")) #year month = int(datet.date.today().strftime("%m")) #month number root = Tk() root.geometry("300x300") app = Frame(root) app.grid() cal = Label(app, text = cl.month(year, month), justify = RIGHT) cal.grid(row = 0, column = 0) root.mainloop()
tagged with: tkinter

http://stackoverflow.com/q/47640724
has answer: http://stackoverflow.com/a/57211208
accepted answer: http://stackoverflow.com/a/57211208
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/82241791
has body: I am working on image for RGB color manipulation using Skimage and having below configuration of packages: Python 3.6.1 scikit-image 0.13.0 pyqt 5.6.0 from skimage import io import sip sip.setapi('QString', 2) from PyQt5 import QtGui io.use_plugin('pil','imread') img=io.imread('RpMkYUX.jpg') io.use_plugin('qt' ,'imshow') io.imshow(img) io.show() expecting output as in image expected output and i am getting below error as: (C:\Users\rahul\Anaconda3) C:\Users\rahul\AnacondaProjects\15_PIL&gt;python 2_.py Traceback (most recent call last): File "C:\Users\rahul\Anaconda3\lib\site-packages\skimage\io\_plugins\qt_plugin.py", line 11, in &lt;module&gt; from PyQt4.QtGui import (QApplication, QImage, ModuleNotFoundError: No module named 'PyQt4' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "2_.py", line 16, in &lt;module&gt; io.use_plugin('qt' ,'imshow') File "C:\Users\rahul\Anaconda3\lib\site-packages\skimage\io\manage_plugins.py", line 255, in use_plugin _load(name) File "C:\Users\rahul\Anaconda3\lib\site-packages\skimage\io\manage_plugins.py", line 299, in _load fromlist=[modname]) File "C:\Users\rahul\Anaconda3\lib\site-packages\skimage\io\_plugins\qt_plugin.py", line 28, in &lt;module&gt; """) ImportError: PyQt4 libraries not installed. Please refer to http://www.riverbankcomputing.co.uk/software/pyqt/intro for more information. PyQt4 is GPL licensed. For an LGPL equivalent, see http://www.pyside.org
tagged with: scikit-image
tagged with: python
linked to: http://stackoverflow.com/q/21637922
type: Question
has title: PyQt5 has issue while importing in skimage
has comment: http://stackoverflow.com/comment/82239980
score: 0
answer count: 1
tagged with: pyqt5

http://stackoverflow.com/comment/82197514
type: QuestionComment
comment on: http://stackoverflow.com/q/47618170
score: 0
has text: edit question and use button `{}` to better format error message
type: Comment

http://stackoverflow.com/a/47612085
has body: names = ["a", "b", "c"] values = [1, 2, 3] for n, v in zip(names, values): print("{} = {}".format(n, v))
has comment: http://stackoverflow.com/comment/82182482
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47611988
type: Answer
answers question: http://stackoverflow.com/q/47611988
score: 2
has comment: http://stackoverflow.com/comment/82182629
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82292347
has text: sorry in* basically it needs to replace the floating point number in the list with a 0 and then print the list
type: AnswerComment
comment on: http://stackoverflow.com/a/47666514
score: 0
type: Comment

http://stackoverflow.com/a/47641924
accepted answer of: http://stackoverflow.com/q/47640787
type: Answer
has comment: http://stackoverflow.com/comment/82246345
answers question: http://stackoverflow.com/q/47640787
score: 0
has comment: http://stackoverflow.com/comment/82249939
type: AcceptedAnswer
has body: CulebraTester can generate tests in a variety of languages: Python Java Kotlin Javascript etc. see Code-Generation-language for details. Each language has its own dependencies in order to run, for example, if you generate UiAutomator tests in Java you will need the corresponding dependencies in your build.gradle. In your specific case, as you have generated Python tests you need androidviewclient. To install it, follow the instructions on AndroidViewClient: Installation
has comment: http://stackoverflow.com/comment/82283108
has comment: http://stackoverflow.com/comment/82274740
has comment: http://stackoverflow.com/comment/82249943

http://stackoverflow.com/comment/82215938
score: 0
type: Comment
type: QuestionComment
has text: [Here's a handy chart to show how confusing this is](https://stackoverflow.com/a/21916253/4799172). The answer below, from Panda's creator; "Welcome to hell" :P
comment on: http://stackoverflow.com/q/47629177

http://stackoverflow.com/a/47681859
has body: Not a precise answer, but some tryes. A hash function seems to be a simple and efficient mean to achieve your goal. Here are some good ideas about integer to integer hash-functions. From this article I try that : from numba import uint64, njit import pylab as pl @njit(uint64(uint64,uint64)) def hash64(i,j) : x= i + (j &lt;&lt; 32) x = (x ^ (x &gt;&gt; 30)) * (0xbf58476d1ce4e5b9); x = (x ^ (x &gt;&gt; 27)) * (0x94d049bb133111eb); x = x ^ (x &gt;&gt; 31); return x; n=1000 im=[[hash64(i,j) for i in range(n)] for j in range(n)] pl.subplot(121) pl.imshow(im) pl.colorbar() pl.subplot(122) pl.hist(np.array(im).ravel(),bins=100) pl.show() This numba hash64 function compute a hash code in ~ 200 ns. And this plot (even it demonstrates nothing) shows that this function could be a good candidate. By contrast the python hash function (hash((i,j)) on tuple) do not pass the test : Here for A Knuth Generator : And some benchmarks : In [61]: %timeit hash64(0,1) 215 ns ± 9.11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [62]: %timeit np.random.seed(0+1&lt;&lt;30);a=np.random.randint(2**30) 4.18 µs ± 126 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [63]:%timeit hash((0,1)) 102 ns ± 19.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
upvote count: 1
answers question: http://stackoverflow.com/q/47678568
has comment: http://stackoverflow.com/comment/82355375
has comment: http://stackoverflow.com/comment/82354870
has comment: http://stackoverflow.com/comment/82323260
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82355653
has comment: http://stackoverflow.com/comment/82355048

http://stackoverflow.com/comment/82081938
type: Comment
type: QuestionComment
has text: "api call against the server which executes 'my_api_endpoint.py'" what do you mean the api call ends up executing `my_api_endpiont.py`? As in subprocess?
comment on: http://stackoverflow.com/q/47561658
score: 0

http://stackoverflow.com/comment/82100065
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47571388
has text: Another example. https://pastebin.com/yyiunAX2 . Same issue. Blank Csv

http://stackoverflow.com/q/47624656
type: Question
has comment: http://stackoverflow.com/comment/82207259
has comment: http://stackoverflow.com/comment/82208313
upvote count: 0
score: -2
downvote count: 2
tagged with: arrays
has answer: http://stackoverflow.com/a/47637840
accepted answer: http://stackoverflow.com/a/47637840
tagged with: python
has comment: http://stackoverflow.com/comment/82207493
linked to: http://stackoverflow.com/q/47587661
type: AnsweredQuestion
has title: Python - Shift/Delete Values in a 2-Dimensional Array
has comment: http://stackoverflow.com/comment/82207173
has comment: http://stackoverflow.com/comment/82208093
answer count: 1
has body: I need help with shifting and deleting elements in a 2-dimensional array. If the value in a list is negative and their is a list above it with positive values in the same location. It should shift everything down, causing the negative values to disappear. If there isn't any list above it or the corresponding values in the list above are just 0. It will replace the negative values with 0. Scenario 1, 3, and 4 are working! But Scenario 2 doesn't work. (I hope I covered all possible scenarios in my examples) Note: The positive values should never disappear, they can only move down when needed. Only the negative values (below -100) disappear. These examples should explain it better: Scenario 1: # This Works DATA [[ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 1, 3, 1, 0, 0], [-102, -102, -102, 0, 0], [ 3, 1, 3, 0, 0]] EXPECT [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]] Scenario 2: # Doesn't Work DATA [[ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 1, 2, 1, 0, 0], [ 2, 1, 2, 0, 0], [-103, -103, -103, 0, 0]] EXPECT [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]] The Current Output (Incorrect): [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0], [0, 0, 0, 0, 0]] Scenario 3: # This Works DATA [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, -101, -101, -101], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]] EXPECT [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]] Scenario 4: # This Works DATA [[ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [-101, 2, 2, 3, 4], [-101, 1, 2, 3, 2], [-101, 3, 3, 2, 3]] EXPECT [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 2, 3, 4], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]] Here is my code - It's definitely overcomplicated for what I am trying to achieve but I have been stuck on this and can't figure out any alternative. (I can't import any outside function...so no numpy) def move(data): # PART 1 ''' Creates a list that contains a tuple (row, coll) of the location where a negati…
favorite count: 0

http://stackoverflow.com/comment/82210267
comment on: http://stackoverflow.com/q/47626223
has text: If you want negation use tilde `~` like `~aa` or `aa = ~filtered.....`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82315698
has text: It is a really good idea, I have implemented it within my program and I get an error " + self._options(cnf, kw)) _tkinter.TclError: bad window path name ".!welcome"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47677964
type: Comment

3d
tags question: http://stackoverflow.com/q/47546626
tags question: http://stackoverflow.com/q/47592732
type: Tag
tag name: 3d
tags question: http://stackoverflow.com/q/47562213
tags question: http://stackoverflow.com/q/47679648
tags question: http://stackoverflow.com/q/47615716
tags question: http://stackoverflow.com/q/47553958

http://stackoverflow.com/q/47691425
has answer: http://stackoverflow.com/a/47691494
answer count: 5
has title: I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/82341856
has answer: http://stackoverflow.com/a/47692066
type: AnsweredQuestion
tagged with: python-2.7
has body: I have a below CSV file with the header(A,B,C,D): A,B,C,D 1,2,3,4 2,1,3,5 6,8,0,9 4,7,9,2 2,5,4,9 1,1,7,3 2,9,5,6 I want output after removing top 5 lines but not header: A,B,C,D 1,1,7,3 2,9,5,6 Below is my Python code snippet, but am not able to add any header retaining code: with open(filename.csv , 'rb') as infile: data_in = infile.readlines() with open ('temp.csv', 'wb') as outfile: outfile.writelines(data_in[5:]) Please help me in this.In my case header is also deleting, but I want to retain header every time.
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82341924
has answer: http://stackoverflow.com/a/47692463
has answer: http://stackoverflow.com/a/47691666
possible better answer: http://stackoverflow.com/a/47691511
has answer: http://stackoverflow.com/a/47691511
accepted answer: http://stackoverflow.com/a/47691494
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47659776
has body: Here is the code (Modified) # Get the filepath from the command line import sys import re I= sys.argv[1] O= sys.argv[2] S= sys.argv[3] T= sys.argv[4] # Your code goes here # open our file for writing file1= open(I, 'r') file2= open(O, 'w') data = file1.read() data = data.replace(S, T) file2.write(data) file1.close() file2.close() file2= open(O, 'r') data = file2.read() print(data)
answers question: http://stackoverflow.com/q/47659506
has comment: http://stackoverflow.com/comment/82278365
type: Answer
score: 0

http://stackoverflow.com/q/47626859
upvote count: 1
tagged with: bitcoind
favorite count: 0
has answer: http://stackoverflow.com/a/47630839
type: Question
tagged with: bitcoin
score: 1
has body: I was playing with the blochain using the python librairy 'bitcoinrpc' and bitcoin-core, however I can never read the transaction in block 9. I even downloaded the blockchain a 2nd time thinking mine had a problem with a 2nd installation of bitcoin-core pointing to a different data directory and I still can't read block 9. Can you reproduce this problem? Any idea why? Script for reading and displaying block 7, 8, 9, 10 : from bitcoinrpc.authproxy import AuthServiceProxy import traceback RPC_ADDRESS="127.0.0.1:8332" RPC_USER="u" RPC_PASSWORD="p" def display_block_info(rpc, block_number): print "-------- block {} start -------".format(block_number) block_hash = rpc.getblockhash(block_number) print "Block hash : " + block_hash block = rpc.getblock(block_hash) for tx in block[u'tx']: print "processing transaction " + tx print rpc.getrawtransaction(tx, True) print "-------- block {} end -------".format(block_number) print "" if __name__ == "__main__": rpc = AuthServiceProxy("http://%s:%s@%s"%(RPC_USER, RPC_PASSWORD, RPC_ADDRESS)) block_numbers = [7, 8, 9, 10] for block_number in block_numbers: try: display_block_info(rpc, block_number) except Exception as e: traceback.print_exc() print "-------- block {} end -------".format(block_number) print "" Result: -------- block 7 start ------- Block hash : 0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444 processing transaction 8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f {u'hash': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blockhash': u'0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac', u'addresses': [u'16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM'], u'asm': u'04a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d…
tagged with: python
accepted answer: http://stackoverflow.com/a/47630839
tagged with: blockchain
type: AnsweredQuestion
answer count: 1
downvote count: 0
has title: Cannot read certain block transactions

http://stackoverflow.com/q/47676660
type: Question
accepted answer: http://stackoverflow.com/a/47926465
tagged with: pyside
has answer: http://stackoverflow.com/a/47926465
tagged with: python
has comment: http://stackoverflow.com/comment/82318760
has body: I'm trying to find a way of selecting QtGui.QTreeWidget.QTreeWidgetItem.text(1) with the cursor. if column == 1: # Makes Row editable item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) # Select item to edit Xitem = self.treewidget.editItem(item, column) # Makes Row uneditable item.setFlags(item.flags() &amp; ~QtCore.Qt.ItemIsEditable) I know that, by default, all the text will be selected. However, because I'm enabling editing then disabling editing is results with the text being unselected. Why are you enabling and disabling edibility? I have it set up so that you can only edit the text of 1 column, out of several. However, simply turning on ItemIsEditable will make all columns editable, i just wanted the one specific column, so i immediately have to disable it again. Knock on effect, it deselects the text in the desired column. I can still edit it, it's just deselected. So i want to ctrl+a selected all. I've been trying to work out how to do this for a while, but am getting no where. Methods for getting my desired results would be running the ctrl+a hotkey through python code, or working out how to get the QTextCursor stuff to work with the QTreeWidgetItem. editor = QtGui.QTextEdit(self.treewidget) cursor = editor.textCursor() cursor.movePosition(QtGui.QTextCursor.Start, QtGui.QTextCursor.KeepAnchor) editor.setTextCursor(cursor) I feel like i'm close, but am just missing something here :/
has title: Selecting Text in a QTreeWidgetItem with the cursor
score: 2
upvote count: 2
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

firefox
type: Tag
tags question: http://stackoverflow.com/q/47586930
tag name: firefox
tags question: http://stackoverflow.com/q/47675184

http://stackoverflow.com/q/47687058
has comment: http://stackoverflow.com/comment/82337115
type: Question
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82334187
score: 0
has title: tkinter lift() not executing in while loop
has comment: http://stackoverflow.com/comment/82334519
has comment: http://stackoverflow.com/comment/82336960
has body: I am a python beginner. I want to bring a tkinter window to focus in while loop. What I want to do is destroy tkinter window once I click a button and recreate it again. import tkinter def get_number_from_entry(event): number_to_machine = NumberEntry.get() print("Number is {} ". format(number_to_machine)) top.destroy() while(True): top = tkinter.Tk() top.lift() top.bind('&lt;Return&gt;', get_number_from_entry) B = tkinter.Label(top, text="1234") B.pack() NumberEntry = tkinter.Entry(top) NumberEntry.insert(0, "1234") NumberEntry.pack() B = tkinter.Button(top, text='Number') B.bind('&lt;Button-1&gt;', get_number_from_entry) B.pack() top.mainloop() # Do some work here I want to bring the tkinter to focus every time while loop re-runs. But it gets focus only first time. Later it doesn't get focus

http://stackoverflow.com/q/47693494
has body: My code works good on my machine, but on another: Process child: Traceback (most recent call last): File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 749, in _callmethod AttributeError: 'ForkAwareLocal' object has no attribute 'connection' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap File "/usr/local/lib/python3.6/multiprocessing/process.py", line 93, in run File "/home/eri/Projects/server/child.py", line 215, in setup_loop File "/home/eri/Projects/server/child.py", line 164, in setup_clients File "&lt;string&gt;", line 2, in append File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 753, in _callmethod File "/usr/local/lib/python3.6/multiprocessing/managers.py", line 740, in _connect File "/usr/local/lib/python3.6/multiprocessing/connection.py", line 487, in Client File "/usr/local/lib/python3.6/multiprocessing/connection.py", line 614, in SocketClient FileNotFoundError: [Errno 2] No such file or directory Python was built from source. Maybe some libs not configured? Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _sqlite3 _ssl _tkinter readline To find the necessary bits, look in setup.py in detect_modules() for the module's name. The following modules found by detect_modules() in setup.py, have been built by the Makefile instead, as configured by the Setup files: atexit pwd time Main process joins child.
type: Question
tagged with: python-3.x
score: 0
accepted answer: http://stackoverflow.com/a/47762781
has title: libraries needed for python multiprocessing manager list?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47762781
tagged with: linux
answer count: 1
tagged with: python

http://stackoverflow.com/comment/105388052
score: 1
has text: I think this was a bug. I know that Celery 4.3 does not require this anymore and I think it was fixed earlier than that.
type: Comment
comment on: http://stackoverflow.com/a/47646668
type: AnswerComment

http://stackoverflow.com/a/47560242
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/82078559
type: Answer
has body: regex is overkill for basic string operations like this. Use the built-in string methods, like partition and replace: for line in lines: first, sep, last = line.partition('\n') newline = first.replace(',','') print (newline) Edit. In case \n is a literal sequence in a line read from a file, use r'\n' instead of '\n'.
upvote count: 2
answers question: http://stackoverflow.com/q/47560087

http://stackoverflow.com/a/52778656
has body: Exactly how J_F above described. Just as a reminder: In case you have more than one Python version on your system e.g. Mac with Python 2.7 and 3.x. ```{r setup, include=FALSE} Library(knitr) Library(reticulate) knitr::knit_engines$set(python3 = reticulate::eng_python) ``` ```{python3} enter code here ```
has comment: http://stackoverflow.com/comment/115334772
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47689968
score: 1
type: Answer

http://stackoverflow.com/comment/82275275
score: 1
type: Comment
has text: The first way (installing by command line) worked for me. The exact command I used is `source path_to_the_project/venv/Scripts/activate` and then `pip install some_downloads/xgboost-0.6+20171121-cp35-cp35m-win_amd64.whl` to install a wheel file, downloaded from Christoph Gohlke's repository you referenced here. Then I run my project again and xgboost loaded successfully.
type: AnswerComment
comment on: http://stackoverflow.com/a/47656042

http://stackoverflow.com/q/47674518
type: Question
has body: I'm creating a simple drawing application and in it, i'd like to add an undo button. What I have tried so far is this: class DrawScreen(Screen): r = NumericProperty(0) g = NumericProperty(0) b = NumericProperty(0) brush_width = NumericProperty(2) def on_touch_down(self, touch): self.slider = self.ids.slider if self.slider.collide_point(touch.x, touch.y): self.brush_width = self.slider.value else: self.undo = [touch.x, touch.y] with self.canvas.before: Color(self.r, self.g, self.b) touch.ud["line"] = Line(points=self.undo, width=self.brush_width) return super(DrawScreen, self).on_touch_down(touch) def on_touch_move(self, touch): if self.slider.collide_point(touch.x, touch.y): self.brush_width = self.slider.value else: try: self.undo += [touch.x, touch.y] touch.ud["line"].points = self.undo except: pass return super(DrawScreen, self).on_touch_move(touch) def color(self, r, g, b): self.r = r self.g = g self.b = b def undo_draw(self): self.undo = [] This undo button clears the list but it doesn't affect the canvas in any way and doesn't remove any lines at all. What would be the appropriate way to go about this?
score: 3
has title: How do I delete lines from the canvas in kivy
tagged with: python
tagged with: kivy
type: AnsweredQuestion
upvote count: 3
tagged with: kivy-language
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47675899
accepted answer: http://stackoverflow.com/a/47675899
has answer: http://stackoverflow.com/a/50184362
possible better answer: http://stackoverflow.com/a/50184362
favorite count: 0

http://stackoverflow.com/q/47584192
type: Question
linked to: http://stackoverflow.com/q/14625509
tagged with: python
tagged with: paramiko
has body: Please let me know how do I use paramiko module to transfer files between two remote hosts. I have seen that 'get' method will get the files from remote host to local host. 'put' method will put the local files to some remote host. Is there any method that combines 'get' and 'put' methods i.e.get files from remote host and put it in remote host. This request will get initiated from localhost.
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47629911
has comment: http://stackoverflow.com/comment/82214384
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: How to use paramiko to transfer files between two remote servers?
favorite count: 0

http://stackoverflow.com/a/47587236
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47586930
accepted answer of: http://stackoverflow.com/q/47586930
has body: I think your issue is related to session cookies vs persistent cookies which is addressed in "Selenium use of firefox profile"
type: AcceptedAnswer
upvote count: 1
score: 1

http://stackoverflow.com/comment/82298838
comment on: http://stackoverflow.com/q/47669999
score: 2
type: QuestionComment
has text: English sentences start with a capital letter, require a verb and a subject.
type: Comment

http://stackoverflow.com/q/47678353
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/82325801
possible better answer: http://stackoverflow.com/a/47679925
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/47719474
has body: I'm getting a strage cascading delete (that I haven't configured) when I delete an item from my database. The category entry corresponding to the deleted item is deleted. How do I stop this from happening? Here's my database setup: from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): """Object holding information about individual registered users""" __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) email = Column(String(250), nullable=False) picture = Column(String(250)) class Category(Base): """Object holding information about item categories""" __tablename__ = 'category' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) class Item(Base): """Object holding information about individual catalog items""" __tablename__ = 'item' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) description = Column(String(5000), nullable=False) category_id = Column(Integer, ForeignKey('category.id')) category = relationship("Category") user_id = Column(Integer, ForeignKey('user.id')) user = relationship("User") engine = create_engine('postgresql+psycopg2://********:********' + '/itemcatalog.db', echo=False) Base.metadata.create_all(engine) Here's the code the triggers the delete: @app.route('/item/&lt;int:item_id&gt;/delete/', methods=['GET', 'POST']) def delete_item(item_id): item = session.query(Item).filter_by(id=item_id).one() if request.method == 'POST': session.delete(item) session.commit() flash('Item Successfully Deleted') return redirect(url_for('show_catalog')) else: return render_template('deleteitem.html', item=item, username=login_session['username'], picture=login_session['picture']) The expected behavior is for only the item specified by its "id" to be deleted, and for there …
has title: Sqlalchemy Unexpected Cascading Delete in Flask Application
tagged with: psycopg2
tagged with: flask
tagged with: flask-sqlalchemy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47719474
has answer: http://stackoverflow.com/a/47679925
tagged with: python

http://stackoverflow.com/comment/82142083
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47590455
score: 0
has text: @Bharath but I am not using networkx graph object as a data input

http://stackoverflow.com/comment/82199567
has text: Can someone explain me why did he downvote? I don't care about my rep., but I really don't understand what I did wrong... `:(`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47620850

http://stackoverflow.com/q/47571689
has answer: http://stackoverflow.com/a/47951358
has title: Unable to use matplotlib functions in my program
has comment: http://stackoverflow.com/comment/82112452
linked to: http://stackoverflow.com/q/44155564
has answer: http://stackoverflow.com/a/52985862
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82111241
has body: I'm running an Anaconda installation in windows 10 (conda version 4.3.8) This is the code I'm trying to run in the python command line: import matplotlib.pyplot as plt x = [1,2,3,4] y = [5,6,7,8] plt.figure(1) plt.plot(x,y) The last line throws the following error: C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:971: MatplotlibDeprecationWarning: The is_string_like function was deprecated in version 2.1. if is_string_like(family): C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:697: MatplotlibDeprecationWarning: The is_string_like function was deprecated in version 2.1. if is_string_like(family): C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\text.py:218: MatplotlibDeprecationWarning: The is_string_like function was deprecated in version 2.1. elif is_string_like(fontproperties): Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 3307, in plot ax = gca() File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 950, in gca return gcf().gca(**kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1368, in gca return self.add_subplot(1, 1, 1, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py", line 1020, in add_subplot a = subplot_class_factory(projection_class)(self, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_subplots.py", line 73, in __init__ self._axes_class.__init__(self, fig, self.figbox, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 529, in __init__ self._init_axis() File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 622, in _init_axis self.xaxis = maxis.XAxis(self) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axis.py", line 676, in __init__ self.cla() File "C:\ProgramData\Anaconda3\lib\site-packages\…
tagged with: anaconda
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
upvote count: 3
score: 3
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/82129151
score: 0
comment on: http://stackoverflow.com/q/47585711
type: Comment
type: QuestionComment
has text: Trying to make tiles global seems a good direction. You should show the code where you try it as a starting point.

http://stackoverflow.com/q/47615652
downvote count: 0
answer count: 3
has title: Why do I need to explicitly import the font module from the tkinter module even if have imported the full module using "*"?
tagged with: import
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47615692
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47615713
has body: I have tried to run the give python snippet: from tkinter import * from tkinter import font root = Tk() list_fonts = list(font.families()) for i in list_fonts: print(i) root.mainloop() I get the output as: Sitka Display Sitka Banner Nirmala UI Semilight Leelawadee UI Gadugi Microsoft New Tai Lue DokChampa Segoe UI Calibri Miriam Angsana New Iskoola Pota Kartika Segoe UI Semilight Vijaya Nirmala UI Mongolian Baiti Microsoft YaHei @Microsoft YaHei Microsoft YaHei UI @Microsoft YaHei UI Vani Arial Black IrisUPC Batang @Batang BatangChe @BatangChe Gungsuh @Gungsuh GungsuhChe @GungsuhChe Gautami Segoe UI Black Calibri Light Cambria Rod Georgia Verdana Symbol Euphemia Raavi Corbel Shruti Consolas Segoe UI Semibold Simplified Arabic Cambria Math DaunPenh Nyala Constantia Yu Gothic @Yu Gothic CordiaUPC Khmer UI Aharoni Microsoft Uighur Times New Roman Times New Roman CYR Times New Roman TUR Times New Roman CE Times New Roman Baltic Times New Roman Greek Segoe Script Candara Ebrima DilleniaUPC MS Mincho @MS Mincho MS PMincho @MS PMincho Browallia New Segoe UI Light Segoe UI Emoji Aldhabi DFKai-SB @DFKai-SB SimHei @SimHei Lao UI Courier New Courier New CYR Courier New TUR Courier New CE Courier New Greek Courier New Baltic Kalinga Microsoft PhagsPa Tahoma EucrosiaUPC KaiTi @KaiTi SimSun @SimSun NSimSun @NSimSun Meiryo @Meiryo Meiryo UI @Meiryo UI Sylfaen Tunga Urdu Typesetting Microsoft YaHei Light @Microsoft YaHei Light Microsoft YaHei UI Light @Microsoft YaHei UI Light Webdings Plantagenet Cherokee Gabriola MS Gothic @MS Gothic MS UI Gothic @MS UI Gothic MS PGothic @MS PGothic Gulim @Gulim GulimChe @GulimChe Dotum @Dotum DotumChe @DotumChe Lucida Sans Unicode Andalus Leelawadee FangSong @FangSong Yu Mincho Demibold @Yu Mincho Demibold David Miriam Fixed Impact Levenim MT Segoe Print Estrangelo Edessa Leelawadee UI Semilight Microsoft JhengHei @Microsoft JhengHei Microsoft JhengHei UI @Microsoft JhengHei UI Narkisim MingLiU-ExtB @MingLiU-ExtB PMingLiU-ExtB @PMingLiU-ExtB Min…
tagged with: tkinter
score: 2
upvote count: 2
tagged with: fonts
has answer: http://stackoverflow.com/a/47615732

http://stackoverflow.com/comment/82270334
type: Comment
comment on: http://stackoverflow.com/a/47649756
score: 0
type: AnswerComment
has text: Thank you so much ! It worked perfectly !!! Just a question, could you explain me the use of the zip() and iter() ?

http://stackoverflow.com/q/47555594
has comment: http://stackoverflow.com/comment/82084248
has comment: http://stackoverflow.com/comment/82077296
has comment: http://stackoverflow.com/comment/82083948
has comment: http://stackoverflow.com/comment/82081377
has title: How to create/plot non over-lapping nodes in NetworkX python 3x?
type: Question
tagged with: networkx
has comment: http://stackoverflow.com/comment/82084183
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to create the final path map for Travelling salesman problem. The code below creates the map as shown in image. I am using random layout for Digraph.Since the number of nodes is much, few nodes are overlapping, which makes the paths hard to recognize. Code map_paths_reduced = map_paths[:10] # Choosing only first 10 paths for simplicity G = nx.DiGraph() G.add_nodes_from(range(len(edge_labels)+1)) black_edges = [edge for edge in G.edges()] pos = nx.random_layout(G) G.add_edges_from(map_paths_reduced) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size=500) nx.draw_networkx_labels(G, pos, font_size=1) nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True) nx.draw_networkx(G, pos, arrows=True) plt.show()
tagged with: python
has comment: http://stackoverflow.com/comment/82084272
score: 0
answer count: 0

string
tags question: http://stackoverflow.com/q/47626223
type: Tag
tags question: http://stackoverflow.com/q/47616440
tags question: http://stackoverflow.com/q/47646954
tags question: http://stackoverflow.com/q/47602422
tags question: http://stackoverflow.com/q/47663704
tags question: http://stackoverflow.com/q/47633559
tags question: http://stackoverflow.com/q/47576803
tags question: http://stackoverflow.com/q/47624499
tags question: http://stackoverflow.com/q/47658522
tags question: http://stackoverflow.com/q/47659506
tags question: http://stackoverflow.com/q/47676972
tags question: http://stackoverflow.com/q/47641938
tags question: http://stackoverflow.com/q/47644532
tags question: http://stackoverflow.com/q/47614010
tags question: http://stackoverflow.com/q/47681756
tags question: http://stackoverflow.com/q/47554466
tags question: http://stackoverflow.com/q/47640523
tags question: http://stackoverflow.com/q/47589446
tags question: http://stackoverflow.com/q/47543824
tags question: http://stackoverflow.com/q/47551654
tags question: http://stackoverflow.com/q/47676270
tags question: http://stackoverflow.com/q/47677276
tags question: http://stackoverflow.com/q/47618036
tags question: http://stackoverflow.com/q/47621797
tags question: http://stackoverflow.com/q/47613061
tags question: http://stackoverflow.com/q/47682450
tags question: http://stackoverflow.com/q/47623109
tags question: http://stackoverflow.com/q/47614316
tags question: http://stackoverflow.com/q/47684623
tags question: http://stackoverflow.com/q/47647413
tags question: http://stackoverflow.com/q/47619682
tags question: http://stackoverflow.com/q/47589853
tags question: http://stackoverflow.com/q/47559993
tags question: http://stackoverflow.com/q/47560087
tags question: http://stackoverflow.com/q/47613575
tags question: http://stackoverflow.com/q/47625950
tags question: http://stackoverflow.com/q/47686207
tags question: http://stackoverflow.com/q/47651993
tags question: http://stackoverflow.com/q/47638795
tags question: http://stackoverflow.com/q/47671795
tags question: http://stackoverflow.com/q/47541295
tags question: http://stackoverflow.com/q/47579847
tag name: string
tags question: http://stackoverflow.com/q/47643961
tags question: http://stackoverflow.com/q/47652885
tags question: http://stackoverflow.com/q/47622775
tags question: http://stackoverflow.com/q/47597831
tags question: http://stackoverflow.com/q/47663809
tags question: http://stackoverflow.com/q/47645562
tags question: http://stackoverflow.com/q/47596479
tags question: http://stackoverflow.com/q/47651925
tags question: http://stackoverflow.com/q/47666687
tags question: http://stackoverflow.com/q/47671865
tags question: http://stackoverflow.com/q/47614169
tags question: http://stackoverflow.com/q/47688907
tags question: http://stackoverflow.com/q/47657555
tags question: http://stackoverflow.com/q/47608374
tags question: http://stackoverflow.com/q/47684314
tags question: http://stackoverflow.com/q/47562030
tags question: http://stackoverflow.com/q/47671985

http://stackoverflow.com/a/47656015
has comment: http://stackoverflow.com/comment/82745832
has comment: http://stackoverflow.com/comment/82274826
has comment: http://stackoverflow.com/comment/82271859
has comment: http://stackoverflow.com/comment/128473448
answers question: http://stackoverflow.com/q/47655242
type: Answer
has body: If you are using IPython as your interpreter, you can use the magic %pdb in IPython to automatically start pdb when an error is encountered. Then you can "Run current cell" and break out into the debugger when you need to. For example I have a simple script: my_var = 4 raise ValueError Now, in the IPython terminal I first run %pdb, and then I run my script. In [4]: my_var = 4 ...: raise ValueError Traceback (most recent call last): File "&lt;ipython-input-4-31dc119cb1f3&gt;", line 2, in &lt;module&gt; raise ValueError ValueError &gt; &lt;ipython-input-4-31dc119cb1f3&gt;(2)&lt;module&gt;() 1 my_var = 4 ----&gt; 2 raise ValueError ipdb&gt; and I have the debugger available.
has comment: http://stackoverflow.com/comment/82271399
has comment: http://stackoverflow.com/comment/82297944
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82272534
has comment: http://stackoverflow.com/comment/82271661
downvote count: 0

mixed
tag name: mixed
type: Tag
tags question: http://stackoverflow.com/q/47660384

http://stackoverflow.com/a/47683542
has comment: http://stackoverflow.com/comment/82326796
has body: After first iteration you list look like [4,4,6] so k.index(4) return 0 index and multiple it by 2. So final result is [8,4,12].
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47683498
has comment: http://stackoverflow.com/comment/82327635
type: Answer

newline
tags question: http://stackoverflow.com/q/47642334
tags question: http://stackoverflow.com/q/47625294
tag name: newline
type: Tag

http://stackoverflow.com/comment/82141242
has text: `ImportError: No module named _caffe` mean `ImportError: No module named _core` where is default `src` path ? `Distributable` or `Standalone module` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47590890
score: 0

if-statement
tags question: http://stackoverflow.com/q/47660227
tags question: http://stackoverflow.com/q/47670089
tag name: if-statement
tags question: http://stackoverflow.com/q/47598973
type: Tag
tags question: http://stackoverflow.com/q/47608612
tags question: http://stackoverflow.com/q/47616073
tags question: http://stackoverflow.com/q/47690056
tags question: http://stackoverflow.com/q/47577829
tags question: http://stackoverflow.com/q/47690558
tags question: http://stackoverflow.com/q/47614135
tags question: http://stackoverflow.com/q/47560444
tags question: http://stackoverflow.com/q/47624751
tags question: http://stackoverflow.com/q/47585074
tags question: http://stackoverflow.com/q/47560474
tags question: http://stackoverflow.com/q/47621797
tags question: http://stackoverflow.com/q/47565559
tags question: http://stackoverflow.com/q/47697240
tags question: http://stackoverflow.com/q/47625126
tags question: http://stackoverflow.com/q/47573907
tags question: http://stackoverflow.com/q/47581938
tags question: http://stackoverflow.com/q/47585503
tags question: http://stackoverflow.com/q/47638090
tags question: http://stackoverflow.com/q/47659592

http://stackoverflow.com/a/47620958
answers question: http://stackoverflow.com/q/47620826
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
has body: You're only plotting it at the x values you're using to fit it, so you're only seeing the agreement there and lines drawn between those points. If you plot it at more points between 0 and 10 (e.g. np.linspace(0, 10, 100), you'll start to see the difference:
accepted answer of: http://stackoverflow.com/q/47620826

http://stackoverflow.com/comment/82360010
has text: Ah `JUPYTER_DATA_DIR` that was it! I could not find it anywhere on the documentation. Thank you very much
type: Comment
comment on: http://stackoverflow.com/a/47699188
type: AnswerComment
score: 1

http://stackoverflow.com/q/47621360
downvote count: 1
type: AnsweredQuestion
score: 3
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/47621564
answer count: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/47621564
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has title: Placing a text with coordinates with drawText()
has body: I am trying to place a text with coordinates, but i don't know how to introduce the arguments. I searched in the net and that only has examples with Qt.Allign ----, and if I place the arguments as in the documentation, I got error. It is built with PyQt5 in python 3.6 import sys from PyQt5.QtCore import QTimer, Qt, QRectF from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QVBoxLayout, QHBoxLayout from PyQt5.QtGui import QColor, QFont, QPainter class Window(QWidget): def __init__(self): super().__init__() self.stopwatch() def stopwatch(self): hbox = QHBoxLayout() self.setLayout(hbox) self.setWindowTitle("Example") self.setGeometry(400,400,400,200) self.formato = "0:00.0" self.show() def paintEvent(self, event): qp = QPainter() qp.begin(self) self.draw_rect(event, qp) qp.end() def draw_rect(self,event, qp): # Black Rectangle col = QColor("Black") col.setNamedColor("Black") qp.setPen(col) qp.setBrush(QColor("Black")) qp.drawRect(130,000,400,200) # formato qp.setPen(QColor("Green")) qp.setFont(QFont('Helvetica', 48)) qp.drawText(event.rect(), QRect(50, 50, 50, 50),5 , self.formato) # Problem app = QApplication(sys.argv) w = Window() sys.exit(app.exec_())
tagged with: python

http://stackoverflow.com/q/47644879
has answer: http://stackoverflow.com/a/47644907
downvote count: 0
tagged with: python
type: AnsweredQuestion
has title: Why are booleans considered integers?
linked to: http://stackoverflow.com/q/37888620
has body: Python considers a boolean as an integer. Why? &gt;&gt;&gt; boolean = True &gt;&gt;&gt; isinstance(boolean, int) True Reverse the condition and ask Python if an integer is a boolean (obviously no), you get this: &gt;&gt;&gt; integer = 123 &gt;&gt;&gt; isinstance(integer, bool) False
answer count: 1
duplicate of: http://stackoverflow.com/q/37888620
has comment: http://stackoverflow.com/comment/82248535
favorite count: 0
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/47644907
upvote count: 8

http://stackoverflow.com/comment/82273663
score: 1
type: Comment
type: QuestionComment
has text: OK in that case, could you run "ssh git@github.com -v"?
comment on: http://stackoverflow.com/q/47657170

http://stackoverflow.com/q/47580526
favorite count: 0
type: Question
answer count: 0
upvote count: 2
tagged with: freetds
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/96981590
score: 2
has body: We’ve been using pymssql and FreeTDS for over 2 years now without problems. We recently upgraded pymssql to 2.1.3 and also from Python 3.4 to 3.6. Since that upgrade we’ve been getting the following error intermittently (but frequently). (20017, b'DB-Lib error message 20017, severity 9:\nUnexpected EOF from the server (FBOps-Prod:1433)\nDB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (FBOps-Prod:1433)\n') There is no apparent pattern to the failures. Well over 99% of the DB calls succeed and it can fail on any stored proc or sql. I’ve scoured the web and come up empty. I’ve reinstalled pymssql and FreeTDS but it still fails. I’ve checked max number of connections and it’s 4096 which should be plenty as there are no more than 10 active users at a time. I've verified that we close all DB connections properly. I believe this is a FreeTDS error and posted to the FreeTDS mailing list but haven't received any response yet Below is an excerpt from the TDS log file (full log file at the end). packet.c:639:Received packet 0000 04 01 00 11 00 5c 01 00-fd 00 00 d4 00 00 00 00 |.....\.. ........| 0010 00 - |.| token.c:565:processing result tokens. marker is fd(DONE) token.c:2081:tds_process_end: more_results = 0 was_cancelled = 0 error = 0 done_count_valid = 0 token.c:2098: rows_affected = 0 token.c:2101:tds_process_end() state set to TDS_IDLE util.c:165:Changed query state from READING to IDLE util.c:83:logic error: cannot change query state from IDLE to PENDING I’ve looked at the FreeTDS code but don’t have sufficient knowledge to understand why it’s failing. Any help is appreciated.
has title: Unexpected EOF error with pymssql
tagged with: pymssql

http://stackoverflow.com/a/47695447
has body: Take a look at this: import bs4 as bs import urllib.request link = 'http://companyinfo.stock.naver.com/v1/company/c1010001.aspx?cn=&amp;cmp_cd=005930&amp;menuType=block' source = urllib.request.urlopen(link) soup = bs.BeautifulSoup(source, 'html.parser') table = soup.find('table', attrs={'id' : 'cTB24'}) for tr in table.find_all('tr'): for td in tr.find_all('td'): print(td.text)
answers question: http://stackoverflow.com/q/47678089
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/47678089
type: Answer

http://stackoverflow.com/a/74832072
score: 0
answers question: http://stackoverflow.com/q/47692960
has body: Note necessarily the answer to this issue, but for others who might find this. I've use TAB to auto complete my pyinstaller command and it defaulted to the .exe file in my root instead of the .py file.
type: Answer

http://stackoverflow.com/comment/82100777
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47571435
has text: Thanks! I really like this solution, it seems clean. For now it works though in the future memory will be an issue since I will be using very large dataframes (that may be >1 gig in size)
type: Comment

http://stackoverflow.com/comment/82254620
has text: Previous line. Parentheses.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47648207
score: 1

http://stackoverflow.com/comment/82123439
comment on: http://stackoverflow.com/a/47582653
has text: @capituscapiti Did you restart your computer after the installation?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82361605
has text: does not work. I have edited the question so that it is more clearly shown the problem.. thank you
type: QuestionComment
comment on: http://stackoverflow.com/q/47683359
score: 0
type: Comment

http://stackoverflow.com/a/47651785
type: Answer
answers question: http://stackoverflow.com/q/47651327
score: 2
upvote count: 2
has body: Another approach would be using pythons built in format function to get a better output current = con_mysql.cursor() current_query = "SELECT name FROM event_categories WHERE visible=1" current.execute(current_query) for name in current: print("{}".format(name[0])
downvote count: 0

http://stackoverflow.com/comment/82286710
comment on: http://stackoverflow.com/q/47663635
type: Comment
type: QuestionComment
score: 0
has text: always put **full** error message (Traceback) in question (as text, not screenshot). There are other ufull informations

http://stackoverflow.com/a/47550644
has comment: http://stackoverflow.com/comment/82058863
answers question: http://stackoverflow.com/q/47549965
score: 0
has comment: http://stackoverflow.com/comment/82058019
has body: I would never recommend storing this many text files in RAM, most of the time, this would take more memory that you have available. Instead, I would recommend restructuring your for loop so that you do not have to iterate over them multiple times. Since you are not saying that you need to change the files, I would recommend storing them all in a dictionary with the filename as a key. If you use an OrderedDict, then you can even just iterate through the contents (using .itervalues()) if the filenames are not important to you as well. In this case, you could iterate over a list of file names using a for loop (create the list of filenames either directly using the according os functionality or provide it beforehand) and read all files into the dictionary: import collections d = collections.OrderedDict() file_list = ["a", "b", "c"] # Fill data here or adapt for loop accordingly for file_path in file_list: d[file_path] = open(file_path, "r").read() Alternative way: This is not an exactly matching solution but an alternative which might speed you up a little: I do not know the files you are using, but if you can distinguish between inputfiles, since they e.g. only contain one line each, ... you could instead copy them all over into one huge file and only walk through this file e.g. with for line in huge_cache_file: # your current logic here This would not speed you up as using your RAM would, but it would get rid of the overhead of opening and closing 17k files a hundred times. At the end of the big cache file, you could then just jump to the beginning again using huge_cache_file.seek(0) If newlines are not an option but your files would have a fixed length, you could still copy them together and iterate like this: for file_content in huge_cache_file.read(file_length): # your current logic here If files have a different length, you could still do this but store the file lengths of each individual file into an array, using those stored file lengths to read from the cache f…
type: Answer
has comment: http://stackoverflow.com/comment/82057915

http://stackoverflow.com/comment/82338843
type: AnswerComment
comment on: http://stackoverflow.com/a/47677981
has text: @ Siyuan Ren so,it s not necessary to save multiple meta graph ?one is enough
score: 0
type: Comment

pca
tag name: pca
tags question: http://stackoverflow.com/q/47548178
tags question: http://stackoverflow.com/q/47579944
type: Tag

http://stackoverflow.com/comment/82265296
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47631556
has text: Strange that this could not be solved more effectively. But thanks anyway for the answers, all of you.
score: 0

http://stackoverflow.com/comment/82293131
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47667002
has text: yes you can do this

http://stackoverflow.com/comment/82043352
type: AnswerComment
score: 0
type: Comment
has text: you still need to remove the 'OR' in the last line, but I agree that would work
comment on: http://stackoverflow.com/a/47542579

http://stackoverflow.com/comment/82238992
type: Comment
comment on: http://stackoverflow.com/a/47639860
type: AnswerComment
has text: I did't solved it yet, I'm just trying to deal with it now.
score: 1

http://stackoverflow.com/comment/82318321
type: AnswerComment
comment on: http://stackoverflow.com/a/47677964
score: 0
type: Comment
has text: Can you show me? because I am pretty confused in certain aspects.

http://stackoverflow.com/a/47682368
type: Answer
has body: The main problem with your code is that you have a while loop on your main GUI thread. So what you need to do is to run the start_alarm on a different thread than your main GUI thread for the GUI thread to be responsive. As for not being able to play alarm next time, you didn't set the alarm_status flag to True again.Once you have that you can start and stop the sound as many times you want. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.widget import Widget import time import winsound import threading class ControlPanel(BoxLayout): def __init__(self, **kwargs): # make sure we aren't overriding any important functionality super(ControlPanel, self).__init__(**kwargs) self.alarm_status = True self.orientation = "vertical" butOn = Button(text = "Start alarm: ", on_release = self.start_thread) butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm) self.add_widget(butOn) self.add_widget(butStop) def start_alarm(self, obj): while self.alarm_status == True: winsound.PlaySound("alarm.wav", winsound.SND_FILENAME) #Set Alarm_Status True so that next time it works self.alarm_status = True def stop_alarm(self, obj): self.alarm_status = False #Function to run your start_alarm on a different thread def start_thread(self,obj): t1 = threading.Thread(target=self.start_alarm,args=(obj,)) t1.start() class LifeApp(App): def build(self): return ControlPanel() if __name__ == '__main__': LifeApp().run() Hope this helps!
has comment: http://stackoverflow.com/comment/82338340
accepted answer of: http://stackoverflow.com/q/47681927
has comment: http://stackoverflow.com/comment/82337528
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82325208
answers question: http://stackoverflow.com/q/47681927

http://stackoverflow.com/comment/82221954
has text: The tweet data in the image looks nothing like what you assume.
score: 0
comment on: http://stackoverflow.com/a/47632086
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47693862
favorite count: 0
type: Question
has title: resolution needed, argument 1 must have a 'write' method. make a dictionary into a csv
has comment: http://stackoverflow.com/comment/82347446
has comment: http://stackoverflow.com/comment/82346818
has comment: http://stackoverflow.com/comment/82346997
upvote count: 2
score: -4
tagged with: python
has body: i cant seem to get my code working its keeps giving me the same 'argument 1 must have a 'write' method import csv tank1 = [{'tank':1, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}] tank2 = [{'tank':2, 'product':['condenstate'], 'temp':12,'ullage':21000, 'level':70000}] key1 = tank1,tank2[0].keys() with open('motherwell.csv','w',newline='') as output_file: writer = csv.writer writer = csv.writer(output_file, key1) writer = csv.writer(key1)
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82347315
has comment: http://stackoverflow.com/comment/82347321
has answer: http://stackoverflow.com/a/47694175
accepted answer: http://stackoverflow.com/a/47694175
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has comment: http://stackoverflow.com/comment/82347129

http://stackoverflow.com/comment/82326588
comment on: http://stackoverflow.com/a/47680866
type: Comment
score: 0
type: AnswerComment
has text: errata: correct c #include reference link is http://en.cppreference.com/w/c/preprocessor/include

http://stackoverflow.com/q/47600501
tagged with: pip
has comment: http://stackoverflow.com/comment/82159672
tagged with: ubuntu
linked to: http://stackoverflow.com/q/26305396
has title: Some issues with pip installation
tagged with: python-2.7
has body: I tried to install pip manager using the file get-pip.py as mentioned in the documentation- https://pip.pypa.io/en/stable/installing/ So, I downloaded the file and ran python get-pip.py and as a result, I had permission issues. So I again ran sudo python get-pip.py and it worked. Now I wanted to install numpy. So I ran pip install numpy and it showed me the Import Error saying- Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip import main ImportError: No module named pip But again when I ran sudo pip install numpy, it worked and got installed. Now, for every python script involving these pip packages, I have to run the script using sudo which I don't like. So how can I resolve these permission issues? Just to mention- python v2.7.12 pip v9.0.1 pip installation location- /usr/local/lib/python2.7/dist-packages
tagged with: python
has comment: http://stackoverflow.com/comment/82160024
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/82159583
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47596226
has body: It is highly recommended to read files in a with statement. That frees you from the responsibility of closing the file and is also shorter! This works: def sum_integers_from_file(file_name): try: with open(file_name, 'r') as f: s = f.read() total = 0 for char in s: total += int(char) return total except: print("error")
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47596154
type: Answer
answers question: http://stackoverflow.com/q/47596154

http://stackoverflow.com/a/47580800
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47580444
has comment: http://stackoverflow.com/comment/82119046
answers question: http://stackoverflow.com/q/47580444
has body: How can i get the index that wrote in .insert? You can't. The "id" that you think you're giving isn't an id, it's an index. And if the index is larger than the last index, it's ignored and the item is placed at the end. In other words, when you do this: lb.insert(5,'data1') lb.insert(8,'data2') Then 'data1 will be inserted at index 0 (zero), and 'data2' will be inserted at index 1 (one). There is no way to retrieve the original values 5 and 8.
type: Answer
has comment: http://stackoverflow.com/comment/82120407
upvote count: 3

http://stackoverflow.com/q/47638326
tagged with: python
tagged with: sorting
has body: I practice python recently. for a few days my script has stopped, because I'm struggling on a problem. I want to sort the items by both values which has in common. like an chain. as you can see lower. what I have: dic= {'A': [62, 17], 'B': [59, 60], 'C': [60, 61], 'D': [57, 58], 'E': [61, 62], 'F': [58, 59]} what I want: dic={'A': [62, 17], 'E': [31, 62],'C': [60, 31],'B': [3, 60],'F': [58, 3],'D': [57, 58]} to see clearly: 'A': [62, 17] 'E': [*31*, 62] 'C': [60, *31*] 'B': [3, 60] 'F': [58, 3] 'D': [57, 58] there is a simple method to sort them ? if the topic already exists, can you send me the link. i haven't found it. thank you in advance. nb. in all case, I know the first and the last value of the chain (17 and 57)
tagged with: dictionary
upvote count: 4
has comment: http://stackoverflow.com/comment/82234952
linked to: http://stackoverflow.com/q/1012185
has title: arrange items by two values in Python dictionary
has comment: http://stackoverflow.com/comment/82235026
has comment: http://stackoverflow.com/comment/82235314
linked to: http://stackoverflow.com/q/9001509
answer count: 2
has answer: http://stackoverflow.com/a/47639129
tagged with: items
has comment: http://stackoverflow.com/comment/82235115
downvote count: 1
has comment: http://stackoverflow.com/comment/82235078
duplicate of: http://stackoverflow.com/q/9001509
has comment: http://stackoverflow.com/comment/82235157
has answer: http://stackoverflow.com/a/47639179
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82235053

screenshot
tags question: http://stackoverflow.com/q/47641974
tags question: http://stackoverflow.com/q/47633765
type: Tag
tag name: screenshot

http://stackoverflow.com/comment/82351595
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47695333
has text: @mkrieger1, that's great info to know and assist me also, thank you.

http://stackoverflow.com/a/55862183
accepted answer of: http://stackoverflow.com/q/47567263
type: Answer
answers question: http://stackoverflow.com/q/47567263
score: 0
type: AcceptedAnswer
has body: It seems, I am ready now (almost 1.5 yeast after posting them) to answer my own questions: It is possible to make test run &amp; pass. Given the code, as it is above, the workaround, provided at the end of the question will do, though it can be shortened to: def testLoop(self): response = self.test_client.get('/', follow_redirects=True) # navigating to '/', directly self.assertTrue('Hello'.encode('ascii') in response.data) in this particular case, there is no need for the self.test_client.get('/redirection/'), line. Though, if some changes were made to session['test'] inside the /redirection/, like so: @app.route('/redirection/') def redirection(): session['test'] = True return redirect(url_for('index')) then, self.test_client.get('/redirection/'), would be necessary, so test would become: from unittest import TestCase from app import app class RedirectTestCase(TestCase): def setUp(self): self.test_client = app.test_client() def testLoop(self): self.test_client.get('/redirection/') response = self.test_client.get('/', follow_redirects=True) self.assertTrue('Hello'.encode('ascii') in response.data) This, so called, "workaround" is just preventing test from doing two redirects to /, in a row (which is exactly what is causing ClientRedirectError: loop detected — see answer to point 3, below). If there is a better way or not — will depend on the exact details of the app implementation. In the example from the question, the redirection inside index is, actually, unnecessary and can be removed: @app.route('/') def index(): session['test'] = session.get('test', True) return "Hello" Such change, by the way, will also make the initial test (from the question) pass. As far as I can tell, such behaviour is "by design", namely: ClientRedirectError: loop detected is raised, when redirection to the same url occurs (at least) two times in a row. Below are some examples. This, test won't encounter ClientRedirectError (as redirection only happens once): isolated_app.py from flask im…

http://stackoverflow.com/q/47574413
has comment: http://stackoverflow.com/comment/82155385
tagged with: testing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82106553
tagged with: python
has title: Return variable from Test class to conftest
score: 0
tagged with: pytest
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82132096
tagged with: fixtures
has comment: http://stackoverflow.com/comment/82132409
has body: In my task, I need to return a value from my test class to conftest file. is it possible? if yes then how to do it? Suppose that I need to return 'element_2' variable from test case file. If possible, please help. This is my conftest file.. import pytest import time from selenium import webdriver @pytest.yield_fixture(scope="function") def oneTimeSetUp(request): print "__CONFTEST ONE TIME SETUP BEGIN__" driver=webdriver.Chrome() driver.maximize_window() yield driver print "__CONFTEST YIELD BEGIN__" #print "ELEMENT_2 TEXT IS------&gt;",element_2.text time.sleep(5) driver.close() This is my test case file: import pytest @pytest.mark.usefixtures("oneTimeSetUp") class TestHomePage(): @pytest.fixture(autouse=True) def setup(self,oneTimeSetUp): self.webdriver = oneTimeSetUp def test_run(self): print "____ TEST START ____" self.webdriver.get("https://www.google.co.in/") element_1 = self.webdriver.find_element_by_css_selector('input[name="btnI"]') print "CLICK ON 'I AM FEELING LUCKY'" element_1.click() element_2 = self.webdriver.find_element_by_css_selector('a[href="/doodles/about"]') print "ELEMENT_2 TEXT IS------&gt;",element_2.text print "CLICK ON 'ABOUT' " #element_2.click() #return element_2 print "____ TEST END ____" The above code is example of Google homepage then click on "I am feeling lucky" on that option I need to return the variable 'element_2' which is the element of "about" option which is present on the top left corner of that page.
type: Question

http://stackoverflow.com/comment/82127383
has text: Huh? What were you *expecting*? The loop variables are working normally...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47584852

dll
tags question: http://stackoverflow.com/q/47606257
tags question: http://stackoverflow.com/q/47594610
tag name: dll
type: Tag

http://stackoverflow.com/comment/82181271
type: AnswerComment
comment on: http://stackoverflow.com/a/47611173
has text: If someone types an uppercase you will lowercase that username. And when a user is registering in the platform you will save the username in lowercase. The user can type an uppercase username but internally you always can work with a lowercase username.
type: Comment
score: 0

http://stackoverflow.com/a/47585738
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47585705
has body: You can try this: f = open('file.txt', 'w') dict = {'a':1,'b':2,'c':3} f.write('.'.join('{},{}'.format(a, b) for a, b in dict.items())+'.\n') f.close()
accepted answer of: http://stackoverflow.com/q/47585705
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/q/47632728
type: UnansweredQuestion
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/47632887
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I want to do something using Pandas that seems to be quite difficult. I hope I'm wrong I want to open a csv-file, set the dtype of every column as int with the exception of one column that I would like to drop. I do not now the names and/or the number of columns present in advance. The non-int column is always present at the same position, every other column consits only of intergers. data: foo.csv: a b c d e f g ... 1 700592 a 23 ... ... ... 2 808295 b 24 ... ... 3 106796 c 25 ... 4 166438 d 26 ... 5 172594 e 27 ... what I would like to do: df = pd.read_csv(foo.csv, usecols=[0,1,3, ...], dtype=int) I could read the complete file, drop the non-int column, and change the type globally but the data may be very large so speed and memory are to be considered.
type: Question
has title: Pandas - Selecting all columns but one in DataFrame while setting dtype

http://stackoverflow.com/comment/82254011
type: Comment
type: QuestionComment
has text: Because NaNs I guess. Need `df3['D'] = df3['O2'].sub(df3['O1'], fillna=0) `
score: 0
comment on: http://stackoverflow.com/q/47647649

http://stackoverflow.com/q/47599379
type: Question
has comment: http://stackoverflow.com/comment/82182264
tagged with: tkinter
tagged with: tkinter-canvas
tagged with: python
has answer: http://stackoverflow.com/a/47599510
has title: Closing an Image After User Clicks (Python and Pillow)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82157169
score: 0
has body: I am working on a Choose-Your-Own-Adventure game in Python. Every so often, I want the user to be given a scene, and be allowed to find objects in that scene. Whatever they find can be put in their inventory, and whenever they are ready to stop looking for items, they can hit an "Exit" button in the bottom left. However, I am running into some errors with actually getting the button click coordinates to actually do something. So far, I have this: root = Tk() imageIQ1 = Canvas(root, width=1000, height=1000) imageIQ1.pack() original = Image.open("prison.jpg") original = original.resize((1000,1000)) #resize image img = ImageTk.PhotoImage(original) imageIQ1.create_image(0, 0, image=img, anchor="nw") def getcoors(eventcoors): global x0,y0 x0 = evencoors.x y0 = evencoors.y print(x0,y0) After the user clicks a certain set of coordinates (or somewhere near them), I want the program to clear the picture from the screen and continue with the program. For insance, clicking anywhere from (300, 400) to (500, 500) would close the picture and continue with the rest of the program. I know this will use some form of loop like while (x not in range) and (y not in range): But I am unsure of what I would actually do to clear the image. I read about using something like .kill() and .terminate(), but they don't work in this situation. Any ideas?
answer count: 1
accepted answer: http://stackoverflow.com/a/47599510
tagged with: image
linked to: http://stackoverflow.com/q/22925599

http://stackoverflow.com/comment/82211024
type: AnswerComment
has text: @AlexanderReynolds I have no clue how it works either. All I know is that if you're only adding or multiplying parts of arrays, `einsum` will do anything other `numpy` functions can't.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47625266

http://stackoverflow.com/q/47659914
downvote count: 1
answer count: 1
favorite count: 0
has title: Does glob work with pdf files?
has answer: http://stackoverflow.com/a/47659955
type: Question
tagged with: glob
tagged with: python
type: UnansweredQuestion
score: -1
tagged with: concatenation
upvote count: 0
tagged with: http://stackoverflow.com/tag/pdf
has body: I am new to python and I am trying to create a code that will search through thousands of pdf files that are organized and titled by 3 different numbers, township, range, and section (file looks like: 07N06E08_4200). I have been trying to get glob to read my pdf files, as I have used glob for excel files, but I haven't had any luck. This is the command so far to bring in the data: glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty') And that reutrns: [] I then have: collectData=[] for filename in glob.glob('./C:/Users/green_000/Documents/Alyssa/Python/FinalProject/Python_Data/SacramentoCounty'): print('processing {:s}'.format(filename)) data = pd.read_pdf(filename) collectData.append(data) AllData = pd.concat(collectData) AllData.columns=['Township','Range','Section'] AllData.to_pdf('AllData.csv',mode='w') And I get the error: No objects to concatenate thanks for any help!

http://stackoverflow.com/a/47660641
has comment: http://stackoverflow.com/comment/82280550
answers question: http://stackoverflow.com/q/47659731
score: 1
type: Answer
has body: xn_1 is a numpy matrix, so it's elements are accessed with the item() method, not like an array. (with []s) So just change x = xn_1[0] y = xn_1[1] to x = xn_1.item(0) y = xn_1.item(1)
has comment: http://stackoverflow.com/comment/82280291
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82280596

http://stackoverflow.com/a/47597800
answers question: http://stackoverflow.com/q/47579954
has body: I found out the answer. Here's what to do: 1. Open Command Prompt as Admin (Search for cmd in the start menu, right click and Run as administrator) 2. Type the following in: takeown /f C:\ 3. If the operation was succesful, close Command Prompt and go to This PC. 4. Right click on the C:\ drive. 5. Click on Properties. 6. Click on the Security tab at the top of the window. 7. Go to your username and click Edit. 8. Tick the Full Control box. 9. Save it. 10. Run the command again. If this persists, the takeown command might not have executed correctly.
accepted answer of: http://stackoverflow.com/q/47579954
score: 0
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/47577762
has comment: http://stackoverflow.com/comment/107457249
linked to: http://stackoverflow.com/q/3596979
upvote count: 9
tagged with: python
has answer: http://stackoverflow.com/a/47579686
score: 9
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/72852
has body: I have a following package to distribute: mymodule/ data/ 1.txt mymodule/ __init__.py tests/ test_mymodule.py setup.py In order to install it under a vitualenv I apply this command: pip install . Everything is installed fine but the path to my data file becomes broken. &gt;&gt;&gt; from mymodule import get &gt;&gt;&gt; print(get()) ... FileNotFoundError: [Errno 2] No such file or directory: '/home/alexander/Stuff/pip_example/mymodule_test/venv/lib/python3.5/site-packages/mymodule/../data/1.txt' I made a research and found, the folder data was create in the root of the virtualenv's folder that caused the error. How should I improve my code to keep my tests working and to have the correct path to the data file? The contents of the files: data/1.txt yes mymodule/__init__.py import os src = os.path.join( os.path.dirname(__file__), '../data/1.txt' ) def get(): with open(src) as f: return f.read().strip() tests/test_mymodule.py import unittest import mymodule class MymoduleTest(unittest.TestCase): def test_get(self): s = mymodule.get() self.assertEqual(s, "yes") setup.py from distutils.core import setup data_files = [ ('data', ['data/1.txt']) ] setup( name='mymodule', version='0.0', packages=['mymodule'], data_files=data_files, ) I am new in packaging Python modules. Please help me with this issue. ===================================================================== I figured out that I need to use sys.prefix to access the virtualenv's root. In other words, if I edit mymodule.__init__.py this way everything will work correctly: import os import sys src = os.path.join(sys.prefix, 'data/1.txt') def get(): with open(src) as f: return f.read().strip() But after that the test fails with the error: FileNotFoundError: [Errno 2] No such file or directory: '/usr/data/1.txt' This is because sys.prefix is /usr without activated virtualenv. So I need a different way to improve the package, I guess.
tagged with: setup.py
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: pip
has title: How do I distribute my pip package with data files correctly?
favorite count: 0

http://stackoverflow.com/comment/82252617
has text: I think you can get it by using ```https://redis.io/commands/client-list```.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47647065

http://stackoverflow.com/comment/82329719
comment on: http://stackoverflow.com/a/47684866
type: Comment
has text: Thank you, this works. There's no duplicate filename in the directory so this will be good for me.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47606219
answer count: 1
tagged with: pip
tagged with: virtualenv
has title: Getting error while using virtualenv venv on fedora 26
accepted answer: http://stackoverflow.com/a/47606470
has body: I installed virtualenv on fedora 26 using pip3 install --user virtualenv. System has both python 2.7 and python 3.6. When I am creating a "virtualenv venv", I am getting this output and error. New python executable in /home/asraisingh/venv/bin/python2 Also creating executable in /home/asraisingh/venv/bin/python Installing setuptools, pip, wheel... Complete output from command /home/asraisingh/venv/bin/python2 - setuptools pip wheel: Traceback (most recent call last): File "", line 7, in File "/home/asraisingh/.local/lib/python2.7/site-packages/virtualenv_support/pip-9.0.1-py2.py3-none-any.whl/pip/init.py", line 7, in File "/usr/lib64/python2.7/optparse.py", line 77, in import textwrap File "/usr/lib64/python2.7/textwrap.py", line 10, in import string, re File "string.py", line 1 KDE: 9 ^ SyntaxError: invalid syntax ---------------------------------------- ...Installing setuptools, pip, wheel...done. Traceback (most recent call last): File "/home/asraisingh/.local/bin/virtualenv", line 11, in sys.exit(main()) File "/home/asraisingh/.local/lib/python2.7/site-packages/virtualenv.py", line 713, in main symlink=options.symlink) File "/home/asraisingh/.local/lib/python2.7/site-packages/virtualenv.py", line 945, in create_environment download=download, File "/home/asraisingh/.local/lib/python2.7/site-packages/virtualenv.py", line 901, in install_wheel call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT) File "/home/asraisingh/.local/lib/python2.7/site-packages/virtualenv.py", line 797, in call_subprocess % (cmd_desc, proc.returncode)) OSError: Command /home/asraisingh/venv/bin/python2 - setuptools pip wheel failed with error code 1
type: Question
has comment: http://stackoverflow.com/comment/82171203
has comment: http://stackoverflow.com/comment/82171380
has comment: http://stackoverflow.com/comment/82170964
tagged with: python
has answer: http://stackoverflow.com/a/47606470
type: AnsweredQuestion
score: 0
tagged with: fedora-26
has comment: http://stackoverflow.com/comment/82171243

http://stackoverflow.com/a/73229167
has body: Try with pip install websockets that's work for me!
answers question: http://stackoverflow.com/q/47665760
score: 0
type: Answer

http://stackoverflow.com/q/47599170
has comment: http://stackoverflow.com/comment/82157090
accepted answer: http://stackoverflow.com/a/47599536
tagged with: pyqt5
favorite count: 0
has answer: http://stackoverflow.com/a/63110046
type: Question
possible better answer: http://stackoverflow.com/a/63110046
has title: QFileDialog preview
tagged with: qfiledialog
has answer: http://stackoverflow.com/a/47599536
tagged with: python
has comment: http://stackoverflow.com/comment/82157206
has body: I am trying to get a Qt5 QFileDialog to show previews for images when selecting them for opening. Method 1: Extending the QFileDialog I used this implementation of the dialog and it worked with Qt 5.6.1 . Now I am using Qt 5.9.2 and it does not work anymore, giving the following error: Traceback (most recent call last): File "main.py", line 74, in mouseDoubleClickEvent self.openFileDialog() File "main.py", line 123, in openFileDialog openDialog = QFileDialogPreview(self, 'Open file', './', self.getDialogFilter()) File "QFileDialogPreview.py", line 22, in __init__ self.layout().addLayout(box, 1, 3, 1, 1) TypeError: addLayout(self, QLayout, stretch: int = 0): too many arguments Here is the translated class. I am using Python 3.5.2: from PyQt5.QtWidgets import QFileDialog, QLabel, QVBoxLayout from PyQt5.QtGui import QPixmap from PyQt5.QtCore import Qt class QFileDialogPreview(QFileDialog): def __init__(self, parent, caption, direcotry, filter): super().__init__(parent, caption, direcotry, filter) self.setObjectName("FileDialogPreview") box = QVBoxLayout(self) self.setFixedSize(self.width() + 250, self.height()) self.mpPreview = QLabel("Preview", self) self.mpPreview.setFixedSize(250, 250) self.mpPreview.setAlignment(Qt.AlignCenter) self.mpPreview.setObjectName("labelPreview") box.addWidget(self.mpPreview) box.addStretch() self.layout().addLayout(box, 1, 3, 1, 1) self.currentChanged.connect(self.onChange) self.fileSelected.connect(self.onFileSelected) self.filesSelected.connect(self.onFilesSelected) self._fileSelected = None self._filesSelected = None def onChange(self, path): pixmap = QPixmap(path) if(pixmap.isNull()): self.mpPreview.setText("Preview") else: self.mpPreview.setPixmap(pixmap.scaled(self.mpPreview.width(), self.mpPreview.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) def onFileSelected(self, file): self._fileSelected = file def onFilesSelected(self, files): self._filesSelected = files def getFileSelected(self): return self._fileSelected def getFi…
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pyqt

http://stackoverflow.com/q/47599461
tagged with: reshape
tagged with: python
has body: Suppose I have a 2D-Tensor T in [M, 1] e.g. T = tf.expand_dims([A1, B1, C1, A2, B2, C2], 1) and I want to reshape it like so: T_reshp = [[[A1], [A2]] [[B1], [B2]] [[C1], [C2]]] I know M and N (the number of tensors in each group) in advance. Further, let t_reshp.shape[0] = M/N = P in the I have tried using tf.reshape T_reshp = tf.reshape(T, [P, N, 1]) However, I end up with: T_reshp = [[[A1], [B1]] [[C1], [A2]] [[B2], [C2]]] Can I do this using some slicing or reshape operation?
tagged with: slice
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47599887
has answer: http://stackoverflow.com/a/47599887
answer count: 1
tagged with: tensorflow
type: Question
has title: TensorFlow - 3D tensor that gathers every Nth tensor from 2D tensor and strides 1

http://stackoverflow.com/a/47558162
has comment: http://stackoverflow.com/comment/82074301
has comment: http://stackoverflow.com/comment/82074413
has body: If to check page source as it initially appears required node will look like VWAP while this is how it appears after JavaScript executed VWAP 27.16 Note that there is no text content in first HTML sample It seem that values comes from below node {"valid":"true","isinCode":null,"lastUpdateTime":"29-NOV-2017 15:30:30","ocLink":"\/marketinfo\/sym_map\/symbolMapping.jsp?symbol=NIFTY&instrument=-&date=-&segmentLink=17&symbolCount=2","tradedDate":"29NOV2017","data":[{"change":"-17.80","sellPrice1":"13.80","buyQuantity3":"450","sellPrice2":"13.85","buyQuantity4":"150","buyQuantity1":"13,725","ltp":"-243019.52","buyQuantity2":"6,225","sellPrice5":"14.00","sellPrice3":"13.90","buyQuantity5":"450","sellPrice4":"13.95","underlying":"NIFTY","bestSell":"-2,41,672.50","annualisedVolatility":"9.44","optionType":"CE","prevClose":"31.10","pChange":"-57.23","lastPrice":"13.30","lowPrice":"11.00","strikePrice":"10400.00","premiumTurnover":"11,707.33","numberOfContractsTraded":"5,74,734","underlyingValue":"10,361.30","openInterest":"58,96,350","impliedVolatility":"12.73","vwap":"27.16","totalBuyQuantity":"10,49,850","openPrice":"35.10","closePrice":"17.85","bestBuy":"-2,43,852.25","changeinOpenInterest":"1,60,800","clientWisePositionLimits":"30517526","totalSellQuantity":"11,07,825","dailyVolatility":"0.49","sellQuantity5":"19,800","marketLot":"75","expiryDate":"30NOV2017","marketWidePositionLimits":"-","sellQuantity2":"75","sellQuantity1":"3,825","buyPrice1":"13.00","sellQuantity4":"900","buyPrice2":"12.90","sellQuantity3":"2,025","buyPrice4":"12.75","buyPrice3":"12.80","buyPrice5":"12.65","turnoverinRsLakhs":"44,94,632.53","pchangeinOpenInterest":"2.80","settlementPrice":"-","instrumentType":"OPTIDX","highPrice":"40.85"}],"companyName":"Nifty 50","eqLink":""} so the code that you might need is import json vwap = json.loads(tree.xpath('//div[@id="responseDiv"]/text()')[0].strip())['data'][0]['vwap']
accepted answer of: http://stackoverflow.com/q/47556812
type: Answer
answers question: http://stackoverflow.com/q/47556812
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47663391
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47663285
has comment: http://stackoverflow.com/comment/82286458
has body: You can use list comprehension: d = { "ok":["lol"] , "no":[] , "hi":["ok","no"] , "lol" : [] } root = [a for a, b in d.items() if all(a not in d for c, d in d.items())][0] Output: 'hi'

http://stackoverflow.com/q/47550885
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82122455
tagged with: handwriting-recognition
has title: Why do i get so bad accuracy in mnist digits recognition
has body: I am new to AI and this code is about mnist digits recognition according to the tutorial from this website: tensorflow tutorial. For some reason, I cant use the mnist data directly like what it is in tutorial. My method is to download the data first, then decompress it into a folder. Then read the data as binary data and decode it into numpy. I dont know why , the accuracy is merely 0.098, which is far from the supposed value 0.92. My code is here : import numpy as np import struct import matplotlib.pyplot as plt class MnistData(): def printImg(self,img): fig = plt.figure() plotwindow = fig.add_subplot(111) plt.imshow(img , cmap = 'gray') plt.show() return def getBinFile(self,filename): binfile = open(filename , 'rb') buf = binfile.read() return buf def decodeLabelsFromBin(self,binFile): offset = 0 fmt_header = '&gt;ii' magic_number, num_images = struct.unpack_from(fmt_header, binFile, offset) offset += struct.calcsize(fmt_header) fmt_image = '&gt;B' labels = np.empty(num_images) for i in range(num_images): labels[i] = struct.unpack_from(fmt_image, binFile, offset)[0] offset += struct.calcsize(fmt_image) return labels def decodeImagesFromBin(self,buf): #读取头四个32bit的interger: index = 0 magic, numImages, numRows, numColumns = struct.unpack_from('&gt;IIII' , buf , index) index += struct.calcsize('&gt;IIII') imageSize = numRows * numColumns fmtImage = '&gt;' + str(imageSize) + 'B' images = np.empty((numImages, numRows, numColumns)) for i in range(numImages): images[i] = np.array(struct.unpack_from(fmtImage, buf, index)).reshape((numRows, numColumns)) index += struct.calcsize(fmtImage) return images def __init__(self): trainImgPath = 'E:/AI projects/mnistPJ/mnist/train-images.idx3-ubyte' trainLabelPath = 'E:/AI projects/mnistPJ/mnist/train-labels.idx1-ubyte' testImgPath = 'E:/AI projects/mnistPJ/mnist/t10k-images.idx3-ubyte' testLabelPath = 'E:/AI projects/mnistPJ/mnist/t10k-labels.idx1-ubyte' trainImgBinFile = self.getBinFile(trainImgPath) self.trainImgs = self.decodeIma…
tagged with: mnist
tagged with: python
tagged with: artificial-intelligence
score: 0
has comment: http://stackoverflow.com/comment/82087380
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82077621

http://stackoverflow.com/a/47693327
upvote count: 5
downvote count: 0
type: Answer
has body: As stated here, sip.voidptr.__int__() method returns the address as an integer while c_void_p documentation says The constructor accepts an optional integer initializer. So you should be able to build a c_void_p passing the return value of sip.voidptr.__int__() method to its constructor: imgPtr = c_void_p(img.__int__()) I tested this solution this way: from PyQt5 import QtGui from ctypes import * lib = CDLL("/usr/lib/libtestlib.so") image = QtGui.QImage("so.png") bits = image.constBits() bytes = image.bytesPerLine() lib.f(c_void_p(bits.__int__()), c_int(image.width()), c_int(image.height()), c_int(bytes)) Which works fine with a function like: #include &lt;cstdio&gt; #include &lt;QImage&gt; extern "C" { void f(unsigned char * c, int width, int height, int bpl) { printf("W:%d H:%d BPL:%d\n", width, height, bpl); QImage image(c, width, height, bpl, QImage::Format_RGB32); image.save("test.bmp"); } }
has comment: http://stackoverflow.com/comment/82359453
answers question: http://stackoverflow.com/q/47689778
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47689778
score: 5

http://stackoverflow.com/comment/82297414
comment on: http://stackoverflow.com/q/47667708
score: 0
type: Comment
type: QuestionComment
has text: How about processing the text to strip off the leading or trailing white space and commas? You can call something like `str1.strip(' ,')` before you pass the string into the function. lstrip() gets rid of leading chars, and rstrip() gets rid of trailing chars.

http://stackoverflow.com/comment/82096421
comment on: http://stackoverflow.com/a/47568920
type: Comment
score: 0
type: AnswerComment
has text: I use Windows 7.1

http://stackoverflow.com/comment/82189143
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47614940
has text: On line 91, you are passing `Turtle.speed` to the forward function. Since speed is an instance method of Turtle and not an expected numeric you get that error. You probably wanted `self.forward(self.speed())` calling speed with no argument returns the current speed as a number and then `forward` is happy.

http://stackoverflow.com/q/47625294
answer count: 3
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82208741
score: 1
accepted answer: http://stackoverflow.com/a/47625788
tagged with: text-files
favorite count: 0
has body: Alright so here's the question. I have some text files that have 14,000+ words in them, but they are all on 1 line, and if you use a editor that doesn't have a auto wrapping feature you can't read the text file. So I would like to add returns or newline characters to my file after at least 1000 words and on the next occurrence of a ".". My first thought was to count the lines then add it up and when it reached 1000 insert a \n character, but with it being all on 1 line. That makes things a bit more difficult, and I haven't been able to find a way to accomplish what I want. Without I, myself, going through the text file and adding newlines myself. Which defeats the purpose of my goal of just running a python script to automatically do it for me. Is this possible? Or am I crazy for thinking so? Thanks in advance for any help you can provide! I have provided my various attempts to do this below. In this attempt the code works as expected, but instead of it printing Word Count is over 1000 about 14 times. Since, the word count for this text file is 14,000 and something. It only prints once since there is only one line for it to read. text_file = "textfile.txt" numLines = 0 numWords = 0 numChars = 0 with open(text_file, 'r') as file: for line in file: wordsList = line.split() numLines +=1 numWords += len(wordsList) numChars += len(line) if numWords &gt; 1000: print("Word Count is over 1000.") In this next attempt I didn't something similar but still got the same result as above. Instead of seeing it write \n\n\n\n to the text file about 14 times it only happened once at the end of the file. def oldWordCounter(input_file): word_count = 0 with open(input_file, 'r') as f: for line in f: word_count = len(line.split(' ')) print("Word count = %s \n" % word_count) if word_count &gt; 1000: with open(input_file, 'a') as f: f.write("\n\n\n\n") I am sure I am just missing something simple but I am pretty new to python. Even though it kills me to ask a question on here. I am at my w…
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47625788
has comment: http://stackoverflow.com/comment/82208836
type: Question
tagged with: newline
has answer: http://stackoverflow.com/a/47626001
tagged with: python
possible better answer: http://stackoverflow.com/a/47625730
tagged with: python-3.6
has answer: http://stackoverflow.com/a/47625730
type: AnsweredQuestion
has title: How could I add a \n Newline character after every 1000 words in a text file?

http://stackoverflow.com/q/47635412
has answer: http://stackoverflow.com/a/49234524
has body: I am using the Agate library to create a table. Using the command as : table = agate.Table(cpi_rows, cpi_types, cpi_titles) Sample values are as below : cpi_rows[0] [1.0,'Denmark','DNK',128.0,'EU',1.0,91.0,7.0,2.2,87.0,95.0,83.0,98.0,0.0,97.0,0.0,96.0,98.0,0.0,87.0,89.0,88.0,83.0,0.0,0.0,0.0] cpi_tiles ['Country Rank','Country / Territory','WB Code','IFS Code','Region','Country Rank','CPI 2013 Score', 'Surveys Used','Standard Error', '90% Confidence interval Lower', 'Upper','Scores range MIN','MAX','Data sources AFDB','BF (SGI)','BF (BTI)','IMD','ICRG','WB','WEF','WJP','EIU','GI','PERC','TI','FH'] When I run the command, I am getting the error as : ValueError: Column names must be strings or None. Though all the names in cpi_titles are type strings only, I am unable to get the cause for error.
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has title: error creating python table using Agate library
answer count: 1

http://stackoverflow.com/q/47585583
upvote count: 71
downvote count: 0
tagged with: django
linked to: http://stackoverflow.com/q/44745355
favorite count: 0
type: Question
score: 71
has title: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS
tagged with: python
has body: I got an error: "The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS". Error says that TooManyFieldsSent at /api/upload. I wrote in my views.py. def upload(request): id, array = common(request) if request.FILES: file = request.FILES['req'].temporary_file_path() else: return HttpResponse(' NG ') return HttpResponse(' OK ') def common(request): id = json_body.get("access", "0") if id == "": id = "0" s = [] with open(ID_TXT, 'r') as f: for line in f: s += list(map(int, line.rstrip().split(',')[:-1])) array = [s[i:i + 2] for i in range(0, len(s), 2)] return id, array I post access & req data by using POSTMAN like: I think this error is limitation of being able to send file size, so I added the code to settings.py DATA_UPLOAD_MAX_MEMORY_SIZE = 100000000 But the error didn't solved. I read this page: How to avoid "The number of GET/POST parameters exceeded" error? as a reference. How should I fix this?
possible better answer: http://stackoverflow.com/a/65915836
accepted answer: http://stackoverflow.com/a/47585694
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/65915836
has answer: http://stackoverflow.com/a/47585694

http://stackoverflow.com/comment/82162211
score: 0
has text: @tamilan Do these explain better how to do it?
type: Comment
comment on: http://stackoverflow.com/a/47601439
type: AnswerComment

http://stackoverflow.com/q/47604611
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82168278
has body: I am currently working with a large dataset that has lists of daily inventory. I want to compare the inventory over 2 days to see what has changed, and continue that process for an entire month. For example for the month of January, I want to see the change between January 1 and 2, and then January 2 and 3, and so on until I reach January 31st. I was able to write a code to compare inventory between 2 dates. But how do I iterate that process for the code to continue running for the next set of days? I am new to programming and would appreciate any help. In the code below, I created 2 subsets: the 1st for the inventory on October 14 and the 2nd for inventory on October 15. In the 3rd line, I calculate what has changed between the 2 days using the unique identifier in the dataset (image). cars_date_1 = cars_extract_drop[(df['as_of_date'] &gt; '2015-10-14') &amp; (df['as_of_date'] &lt; '2015-10-15')] cars_date_2 = cars_extract_drop[(df['as_of_date'] &gt; '2015-10-15') &amp; (df['as_of_date'] &lt; '2015-10-16')] cars_sold = cars_date_1[~cars_date_1['image'].isin(cars_date_2['image'])]
tagged with: python
has answer: http://stackoverflow.com/a/47621265
has comment: http://stackoverflow.com/comment/82168665
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82168686
has title: Iterating through dates over a specific period of time in python
answer count: 1
tagged with: loops
favorite count: 0

http://stackoverflow.com/q/47636473
has comment: http://stackoverflow.com/comment/82231806
duplicate of: http://stackoverflow.com/q/35249489
tagged with: matplotlib
linked to: http://stackoverflow.com/q/40796117
has comment: http://stackoverflow.com/comment/82235669
has title: matplotlib set size of text box
linked to: http://stackoverflow.com/q/47611399
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/40796117
answer count: 0
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/47611399
linked to: http://stackoverflow.com/q/35249489
downvote count: 0
has body: I want to add text to an axis that will display a title, but need some standardization as it will be used in a process to dynamically create axes. The text has a black background, so I want the width to be set to a number where the longest title will fit. Is there something similar to bbox that can be used? Setup in a nutshell: there's an outergrid of 5 objects, with each having several subplots that make up an inner grid. I don't know if subplots have limited customization, but that's currently what I'm working with. ax = plt.Subplot(fig, inner_grid[:3, :8]) ax.text(x, y, txt, rotation=0, color='white', size=10, fontweight='bold', backgroundcolor='black' ) How do I set a width?
tagged with: python
has comment: http://stackoverflow.com/comment/82237555
score: 2

http://stackoverflow.com/comment/82206017
type: QuestionComment
has text: FYI, you can use `QNetworkAccessManager` and `QNetworkRequest` from `QtNetwork` instead of `urllib2`. You can get an exemple [here](https://gist.github.com/bootchk/9025575)
comment on: http://stackoverflow.com/q/47621525
score: 1
type: Comment

http://stackoverflow.com/comment/82042603
has text: What happens if you move it?
comment on: http://stackoverflow.com/q/47541858
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47578622
score: 1
linked to: http://stackoverflow.com/q/45327767
tagged with: python
has answer: http://stackoverflow.com/a/47593748
type: Question
answer count: 2
has title: Simple tsplot for timeseries
accepted answer: http://stackoverflow.com/a/47584045
upvote count: 1
tagged with: seaborn
possible better answer: http://stackoverflow.com/a/47593748
favorite count: 0
has body: I have below dataframe: Date group count 0 2015-01-12 Category1 27 1 2015-01-19 Category1 2 2 2015-01-26 Category1 31 3 2015-02-02 Category1 20 4 2015-02-09 Category1 24 5 2015-02-16 Category1 16 6 2015-02-23 Category1 18 7 2015-03-02 Category1 15 8 2015-03-09 Category1 29 9 2015-03-16 Category1 6 10 2015-03-23 Category1 19 11 2015-03-30 Category1 27 12 2015-04-06 Category1 6 13 2015-04-07 Category1 7 14 2015-04-13 Category1 25 15 2015-04-20 Category1 9 I want to plot a simple timeseries using seaborn. Just a line chart of count on the Y-Axis, with Date on the X-axis something like this just for example: I thought it would be as simple as: sns.tsplot(data=df, time=df['Date'], value=df['count']) or sns.tsplot(data=df, time='Date', value='count') and following the tsplot() documentation I can't quite get this simple line of code. The datatypes seem fine, but what am i missing here?: #df.dtypes Date datetime64[ns] group object count int64 Side note, does anyone know why tsplot() is being deprecated for? (beyond the vague definition in the docs)
linked to: http://stackoverflow.com/q/47581672
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47584045

http://stackoverflow.com/q/47613403
favorite count: 0
has comment: http://stackoverflow.com/comment/82185318
type: Question
has body: If I have a class like this. class Person(): def __init__(self, name): self._name = name self._name_list = [] if(self._name not in self._name_list): self._name_list.append(self._name) father = Person("Michael") mother = Person("Sharon") &gt;&gt;&gt;self._name_list ["Michael", "Sharon"] How can I do this without creating a global variable? Everytime I instantiate a new person it creates their own list. But I need a list inside the scope of the class that appends a name everytime a new person is created.
tagged with: python
accepted answer: http://stackoverflow.com/a/47613423
possible better answer: http://stackoverflow.com/a/47613491
tagged with: class
has answer: http://stackoverflow.com/a/47613423
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47613491
score: 0
tagged with: list
answer count: 2
tagged with: global
upvote count: 1
downvote count: 1
has title: Mutable variable in a class

http://stackoverflow.com/comment/82285885
type: QuestionComment
comment on: http://stackoverflow.com/q/47662245
type: Comment
score: 0
has text: @WilbusFugu No, I don't mean features. Imagine those pictures are two sheets of paper. You have them edge by edge, they have a scenario where part of one lies on top of the other. The overlapping area is what you blend to make that gradual transition.

http://stackoverflow.com/comment/82236519
type: Comment
comment on: http://stackoverflow.com/a/47639129
has text: `[(key,value) for key,value in d.items()]` ==> `list(d.items())`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82068867
type: QuestionComment
has text: you're actually executing `query1` *twice* - once as a non-query, once via a reader; also - you then redirect, so ... what you write to the response is either going to be discarded (if buffered), or it will fundamentally fail (if not buffered)
score: 0
comment on: http://stackoverflow.com/q/47555711
type: Comment

http://stackoverflow.com/comment/82156016
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47550498
has text: Yes, I know what the shape of the image_tensor placeholder will be.
score: 0

http://stackoverflow.com/comment/82226132
type: AnswerComment
comment on: http://stackoverflow.com/a/47602888
type: Comment
has text: Thank you for your reply. Yes in MEL i would have used that. But sadly i dont really know how to wrap this command into python. Could you give me a complete example?
score: 0

http://stackoverflow.com/q/47568937
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82096003
type: UnansweredQuestion
score: 1
has body: I have a code that displays questions from the database in random order. But I would like shuffling the questions only once per session (if user refreshes the page/url he should get the same questions as earlier). The code that i have used is def platform(request,e,slug): tdetail=get_object_or_404(test_detail,test_id=article) ques=list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) return render(request, 'articles/platform.html',{'ques':ques}) the ques variable takes all the questions in a list and then they are accessed at template.....but when the user refreshes the page the questions reshuffle... How should I do ?
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/82095967
has title: django shuffle query set and remember the pattern of shuffling
has comment: http://stackoverflow.com/comment/82095608
downvote count: 0
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/82095479

http://stackoverflow.com/a/47586819
score: 4
answers question: http://stackoverflow.com/q/47586741
downvote count: 0
type: Answer
upvote count: 4
has body: According to the docs , using 'with' and setting stream to True should get you what you need. with requests.get('http://httpbin.org/get', stream=True) as r: # Do things with the response here.

http://stackoverflow.com/q/47612783
type: Question
score: 0
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: hover
has title: Changing the hover box values in Pygal/Python
has body: I have created a scatterplot in Python using the Pygal library. Now, I want to change the information inside of the boxes that show up when you hover over them (I think it's called the dynamic_print_values???). I want to be able to write an explanation in it.
tagged with: pygal
has answer: http://stackoverflow.com/a/51442564

http://stackoverflow.com/comment/82303311
type: Comment
comment on: http://stackoverflow.com/q/47655600
type: QuestionComment
score: 0
has text: Thanks, it worked with a parameterized query.

sqlite
tags question: http://stackoverflow.com/q/47572672
tags question: http://stackoverflow.com/q/47632288
tags question: http://stackoverflow.com/q/47648983
tags question: http://stackoverflow.com/q/47583295
tags question: http://stackoverflow.com/q/47690138
tags question: http://stackoverflow.com/q/47644919
tags question: http://stackoverflow.com/q/47636631
tags question: http://stackoverflow.com/q/47573423
tags question: http://stackoverflow.com/q/47603191
tags question: http://stackoverflow.com/q/47620487
tags question: http://stackoverflow.com/q/47575305
type: Tag
tags question: http://stackoverflow.com/q/47624931
tags question: http://stackoverflow.com/q/47565490
tags question: http://stackoverflow.com/q/47658519
tags question: http://stackoverflow.com/q/47584530
tags question: http://stackoverflow.com/q/47682946
tags question: http://stackoverflow.com/q/47546804
tags question: http://stackoverflow.com/q/47652769
tags question: http://stackoverflow.com/q/47561078
tags question: http://stackoverflow.com/q/47616490
tags question: http://stackoverflow.com/q/47564702
tags question: http://stackoverflow.com/q/47603959
tag name: sqlite
tags question: http://stackoverflow.com/q/47611305

http://stackoverflow.com/q/47670089
has comment: http://stackoverflow.com/comment/82301324
has answer: http://stackoverflow.com/a/47670315
type: Question
tagged with: if-statement
has body: i use this code to store items of dictionaries in doc variable. This code works fine but I miss the first element of time because of the if statement. def convert(old): time_key = 'Time ' # Save the time time_item = (time_key, old[time_key]) # Add remove it del old[time_key] # Copy remaining items to new dicts and save them in a list return [dict([time_item, item]) for item in old.items()] row = { 'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01', 'Voltage [V]': '221.64', 'Current [A]': '0.08', } new_data = convert(row) #print(new_data) Zeitvalue= "" Device="" Value="" for d in new_data: #print(d) for key, value in d.items(): if key == 'Time ': Zeitvalue = value #print(value) continue else: Device = key Value = value doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value} print("This is doc variable:",doc) # doc vaiable with missed time element SO when i print doc i got this Output: doc: {'Device': 'Voltage [V]', 'Measure': '221.64', 'Time ': ''} # **ISSUE: variable time is missed here, How to fix it ?** doc: {'Device': 'Current [A]', 'Measure': '0.08', 'Time ': '2017-12-01T13:54:04'} doc: {'Device': 'Energy [kWh]', 'Measure': '0.01', 'Time ': '2017-12-01T13:54:04'}
has answer: http://stackoverflow.com/a/47670422
accepted answer: http://stackoverflow.com/a/47670311
has comment: http://stackoverflow.com/comment/82300958
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/47670315
has answer: http://stackoverflow.com/a/47670311
has comment: http://stackoverflow.com/comment/82301736
has comment: http://stackoverflow.com/comment/82299311
has comment: http://stackoverflow.com/comment/82299151
has comment: http://stackoverflow.com/comment/82299141
has title: Missing one element of dictionary cause of If statement
has comment: http://stackoverflow.com/comment/82299039
type: AnsweredQuestion
score: 0
answer count: 3

http://stackoverflow.com/comment/82330664
type: QuestionComment
comment on: http://stackoverflow.com/q/47685425
has text: Use temporary variables.
score: 2
type: Comment

http://stackoverflow.com/comment/108997943
type: AnswerComment
has text: The reason this is not absurd is because there are cases where a dictionary is taking up a lot of memory and all you need to do is process a record and get rid of it, so you are freeing up memory as you process data
comment on: http://stackoverflow.com/a/47695089
type: Comment
score: 0

http://stackoverflow.com/q/47541125
has title: Pocketsphinx Decoder.hyp does not return a Hypothesis object
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/82072095
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82039489
tagged with: python
has comment: http://stackoverflow.com/comment/82039542
has comment: http://stackoverflow.com/comment/82081515
tagged with: cmusphinx
score: 0
has comment: http://stackoverflow.com/comment/82040603
tagged with: pocketsphinx
answer count: 0
has comment: http://stackoverflow.com/comment/82077416
tagged with: speech-recognition
has body: I am programming a speech to text decoder with pocketsphinx. The program runs properly but when I try to do keyword spotting an error occurs. The problem seems to be in the final print, when I try to get hypstr. I get the error. AttributeError: 'NoneType' object has no attribute 'hypstr' How can I fix it? # Decoder config config = Decoder.default_config() config.set_string('-hmm', os.path.join(MODEL_DIR, 'es/es')) config.set_string('-dict', os.path.join(MODEL_DIR, 'voxforge_es_sphinx.dic')) config.set_string('-lm', os.path.join(MODEL_DIR, 'es-20k.lm')) #config.set_string('-keyphrase', 'escucha') #config.set_float('-kws_threshold', 1e+20) #config.set_string('-jsgf', GRAMMAR) decoder = Decoder(config) #decoder.set_jsgf_file('grammar', GRAMMAR) decoder.set_keyphrase('keyphrase', 'escucha') decoder.set_search('keyphrase') # Pyaudio config p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024) stream.start_stream() in_speech_bf = False decoder.start_utt() while True: buf = stream.read(1024, exception_on_overflow = False) if buf: decoder.process_raw(buf, False, False) if decoder.get_in_speech() != in_speech_bf: in_speech_bf = decoder.get_in_speech() if not in_speech_bf: decoder.end_utt() #Print hypothesis print 'Result:', decoder.hyp().hypstr if decoder.get_search() == 'keyphrase': decoder.set_search('lm') else: decoder.set_search('keyphrase') decoder.start_utt() else: break decoder.end_utt() Error Traceback: INFO: ngram_search_fwdtree.c(323): Max nonroot chan increased to 55041 INFO: ngram_search_fwdtree.c(333): Created 233 root, 54913 non-root channels, 30 single-phone words INFO: ngram_search_fwdflat.c(157): fwdflat: min_ef_width = 4, max_sf_win = 25 INFO: kws_search.c(406): KWS(beam: -1080, plp: -23, default threshold 0, delay 10) INFO: cmn_live.c(120): Update from &lt; 40.00 3.00 -1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 &gt; INFO: cmn_live.c(138): Update to &lt; 25.82 -4.30 -6.09 0.55 -…
type: Question
has comment: http://stackoverflow.com/comment/82040810

http://stackoverflow.com/a/47609574
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47609281
downvote count: 0
has comment: http://stackoverflow.com/comment/82177613
has body: You're trying to convert the string "" into a float. "" doesn't make sense as a float, so you'll have to do one of the following. 1 Populate your fields with strings that make sense as floats. For example "0". 2 Set a default value. The following code sets wins as the float value of wins or 0.0 if not applicable. try: wins = float(wins) except: wins = 0.0 3 Specify "" to convert to 0.0: if wins == "": wins = 0.0 else: wins = float(wins)
type: Answer

http://stackoverflow.com/comment/82072180
has text: Possibly... conda is open source, feel free to add a new option! (I am not affiliated with Continuum nor a developer of conda, so my statement does not indicate that the conda developers would find such a feature useful) :-)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47549969

http://stackoverflow.com/a/47608699
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47608523
accepted answer of: http://stackoverflow.com/q/47608523
type: Answer
score: 2
has body: Initialize your variables as lists right below their declaration. By default, when you assign raw input to them for the first time, they become strings. Do something like: global scores, name, difficulties scores=[] name=[] difficulties=[] During global declaration. Need not initialize again within the function.
upvote count: 2

http://stackoverflow.com/q/47555375
downvote count: 0
answer count: 1
has body: I need to add a column to a dataframe and fill it with values from another dataframe, but I do not have a unique ID or key or index that is shared between them. They do have two identifiers in common that make each row unique between them, and I want to try and match on both those columns. Here is an example... Student ID Test Day Student ID Test Day Grade E0304003 Quiz 1 E0304003 Quiz 1 A E3305002 Quiz 1 E0303003 Test 2 A E0303002 Test 1 E0304005 Quiz 2 D E0304004 Quiz 1 E3306001 Test 1 C E0301001 Quiz 1 E0301001 Quiz 1 A E0307002 Test 2 E0307002 Test 2 C E0303003 Test 2 E0308002 Quiz 2 A E0304005 Quiz 2 E0301002 Test 2 C E3306001 Test 1 E3305002 Quiz 1 C E0308002 Quiz 2 E0303002 Test 1 F E0301002 Test 2 E0304004 Quiz 1 C I want to create a third column in the first set that is also Grade, and contains the same values for rows that match the student ID and Test Day in the other dataframe. You can see that the column order in each set doesn't match, and in the real data, there will be missing values, so I need this to be dynamic; it's not as simple as just sorting and then matching. Can I do something like: For row in df_one: if df_one["Student ID"] == df_two["Student ID"] and df_one["Test Day"] == df_two["Day"]: df_one["Grade"] = df_two["Grade"] else: df_one["Grade"] = "Unknown"
tagged with: multiple-columns
favorite count: 0
accepted answer: http://stackoverflow.com/a/47555414
type: Question
has answer: http://stackoverflow.com/a/47555414
tagged with: dataframe
tagged with: python
score: 2
type: AnsweredQuestion
has title: Fill new column in one dataframe with values from another, based on values in two other columns? (Python/Pandas)
tagged with: pandas
upvote count: 2

http://stackoverflow.com/q/47566763
has answer: http://stackoverflow.com/a/47568118
has title: Using multiprocessing to process many files in parallel
score: 0
has comment: http://stackoverflow.com/comment/82091462
answer count: 1
has comment: http://stackoverflow.com/comment/82098065
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has body: I am trying to understand whether my way of using multiprocessing.Pool is efficient. The method that I would like to do in parallel is a script that reads a certain file, do calculation, and then saves the results to a different file. My code looks something like this: from multiprocessing import Pool, TimeoutError import deepdish.io as dd def savefile(a,b,t,c,g,e,d): print a dd.save(str(a),{'b':b,'t':t,'c':c,'g':g,'e':e,'d':d}) def run_many_calcs(): num_processors = 6 print "Num processors - ",num_processors pool = Pool(processes=num_processors) # start 4 worker processes for a in ['a','b','c','d','e','f','g','t','y','e','r','w']: pool.apply(savefile,args=(a,4,5,6,7,8,1)) How can I see that immediately after one process is finished in one of the processors it continues to the next file?
has comment: http://stackoverflow.com/comment/82146652
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/82092323

http://stackoverflow.com/a/47583389
score: 1
type: Answer
has body: I would recommend looking into pandas pivot method (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot). This will allow you to make the dates the column names. From there you can use pd.timedelta (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timedelta.html) to get a datetime for either the day prior or post the current date. You can then use this new datetime object to reindex into the dataframe to get the proper day. I believe there is probably an easier way to do this by using the shift method, but this assumes that you have a value for everyday and that they are in order.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82142642
answers question: http://stackoverflow.com/q/47579250

http://stackoverflow.com/comment/82291358
comment on: http://stackoverflow.com/q/47665889
score: 0
has text: Biology is not my area of expertise; therefore,I am not entire sure what a correct solution for this problem looks like. It is my belief that, X0 = S0 = P0 = 0.1. Regardless, I am not sure how to solve the issue of infinite recusion with dX/dt and dS/dt. @eyllanesc
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47543099
tagged with: cpanel
answer count: 0
has comment: http://stackoverflow.com/comment/82050932
tagged with: cgi
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Flask CGI deploy on cPanel gives error 500
type: UnansweredQuestion
tagged with: apache
has body: Stucked on little thing. I'm getting error 500, when running Flask app on cPanel. [begaeuor@miami ~]$ python -V Python 2.7.5 [begaeuor@miami ~]$ When I open python, I can import Flask package (Flask is installed system-wide). Also I got installed, VirtualEnv, with Flask, but still no success. [begaeuor@miami ~]$ which python /usr/bin/python [begaeuor@miami ~]$ Now. I get into cgi-bin, and created .cgi file: #!/home/begaeuor/flaskdeploy/virtualenv-12.0.7/venv/bin/ from wsgiref.handlers import CGIHandler from app import app CGIHandler().run(app) and also .py file: from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello!" if __name__ == '__main__': app.run(debug=True) Chmod is 0755 on both files. Line endings is Unix (Sublime Text 3) What am I missing?
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82045398
tagged with: flask

http://stackoverflow.com/a/47632347
type: Answer
has body: from bs4 import BeautifulSoup page = """ 1. Start big Make a slam dunk right away. Boom! Just do it! Start strong! If you’re making a list article about poodle outerwear, don’t save the best for last: put that sporty little pool-vest idea right up there at the top. 2. Hook them and hook them good A recent study of lists (included in another article about the top ten research studies, natch), assembled by some guy you’ve never heard of from an obscure European university in his spare time, found that Web readers usually don’t make it past the first few items on a list. Sad, isn’t it? I bet you’re already thinking about stopping. Yes, it sucks to know people have shorter attention spans than an overly-caffeinated Himalayan fruit-fly. Make the first few count, okay? 3. Stay on message Let’s say you’re writing a list article about the top movies starring Naomi Watts that don’t suck. It’s a short list, if you remember anything about King Kong or her early indie films. I see this kind of thing pop up on Fox News and Metacritic once in awhile, and I usually can’t stop myself from clicking on them. You get into sort of a click-trance. In fact, hang on a second. I think there might be one on the top opening acts when The Bieb performs in space. Oh yes there is! Okay, back. So, in your article list of the top movies that use a Meatloaf song in the soundtrack, adding that one from Black Sabbath is just not proper usage. We want Meatloaf and Meatloaf only, people! Besides, Black Sabbath is for sissies. """ soup = BeautifulSoup(page, 'lxml') for content in soup.select('p > strong'): print(content) Output: 1. Start big 2. Hook them and hook them good 3. Stay on message You need to use the .select method for CSS selectors, not the .find You can find the bs4 docs on .select here, and some CSS selector docs from w3schools here.
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47632203
has comment: http://stackoverflow.com/comment/82222375
answers question: http://stackoverflow.com/q/47632203
has comment: http://stackoverflow.com/comment/82222453
score: 1

http://stackoverflow.com/q/47656606
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82272777
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82271493
has comment: http://stackoverflow.com/comment/82271433
has title: could not find a version that satisfies the requirement pywinauto-0.6.3 in windows 10
answer count: 0
has body: I am trying to install python library pywinauto-0.6.3 but m getting error could not find a version that satisfies the requirement pywinauto-0.6.3(from versions:) I am using windows 10.Is any one there who faced same issue please help in in this.
score: 0
tagged with: windows-10
has comment: http://stackoverflow.com/comment/82273341
type: Question
has comment: http://stackoverflow.com/comment/82289214

http://stackoverflow.com/q/47659318
tagged with: keras
has comment: http://stackoverflow.com/comment/82280058
favorite count: 0
has comment: http://stackoverflow.com/comment/82333608
type: Question
has answer: http://stackoverflow.com/a/54961741
score: 5
answer count: 5
possible better answer: http://stackoverflow.com/a/52134045
upvote count: 5
has title: Keras installation
has body: I create an virtual environment in my conda named 'keras_ev' and install the keras in it by conda install keras after that when i activate keras_ev jupyter notebook the notebook does not show my keras_ev environment and i fail to import the keras in my notebook. Does anybody know how to fix this! Thank you
has answer: http://stackoverflow.com/a/56838539
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82334149
tagged with: installation
accepted answer: http://stackoverflow.com/a/47921392
has answer: http://stackoverflow.com/a/53327960
downvote count: 0
has answer: http://stackoverflow.com/a/47921392
has answer: http://stackoverflow.com/a/52134045

http://stackoverflow.com/comment/82332844
type: Comment
score: 1
type: QuestionComment
has text: The [`csv` module](https://docs.python.org/3/library/csv.html) in the standard library is the best way to read CSV files.
comment on: http://stackoverflow.com/q/47686454

http://stackoverflow.com/comment/82201324
type: AnswerComment
score: 1
has text: Might be worth mentioning that you can also have nested for-loops in a list-comprehension for completeness, but great answer!
comment on: http://stackoverflow.com/a/47621580
type: Comment

http://stackoverflow.com/comment/82251008
comment on: http://stackoverflow.com/q/47646030
score: 0
has text: Would it be good to share the content of csv?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82281090
has text: You were quicker ;) I just wanted to add this link, since it describes this common problem: https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
score: 6
type: Comment
comment on: http://stackoverflow.com/a/47660995
type: AnswerComment

http://stackoverflow.com/comment/82243601
type: Comment
score: 0
type: AnswerComment
has text: Hi, All functions are in the same file. However, I'm making use of it from another program now and, yeah, I included the line to call methods from outside Thanks!
comment on: http://stackoverflow.com/a/47610783

http://stackoverflow.com/a/47550892
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82058628
score: 2
has comment: http://stackoverflow.com/comment/82058975
type: Answer
has body: Format it properly: for rows in range(1, 11): print('{:&gt;2d}'.format(rows), 10 * '* ') Yields: 1 * * * * * * * * * * 2 * * * * * * * * * * 3 * * * * * * * * * * 4 * * * * * * * * * * 5 * * * * * * * * * * 6 * * * * * * * * * * 7 * * * * * * * * * * 8 * * * * * * * * * * 9 * * * * * * * * * * 10 * * * * * * * * * * For more on formatting, take a look at this and this.
accepted answer of: http://stackoverflow.com/q/47550832
answers question: http://stackoverflow.com/q/47550832
upvote count: 2
has comment: http://stackoverflow.com/comment/82058532

http://stackoverflow.com/comment/82271357
score: 0
type: AnswerComment
has text: thank you for your help, if you could just help me to understand this line : new_list[-1][new_list[-1].keys()[0]][k]=w , why [-1] and what does .keys() do ?
comment on: http://stackoverflow.com/a/47649957
type: Comment

http://stackoverflow.com/q/47598706
has comment: http://stackoverflow.com/comment/82157040
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47694291
has answer: http://stackoverflow.com/a/47634772
tagged with: python
answer count: 4
has title: Web scraping multiple sites in python
has comment: http://stackoverflow.com/comment/82155591
score: 0
has comment: http://stackoverflow.com/comment/82156602
has answer: http://stackoverflow.com/a/47637906
has answer: http://stackoverflow.com/a/47610626
upvote count: 1
has body: I signed up to this website just to ask this question as I have been searching for hours over multiple days and haven't found anything. I am trying to, within 10 seconds, scrape the 2-3 characters from 5 websites, combine them, and paste them into a box. I have a rough idea of what I would need, but no idea how to go about this. I believe I want to assign variables the scraped contents from a certain website, and then get it to print the combination of these variables for me to copy and paste. I'm not an expert by any means in Python, so if possible, a copy/pasteable script would be great. The websites are: https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D Keeping this up now only because I cannot take it down. Thank you to those who have helped, I hope this helps someone else. Sorry for being dumb

http://stackoverflow.com/a/47663189
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82287621
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82293455
accepted answer of: http://stackoverflow.com/q/47663114
has comment: http://stackoverflow.com/comment/82287510
has body: IIUC (df.rpm!=df.rpm.shift(-1)).cumsum() Out[796]: 0 0 1 1 2 1 3 2 4 2 5 3 Name: rpm, dtype: int32 More info df['loop']=(df.rpm!=df.rpm.shift(-1)).cumsum() df Out[799]: rpm temp loop 0 5000 23 0 1 5000 23 1 2 10000 24 1 3 10000 23 2 4 15000 24 2 5 15000 25 3
answers question: http://stackoverflow.com/q/47663114

http://stackoverflow.com/a/47612064
type: Answer
has body: You can create a class and use __setitem__: import string class Board: def __init__(self, width): self.w = width self.board = [[[] for i in range(width)] for b in range(width)] def __setitem__(self, coords, val): self.board[coords[0]][coords[-1]] = [val] def __repr__(self): return ' '+' '.join(list(string.ascii_lowercase[:self.w]))+"\n"+'\n'.join(string.ascii_lowercase[a]+' '.join(str(i) for i in b) for a, b in enumerate(self.board)) board = Board(4) board[(2, 2)] = 'X' print(board) Output: a b c d a[] [] [] [] b[] [] [] [] c[] [] ['X'] [] d[] [] [] []
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47611949

http://stackoverflow.com/comment/82078640
has text: If you already have a window open, you should use a TopLevel widget to create a pop up box with a snooze button in it.
comment on: http://stackoverflow.com/q/47560444
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/47697240
accepted answer: http://stackoverflow.com/a/47697298
has comment: http://stackoverflow.com/comment/82354316
downvote count: 1
has answer: http://stackoverflow.com/a/47697298
type: AnsweredQuestion
tagged with: if-statement
score: 1
tagged with: python
has body: I am following this: if else in a list comprehension but the following small program is generating a syntax error: def to_rna(dnasequences): xlate = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'} return ''.join(xlate[sequence] for sequence in dnasequences if sequence in xlate.keys() else raise ValueError) The else clause is generating the error. If I remove the else clause it runs, however, I want to raise a ValueError for any input that is NOT a key in my dictionary 'xlate'. NOTE I am working on the rna-transcription problem from exercism.io. I pass 5 unit tests but I fail the three unit tests requiring a ValueError for invalid input.
tagged with: valueerror
has title: if else to raise a ValueError
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82354174
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/4406389
answer count: 1

binary
tags question: http://stackoverflow.com/q/47550126
tags question: http://stackoverflow.com/q/47603964
tags question: http://stackoverflow.com/q/47549176
tag name: binary
tags question: http://stackoverflow.com/q/47684650
tags question: http://stackoverflow.com/q/47553527
tags question: http://stackoverflow.com/q/47546593
tags question: http://stackoverflow.com/q/47612412
type: Tag
tags question: http://stackoverflow.com/q/47598000

http://stackoverflow.com/a/47757771
downvote count: 0
has comment: http://stackoverflow.com/comment/82560586
has comment: http://stackoverflow.com/comment/82560641
has comment: http://stackoverflow.com/comment/82483576
score: 3
has body: Running a session with a feed_dict is indeed pretty slow: Feed_dict does a single-threaded memcpy of contents from Python runtime into TensorFlow runtime. A faster way to feed the data is by using tf.train.string_input_producer + *Reader + tf.train.Coordinator, which will batch the data in multiple threads. For that, you read the data directly into tensors, e.g., here's a way to read and process a csv file: def batch_generator(filenames): filename_queue = tf.train.string_input_producer(filenames) reader = tf.TextLineReader(skip_header_lines=1) _, value = reader.read(filename_queue) content = tf.decode_csv(value, record_defaults=record_defaults) content[4] = tf.cond(tf.equal(content[4], tf.constant('Present')), lambda: tf.constant(1.0), lambda: tf.constant(0.0)) features = tf.stack(content[:N_FEATURES]) label = content[-1] data_batch, label_batch = tf.train.shuffle_batch([features, label], batch_size=BATCH_SIZE, capacity=20*BATCH_SIZE, min_after_dequeue=10*BATCH_SIZE) return data_batch, label_batch This function gets the list of input files, creates the reader and data transformations and outputs the tensors, which are evaluated to the contents of these files. Your scene generator is likely to do different transformations, but the idea is the same. Next, you start a tf.train.Coordinator to parallelize this: with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for _ in range(10): # generate 10 batches features, labels = sess.run([data_batch, label_batch]) print(features) coord.request_stop() coord.join(threads) In my experience, this way feeds the data much faster and allows to utilize the whole available GPU power. Complete working example can be found here.
answers question: http://stackoverflow.com/q/47568998
type: Answer
upvote count: 3

http://stackoverflow.com/q/47585674
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82129270
has comment: http://stackoverflow.com/comment/82129398
linked to: http://stackoverflow.com/q/6587507
tagged with: sudo
type: Question
tagged with: installation
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47585697
has title: sudo install - Python 3?
has comment: http://stackoverflow.com/comment/82129022
score: 0
tagged with: linux
has body: I'm new to Linux and I'm trying to install packages through a Makefile so users can run my Python 3 program. sudo pip install python3-weather-api However, even after uninstalling a previously installed version, the package seems to be going to the 2.7 version of Python. Requirement already satisfied: python3-weather-api in /usr/local/lib/python2.7/dist-packages Then, when I run the program, it can't find the module (it works locally in Python 3 just fine). SystemExit: 1 Traceback (most recent call last): File "project.py", line 11, in &lt;module&gt; from weather import Weather ImportError: No module named 'weather' Is there a way I can point the original installation so when I run python3 project.py it can find the module? Thanks very much!

http://stackoverflow.com/q/47646371
has answer: http://stackoverflow.com/a/47646406
favorite count: 0
type: Question
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47646527
has answer: http://stackoverflow.com/a/47646570
duplicate of: http://stackoverflow.com/q/27974126
tagged with: python
has body: How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me. def combo(w, l): lst = [] for i in range(len(w)): if l == 1: lst.append(w[i]) for c in combo(w[i+1:], l-1): lst.append(w[i] + c) return lst comb=map(list,combo('12345',3)) above code is to get the combinations of string it gives correct output: ['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
has title: possible all combinations of list of length n in python without itertools
tagged with: python-3.x
tagged with: python-2.7
linked to: http://stackoverflow.com/q/8371887
upvote count: 2
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/82090471
comment on: http://stackoverflow.com/a/47564786
has text: It would be O(log n) if we had O(1) arbitrary precision arithmetic which we don't.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47683652
has comment: http://stackoverflow.com/comment/82328477
answers question: http://stackoverflow.com/q/47683265
score: 0
has comment: http://stackoverflow.com/comment/82328242
type: AcceptedAnswer
has body: I'm going to assume this is in a function, due to the return statement. You need to collect outputs into a list and then average that at the end. def calc_throws(simulations): throw_list = [] average = lambda x: sum(x)/len(x) for i, money in enumerate(range(0, 2501, 500)): print("{} Euro".format(money), end='') throw_list.append([money, []]) for _ in range(simulations): throws = 0 d = trump.possession(board) while False in d.values(): prevLoc = piece.location piece.move(trump.throw()) throws += 1 if piece.location &lt; prevLoc: money += 200 if board.names[piece.location] in d and d[board.names[piece.location]] == False and money &gt;= board.values[piece.location]: money -= board.values[piece.location] d[board.names[piece.location]] = True throw_list[i][1].append(throws) throw_list[i][1] = average(throw_list[i][1]) return throw_list Rather than a single number, this returns a list of lists like #[[0,20],[500,15],...[2500,3]] (or whatever reasonable numbers are) which gives you the average for each amount of starting money.
has comment: http://stackoverflow.com/comment/82328169
accepted answer of: http://stackoverflow.com/q/47683265
type: Answer

http://stackoverflow.com/q/47637268
has body: I have an https url that has TLSv1.2 certificates, I have updated to Python 2.7.14 from 2.7.9 which should support TLSv1.2 but still doesn't work: &gt;&gt;&gt; import urllib&gt;&gt;&gt; urllib.urlopen(url) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\urllib.py", line 87, in urlopen return opener.open(url) File "C:\Python27\lib\urllib.py", line 213, in open return getattr(self, name)(url) File "C:\Python27\lib\urllib.py", line 443, in open_https h.endheaders(data) File "C:\Python27\lib\httplib.py", line 1038, in endheaders self._send_output(message_body) File "C:\Python27\lib\httplib.py", line 882, in _send_output self.send(msg) File "C:\Python27\lib\httplib.py", line 844, in send self.connect() File "C:\Python27\lib\httplib.py", line 1263, in connect server_hostname=server_hostname) File "C:\Python27\lib\ssl.py", line 363, in wrap_socket _context=self) File "C:\Python27\lib\ssl.py", line 611, in __init__ self.do_handshake() File "C:\Python27\lib\ssl.py", line 840, in do_handshake self._sslobj.do_handshake() IOError: [Errno socket error] [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:661)
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47638230
has title: I have updated to Python 2.7.14 which should support TLSv1.2 but still doesn't work
has comment: http://stackoverflow.com/comment/82233233
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82232934
upvote count: 1
tagged with: python
tagged with: python-2.7
score: 1
answer count: 1
tagged with: ssl
has comment: http://stackoverflow.com/comment/82233929
tagged with: tls1.2

http://stackoverflow.com/comment/82296408
comment on: http://stackoverflow.com/a/47648429
has text: Hey, thanks for the feedback. I will update the answer.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47576775
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82110791
tagged with: python
has body: From what I am aware, Python stores Lists as "arrays" in memory; however, the "array" stores pointers to the PyObject's in the List. I am using hex(id(...)) to view the memory addresses of the List and of all the items in the list. But I also want to see the memory location of the "array" positions. This is my interpreter code so far... &gt;&gt;&gt; def memory_locations_of(value): for index, element in enumerate(value): print("{: &lt;15}{}\n{: &lt;15}{}\n".format("index[" + str(index) + "] ", hex(id(element)), str(element), hex(id(str(element))))) &gt;&gt;&gt; a = ["hello", "world", "!", "!"] &gt;&gt;&gt; a ['hello', 'world', '!', '!'] &gt;&gt;&gt; memory_locations_of(a) index[0] 0x34b4bc0 hello 0x34b4bc0 index[1] 0x4053dc0 world 0x4053dc0 index[2] 0x3616620 ! 0x3616620 index[3] 0x3616620 ! 0x3616620 &gt;&gt;&gt; a[0] = "Hello" &gt;&gt;&gt; a ['Hello', 'world', '!', '!'] &gt;&gt;&gt; memory_locations_of(a) index[0] 0x406e260 Hello 0x406e260 index[1] 0x4053dc0 world 0x4053dc0 index[2] 0x3616620 ! 0x3616620 index[3] 0x3616620 ! 0x3616620 &gt;&gt;&gt; hex(id(a)) '0x3f7cc10' The last 2 lines are the closest memory location that I want. That memory location is the location of the actual List. That should also be the location of the actual a[0] position (or very close to it). I also want to get the real location of a1, a[2], and a[3]. It based on my code they should be at '0x3f7cc10' + "index_offset". Is there an easy way of getting this or is it rather contrived?
has comment: http://stackoverflow.com/comment/82110836
has title: Getting List indexed memory locations. Not value locations but List index locations
score: 0
tagged with: list
tagged with: heap-memory
answer count: 0
has comment: http://stackoverflow.com/comment/82110579
has comment: http://stackoverflow.com/comment/82110560
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82111220
has comment: http://stackoverflow.com/comment/82110592
has comment: http://stackoverflow.com/comment/82111063

http://stackoverflow.com/comment/82076904
type: Comment
has text: I will do that thank you
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47559214

http://stackoverflow.com/q/47572514
tagged with: python-3.6
downvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/82101920
has body: I am new to Python and when writing a loop module i bumped into the problem that I can't to find a way to put a command in the 'loopme' (it just gets ignored and then the script goes on). I hope you guys can help me with my problem. Thanks in advance :D! def loop(loopme): start = 'y' while True: start != 'y' restart = input('restart? (y/n) ') if restart == 'y': start = 'y' elif restart == 'n': break else: print('invalid input') continue loopme #it works with print('hi') if start == 'y': start = 'n'
has comment: http://stackoverflow.com/comment/82102300
type: Question
has answer: http://stackoverflow.com/a/47572636
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
has title: How do I assign a command to a variable

http://stackoverflow.com/q/47663883
upvote count: 0
tagged with: seaborn
accepted answer: http://stackoverflow.com/a/47681316
has comment: http://stackoverflow.com/comment/82287959
has answer: http://stackoverflow.com/a/47681316
downvote count: 1
has comment: http://stackoverflow.com/comment/82287265
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82287229
has comment: http://stackoverflow.com/comment/82291353
tagged with: pandas
answer count: 1
tagged with: python
score: -1
favorite count: 0
has body: This is my Pandas DF structure: Id channel 0 0140268216898719 RIA 2 022427195461267 Wire 3 023552004060340 Ind With more columns that are not important, and more data. I am looking to plot a histogram using seaborn to show frequency of contactId for each channel, however I am failing miserably not matter what I try. The way I see it, I can either group Id by channel and have a bar plot (attempted as follows): df=df['channel'].groupby(['Id']).count() #count occurrences of Id for each channel Results in: channel Ind 174 RIA 60 Wire 77 And tips = sns.load_dataset("df") ax = sns.barplot(x="channel", y="Id", data=tips) HTTPError: HTTP Error 404: Not Found or a histogram of channel vs. frequency of Id, something like the below: sns.distplot(df, kde=False, rug=True) Here I get a plot with Id on x axis and frequency between 0 to 2 on y axis. In other words neither of these options provide the output I need. Can anyone give me a hand to properly plot the initially given data? Thank you!
type: Question
has title: Plot frequency of contact id in channel for a Pandas DF

http://stackoverflow.com/comment/82291010
type: Comment
comment on: http://stackoverflow.com/q/47663641
type: QuestionComment
score: 0
has text: How can i convert my queryset into something that will return report_name_sc from the checkedlist? Displaying the reportlist in my template using a for loop works, but in the for loop on the save it won't. I'll paste my models tomorrow once i can get on my schools network.

http://stackoverflow.com/q/47544151
accepted answer: http://stackoverflow.com/a/47547299
type: AnsweredQuestion
score: 0
tagged with: pytorch
answer count: 1
has title: Calculating Distance in Parameter Space for PyTorch Network
has body: I'm new to PyTorch. I want to keep track of the distance in parameter-space my model travels through its optimization. This is the code I'm using. class ParameterDiffer(object): def __init__(self, network): network_params = [] for p in network.parameters(): network_params.append(p.data.numpy()) self.network_params = network_params def get_difference(self, network): total_diff = 0.0 for i, p in enumerate(network.parameters()): p_np = p.data.numpy() diff = self.network_params[i] - p_np # print(diff) scalar_diff = np.sum(diff ** 2) total_diff += scalar_diff return total_diff Will this work? I keep track of total_diff through time, and am logging it, but it seems to be zero ALWAYS. Even though the model's performance is improving, which confuses me greatly.
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47547299

http://stackoverflow.com/comment/82335675
type: QuestionComment
has text: @VivekKumar I’m passing into the constructor my X feature space with my dummified variables included. I believe it is indeed a df. What is the improvement by passing in df.values as opposed to a data frame?
comment on: http://stackoverflow.com/q/47682681
score: 0
type: Comment

http://stackoverflow.com/comment/121616518
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47547897
has text: pyminizip doesn't work with in-memory files. If you need in-memory functionality, use pyzipper.
type: Comment

http://stackoverflow.com/a/47616045
has comment: http://stackoverflow.com/comment/82197600
score: -2
type: Answer
has body: Extend your models with django.db.models.Model then it will have some unique field in it, say id. Please refer to documentation here
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/47614596

http://stackoverflow.com/q/47655932
tagged with: python
has comment: http://stackoverflow.com/comment/82272430
has body: I've got a pandas dataframe where each column represents the y values of a descending line from 1 to 0 and the indexes represent the x values. Now I'm interested in finding the intersection points between these lines and a given constant (linearly interpolated). Example of the desired output: &gt;&gt;&gt; df = pd.DataFrame({'y1': [1, .7, .4, .1, 0], 'y2': [1, .9, .7, .3, 0], 'y3': [1, .6, .3, .2, 0], 'y4': [1, .7, .5, .3, 0]}, index=[0, 10, 20, 30, 40]) &gt;&gt;&gt; xs = get_intersection(df, .5) &gt;&gt;&gt; xs {'x1': 16.6667, # = scipy.interpolate.interp1d([.7, .4], [10, 20])(.5) 'x2': 25.0, # = interp1d([.7, .3], [20, 30])(.5) 'x3': 13.3332, # = interp1d([.6, .3], [10, 20])(.5) 'x4': 20} # No interpolation required My data consists of roughly 400 rows and 50.000 columns. possible solution: I found this SO answer that finds the intersection points between two lines with the following method: idx = np.argwhere(np.diff(np.sign(f - g)) != 0).reshape(-1) + 0 I think this can be adjusted to work with my dataframes, but I'm not sure how to proceed from here: &gt;&gt;&gt; idx = np.argwhere(np.diff(np.sign(df - .5), axis=0) != 0) &gt;&gt;&gt; idx array([[1, 0], [1, 2], [1, 3], [2, 1], [2, 3]], dtype=int64) Since people seem to misunderstand the question, I'm interested in finding these points: Which can be found by linearly interpolating the two nearest points. Solution: B. M. gave me a step in the right direction: def get_intersection(df, c): dfind = len(df) - df.loc[::-1].apply(np.searchsorted, args=(c,), raw=True) result = {} for i, v in enumerate(dfind): result[df.columns.values[i]] = interp1d([df.iloc[v][i], df.iloc[v - 1][i]], [df.index[v], df.index[v - 1]])(.5) return result &gt;&gt;&gt; get_intersection(df, .5) {'y1': array(16.666666666666668), 'y2': array(25.0), 'y3': array(13.333333333333332), 'y4': array(20.0)}
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/47657584
score: 1
upvote count: 1
answer count: 1
tagged with: line-intersection
linked to: http://stackoverflow.com/q/28766692
has comment: http://stackoverflow.com/comment/82270295
has title: Pandas columns line intersection
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82270196
has comment: http://stackoverflow.com/comment/82271312
has answer: http://stackoverflow.com/a/47657584

http://stackoverflow.com/comment/82182513
has text: My run_query function works fine, I was calling it but i don't know why it doesn't work.
score: 0
comment on: http://stackoverflow.com/a/47611908
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82314568
type: Comment
score: 0
type: QuestionComment
has text: with `im.shape = (335, 500, 3)` , `dxy.shape is (335000, 167500)` . I don't know so huge screens :) . Probably not images.
comment on: http://stackoverflow.com/q/47677065

http://stackoverflow.com/q/47644042
answer count: 1
has answer: http://stackoverflow.com/a/49140118
type: Question
tagged with: opencv
type: AnsweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: ellipse
score: 0
has title: cv2.fitEllipse creates an ellipse totally different from what it should be
has body: I want to fit ellipses around different clusters. Until now, I used cv2.fitEllipse and it worked fine. But I discovered a problem with one ellipse (out of more than 100). Here is a sample of code that reproduces the unexpected behavior. import numpy as np import cv2 import itertools import matplotlib.pyplot as mpl test=np.zeros((40,40)) test[27,12]=1 test[28,11:13]=1 test[29,11:14]=1 test[30,10:14]=1 test[31,11:14]=1 test[32,12:14]=1 test[33,13]=1 def getContours(clusters): map_contour=np.ones(clusters.shape).astype(np.uint8) int_cnts=[] for label in np.unique(clusters): # if the label is zero, we are examining the 'background' if label == 0: continue mask = np.zeros(test.shape, dtype="uint8") mask[clusters == label] = 255 cnts, hierarchy = \ cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) int_cnts.append(cnts) c = max(cnts, key=cv2.contourArea) cv2.drawContours(map_contour, cnts, 0, (0, 255, 0), 1) list_contours=list(itertools.chain.from_iterable(int_cnts)) return list_contours, map_contour list_test,map_test=getContours(test) info=np.zeros((len(list_test),5)) map_ellipse=np.ones(test.shape).astype(np.uint8) for index,cnt in enumerate(list_test): ellipse=cv2.fitEllipse(cnt) info[index,0:2],info[index,2:4],info[index,4] = ellipse cv2.ellipse(map_ellipse,ellipse,(255,0,0)) print cnt print ellipse mpl.contourf(map_ellipse) mpl.contour(test) mpl.show() cnt gives: array([[[12, 27]], [[11, 28]], [[11, 29]], [[10, 30]], [[13, 33]], [[13, 29]], [[12, 28]]], dtype=int32) ellipse is: ((23.71430015563965, -20.397018432617188), (8.957982063293457, 98.63383483886719), 0.0) As you can see if you copy/paste and run the code above, the top of the ellipse (cut in half) appears to be totally disconnected from the zone that it is supposed to represent (top left). I have no idea what is wrong is the code, especially since it works for other forms in the same picture. What is causing this issue? Edit: It seems that the ellipse is much better placed and sized (al…
accepted answer: http://stackoverflow.com/a/49140118

http://stackoverflow.com/q/47672435
has title: Python script doesn't execute bash commands in cron job
tagged with: python
type: AnsweredQuestion
has body: I have written Python script which I want to execute everyday on my server (Cent OS). I need to execute some bash commands directly from my Python script. Everything works fine when I run the script directly from terminal, but bash commands are not executed when cron job executes the script, although the script does the rest of it is job (inserting to database etc). My crontab looks as follows: 00 20 * * 1-5 /home/skanydok/script.sh script.sh contains #!/bin/bash python /home/skanydok/serverBarcodeScanner.py I have several methods which are meant to move, copy or delete files from server, an example method looks as follows: def copyBackup(): cmd = "cp -r SKANY_DOKUMENTOW_" + str(now)[:10] + '_' + str(random) + " ./backupy" call(cmd.split(" ")) Also I use this code to save all output from method print to a log file: class Logger(object): def __init__(self): self.terminal = sys.stdout self.log = open("./backupy/log.txt", "a") def write(self, message): self.terminal.write(message) self.log.write(message) sys.stdout = Logger() The log.txt file is not created, all methods which are supposed to execute commands like cp, mv, rm etc. does not work, although they work fine when executing script on server with: python /home/skanydok/serverBarcodeScanner.py I think there must be something in the water with cron jobs, all help would be much appreciated.
tagged with: bash
tagged with: cron
accepted answer: http://stackoverflow.com/a/47672678
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82303866
answer count: 1
tagged with: shell
upvote count: 1
has comment: http://stackoverflow.com/comment/82311885
favorite count: 0
type: Question
tagged with: linux
has answer: http://stackoverflow.com/a/47672678

http://stackoverflow.com/comment/82173371
comment on: http://stackoverflow.com/q/47606877
has text: @csharpcoder Sorry, but it took me a few to respond since I was trying to answer someone else. Please come back if you don't mind and have a look.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82097965
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47569312
type: AnswerComment
has text: In which case you need to show how and where you're iterating over the choices.

http://stackoverflow.com/a/47652977
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47652022
type: Answer
score: -1
has body: I would approach this with a groupby statement import pandas years_of_interest = [2010, 2011, 2012, 2013, 2014, 2015, 2016] data = {'Claim Number': ['1234x', '2345x', '34567x', '78910x', '87911x', '98732x'], 'Month': [1, 2, 3, 2, 1, 7], 'Year': [2010, 2010, 2013, 2014, 2015, 2015]} df = pandas.DataFrame(data).set_index('Claim Number'): grouper = df.groupby('Year') for year, data in grouper: if year in years_of_interest: q1_data = data[df.Month &lt;=3] # Do your other work and save

http://stackoverflow.com/comment/129529480
has text: This was a huge help
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/66737062
type: Comment

http://stackoverflow.com/q/47623565
tagged with: numpy
type: AnsweredQuestion
score: 0
tagged with: apache-spark
answer count: 1
has body: I have a dataframe: index | Distribution | +-----+--------------------+ | 0| [1, 2, 0 ] | | 1| [1, 5, 0 ] | | 2| [1, 9, 0 ] | ... and a list: a = [1, 0, 0] Now I want a new column in this data frame which shows the distance between list a and elements in the Distribution column: index | Distribution | distan | +-----+------------------------+ | 0| [1, 2, 0 ] | 2 | | 1| [1, 5, 0 ] | 5 | | 2| [1, 9, 0 ] | 9 | ... I tried to use numpy.linalg.norm() But I dont know how to loop it into this dataframe. May I ask how to do this? Thanks a lot!
type: Question
tagged with: apache-spark-sql
accepted answer: http://stackoverflow.com/a/47623780
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47623780
has title: Spark: Compare the similarity

http://stackoverflow.com/comment/82215218
score: 0
comment on: http://stackoverflow.com/a/47628862
type: Comment
type: AnswerComment
has text: For me this gives cheese 1, dwadaw 3, cheese dwa. I think it's copying AD and FA and cheese 1 does not appear.

http://stackoverflow.com/a/47558692
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82080877
answers question: http://stackoverflow.com/q/47558503
has comment: http://stackoverflow.com/comment/82075185
has comment: http://stackoverflow.com/comment/82075281
score: 3
has body: When your code hits the line quiz(f), no f has been defined. At that point in your code, only one thing has happened -- a function name quiz has been defined. That's the only identifier you can refer to at that point in your code. You have declared function quiz to accept a parameter, but it makes no use of that parameter. The correct definition would be def quiz().
type: Answer
has comment: http://stackoverflow.com/comment/82081716

url
tags question: http://stackoverflow.com/q/47584413
tags question: http://stackoverflow.com/q/47612023
tags question: http://stackoverflow.com/q/47666302
tags question: http://stackoverflow.com/q/47602282
tag name: url
tags question: http://stackoverflow.com/q/47615802
tags question: http://stackoverflow.com/q/47638142
tags question: http://stackoverflow.com/q/47660924
tags question: http://stackoverflow.com/q/47608619
type: Tag

http://stackoverflow.com/comment/82182718
score: 0
has text: @juanpa.arrivillaga, at Tom Karzes - wrapping the range() with list() was my attempt to copy the 'i' variable. I know that it is not good to place list() around range() but I was hoping that iterating through a list as opposed to iterating through a generator could fix the problem...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47602645

http://stackoverflow.com/q/47614961
has answer: http://stackoverflow.com/a/47615008
has body: While converting from python 2.x -> python 3.x, I found this change in the behavior of the built-in max function. I didn't find it documented in any of the standard locations for migration issues. https://eev.ee/blog/2016/07/31/python-faq-how-do-i-port-to-python-3/ http://python-future.org/compatible_idioms.html How do I fix this? Python 2.x: In [1]: max([None, None, None]) In [2]: Python 3.x: In [3]: max([None, None, None]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-3-f82c85b9875c&gt; in &lt;module&gt;() ----&gt; 1 max([None, None, None]) TypeError: '&gt;' not supported between instances of 'NoneType' and 'NoneType'
has comment: http://stackoverflow.com/comment/82188487
accepted answer: http://stackoverflow.com/a/47615008
has comment: http://stackoverflow.com/comment/82188434
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82188358
has comment: http://stackoverflow.com/comment/82188550
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82188367
tagged with: python
has title: max() fails in python2 -> python3 conversion with `>` not supported
linked to: http://stackoverflow.com/q/26575183
has answer: http://stackoverflow.com/a/47616218
has comment: http://stackoverflow.com/comment/82188445
possible better answer: http://stackoverflow.com/a/47616218
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/82188538
linked to: http://stackoverflow.com/q/13795758
has comment: http://stackoverflow.com/comment/82188499

http://stackoverflow.com/a/47647018
has body: str = "this is string example....wow!!! this is really string" print(str.replace("is", "was")) Here's an example of how to correctly use the replace function. This replaces all the is's with was's. It's hard to see what you're trying to do but use this as a guide.
answers question: http://stackoverflow.com/q/47646954
score: 0
type: Answer

http://stackoverflow.com/q/47607115
has answer: http://stackoverflow.com/a/47607525
has comment: http://stackoverflow.com/comment/82172617
linked to: http://stackoverflow.com/q/3220404
has answer: http://stackoverflow.com/a/73144816
has comment: http://stackoverflow.com/comment/82172602
has title: Where are raspberryPi python packages installed?
favorite count: 0
has comment: http://stackoverflow.com/comment/82172777
type: Question
linked to: http://stackoverflow.com/q/10763440
tagged with: raspberry-pi
has body: I was given a raspberry pifor my birthday and decided to make an alarm clock out of one. I wrote all the code on my PC, works completely fine and expected but I'm having slight issues with installing packages on the raspberry pi. When I open the terminal, I'm in the directory "home/pi". I then run the command sudo easy_install -U schedule which installs fine, I then try to run my code which is stored in "home/pi", but get an error on: Traceback (most recent call last): File "/home/pi/LED.py", line 1, in &lt;module&gt; import schedule ImportError: No module named 'schedule' any tips? I've also installed schedule via pip in the same directory - pip install schedule which installs perfectly fine. #!/usr/bin/python import schedule import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) time.sleep(5) GPIO.output(18, GPIO.LOW) GPIO.cleanup()
has comment: http://stackoverflow.com/comment/82172677
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82172555
has answer: http://stackoverflow.com/a/63948043
has comment: http://stackoverflow.com/comment/82172805
has comment: http://stackoverflow.com/comment/82172597
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82172841
tagged with: linux
answer count: 3
has comment: http://stackoverflow.com/comment/82172747
downvote count: 0
has comment: http://stackoverflow.com/comment/82172727

http://stackoverflow.com/comment/82415994
score: 0
type: Comment
type: QuestionComment
has text: Yes, but that directory is empty.
comment on: http://stackoverflow.com/q/47683541

http://stackoverflow.com/comment/82053196
has text: how can i make the call from template
type: Comment
comment on: http://stackoverflow.com/q/47548076
type: QuestionComment
score: 0

http://stackoverflow.com/q/47583819
has body: I am trying to find a way to safely stop my running watchdog event handler. My function is getting a command parameter, if a command is to stop watchdog event observer, then it should stop the event and listener as long as it completes its task safely which means that I do not want to interrupt the task. I would appreciate if you provide supports on that issue. Thank you. UPDATE:1 I tried to follow library documentation, my implementation was like below: observer.schedule(event_handler, this_cfg.inbound_folder_path) observer.start() print('Listening {} folder..........'.format(this_cfg.inbound_folder_path)) try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() After that I found an attribute in observer class, and changed the implementation as below: observer.schedule(event_handler, this_cfg.inbound_folder_path) observer.start() print('Listening {} folder..........'.format(this_cfg.inbound_folder_path)) try: while (observer.event_queue.unfinished_tasks != 0 and stop_signal!=True): time.sleep(1) observer.stop() observer.join() except KeyboardInterrupt: observer.stop() What do you think about my approach? I would appreciate if you know a better solution. Thank you
answer count: 0
tagged with: python-watchdog
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: watchdog
has title: How to safely stop watchdog observer?
has comment: http://stackoverflow.com/comment/82150649
has comment: http://stackoverflow.com/comment/82160148
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82152711
has comment: http://stackoverflow.com/comment/82126542

http://stackoverflow.com/q/47608506
type: AnsweredQuestion
has title: Issue in using win32com to access Excel file
score: 15
has comment: http://stackoverflow.com/comment/118310897
linked to: http://stackoverflow.com/q/65315188
linked to: http://stackoverflow.com/q/63616011
has answer: http://stackoverflow.com/a/61842925
has comment: http://stackoverflow.com/comment/82176011
downvote count: 0
answer count: 7
possible better answer: http://stackoverflow.com/a/51993846
has answer: http://stackoverflow.com/a/54540842
has body: everyone! I have been using the win32com.client module in Python to access cells of an Excel file containing VBA Macros. A statement in the code xl = win32com.client.gencache.EnsureDispatch("Excel.Application") has been throwing an error: AttributeError: module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x6' has no attribute 'MinorVersion' Has anyone faced a similar situation and, if yes, what can a possible remedy for this? (I've had a look at the source code for win32com on GitHub, but haven't been able to make much sense from it.)
has answer: http://stackoverflow.com/a/51993846
linked to: http://stackoverflow.com/q/57488885
favorite count: 0
linked to: http://stackoverflow.com/q/40892952
type: Question
upvote count: 15
linked to: http://stackoverflow.com/q/52889704
has answer: http://stackoverflow.com/a/74277808
tagged with: win32com
accepted answer: http://stackoverflow.com/a/47612742
has answer: http://stackoverflow.com/a/55256887
tagged with: python
has answer: http://stackoverflow.com/a/47612742
tagged with: excel
has answer: http://stackoverflow.com/a/61532508

http://stackoverflow.com/q/47629877
has answer: http://stackoverflow.com/a/47630082
score: 2
upvote count: 2
type: AnsweredQuestion
has title: How to execute awk command inside python
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/16675211
has comment: http://stackoverflow.com/comment/82217896
linked to: http://stackoverflow.com/q/30105904
tagged with: awk
possible better answer: http://stackoverflow.com/a/47630082
has body: I am trying to run the following awk command inside python but I get a syntax error related to the quotes: import subprocess COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 &gt;= 80) {printf "Warning! Space usage is %d%%", $5}}" subprocess.call(COMMAND, shell=True) I tried to escape the quotes but I am still getting the same error.
favorite count: 0
has answer: http://stackoverflow.com/a/60890791
type: Question
has comment: http://stackoverflow.com/comment/82217838
has comment: http://stackoverflow.com/comment/82217767
has answer: http://stackoverflow.com/a/47630196
accepted answer: http://stackoverflow.com/a/47630196
tagged with: python
has comment: http://stackoverflow.com/comment/82217858

http://stackoverflow.com/a/47632918
answers question: http://stackoverflow.com/q/47632891
has body: You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)
has comment: http://stackoverflow.com/comment/82223579
has comment: http://stackoverflow.com/comment/82223716
type: Answer
has comment: http://stackoverflow.com/comment/82223677
score: -2
downvote count: 3
has comment: http://stackoverflow.com/comment/82223658
has comment: http://stackoverflow.com/comment/82223787
upvote count: 1

http://stackoverflow.com/comment/82250774
score: 4
has text: Django already has a built-in authentication system. Why are you implementing your own?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47646097

http://stackoverflow.com/comment/117061738
type: Comment
has text: Rather than just posting short comments `you could do this and then this` as an answer, you should illustrate how this can be achieved by for example showing the code implemented in the question. As it is now, this is a comment not an answer. Consider editing your answer to give more details.
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/66212634

http://stackoverflow.com/comment/82186858
has text: I've changed my answer to make it clearer. s.a. Nice card trick b.t.w.
comment on: http://stackoverflow.com/a/47613007
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82301329
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga I know that well and this is precisely what I want to prove. And it seems I cannot prove it using `getsizeof()`. From the question you marked that I duplicated, they indeed say the same thing as I said, i.e. that `getsizeof()` is not efficient ("Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to."). But the accepted answer actually uses` getsizeof()`...
score: 0
comment on: http://stackoverflow.com/q/47670803

http://stackoverflow.com/q/47626744
type: Question
has body: I am using the bottle.py app to connect two pages, an HTML form page and a result page that takes the form responses, which are names, and converts them to a corresponding value that I have paired in a dictionary. This is the HTML code I am trying to link up: Basketball Golf Football And then this is where it takes the choice and converts it to the corresponding value from bottle import request top = request.forms.get('sample') val = d[top] answer = float[val] And then this is my bottle app code from bottle import default_app, route, post, template @route('/') def form(): return template('form.html') @post('/convert') def convert(): return template('result.html') application = default_app() However, when I run this, it says KeyError:None. So at first I thought it was a problem with my dictionary, but when I ran the dictionary by itself, it printed like it should. So then I commented out every section except for the request.forms.get line to see if it was pulling the name, and tried to print the variable, and it said that the variable was undefined, so that's where the problem lies. Does anyone see what the problem in this is?
has answer: http://stackoverflow.com/a/47768862
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: request
favorite count: 0
has title: request.forms.get not working with bottle.py app
tagged with: python
tagged with: bottle

http://stackoverflow.com/comment/82151656
type: QuestionComment
has text: Based on what you're giving us, this is probably the best you can do. That said, generally when you're using long chains of 'if... else...' theres something wrong with the larger design. Those long chains of checks are expensive.
comment on: http://stackoverflow.com/q/47596837
score: 1
type: Comment

http://stackoverflow.com/comment/82192317
score: 0
type: Comment
has text: why it should stop at 38 , any condition for that
type: QuestionComment
comment on: http://stackoverflow.com/q/47617045

http://stackoverflow.com/q/47563103
answer count: 3
tagged with: datetime
has comment: http://stackoverflow.com/comment/82085565
tagged with: python
has title: Why datetime.now() and datetime.today() show time in UTC and not local time on my PC?
upvote count: 14
has body: datetime.now() and datetime.today() return time in UTC on my computer even though the documentation says they should return local time. Here's the script I ran: #!/usr/bin/python import time import datetime if __name__ == "__main__": print(datetime.datetime.now()) print(datetime.datetime.today()) print(datetime.datetime.fromtimestamp(time.time())) and here's the output: 2017-11-29 22:47:35.339914 2017-11-29 22:47:35.340399 2017-11-29 22:47:35.340399 The output of running date right after it is: Wed, Nov 29, 2017 3:47:43 PM Why is my installation returning time in UTC? What can I do get those functions to return local time? PS We are in MST, which is UTC-7. PS 2 I realize there are methods to convert a UTC time to local time, such as those explained in Convert a python UTC datetime to a local datetime using only python standard library?. However, I am trying to understand the cause of the fundamental problem and not looking for a method to patch the problem in my own code. In response to comment by @jwodder: The output of executing print(time.altzone) print(time.timezone) print(time.tzname) is: -3600 0 ('Ame', 'ric')
has comment: http://stackoverflow.com/comment/82085456
has comment: http://stackoverflow.com/comment/82113996
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48715648
linked to: http://stackoverflow.com/q/4563272
accepted answer: http://stackoverflow.com/a/48715648
has answer: http://stackoverflow.com/a/50333163
has answer: http://stackoverflow.com/a/47578455
has comment: http://stackoverflow.com/comment/82085465
downvote count: 1
has comment: http://stackoverflow.com/comment/82089876
score: 13
has comment: http://stackoverflow.com/comment/82084382
has comment: http://stackoverflow.com/comment/82085409
favorite count: 0
has comment: http://stackoverflow.com/comment/82084548
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/40350812
possible better answer: http://stackoverflow.com/a/47578455

http://stackoverflow.com/q/47616756
type: Question
has answer: http://stackoverflow.com/a/47659083
tagged with: transformation
has comment: http://stackoverflow.com/comment/82275417
upvote count: 1
type: UnansweredQuestion
has body: Firstly, thank you for helping I have large pandas DataFrame and I need fast "rank" transformation for each column: 1] if column is only 0-1, do nothing 2] else (for each column): a] find unique values in the column b] sort them c] for each element of the column replace its value with the position in sort-unique "ranking" list optional: d] transform this new values to interval [-0.99, 0.99] e] apply scipy.special.erfinv to each element (to get "normal" like distribution) How can I do this with Pandas, when need to take care about speed.. Thanx
downvote count: 0
answer count: 1
has title: Pandas - fast DataFrame transformation for neural nets ("gausrank")
favorite count: 0
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/82275192
tagged with: dataframe
tagged with: python
tagged with: ranking

http://stackoverflow.com/comment/82177305
type: AnswerComment
score: 0
has text: Ohhh I get it you want me to study this example then apply it to my own code in order for me to solve the problem. That is exactly what I will plan on doing.
type: Comment
comment on: http://stackoverflow.com/a/47609407

http://stackoverflow.com/comment/133159739
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47562412
type: Comment
has text: @DirkSchiller Regarding "It is not possible to import..." _ I did not write clearly enough, I meant when you define a method in another file (so something like `def func(self, args...)`, you can use the `self` argument to do that - `super(type(self), self)`. You don't have to import anything for that, and can't as you note.

imshow
tags question: http://stackoverflow.com/q/47572067
tags question: http://stackoverflow.com/q/47688556
tag name: imshow
type: Tag
tags question: http://stackoverflow.com/q/47632758

instantiation
type: Tag
tags question: http://stackoverflow.com/q/47590922
tag name: instantiation

http://stackoverflow.com/comment/82462727
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47739631
type: AnswerComment
has text: Can you take a look here: https://github.com/huyouare/CS231n/blob/master/assignment1/cs231n/classifiers/linear_svm.py

http://stackoverflow.com/q/47690615
has title: Whats is the correct way to sum different dataframe columns in a list in pyspark?
answer count: 3
tagged with: apache-spark
possible better answer: http://stackoverflow.com/a/47699002
score: 7
downvote count: 0
has answer: http://stackoverflow.com/a/47699002
upvote count: 7
has answer: http://stackoverflow.com/a/61380465
favorite count: 0
accepted answer: http://stackoverflow.com/a/47692552
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/47692552
tagged with: pyspark
tagged with: python
has body: I want to sum different columns in a spark dataframe. Code from pyspark.sql import functions as F cols = ["A.p1","B.p1"] df = spark.createDataFrame([[1,2],[4,89],[12,60]],schema=cols) # 1. Works df = df.withColumn('sum1', sum([df[col] for col in ["`A.p1`","`B.p1`"]])) #2. Doesnt work df = df.withColumn('sum1', F.sum([df[col] for col in ["`A.p1`","`B.p1`"]])) #3. Doesnt work df = df.withColumn('sum1', sum(df.select(["`A.p1`","`B.p1`"]))) Why isn't approach #2. &amp; #3. not working? I am on Spark 2.2
type: AnsweredQuestion

http://stackoverflow.com/q/47580701
tagged with: python
has comment: http://stackoverflow.com/comment/82119165
linked to: http://stackoverflow.com/q/47765551
has comment: http://stackoverflow.com/comment/82127635
favorite count: 0
has comment: http://stackoverflow.com/comment/82118882
type: Question
has comment: http://stackoverflow.com/comment/82118798
tagged with: numpy
has comment: http://stackoverflow.com/comment/82125917
has comment: http://stackoverflow.com/comment/82121684
accepted answer: http://stackoverflow.com/a/47588043
has comment: http://stackoverflow.com/comment/82118920
downvote count: 0
upvote count: 1
has body: I have a pandas dataframe: 'customer_id','transaction_dt','product','price','units' 1,2004-01-02 00:00:00,thing1,25,47 1,2004-01-17 00:00:00,thing2,150,8 2,2004-01-29 00:00:00,thing2,150,25 3,2017-07-15 00:00:00,thing3,55,17 3,2016-05-12 00:00:00,thing3,55,47 4,2012-02-23 00:00:00,thing2,150,22 4,2009-10-10 00:00:00,thing1,25,12 4,2014-04-04 00:00:00,thing2,150,2 5,2008-07-09 00:00:00,thing2,150,43 5,2004-01-30 00:00:00,thing1,25,40 5,2004-01-31 00:00:00,thing1,25,22 5,2004-02-01 00:00:00,thing1,25,2 And I have written the following to apply date range columns: import numpy as np import pandas as pd start_date_period = pd.period_range('2004-01-01', '12-31-2017', freq='30D') end_date_period = pd.period_range('2004-01-30', '12-31-2017', freq='30D') def find_window_start_date(x): window_start_date_idx = np.argmax(x &lt; start_date_period.end_time) return start_date_period[window_start_date_idx] df['window_start_dt'] = df['transaction_dt'].apply(find_window_start_date) def find_window_end_date(x): window_end_date_idx = np.argmin(x &gt; end_date_period.start_time) return end_date_period[window_end_date_idx] df['window_end_dt'] = df['transaction_dt'].apply(find_window_end_date) However this is very slow, so I have been trying to vectorize it: import numpy as np import pandas as pd start_date_period = pd.period_range('2004-01-01', '12-31-2017', freq='30D') end_date_period = pd.period_range('2004-01-30', '12-31-2017', freq='30D') def find_window_start_date(x): window_start_date_idx = np.argmax(x &lt; start_date_period.end_time) return start_date_period[window_start_date_idx] df['window_start_dt'] = find_window_start_date(df['transaction_dt'].values) def find_window_end_date(x): window_end_date_idx = np.argmin(x &gt; end_date_period.start_time) return end_date_period[window_end_date_idx] df['window_end_dt'] = find_window_end_date(df['transaction_dt'].values) However this produces a value error: "Lengths must match to compare". I am new to trying to write vectorized functions…
tagged with: vectorization
has answer: http://stackoverflow.com/a/47763764
possible better answer: http://stackoverflow.com/a/47763764
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47588043
answer count: 3
has answer: http://stackoverflow.com/a/47582020
tagged with: pandas
score: 1
has title: python pandas: vectorized function value error "lengths do not match"

http://stackoverflow.com/q/47596037
tagged with: geo
accepted answer: http://stackoverflow.com/a/47599321
has body: I am trying to fetch Digital Elevation Model data from a WMS (this works) and output an .obj file of the model (this doesn't). It mostly works, and you can see real geologic features in the data, however there are strange spikes where there are triangles connected across rows. Here is my code, to run it you need to install the libraries, create a file called model.obj in the directory you're running it from, and you're good to go. https://pastebin.com/raw/UiMKKhW3
has answer: http://stackoverflow.com/a/47599321
type: Question
tagged with: computational-geometry
tagged with: python
answer count: 1
has title: Delauny Triangulation Overlapping Across Rows
tagged with: mesh
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47622901
accepted answer of: http://stackoverflow.com/q/47614728
type: Answer
answers question: http://stackoverflow.com/q/47614728
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82204913
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82205149
has body: As you may have noticed, each version of Python has its own package hierarchy. So the installation on Python 3.6 will not give you access on 3.4 and 3.5. With that said, there seems to be some problem with the system's standard lib with Python 3.6. One solution to that could be to install without binaries, like this: python3.6 -m pip uninstall psycopg2 python3.6 -m pip install --no-binary :all: psycopg2 To install psycopg2 on 3.4 and 3.5 you would run these with or without the --no-binary option: python3.4 -m pip install psycopg2 python3.5 -m pip install psycopg2
has comment: http://stackoverflow.com/comment/82204850

http://stackoverflow.com/q/47618438
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82195123
score: 1
has answer: http://stackoverflow.com/a/47618470
tagged with: python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82195056
has body: I made this program. What I want to do now, is to make a new method in the class Star_cluster that will count and return all planets in the star cluster that are in danger. In this case, a planet in danger is a planet with a star that has a short lifespan. A star has a short lifespan when it's total mass is more than 9.5 solar masses. class Planet: def __init__ (self, a_str1, a_str2, a_float): self.name = a_str1 self.type = a_str2 self.orbital_period = a_float class Star: def __init__ (self, a_float, a_planet_list): self.total_mass = a_float # in solar masses self.orbiting_planets = a_planet_list # list of Planet-objects class Star_cluster: def __init__ (self): self.star_list = [] # list of Star-objects def add(self, Star): self.star_list.append(Star) My problem is that I don't get how I should combine the values in the different methods to make one for loop. For example, I tried to make something like this: class Star_cluster: def planets_in_danger (self): for i in self.orbiting_planets: if i.total_mass &gt; 9.5: k = self.orbiting_planets.count(i) return k But I can't get this working. I want to understand how I should approach this problem, because I know what to do, but not entirely sure about how to do it the best way. Especially whether to use self and the fact that there are multiple methods involved and just one for loop, confuses me. Could someone point me in the right direction?
accepted answer: http://stackoverflow.com/a/47618470
has title: How to iterate for loop with values in different methods?
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47618651
possible better answer: http://stackoverflow.com/a/47618651

http://stackoverflow.com/q/47558503
has comment: http://stackoverflow.com/comment/82074731
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82074718
tagged with: python
has body: I am working to create a quiz on Python with different difficulty levels. I am trying to use functions so I can keep calling the most frequent part of the code, appending the questions into a list from an external text file. However, I am running into a problem. When attempting to call my function I get the error: NameError: name 'f' is not defined I've tried everything I can think of but if anyone could provide any help, it would be greatly appreciated! Here is the function: def quiz(f): f = open("quiz.txt", "r").read().split('\n') for line in f: f.append(questions) f.close() quiz(f) print(questions) The print(questions) bit is just a way for me to check if the lines have appended to the list.
has comment: http://stackoverflow.com/comment/82074705
has comment: http://stackoverflow.com/comment/82075027
has title: NameError: name 'f' is not defined
has answer: http://stackoverflow.com/a/47558692
score: 1
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/104254125
favorite count: 0
has comment: http://stackoverflow.com/comment/82074928
type: Question
upvote count: 4

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

http://stackoverflow.com/comment/82186741
comment on: http://stackoverflow.com/q/47613832
type: QuestionComment
score: 0
type: Comment
has text: Fowllow this: https://stackoverflow.com/questions/35991403/python-pip-install-gives-command-python-setup-py-egg-info-failed-with-error-c

http://stackoverflow.com/a/56686805
has body: I couldn't find a function for this from Statsmodels. However, this website goes over the maths for generating the confidence interval as well as being the source of the below function: def two_proprotions_confint(success_a, size_a, success_b, size_b, significance = 0.05): """ A/B test for two proportions; given a success a trial size of group A and B compute its confidence interval; resulting confidence interval matches R's prop.test function Parameters ---------- success_a, success_b : int Number of successes in each group size_a, size_b : int Size, or number of observations in each group significance : float, default 0.05 Often denoted as alpha. Governs the chance of a false positive. A significance level of 0.05 means that there is a 5% chance of a false positive. In other words, our confidence level is 1 - 0.05 = 0.95 Returns ------- prop_diff : float Difference between the two proportion confint : 1d ndarray Confidence interval of the two proportion test """ prop_a = success_a / size_a prop_b = success_b / size_b var = prop_a * (1 - prop_a) / size_a + prop_b * (1 - prop_b) / size_b se = np.sqrt(var) # z critical value confidence = 1 - significance z = stats.norm(loc = 0, scale = 1).ppf(confidence + significance / 2) # standard formula for the confidence interval # point-estimtate +- z * standard-error prop_diff = prop_b - prop_a confint = prop_diff + np.array([-1, 1]) * z * se return prop_diff, confint
downvote count: 0
answers question: http://stackoverflow.com/q/47570903
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/q/47607931
answer count: 1
has title: numpy histogram boolean index did not match indexed array along dimension 0; dimension is
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
tagged with: arrays
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47608416
accepted answer: http://stackoverflow.com/a/47608416
has body: I am trying to sky subtract astronomical images by creating histograms of the pixel intensities in each image, and then seting the sky value equal to the intensity of the bin with the highest frequency. Then the idea is to subtract this sky value from each pixel within that frame.IndexError: boolean index did not match indexed array along dimension 0; dimension is 3651469 but corresponding boolean dimension is 3651468 #sciFlat is a list containing three images in array form. sciFlat = np.asarray(sciFlat) minpix = min(sciFlat.flatten()) maxpix = max(sciFlat.flatten()) rng = int(maxpix-minpix) #These are histogram ranges, now loop through each image. #Sky subtract science images. sciSky = [] for i in range(3): hf = np.histogram(sciFlat[i].flatten(), bins=rng, range=(minpix,maxpix)) skyval = hf[1][hf[0] == max(hf[0])] print(skyval) skySub = sciFlat[i] - skyval sciSky.append(skySub) I expect the code to complete successfully as numpy.histogram should return hist (a flattened array of size n) and bin_edges (1D array of length n). IndexError Traceback (most recent call last) 142 hf = np.histogram(sciFlat[i].flatten(), bins=rng, range=(minpix,maxpix)) 143---&gt; **skyval = hf[1][hf[0] == max(hf[0])]** &lt;---- 144 print(skyval) 145 skySub = sciFlat[i] - skyval IndexError: boolean index did not match indexed array along dimension 0; dimension is 3651469 but corresponding boolean dimension is 3651468
score: 2
has comment: http://stackoverflow.com/comment/82174392
type: AnsweredQuestion

http://stackoverflow.com/comment/120681167
comment on: http://stackoverflow.com/a/47665700
has text: @DanielMöller I need an input shape of ndim=5, But my input shape= (18, 64, 1688), so I reshaped it as: data=data.reshape(18, 64, 1688, 1, 1). And pass this to my model that contains conv2D and convLSTM2D layers. But it gives me an error: Input 0 of layer conv_lst_m2d_88 is incompatible with the layer: expected ndim=5, found ndim=6. Full shape received: (None, None, 64, 211, 1, 128). How do I resolve it, kindly guide me, it will be a great favor.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47544027
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47544079
tagged with: for-loop
answer count: 3
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47544387
has body: I am trying to make a program where hollow squares are made based on the user input. The code is running correctly except for one part. Can anyone suggest a way to fix this? My code looks like this: size = int(input("Please enter size of square ")) for row in range(size-1): print("*",end=" ") for column in range(size-1): print("*",end=" ") for i in range(size-2): print(" ",end=" ") print("*") for row in range(size): print("*",end=" ") I want the code to print out like this: For example: size = 4 **** * * * * **** But when I run the code the square comes out as this: For example: size = 4 **** * * * * * **** Can anyone suggest a way to fix this?
favorite count: 0
has title: How to fix issue in Python program printing hollow squares
type: Question
has answer: http://stackoverflow.com/a/47544079
accepted answer: http://stackoverflow.com/a/47544104
tagged with: python
has answer: http://stackoverflow.com/a/47544104

http://stackoverflow.com/a/47669449
has comment: http://stackoverflow.com/comment/82297681
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47669389
has comment: http://stackoverflow.com/comment/82297669
type: Answer
has body: You are simply indexing the array with a list, so center[...] is passed [0,0,0,0,0,1,1], there is no 'double' bracket syntax. Indexing with a list is a NumPy feature; from the Indexing chapter of the documentation: NumPy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array, such as lists, with the exception of tuples; see the end of this document for why this is). You indexed the centers with another sequence, a list in this case, so a new array is created with index 0 repeated, followed by the value of index 1, once. Note that this is not slicing the original array; you are indexing, and a new array with copies of the values is produced (altering values in centers won't be reflected in the new copy).

http://stackoverflow.com/a/47681359
has comment: http://stackoverflow.com/comment/82321754
type: Answer
answers question: http://stackoverflow.com/q/47681303
score: 0
type: AcceptedAnswer
has body: You can concatenate the string with the variable to make your message 1 argument message_to_user("You managed to complete " + levelcounter + " levels",green,0,40) This would fix the function call to make the arguments match the variables
accepted answer of: http://stackoverflow.com/q/47681303
has comment: http://stackoverflow.com/comment/82321785

http://stackoverflow.com/comment/82185818
type: AnswerComment
has text: @SeanMalhotra I updated my answer so that it might help, could you explain a bit more what you need because it's kind of ambiguous?
score: 0
comment on: http://stackoverflow.com/a/47613561
type: Comment

http://stackoverflow.com/q/47633406
has comment: http://stackoverflow.com/comment/82225445
answer count: 1
tagged with: sys
downvote count: 0
score: 4
favorite count: 0
type: AnsweredQuestion
has body: In the Python documentation, it is said that it is possible to intercept the exit call at the outer level. So what does "intercept at the outside level" actually mean here? More specifically, what is meant by intercepting a call?
tagged with: exit
has title: What is meant by intercepting a Python call in the sys.exit documentation?
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/47633515
type: Question
accepted answer: http://stackoverflow.com/a/47633515
tagged with: python-3.x

http://stackoverflow.com/a/47614355
answers question: http://stackoverflow.com/q/47613627
accepted answer of: http://stackoverflow.com/q/47613627
type: AcceptedAnswer
type: Answer
has body: When using StreamFields and StructBlocks, you can define the min_num and/or max_num of how many of those blocks you want the user to be able to create. See StructBlock docs. Example: class MyPage(Page): map = StreamField( MapBlock(max_num=1, min_num=1, required=True) ) This feature was added in 1.12.
downvote count: 1
score: 3
upvote count: 4

http://stackoverflow.com/a/47648764
type: Answer
has comment: http://stackoverflow.com/comment/82299155
score: 0
has body: I'm not certain this is a question for Stack Overflow but here goes my attempt at a reply... You have the basic notions right, though you're mixing the definition of the goal with the implementation when you mention neural nets, there are other ways to get at word embedding for CBOW and skip-gram. The word embedding can then be transferred (called transfer learning usually but in NLP they simply term it the embedding layer, which is standard practice to put as the first layer) to another domain and either kept frozen or tweaked for the more complex NLP task at hand, So... As for your last question, it really depends on the specifics of the task what are you using the tweet distance for? Is it supervised or unsupervised? What is the output space? I think for unsupervised learning of doc2vec for something like clustering for topics a good bet would be to try autoencoders (see Hinton's dimensionality reduction paper) a language model (and taking the last hidden vector) wmd (I think its implemented in gensim) and many others (there are also other BOW like methods that don't use word embedding at all)
answers question: http://stackoverflow.com/q/47643249
has comment: http://stackoverflow.com/comment/82299158
has comment: http://stackoverflow.com/comment/82274419

http://stackoverflow.com/a/47594385
accepted answer of: http://stackoverflow.com/q/47591035
score: 0
answers question: http://stackoverflow.com/q/47591035
type: AcceptedAnswer
type: Answer
has body: As you have already calculated the ratio, I think you are stuck at scaling up the characteristic sublist because its nested. One solution could be this, I believe this is not the most optimized and elegant way of doing it, but it will work. first_list = [8, 12, [1, 2, 3, 4]] second_list = [4, 6, [5, 6, 7, 8]] scaled_second_list = [] ratio = 3 for i in second_list: characteristic = [] if isinstance(i, list): for j in i: characteristic.append(j*2) scaled_second_list.append(characteristic) else: scaled_second_list.append(i*2) print scaled_second_list I hope this helps!

http://stackoverflow.com/comment/82040806
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47541367
has text: The reason to change it is not to have years and months sticking around in a graph that shows a timespan of 50 seconds or so.
score: 0

http://stackoverflow.com/a/47625698
score: 2
accepted answer of: http://stackoverflow.com/q/47625436
type: Answer
has comment: http://stackoverflow.com/comment/82212469
answers question: http://stackoverflow.com/q/47625436
has body: Move Data.to_csv('Google Trend.csv') after time.sleep(9) and change it's mode to a time.sleep(9) Data.to_csv('Google Trend.csv', mode='a') The mode a will append to the end of your csv file rather than overwriting it.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82210729
has comment: http://stackoverflow.com/comment/82209464

http://stackoverflow.com/a/47611966
type: AcceptedAnswer
has body: You forgot to set a layout for your MatplotlibFigure class (remember that it is a QWidget in your case, not a canvas) def __init__(self): super().__init__() #self.layout = QBoxLayout() self.figure = matplotlib.figure.Figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout(self) layout.addWidget(self.toolbar) layout.addWidget(self.canvas)
has comment: http://stackoverflow.com/comment/82182730
has comment: http://stackoverflow.com/comment/82182312
has comment: http://stackoverflow.com/comment/82183404
accepted answer of: http://stackoverflow.com/q/47611871
type: Answer
answers question: http://stackoverflow.com/q/47611871
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/82039586
type: Comment
type: QuestionComment
has text: (1) `plt.savefig` needs to come before `plt.show`. (2) `plt.show()` should be outside the loop. (3) You can create an axes to plot to outside the loop, `ax=plt.gca(); for i in range(1,10): ... df.plot(ax=ax)`
comment on: http://stackoverflow.com/q/47541127
score: 0

http://stackoverflow.com/q/47614815
has answer: http://stackoverflow.com/a/47615206
has title: Merging Two Pandas DataFrames on Year
favorite count: 0
linked to: http://stackoverflow.com/q/46035432
downvote count: 2
answer count: 3
tagged with: pandas
tagged with: dataframe
has body: I'm trying to merge two dataframes together but every time I try the merge I get the following message: TypeError: merge() missing 1 required positional argument: 'right' d = {'year': [2001, 2002], 'wsp': [0.51, 0.42]} df = pd.DataFrame(data=d) d2 = {'year': [2001, 2002], 'age': [50, 60]} df2 = pd.DataFrame(data=d2) join = pd.merge([df, df2], on='year') The output I'm trying to get is: this Any ideas? Thanks!
has comment: http://stackoverflow.com/comment/82189740
has answer: http://stackoverflow.com/a/47614867
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/47614948
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: merge

http://stackoverflow.com/q/47629215
type: Question
tagged with: angularjs
type: UnansweredQuestion
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/8685678
has body: This is my angularJs request: url = root + "/products"; $http.post(url, params) .then(function(response) { console.log('Successfull...'); }); This is my server side headers in python tornado: self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") And this is my option method: def options(self, *args, **kwargs): self.set_status(204) self.finish() Why angularJS sends only an option request and no post request?
score: 0
has answer: http://stackoverflow.com/a/47630863
has comment: http://stackoverflow.com/comment/82217288
has title: AngularJS post request send option request but I've considered server side headers
tagged with: httprequest

http://stackoverflow.com/q/47557594
has comment: http://stackoverflow.com/comment/82072890
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82072883
accepted answer: http://stackoverflow.com/a/47557750
has answer: http://stackoverflow.com/a/47557757
has title: Nested Dictionary Comprehension from a List of Lists in Python 3
has body: edgeList is a list of lists I have this working but its slower than I want: for rowIndex, rowVal in enumerate(edgeList): for colIndex, colVal in enumerate(rowVal): EdgeDict[rowIndex][colIndex] = colVal Would it be faster using dict comprehension? I tried, but got tangled up in the syntax
tagged with: python
score: -1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82072984
possible better answer: http://stackoverflow.com/a/47557757
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47557750
upvote count: 0

http://stackoverflow.com/q/47564787
linked to: http://stackoverflow.com/q/141525
answer count: 1
upvote count: 1
tagged with: python
has title: Obtaining RGB colors
tagged with: rgb
downvote count: 1
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82087748
has answer: http://stackoverflow.com/a/47564946
tagged with: colors
has body: So I was looking how to get a list of RGB colors depending on a desired total of colors to retrieve and I found this piece of code. And there's a part that I can't understand, I already read the notes where the ">>" and "&amp;" operators are bitwise operators but I can't fully understand what they are doing. Can anybody help me on understanding the part where the colors values are been assigned? def getDinstinctRGBColorsList(desiredColors) availableColors = 16000000 inc = availableColors/desiredColors colorsList = {} RGB = 0 count = 0 while count &lt;= desiredColors: RGB = RGB+inc colorBlue = RGB &amp; 255 colorGreen = (RGB &gt;&gt; 8) &amp; 255 colorRed = (RGB &gt;&gt; 16) &amp; 255 colorsList[count] = str(colorRed) + "," + str(colorGreen) + "," + str(colorBlue) count += 1 return colorsList
accepted answer: http://stackoverflow.com/a/47564946
favorite count: 0
type: Question

http://stackoverflow.com/a/47618976
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47618804
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47618804
has body: you are receiving a Unicode json just as the comment says, if you want the output there's no need to convert to normal function. You can simply do something like this: result1 = firebase.get('/Rooms/Room1/2017-11-29/Inspection/Scan-in/Inspector/', None) result2 = firebase.get('/Rooms/Room1/2017-11-29/Inspection/Scan-out/Inspector/', None) result1 = result1["brix"]["Nov 29, 2017 11:20:15 PM"]["Checklist"]["Luggage bench fabric top is clean"] You will be receiving the No string, without the 'u Here's the reference: https://docs.python.org/2/library/json.html Look at the Decoding JSON part, there's the StringIO import, refer there for more information if you haven't read it yet.

http://stackoverflow.com/a/47658745
score: 1
answers question: http://stackoverflow.com/q/47658467
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47658467
has comment: http://stackoverflow.com/comment/82282051
downvote count: 0
type: Answer
upvote count: 1
has body: It is not showing a log scale. The axis just has a label for each point. In matplotlib 2.0 strings were automatically converted to floats internally. This was never the intended usage, but people tended to misuse this to circumvent converting the strings themselves. From matplotlib 2.1 on, strings are interpreted as strings, meaning they are categories and there will be one label per category. In both matplotlib 2.0 and 2.1 you should actually convert your strings to floats if they are meant to be interpreted as numbers before plotting them. lines = np.array(lines).astype(float)

http://stackoverflow.com/comment/82040076
type: Comment
has text: how about string only with spaces ? `if s` will not remove it.
type: AnswerComment
comment on: http://stackoverflow.com/a/47541411
score: 0

http://stackoverflow.com/a/47589082
downvote count: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47588971
score: 2
answers question: http://stackoverflow.com/q/47588971
upvote count: 2
has body: Sort then use drop_duplicates. But make sure to turn the date column into datetime first. df['tenant_date'] = pd.to_datetime(df['tenant_date']) df.sort_values(['tenant_id', 'tenant_date']).drop_duplicates('tenant_id') tenant_id tenant_class_id tenant_date 0 100 10001 2004-01-10 2 101 10001 2016-09-20 3 102 10002 2013-07-12 5 103 10004 2002-05-05

http://stackoverflow.com/comment/114938093
score: 0
type: AnswerComment
type: Comment
has text: I don't think this works the way you imagine. >>> print(*zip((1,2,3), (4,5,6), (7, 8, 9), (10, 11, 12))) (1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12) >>> print(*((1,2,3), (4,5,6), (7, 8, 9), (10, 11, 12))) (1, 2, 3) (4, 5, 6) (7, 8, 9) (10, 11, 12)
comment on: http://stackoverflow.com/a/63273454

http://stackoverflow.com/a/47662002
type: Answer
answers question: http://stackoverflow.com/q/47661395
downvote count: 0
has comment: http://stackoverflow.com/comment/82283475
has comment: http://stackoverflow.com/comment/82283388
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47661395
has body: try this def row_clean(df): for i in range(0, len(df)): if pd.isnull(df.Shape.values[i]): df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1] return df
upvote count: 1
score: 1

http://stackoverflow.com/q/47548722
score: 0
has body: I can't pass a dict of dict between processes with multiprocessing in Python2.7 from multiprocessing import Process, Manager class TestProcess(Process): def __init__(self, d, w): super(TestProcess, self).__init__() self.daemon = True self.d = d self.w = w def run(self): self.d['a'][self.w] = self.w class Test(object): def __init__(self): manager = Manager() self.d = manager.dict() self.d['a'] = {} p = TestProcess(d=self.d, w=1) p.start() p.join() p = TestProcess(d=self.d, w=2) p.start() p.join() def show(self): print(self.d) if __name__ == '__main__': t=Test() t.show() Expecting result: {'a': {1:1, 2:2}}, but got {'a': {}} instead
answer count: 1
has title: passing dict of dict between process
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/47548798
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47548798

http://stackoverflow.com/comment/82165197
has text: maybe use threads.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47603024
type: Comment

http://stackoverflow.com/a/47682097
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47681617
has body: One method of converting graphviz.dot.Digraph to a networkx.Graph is to convert it to a pydotplus.graphviz.Dot object, and convert that into a networkx.classes.multidigraph.MultiDiGraph object which inherets from graph. #-------------------- # Do whatever it is you do to create the graphviz.Digraph object import lightgbm as lgbm # ....... digraph = lgbm.create_tree_digraph(model) print(type(digraph)) # prints &lt;class 'graphviz.dot.Digraph'&gt; #-------------------- # Perform the conversion to networkx import pydotplus import networkx dotplus = pydotplus.graph_from_dot_data(digraph.source) print(type(dotplus)) # prints &lt;class 'pydotplus.graphviz.Dot'&gt; # if graph doesn't have multiedges, use dotplus.set_strict(true) nx_graph = networkx.nx_pydot.from_pydot(dotplus) print(type(nx_graph)) # prints &lt;class 'networkx.classes.multidigraph.MultiDiGraph'&gt; The rest is just for people considering conversion to JSON #-------------------- # Optionally, convert to json import json # must specify whatever node is the root of the tree, here its 'split0' # or you can try list(graph)[0] if you're not sure. data = networkx.readwrite.json_graph.tree_data(nx_graph,root='split0') # data is just a dictionary. Dump results in proper json format. json.dump(data,open(file_path,'w')) Later I found out LightGBM actually has a dump_model method that shortcuts all of this...but I'll leave this here.
type: Answer

http://stackoverflow.com/comment/82327635
type: AnswerComment
has text: Makes logical sense now. Thank you!
type: Comment
comment on: http://stackoverflow.com/a/47683542
score: 0

http://stackoverflow.com/q/47547164
has answer: http://stackoverflow.com/a/47550049
answer count: 1
downvote count: 1
tagged with: python
tagged with: kivy
type: Question
tagged with: python-3.x
tagged with: kivy-language
upvote count: 1
accepted answer: http://stackoverflow.com/a/47550049
has body: I have written some code in Python (test.py) and kivy (test.kv).When i run test.py.then show Test Menu and user submenu.When i click on user then +Add button show.When click on +add then show Number TextBox Type. I am using treeView in number textbox.when i click on select number then it gives error File "kivy/_event.pyx", line 273, in kivy._event.EventDispatcher.init (kivy/_event.c:5375) File "kivy/properties.pyx", line 478, in kivy.properties.Property.set (kivy/properties.c:5171) File "kivy/properties.pyx", line 513, in kivy.properties.Property.set (kivy/properties.c:5882) ValueError: TreeViewLabelAccountGroup.text accept only str if i use rows = [(1, 'Male'), (2, 'Female'), (3, 'Dog')] instead of rows = [(1, 111), (2, 112), (3, 113)] then its working fine. I do not know where I'm making a mistake. If i change text to int then its working but data not showing. if parent is None: tree_node = tree_view_account_group.add_node(TreeViewLabelAccountGroup(text=node['node_id'], is_open=True)) else: tree_node = tree_view_account_group.add_node(TreeViewLabelAccountGroup(text=node['node_id'], is_open=True), parent) test.py import kivy kivy.require('1.9.0') # replace with your current kivy version ! import sqlite3 as lite from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty from kivy.lang import Builder from kivy.uix.dropdown import DropDown from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.button import Button from kivy.uix.recyclegridlayout import RecycleGridLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.popup import Popup from kivy.core.window import Window from kivy.uix.label import Label Window.maximize() from kivy.clock import Clock from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode from kivy.uix.image import AsyncImage import …
favorite count: 0
has title: Python/Kivy : ValueError: TreeViewLabelAccountGroup.text accept only str
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/47577770
has comment: http://stackoverflow.com/comment/82113291
answers question: http://stackoverflow.com/q/47577108
type: Answer
has body: In your code, next_element is a tuple of two tensors, matching the structure of your datasets: i.e. it is a tuple whose first element is an image, and second element is a label. To access the individual tensors, you can do the following: next_element = iterator.get_next() next_image = next_element[0] next_label = next_element[1] # Or, in a single line: next_image, next_label = iterator.get_next() To batch a tf.data.Dataset, you can use the Dataset.batch() transformation. Your commented out code for this should simply work: train_data = train_data.batch(batch_size = 100) test_data = train_data.batch(batch_size = 100)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82116199
downvote count: 0

http://stackoverflow.com/comment/82073245
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47556899
type: Comment
has text: Your first problem is the incorrect use of `shellslash` (cf. `:h syntastic-shellslash`). There are probably others.

http://stackoverflow.com/comment/82157342
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47598200
type: Comment
has text: @Craig yw~ happy coding

http://stackoverflow.com/q/47663839
answer count: 1
tagged with: django
tagged with: lambda
downvote count: 1
favorite count: 0
type: Question
has body: I'm trying to populate my Django project with some random data using factory_boy and faker. However, when I try to create an instance of my UserFactory object I'm getting the error TypeError: () missing 1 required positional argument: 'a'. It seems to have something to do with the fake_date and date_joined attributes and their lambda functions. A couple of the tutorials I've found have laid out using lambda functions in this way for the Factory objects but it isn't working for me. import datetime import factory import faker from dataStoreApp.models import Category, Goal, Transaction from django.contrib.auth.models import User fake = faker.Faker() class CategoryFactory(factory.django.DjangoModelFactory): class Meta: model = Category name = factory.Iterator(['Category1', 'Category2', 'Category3', 'Category4', 'Category5', ], cycle=False) class UserFactory(factory.django.DjangoModelFactory): FACTORY_HIDDEN_ARGS = ('fake_date', ) class Meta: model = User fake_date = factory.LazyAttribute( lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) date_joined = factory.LazyFunction(lambda a: a.fake_date) first_name = factory.LazyAttribute(lambda b: fake.first_name()) last_name = factory.LazyAttribute(lambda c: fake.last_name()) email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com') class GoalFactory(factory.DjangoModelFactory): class Meta: model = Goal class TransactionFactory(factory.django.DjangoModelFactory): class Meta: model = Transaction When running in the python console I get the following errors: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create return cls._generate(enums.CREATE_STRATEGY, kwargs) File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 505, in _generate return step.build() File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 272, in build step.resolve(pre) File "C:\Program…
tagged with: factory-boy
has title: TypeError: <lambda>() missing 1 required positional argument:
tagged with: python
has comment: http://stackoverflow.com/comment/82287917
accepted answer: http://stackoverflow.com/a/47663931
upvote count: 6
has answer: http://stackoverflow.com/a/47663931
type: AnsweredQuestion
score: 5

http://stackoverflow.com/comment/82047244
type: Comment
comment on: http://stackoverflow.com/q/47543909
type: QuestionComment
score: 0
has text: There is no error details as I have to end the task and kill the python.exe manually through Task Manager. It just gets stuck there. With the trace option the logfile just bloats and bloats until I stop the task.

gensim
tags question: http://stackoverflow.com/q/47604717
tags question: http://stackoverflow.com/q/47666699
tags question: http://stackoverflow.com/q/47610985
type: Tag
tag name: gensim
tags question: http://stackoverflow.com/q/47624644

http://stackoverflow.com/a/79160616
type: Answer
has body: You can check this out, it looks simple. You have to include the number as well. num = int(input("Enter a number: ")) for i in range(1, num + 1): if num % i == 0: print(i, end=" ")
score: 0
answers question: http://stackoverflow.com/q/47678112

http://stackoverflow.com/q/47572650
answer count: 1
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47572995
has comment: http://stackoverflow.com/comment/82102243
upvote count: 2
has answer: http://stackoverflow.com/a/47572995
downvote count: 1
has body: I have a dataframe that looks like this(every date row describes the moment of each event occured): date 93286 2017-11-24 20:44:51.571 93287 2017-11-24 20:45:01.571 93288 2017-11-24 20:45:11.664 93289 2017-11-24 20:45:21.664 93290 2017-11-24 20:45:23.758 93291 2017-11-24 20:45:34.071 93292 2017-11-24 20:45:39.164 93293 2017-11-24 20:45:44.664 93294 2017-11-24 20:45:58.664 93295 2017-11-24 20:46:54.774 93296 2017-11-24 20:46:55.571 My goal is to calculate mean times per minute. So I thought I first need to subtract prior date from current date by df['diff'] = df['date'] - df['date'].shift(1) date diff 93286 2017-11-24 20:44:51.571 NaT 93287 2017-11-24 20:45:01.571 00:00:10 93288 2017-11-24 20:45:11.664 00:00:10.093 93289 2017-11-24 20:45:21.664 00:00:10 93290 2017-11-24 20:45:23.758 00:00:02.094 93291 2017-11-24 20:45:34.071 00:00:10.313 93292 2017-11-24 20:45:39.164 00:00:05.093 93293 2017-11-24 20:45:44.664 00:00:05.5 93294 2017-11-24 20:45:58.664 00:00:14 93295 2017-11-24 20:46:58.774 00:00:00.11 93296 2017-11-24 20:46:59.571 00:00:00.797 But now I have no idea how to get a result that shows the average mean time of each minute like: date mean 2017-11-24 20:45:00 8.386625 I tried using pivot_table, but it doesn't work this way. &gt;&gt;&gt; df.pivot_table(index=[pd.Grouper(key='date', freq='1min')],aggfunc='mean') Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "d:\python36-32\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'pivot_table' How could I calculate mean times with with this dataframe?
type: AnsweredQuestion
has title: How can I calculcate mean times in pandas?
tagged with: pandas
score: 1

http://stackoverflow.com/a/47619261
score: 2
answers question: http://stackoverflow.com/q/47618888
upvote count: 2
downvote count: 0
type: Answer
has body: You can define a custom function that is applied to each group. Both input and output are a dataframe: def combine(group): return pd.DataFrame.from_records(itertools.combinations(group.word, 2)) df.groupby('ID').apply(combine) Result: 0 1 ID 1 0 word1 word2 1 word1 word3 2 word2 word3 2 0 word4 word5 3 0 word6 word7 1 word6 word8 2 word6 word9 3 word7 word8 4 word7 word9 5 word8 word9

http://stackoverflow.com/a/47586922
score: 9
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/47586614
downvote count: 0
has body: Looking in the pandas documentation, there is a parameter for read_csv function: skiprows If a list is assigned to this parameter it will skip the line indexed by the list: skiprows = [0,1] This will skip the first one and the second line. Thus a combination of nrow and skiprows allow to read each line in the dataset separately.

http://stackoverflow.com/comment/82170720
score: 0
has text: After my code you can run your code, so you adjust your `date = datelst[i]` (it picks the i-th element of datelst, which contains all dates of 2013. Now you make a for-loop: `for i in datelst:` and you need to indent everything from `api_key` to `print(df)`. So my code comes before this for-loop. Hope you understand it! If not, let me know!
type: Comment
comment on: http://stackoverflow.com/a/47596576
type: AnswerComment

http://stackoverflow.com/comment/82145334
score: 0
has text: @mhawke timsort (the default sort algorithm in Python) has O(n log n) complexity _in the worst case_ only - on already sorted data it's linear.
type: Comment
comment on: http://stackoverflow.com/a/47593707
type: AnswerComment

http://stackoverflow.com/comment/82207902
has text: `spellClassMage` is a string, so your loop over it (`for userinput in ...`) returns single characters. Is that what you expect?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47624751

http://stackoverflow.com/comment/82076873
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47557558
type: QuestionComment
has text: The first thing would be trying with smaller numbers, try limiting the values to 10000, for instance, and check if you can make it work. Does your project need number that big?

http://stackoverflow.com/comment/82040602
type: QuestionComment
type: Comment
score: 0
has text: I do know there is an API for IMDb but I am practicing my web scraping.
comment on: http://stackoverflow.com/q/47540852

http://stackoverflow.com/a/47541942
has comment: http://stackoverflow.com/comment/82041053
type: Answer
has body: array=[1,2,3] is a list, not an array. It is dynamically allocated (resizes automatically), and you do not have to free up memory. The same applies to arrays from the array module in the standard library, and arrays from the numpy library. As a rule, python handles memory allocation and memory freeing for all its objects; to, maybe, the exception of some objects created using cython, or directly calling c modules.
has comment: http://stackoverflow.com/comment/82041129
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47541915
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47541915

http://stackoverflow.com/comment/82321575
score: 0
type: QuestionComment
has text: You really do need to read the [MCVE documentation](https://stackoverflow.com/help/mcve). But to answer, use reduce with a partial function. `from functools import partial, reduce; def f(day, x, y): x.update({y['car']: y['count']}) if y['day'] == day else x; return x; days = {dict_['day'] for dict_ in dict_list}; output = [reduce(partial(f, day), dict_list, {'day': day}) for day in days]`
type: Comment
comment on: http://stackoverflow.com/q/47680089

bounding-box
tags question: http://stackoverflow.com/q/47586587
tags question: http://stackoverflow.com/q/47682830
type: Tag
tag name: bounding-box
tags question: http://stackoverflow.com/q/47595684

http://stackoverflow.com/comment/82126267
comment on: http://stackoverflow.com/q/47584126
score: 0
type: Comment
type: QuestionComment
has text: Sorry, just checked. The igraph module at least according to the docs for R package uses Johnson-Dijkstra. According to Wikipedia, Johnson-Dijkstra is O(EV + V2 log V) whereas Floyd-Warshall is O(V3). But disregarding the differences in time complexity, it just takes a long time. In a way, my (naive) question was whether one could benefit from these efficient algorithms but just for a subset of all possible node pairs.

http://stackoverflow.com/comment/82166226
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47603665
has text: You aren't building a list, why would you use a list comprehension?

http://stackoverflow.com/comment/82175163
has text: I'm totally down with that, but how do I install bs4 on the microsoft 2017 server management studio? couldn't find the answer on google. I even wonder if it CAN be installed
comment on: http://stackoverflow.com/q/47607971
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82175946
type: QuestionComment
has text: I added an answer
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47608112

http://stackoverflow.com/q/47605047
possible better answer: http://stackoverflow.com/a/47851410
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/47679811
has comment: http://stackoverflow.com/comment/82175357
has answer: http://stackoverflow.com/a/47851410
tagged with: python
has comment: http://stackoverflow.com/comment/82175942
has comment: http://stackoverflow.com/comment/82174775
has answer: http://stackoverflow.com/a/47679811
linked to: http://stackoverflow.com/q/43472847
has title: How do I remove the blank spaces in my csv scrapy
has comment: http://stackoverflow.com/comment/82175069
has comment: http://stackoverflow.com/comment/82174573
type: AnsweredQuestion
answer count: 2
linked to: http://stackoverflow.com/q/34485789
score: 1
has comment: http://stackoverflow.com/comment/82168687
has body: How do I remove the blank spaces in my csv? I run: scrapy crawl quotes -o quotes.csv. And output is like that in the picture. I know it's a windows problem as I have to use below code when working with csv's on windows. For example when working with selenium. with open('C:\\fa.csv', 'a+', newline='', encoding="utf-8") as outfile: Scrapy deals with Csv's differently and I launch with scrapy crawl quotes -o quotes.csv There is no: scrapy crawl quotes -o /n quotes.csv Code: import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1/', ] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').extract_first(), 'author': quote.css('small.author::text').extract_first(), 'tags': quote.css('div.tags a.tag::text').extract(), } next_page = response.css('li.next a::attr(href)').extract_first() if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse)
downvote count: 0
has comment: http://stackoverflow.com/comment/82174608
upvote count: 1
has comment: http://stackoverflow.com/comment/82175670
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82175436
has comment: http://stackoverflow.com/comment/82174530
favorite count: 0
has comment: http://stackoverflow.com/comment/82175725
type: Question
has comment: http://stackoverflow.com/comment/82174848
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82175024
has comment: http://stackoverflow.com/comment/82174546

http://stackoverflow.com/comment/82181691
comment on: http://stackoverflow.com/q/47611720
has text: Note: the line `if new_password == new_password2:` is not required, as that line will only be run when they DO equal.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82245553
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47635212
type: Comment
has text: well, posting complete code (with data) of a simple working example would probably help. Another suggestion is to plot the data with the model using your initial parameter values and see if it is even close to a good match to your data.

http://stackoverflow.com/a/76379379
type: Answer
answers question: http://stackoverflow.com/q/47654923
score: 0
has comment: http://stackoverflow.com/comment/134683824
has body: The Heap sort takes on the basis of heap time complexity which amy lead upto O(nlogn) + Time taken to setup the Heap

http://stackoverflow.com/q/47600508
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I'm new to Pandas... and I couldn't find a way to solve this simple problem. How can I take data between [22h to 06h of the next day] both included, compute them to count-min-max-mean, resample the result in a Dataframe by day with custom label like night #1 2017-10-12 22h-06h night #2 2017-10-13 22h-06h etc ? Data comes from a csv file that comes from a temperature probe at a rate of 1 per minute, it is sorted, but the start and end are not always clean and neither does the recording rate. Sometimes it starts at 21:13:00 with a rate of 5 per minute. So I try to work only with date and not count a number of rows. You can find below a small setup which mimics the problem (I use increasing numbers instead of °C values to check the average after compute): import pandas as pd import datetime as dt import numpy as np index = pd.date_range('01/11/2017 21:00:00', periods=10000, freq='min') df = pd.DataFrame(list(range(10000)), columns=['T1'], index=index) df.index.name='Datetime' #df I can extract data from 22h to 06h with between_time df_light = df.between_time('22:00','06:00') #print(df_light.to_string()) #Useful to see the whole list df_light.head() T1 Datetime 2017-01-11 22:00:00 60 2017-01-11 22:01:00 61 2017-01-11 22:02:00 62 2017-01-11 22:03:00 63 2017-01-11 22:04:00 64 And use resample().agg() result = df_light.resample('D', base=0).agg(['count','min','max','mean']).round(2) result.head() T1 count min max mean Datetime 2017-01-11 120 60 179 119.50 2017-01-12 481 180 1619 659.25 2017-01-13 481 1620 3059 2099.25 2017-01-14 481 3060 4499 3539.25 2017-01-15 481 4500 5939 4979.25 first problem resample calculates all the data in the day, i.e [00h01..06h and 22h..23h59] whereas I would like it to calculate from the end of the day until the morning of the next day, i.e [22h..06h of the next day]. In addition I couldn't find a way to make both inclusive. I searched with base argument and closed : {‘right’, ‘left’} but I didn't find anything very convincing. second problem …
tagged with: datetime
has answer: http://stackoverflow.com/a/47603240
tagged with: python
has title: Resample over midnight 00h - compute min, max mean - custom label
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47603240

http://stackoverflow.com/comment/82254050
has text: You can use Selenium for Scrapping. Using that you can send Click Events to all collapsed bars.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47647938
type: Comment

http://stackoverflow.com/q/47633009
upvote count: 3
tagged with: matplotlib
tagged with: histogram
has body: I'm trying to plot a histogram based on monte carlo simulation with 10k iterations. Plotting using plt.plot(price_list) is fine but, the histogram doesn't load or it's taking extremely long(I think). I've been running the code for an hour and gave up after it still doesn't load. I've tried changing the backend to qt5agg and lowering the bins to no avail. The code works if I significantly lower the iteration. I've tried using 100 and the graphs plots just fine. I'm using jupyter notebook to run. Below is the codes I've written. import numpy as np import pandas as pd import pandas_datareader.data as wb import matplotlib.pyplot as plt from scipy.stats import norm %matplotlib inline plt.rc("axes.spines", top=False, right=False) ticker = 'PG' data = pd.DataFrame() data[ticker] = wb.DataReader(ticker, 'yahoo', '2007-1-1')['Adj Close'] log_returns = np.log(data / data.shift(1)) u = log_returns.mean() var = log_returns.var() stdev = log_returns.std() drift = u - (0.5 * var) t_intervals = 250 iterations = 10000 daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations))) s0 = data.iloc[-1] price_list = np.zeros_like(daily_returns) price_list[0] = s0 for t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t] plt.figure(figsize=(20,12)) plt.plot(price_list); plt.figure(figsize=(20,12)) plt.hist(price_list, bins = 20);
has title: Matplotlib Hist can't load or is taking too long?
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: graph-visualization
tagged with: montecarlo
score: 3
answer count: 0

http://stackoverflow.com/q/47594258
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48085965
downvote count: 0
tagged with: django-1.8
score: 1
upvote count: 1
has body: Unable to open uploaded file when using Django1.8, I am facing an error "ValueError: I/O operation on closed file". But this works well and good in Django 1.6: Django1.8 &gt;&gt;&gt;type(in_file) &lt;class 'django.core.files.uploadedfile.TemporaryUploadedFile'&gt; &gt;&gt;&gt;in_file.closed True Django1.6 &gt;&gt;&gt;type(in_file) &lt;class 'django.core.files.uploadedfile.TemporaryUploadedFile'&gt; &gt;&gt;&gt;in_file.closed False def save_to_file(in_file, dest_file, type='w'): try: with open(dest_file, type) as out_file: for line in in_file: out_file.write(line) except Exception as e: print "Error::--{}".format(e) &gt;&gt;&gt;save_to_file(in_file, '/Work/YYY.FLAT') Error::--I/O operation on closed file
answer count: 1
has title: "I/O operation on closed file" error when trying to open uploaded file django 1.8
tagged with: django-forms
tagged with: django-1.6
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/82175431
score: 0
comment on: http://stackoverflow.com/q/47606995
type: Comment
has text: `new_dict = {tuple(k.split()): d[k] for k in d}`
type: QuestionComment

http://stackoverflow.com/q/47612518
tagged with: node.js
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82525446
has body: So I'm just trying to get a GET request to go through from a node.js app to a python app and for some reason the code works when I'm running it in a Jupyter Notebook but not otherwise. Here's the Python code. from http.server import BaseHTTPRequestHandler , HTTPServer class HTTPServer_RequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) print('got a request') server_address = ('localhost', 9000) httpd = HTTPServer(server_address, HTTPServer_RequestHandler) print('running server...') httpd.serve_forever() and here's the node code var request = require('request'); request.get({ uri: 'http://localhost:9000', type:'GET ' }, function(res,err,body){ console.log(res) console.log(err) console.log(body) }); This of course prints an error on the node side, but the interesting thing is that on Jupyter Notebook I get "running server..." output and I also get the "got a request" whenever I run the node, however when I run Python normally I don't get any output at all.
has title: Can't quite get a simple HTTP server to work on python and get requests from node
tagged with: http
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82186520
tagged with: python
tagged with: request

http://stackoverflow.com/comment/82310313
type: Comment
comment on: http://stackoverflow.com/q/47675177
score: 0
has text: Problems are : 1 - the source files are part of a git submodule which does not belong to me. Meaning I can't upstream changes to it, therefore can't "move my current sources into a new subfolder"... 2 - I don't have an Sconscript file and, as a matter of fact, I'd greatly appreciate not to have to create one (I had one makefile, is it not possible to just have one Sconstruct file ?)
type: QuestionComment

http://stackoverflow.com/q/47577828
tagged with: pandas
has comment: http://stackoverflow.com/comment/82114749
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/47578356
upvote count: 1
has answer: http://stackoverflow.com/a/47578356
favorite count: 0
type: Question
has title: Resample by some timeframe
tagged with: python
score: -1
has body: I have dataframe like: Timestamp Sold 10.01.2017 10:00:20 10 10.01.2017 10:01:55 20 10.01.2017 11:02:11 15 11.01.2017 11:04:30 10 11.01.2017 11:15:35 35 12.01.2017 10:02:01 22 How to resample it by hour. Ordinary resample resamples by all hours from first row to last. But what I need is to make timeframe (10-11) and resample it within this timeframe. Last df should be like this: Timestamp Sold 10.01.2017 10:00:00 30 10.01.2017 11:00:00 15 11.01.2017 10:00:00 NAN 11.01.2017 11:00:00 45 12.01.2017 10:00:00 22 12.01.2017 11:00:00 NAN
type: AnsweredQuestion

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/47561142

http://stackoverflow.com/a/47613334
has comment: http://stackoverflow.com/comment/82208254
has comment: http://stackoverflow.com/comment/82208960
score: 0
answers question: http://stackoverflow.com/q/47585268
has comment: http://stackoverflow.com/comment/82208234
has comment: http://stackoverflow.com/comment/82249660
has body: Just return a string representation of the Fraction object. E.g., @route('/') def index(): f = Fraction(3, 4) return str(f) Also (just FYI): # -*- coding:utf-8 -*- is not necessary unless you include non-ascii characters in your source code. EDIT: OP has indicated that s/he wants to return the type of the Fraction object, not its value. In that case just return the type (as a string). @route('/') def index(): f = Fraction(3, 4) return str(type(f)) EDIT #2: OP is (I'm guessing) using a browser to test, and the response is being rendered as html, which is confusing the OP since the page appears blank. To work around this, I suggest returning a text response, like this: from bottle import response @route('/') def index(): f = Fraction(3, 4) response.content_type = 'text/plain' return str(type(f))
has comment: http://stackoverflow.com/comment/82208392
has comment: http://stackoverflow.com/comment/82208434
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47585268
type: Answer

http://stackoverflow.com/q/47593679
has comment: http://stackoverflow.com/comment/82155369
tagged with: word-embedding
tagged with: python
has title: Tensorflow Word Embedding runs too slow on GPU
answer count: 0
has body: EDIT: I can provide some rudimentary run times now: next epoch: 0.5456549558716741 ('time point 0') next epoch: 892.5030143482156 (~14:30min) next epoch: 1757.6139726727963 (~14:30min) Time elapsed: 2622.23 seconds (~14min, total of 44min) These times are with a vocab_size of only 5000 compared to the actual corpus size of 13k... I'm working on a word embedding task in Tensorflow that works with the King James bible as corpus, so it's got a decent size of 13000 something unique words. On my machine (GTX 970), I'm not even getting a print-out of reaching another epoch whereas on the CPU of a friend of mine, the process finished within a few minutes. Could someone shed some light on this mystery? import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from book_helper import Book from collections import Counter from math import sqrt import random as rnd import time %matplotlib notebook book = Book('./pg10.txt') vocab_size = len(Counter(book._book_text)) # 13079 book.create_dictionaries(vocab_size) samples = [x for x in rnd.sample(book._book_text, 10) if x.isalpha()] print('Sample words:\t' + ', '.join(samples)) print('Words2ids:\t' + ', '.join([str(book.words2ids(samples))])) print('Ids2words:\t' + ', '.join(book.ids2words(book.words2ids(samples)))) # hyperparameters batch_size = 128 epochs = 3 lrate = 1 embedding_size = 64 skip_window = 2 noise_samples = 64 X = tf.placeholder(tf.int32, [batch_size], "Input_Placeholder") desired = tf.placeholder(tf.int32, [batch_size, 1], "DesiredOutput_Placeholder") with tf.variable_scope("embeddings"): # create word embedding ru_init = tf.random_uniform_initializer(-1.0, 1.0) embeddings = tf.get_variable("embedding", [vocab_size, embedding_size], initializer=ru_init) # retrieve word ids from embedding embed = tf.nn.embedding_lookup(embeddings, X) with tf.variable_scope("output_layer"): weights1 = tf.get_variable("weights", [vocab_size, embedding_size], initializer=tf.truncated_normal_initializer(1 / sqrt(embedding…
score: 0
has comment: http://stackoverflow.com/comment/82148741
has comment: http://stackoverflow.com/comment/82148476
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82148079
has comment: http://stackoverflow.com/comment/82147909
type: UnansweredQuestion

http://stackoverflow.com/a/47599384
has body: You have to get value inside function which you bind with &lt;&lt;ListboxSelect&gt;&gt; import tkinter as tk # --- function --- def on_selection(event): # here you can get selected element print('previous:', listbox.get('active')) print(' current:', listbox.get(listbox.curselection())) # or using `event` #print('event:', event) #print('widget:', event.widget) print('(event) previous:', event.widget.get('active')) print('(event) current:', event.widget.get(event.widget.curselection())) print('---') # --- main --- root = tk.Tk() listbox = tk.Listbox(root) listbox.pack() listbox.insert(1, 'Hello 1') listbox.insert(2, 'Hello 2') listbox.insert(3, 'Hello 3') listbox.insert(4, 'Hello 4') listbox.bind('&lt;&lt;ListboxSelect&gt;&gt;', on_selection) root.mainloop()
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47598150
accepted answer of: http://stackoverflow.com/q/47598150

http://stackoverflow.com/comment/82323927
comment on: http://stackoverflow.com/q/47682356
has text: This is how i run the code in PyCharm and it works with the exact indentations.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47617555
has body: I have been trying to make a simple dice rolling GUI where you press a button and a dice rolls and gives you the output in a label. When I run my code I get the error that "diceOutput" is not defined. Here is my code: from tkinter import * import random window = Tk() window.title("Dice") def rollDice(): diceOutput = str(random.randint(1,6)) return diceOutput roll = Button(window, text="Roll", command=rollDice) output = Label(window, textvariable=diceOutput) window.mainloop()
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82195074
tagged with: tkinter
upvote count: 1
has title: How do I return variables from a function in Tkinter?
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47618608
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47617598

http://stackoverflow.com/q/47551939
answer count: 1
type: Question
tagged with: performance
has body: I have an excel file which contains two columns and 743914 rows. What I want to do is iterate row by row, and if the combination of the two rows is found for the first time then assign next to it, in a third column, a value. Else the value is the value that I assigned next to this combination the first time it was found. The problem is analogous to trying to build a dictionary where the key is the combination of the two existing rows and the value is the third row. I have written the above code which I have tested for 20 rows and works fine. from openpyxl import load_workbook wb = load_workbook('test.xlsx') dicta = {} i = 0 lista = [] listb = [] ws = wb.active for row in ws.iter_rows(min_row=1, max_col=3, max_row=743914): for cell in row: i += 1 if i%3 != 0: lista.append(cell.value) if i%3 == 0: if lista in listb: cell.value = dicta[tuple(lista)] else: cell.value = i dicta[tuple(lista)] = i listb.append(lista) lista = [] My problem is when I scale up the rows to 743914 it seems to run infinitely and totally unefficiently, as it is already running for 15 hours and hasn't terminated yet.
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/47553035
accepted answer: http://stackoverflow.com/a/47553035
type: AnsweredQuestion
score: 0
has title: Bad performance with big dataset
tagged with: openpyxl

http://stackoverflow.com/q/47596122
tagged with: python-internals
has title: Function call execution speed is faster than non-function call
tagged with: python
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/12590058
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47596181
has body: Function call will always yield some overhead. But why the code below shows that non-function call is slower. Code: import time def s(): for i in range(1000000000): 1 + 1 t = time.time() s() print("Function call: " + str(time.time() - t)) t = time.time() for i in range(1000000000): 1 + 1 print("Non function call: " + str(time.time() - t)) Output: Function call: 38.39736223220825 Non function call: 60.33238506317139
accepted answer: http://stackoverflow.com/a/47596181
downvote count: 0
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/88097513
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47625049
has body: You could at least use apply_along_axis: result = np.apply_along_axis(lambda point: np.outer(point, point), 1, p) Surprisingly, however, this is in fact slower than your method: In [ ]: %%timeit N = int(1e4); p = np.random.random((N, 3)) ...: result = np.apply_along_axis(lambda point: np.outer(point, point), 1, p) 61.5 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [ ]: %%timeit N = int(1e4); p = np.random.random((N, 3)) ...: result = np.zeros((N, 3, 3)) ...: for i in range(N): ...: result[i, :, :] = np.outer(p[i, :], p[i, :]) 46 ms ± 709 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
score: 0
has comment: http://stackoverflow.com/comment/82208035
type: Answer
has comment: http://stackoverflow.com/comment/82208070
has comment: http://stackoverflow.com/comment/82208134
answers question: http://stackoverflow.com/q/47624948

http://stackoverflow.com/a/71654131
type: Answer
answers question: http://stackoverflow.com/q/47684616
score: 0
has body: Go to windows and search for your IDE (e.g. VsCode) Then Go to the folder of your IDE and go to the properties of file that end .exe go to properties -&gt; compatibility -&gt; [✔️] Run this program as an administrator (apply and then Ok)

http://stackoverflow.com/comment/82218198
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47630150
has text: I'm passing {{server.id}} and all the {{server.ServerName}}
score: 0

http://stackoverflow.com/q/47622186
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47622849
possible better answer: http://stackoverflow.com/a/47622244
tagged with: python
type: Question
has body: When I type level4 or level3 or level2 my game does not go to the requested level. It prints the entered level (e.g. level1) and stays on level one. print("Welcome to the maths skills testing machine!") userinput = input("\nAre you ready to test your maths skills?") print("\nWhich level would you like to play?") userinput = input('''Level 1, Level 2, Level 3, Level 4''') if userinput=="level1": level1() elif userinput=="level2": level2() elif userinput=="level3": level3() elif userinput=="level4": level4() def level1(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(1, 10) num_b = random.randint(1, 10) op = random.choice(tuple(ops.keys())) print('{}{}{}=?'.format(num_a, op, num_b)) expected_answer = ops[op](num_a, num_b) user_answer = int(input()) if user_answer == expected_answer: print('Correct') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) else: print('Wrong') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) while user_answer == expected_answer: level1() else: exit() level1() def level2(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(10, 50) num_b = random.randint(10, 50) op = random.choice(tuple(ops.keys())) print('{}{}{}=?'.format(num_a, op, num_b)) expected_answer = ops[op](num_a, num_b) user_answer = int(input()) if user_answer == expected_answer: print('Correct') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) else: print('Wrong') print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) while user_answer == expected_answer: level2() else: exit() level2() def level3(): import operator import random import time start = time.time() ops = {'+': operator.add, '-': operator.sub} num_a = random.randint(50, 100) num_b = random.randint(50, 100) op …
accepted answer: http://stackoverflow.com/a/47622849
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47622244
has title: Python maths game level not changing

http://stackoverflow.com/q/47649915
has body: Below code is for a PIR sensor written in Python. What it should do When the sensor was activate the first time, it should wait for 10 second once and then keep printing "Intruder detected" until the sensor was = 0. what is actually do Rather than waiting 10s once, the code below wait ever 10s when the pir sensor was tigger. Why is that? import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor GPIO.setup(3, GPIO.OUT) #LED output pin while True: i=GPIO.input(11) if i==0: #When output from motion sensor is LOW print "No intruders",i GPIO.output(3, 0) #Turn OFF LED time.sleep(0.1) elif i==1: #When output from motion sensor is HIGH time.sleep(10) #This should be only run once when the pir sensor is trigger print "Intruder detected",i GPIO.output(3, 1) #Turn ON LED time.sleep(0.1)
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82258630
tagged with: python
accepted answer: http://stackoverflow.com/a/47650069
type: Question
has answer: http://stackoverflow.com/a/47650069
has title: Python if loop time.sleep only execute once
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82258344
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82301526
comment on: http://stackoverflow.com/q/47670914
score: 0
type: QuestionComment
has text: if my answer solves your issue, can you accept it? a right tick mark below down vote button
type: Comment

http://stackoverflow.com/comment/82321077
type: AnswerComment
comment on: http://stackoverflow.com/a/47680265
type: Comment
has text: @PTerm2 I added another option with a classmethod. I think that's a better way to achieve what you want.
score: 0

http://stackoverflow.com/q/47642021
tagged with: python
has answer: http://stackoverflow.com/a/47642226
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: error-handling
has body: What's the best way to handle this? I want to create a file and add a record to a database, but if either one fails, I want to undo the other. It looks kind of messy to have a try, except, else with another try, except inside it to handle undoing the first task if the second fails. try: open and write file except: pass else: try: add record to db except: delete file
has title: Python error handling two dependent tasks
has answer: http://stackoverflow.com/a/47642639
type: Question

http://stackoverflow.com/q/47588194
type: UnansweredQuestion
tagged with: sys
tagged with: python
linked to: http://stackoverflow.com/q/6787233
has answer: http://stackoverflow.com/a/47588710
tagged with: bytestream
tagged with: python-2.7
has body: I would like to read a fixed number of bytes from stdin of a python script and output it to one temporary file batch by batch for further processing. Therefore, when the first N number of bytes are passed to the temp file, I want it to execute the subsequent scripts and then read the next N bytes from stdin. I am not sure what to iterate over in the top loop before While true. This is an example of what I tried. import sys While True: data = sys.stdin.read(2330049) # Number of bytes I would like to read in one iteration if data == "": break file1=open('temp.fil','wb') #temp file file1.write(data) file1.close() further_processing on temp.fil (I think this can only be done after file1 is closed)
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/1035340
type: Question
has title: Read N number of bytes from stdin of python and output to a temp file for further processing

http://stackoverflow.com/comment/82192787
type: AnswerComment
has text: __import__(module) File "/app/myproject/wsgi.py", line 20, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi Worker exiting (pid: 9) Shutting down: Master Reason: Worker failed to boot. Process exited with status 3 State changed from starting to crashed
comment on: http://stackoverflow.com/a/47616922
score: 0
type: Comment

http://stackoverflow.com/q/47645842
tagged with: scapy
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47658653
downvote count: 1
favorite count: 0
type: Question
tagged with: netflow
has title: Decode UDP Packet to Netflow
type: UnansweredQuestion
has body: I've come across the Wireshark decode as feature where I can decode UDP packet as CFLOW to get my Netflow data. Is it possible to code a script that decode the UDP Packet and get the Netflow data? Currently I am trying it out using python3-scapy. Where I sniff the interface and retrieve only UDP packet. I am stuck now as I don't know what I should do next. Note: My focus is on Netflow Version 9 Below is my code: from scapy.all import * ## Create a Packet Counter counter = 0 INTERFACE = "&lt;interface_name&gt;" ## Define our Custom Action function def custom_action(pkts): for packet in pkts: if (packet.haslayer(UDP)): # do something , what should i do? if __name__ == "__main__": ## Setup sniff, filtering for IP traffic sniff(iface=INTERFACE, prn = custom_action, store=0)
tagged with: python
score: 0

http://stackoverflow.com/a/47598696
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47589853
has body: Please check the order of the printing statements to confirm that the script is looking for what you exactly want to parse from the HTML code, which is basically targeting this tag: The Dormouse's story. Code: #!/usr/bin/env python from bs4 import BeautifulSoup import re html_doc = """ The Dormouse's story The Dormouse's story The Dormouse's story """ soup = BeautifulSoup(html_doc, 'html.parser') title = soup.find(class_=re.compile("^title"), string="The Dormouse's story") print(title) string = soup.find(str(title), 'html.parser') final_string = soup.find('b') print(final_string) if final_string is not None: print("String found:", final_string) else: print("String not found.") Output: The Dormouse's story The Dormouse's story String found: The Dormouse's story

http://stackoverflow.com/comment/82260784
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47651132
has text: Sure, replace the line `res.append(line.rsplit("\n")[0])` with `res.append(line.split(substring, 1)[1].rsplit("\n")[0])`, that will give the output `['8003']`
type: Comment

http://stackoverflow.com/a/60890791
type: Answer
has body: I was writing a python script for my deployment purpose and one part of the script was to explicitely kill the process if its not stopped successfully. Below is the python code which actually performs Find the processId of the process named myApplication ps -ef | grep myApplication | grep -v grep | awk {'print $2'} and then perform kill -9 PID //where PID is output of earlier command import subprocess import signal def killApplicationProcessIfStillRunning(app_name): p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['grep', app_name],stdin=p1.stdout, stdout=subprocess.PIPE) p3 = subprocess.Popen(['grep', '-v' , 'grep'],stdin=p2.stdout, stdout=subprocess.PIPE) p4 = subprocess.Popen(['awk', '{print $2}'],stdin=p3.stdout, stdout=subprocess.PIPE) out, err = p4.communicate() if out: print 'Attempting to kill '+app_name +' process with PID ' +out.splitlines()[0] os.kill(int(out.splitlines()[0]),signal.SIGKILL) Now invoke the above method as killApplicationProcessIfStillRunning(myApplication) Hope it helps someone.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47629877

http://stackoverflow.com/q/47605702
tagged with: python
has answer: http://stackoverflow.com/a/47609193
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47606195
answer count: 3
possible better answer: http://stackoverflow.com/a/47605827
upvote count: 2
accepted answer: http://stackoverflow.com/a/47609193
has answer: http://stackoverflow.com/a/47605827
downvote count: 0
has title: Preserve content of fig after show() in matplotlib?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82174251
has comment: http://stackoverflow.com/comment/82170291
tagged with: matplotlib
linked to: http://stackoverflow.com/q/21875356
has body: I'm creating a violinplot of some data and afterwards I render a scatterplot with individual data points (red points in example) to three subplots. Since the generation of the violinplot is relatively time consuming, I'm generating the violinplot only once, then add the scatterplot for one data row, write the result file, remove the scatterplots from the axes and add the scatterplots for the next row. Everything works, but I would like to add the option, to show() each plot prior to saving it. If I'm using plt.show(), the figure is shown correctly, but afterwards the figure seems to be cleared and in the next iteration I'm getting the plot without the violin plots. Is there any way to preserve the content of the figure after plt.show()? In short, my code is fig = generate_plot(ws, show=False) #returns the fig instance of the violin plot #if I do plt.show() here (or in "generate_plot()"), the violin plots are gone. ax1, ax3, ax2 = fig.get_axes() scatter1 = ax1.scatter(...) #draw scatter plot for first axes [...] #same vor every axis plt.savefig(...) scatter1.remove()

http://stackoverflow.com/comment/82274711
type: QuestionComment
comment on: http://stackoverflow.com/q/47657824
type: Comment
has text: I am submitting this code on (www.interviewbit.com) @tzaman
score: 0

http://stackoverflow.com/a/47680082
score: 3
has comment: http://stackoverflow.com/comment/82320786
upvote count: 3
has comment: http://stackoverflow.com/comment/82321019
downvote count: 0
answers question: http://stackoverflow.com/q/47679627
has body: Linear models are not restricted to only 1 predictor variable and 1 response variable. In other words, you can have X and Y as the two predictors being used to predict the response variable Z, where Z might depend linearly on X and Y. In your case you are only trying to predict Y from X, so change your code to the following: from sklearn import linear_model reg = linear_model.LinearRegression() reg.fit ([[0], [1], [2]], [0, 1, 2])
has comment: http://stackoverflow.com/comment/82320960
has comment: http://stackoverflow.com/comment/82320696
type: Answer

http://stackoverflow.com/comment/82171174
has text: You just cannot use SQLAlchemy ORM with any async framework -- it kills performance. The only way is running all SQL queries in thread pool -- or using low level libraries like aiopg and asyncpg
comment on: http://stackoverflow.com/q/47577274
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47590899
score: 4
has body: import re import nltk from nltk.corpus import stopwords stop = stopwords.words('english') from nltk.corpus import wordnet String = 'Ravana was killed in a war' Sentences = nltk.sent_tokenize(String) Tokens = [] for Sent in Sentences: Tokens.append(nltk.word_tokenize(Sent)) Words_List = [nltk.pos_tag(Token) for Token in Tokens] Nouns_List = [] for List in Words_List: for Word in List: if re.match('[NN.*]', Word[1]): Nouns_List.append(Word[0]) Names = [] for Nouns in Nouns_List: if not wordnet.synsets(Nouns): Names.append(Nouns) print (Names) Check this code. I am getting Ravana as output. EDIT: I used a few sentences from my resume to create a text file, and gave it as input to my program. Only the changed portion of the code is shown below: import io File = io.open("Documents\\Temp.txt", 'r', encoding = 'utf-8') String = File.read() String = re.sub('[/|.|@|%|\d+]', '', String) And it is returning all the names that are not in the wordnet corpus, like my name, my house name, place, college name and place.
downvote count: 0
upvote count: 4
has comment: http://stackoverflow.com/comment/82140396
answers question: http://stackoverflow.com/q/47571213
type: Answer

http://stackoverflow.com/comment/82177655
score: 1
type: Comment
has text: What have you done to debug this? Are you printing out the coordinates of the mouse and the coordinates of the image that you're trying to crop, etc.?
type: QuestionComment
comment on: http://stackoverflow.com/q/47609584

http://stackoverflow.com/comment/82306807
comment on: http://stackoverflow.com/a/47664376
has text: Added a few extra details.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82342041
comment on: http://stackoverflow.com/q/47685350
score: 0
type: Comment
type: QuestionComment
has text: Yes, again, [edit] your question to show the actual problem.

http://stackoverflow.com/comment/82158200
type: QuestionComment
type: Comment
has text: @Gakis41 yes. You can actually click on the link in my answer below and on the left hand side there's a button labeled **Code Generator** and select python. It autogenerates code based on the regex.
score: 0
comment on: http://stackoverflow.com/q/47598687

http://stackoverflow.com/comment/82084545
type: QuestionComment
has text: Side note - I think you want to be returning the result of `scipy.stats.spearmanr` in `applyspearman`, not assigning it to every row as an an additional column in the grouped dataframe? Spearman rank is meant to be a summary statistic, not a per-row measure.
type: Comment
comment on: http://stackoverflow.com/q/47562775
score: 0

http://stackoverflow.com/comment/82352743
type: Comment
type: QuestionComment
has text: @MichaelButscher so essentially I need to print out getInputStream()?
comment on: http://stackoverflow.com/q/47696409
score: 0

http://stackoverflow.com/q/47636896
has comment: http://stackoverflow.com/comment/83554121
has comment: http://stackoverflow.com/comment/82231972
has comment: http://stackoverflow.com/comment/82231831
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/82239099
answer count: 0
type: UnansweredQuestion
has title: Insert value of list in xlsx file with python
has body: I'm tring to insert value of list in a column of xlsx file with python. this is the code def trasformazione (original): inProj = Proj(init='epsg:4326') outProj = Proj(init='epsg:3395') transformat=[] for g in range (0,row_count-1): x2,y2 = transform(inProj,outProj,original[g][0],original[g][1]) transformat.append([x2,y2]) return (transformat) transformat=trasformazione (original) print(trasformazione (original)) # Create a workbook and add a worksheet. workbook = xlsxwriter.Workbook('campioni1.xlsx') worksheet = workbook.add_worksheet() # Start from the first cell below the headers. row = 1 col=0 # Iterate over the data and write it out row by row. worksheet.write(row, col,transformat) row += 1 workbook.close() Thanks for the support
tagged with: excel
score: 0

http://stackoverflow.com/q/47551111
tagged with: ansible
has answer: http://stackoverflow.com/a/47551327
possible better answer: http://stackoverflow.com/a/47551327
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: automation
has title: Ansible Local Python Script with Parameters
has answer: http://stackoverflow.com/a/47562037
accepted answer: http://stackoverflow.com/a/47562037
tagged with: python
type: AnsweredQuestion
has body: So here is what I want to do I want to run a playbook like this ansible-playbook playbookX.yml --ask-vault-pass [host or hostgroup] The playbook should run a local (on the ansible server) python script with parameters python scriptname.py Parameter1 Parameter2 Parameter1: a secret that should be encrypted and not visible i.e. with ps -aufx and I should get the password from a vault-file. Maybe I should decrypt it in the python script? Parameter2: The hostname specified in host or hostgroup (Note: The script should be run for every host when the playbook is run with a hostgroup) Another note: The python script should best be executed in a virtual_env while the environment should have urllib3 installed. How could I accomplish that?
answer count: 2
downvote count: 0

http://stackoverflow.com/q/47676250
has body: I'm converting some numpy code to use pandas DataFrame. The data potentially contains NaN values, so I make use of numpy's nan functions such as nanstd in the original code. I was of the impression that pandas skips NaN values by default, so I switched to using the regular versions of the same functions. I want to group the data and compute some statistics on it using agg(), however when I use np.std() I am getting different results to the original code, even in cases where the data doesn't contain any NaNs Here's a small example demonstrating the problem &gt;&gt;&gt; arr = np.array([[1.17136, 1.11816], [1.13096, 1.04134], [1.13865, 1.03414], [1.09053, 0.96330], [1.02455, 0.94728], [1.18182, 1.04950], [1.09620, 1.06686]]) &gt;&gt;&gt; df = pd.DataFrame(arr, index=['foo']*3 + ['bar']*4, columns=['A', 'B']) &gt;&gt;&gt; df A B foo 1.17136 1.11816 foo 1.13096 1.04134 foo 1.13865 1.03414 bar 1.09053 0.96330 bar 1.02455 0.94728 bar 1.18182 1.04950 bar 1.09620 1.06686 &gt;&gt;&gt; g = df.groupby(df.index) &gt;&gt;&gt; g['A'].agg([np.mean, np.median, np.std]) mean median std bar 1.098275 1.093365 0.064497 foo 1.146990 1.138650 0.021452 &gt;&gt;&gt; g['A'].agg([np.mean, np.median, np.nanstd]) mean median nanstd bar 1.098275 1.093365 0.055856 foo 1.146990 1.138650 0.017516 If I compute the std values with the numpy functions, I get the expected result in both cases. What's going on inside the agg() function? &gt;&gt;&gt; np.std(df.loc['foo', 'A']) 0.01751583474079002 &gt;&gt;&gt; np.nanstd(df.loc['foo', 'A']) 0.017515834740790021 Edit: As mentioned in the answer linked by Vivek Harikrishnan, pandas uses a different method to compute the std. This seems to match my results &gt;&gt;&gt; g['A'].agg(['mean', 'median', 'std']) mean median std bar 1.098275 1.093365 0.064497 foo 1.146990 1.138650 0.021452 And if I specify a lambda that calls np.std() I get the expected result &gt;&gt;&gt; g['A'].agg([np.mean, np.median, lambda x: np.std(x)]) mean median &lt;lambda&gt; bar 1.098275 …
has answer: http://stackoverflow.com/a/47699378
score: 9
has comment: http://stackoverflow.com/comment/82315590
linked to: http://stackoverflow.com/q/25695986
tagged with: pandas
answer count: 1
downvote count: 0
has title: Pandas agg function gives different results for numpy std vs nanstd
favorite count: 0
type: Question
upvote count: 9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82312055
tagged with: python

http://stackoverflow.com/q/47544073
tagged with: pypi
tagged with: packaging
has title: What are the norms for releasing the same package under multiple names on PyPI?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52896730
tagged with: python
score: 0
tagged with: python-packaging
has body: Suppose I've uploaded a package called foobar to PyPI. Because the package is a Django module, I'd also like to publish it as django-foobar. What is the general consensus towards releasing the same package under multiple names? Is it allowed or forbidden? Encouraged or discouraged? (To prevent this question from appearing or becoming too opinion-based, I'm hoping someone can point me to some specific, published norms or obvious precedents. Thank you!)
answer count: 1

http://stackoverflow.com/comment/82062563
comment on: http://stackoverflow.com/q/47552894
type: Comment
has text: `np.transpose(a)`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82221195
comment on: http://stackoverflow.com/a/47631630
type: AnswerComment
score: 0
has text: I am slightly confused as I am setting the file variable before the error which happens on this line: "timestamp = oupload.stat(file).st_atime" - How would I re-write this? Thanks
type: Comment

http://stackoverflow.com/a/47660775
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47660635
type: Answer
accepted answer of: http://stackoverflow.com/q/47660635
has body: use index this one It should end with four brackets check that number of open brackets should match number of closed brackets index=[['udacity',['http_qualquer'],['udacity',['http_any']]]]
score: 0

http://stackoverflow.com/a/47611252
answers question: http://stackoverflow.com/q/47606214
downvote count: 0
upvote count: 2
has body: The problem is that you are setting blocking=True which does not allow for any other functions to be run before this exits. Combined with loop=True, this produces an infinite loop. What you want is: import soundfile as sf import sounddevice as sd weight = 1.4 data, fs = sf.read('sound.wav') sd.play(data * weight, fs,loop=True) sd.stop() Hope this helps!
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82191127
accepted answer of: http://stackoverflow.com/q/47606214
score: 2

http://stackoverflow.com/q/47568505
answer count: 0
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82113072
has body: Python 3.6 on windows 7 (Jupyter Notebook) I'm trying to load label csv file. but it's not working properly. The csv file has been created already. (1 column, 570 rows) I'v been googled to debug this problem, but i can't find the exact case like this. finally, I wanna train jpg files with this label file. in model.py imagename_queue = tf.train.string_input_producer(images, shuffle=False) labelname_queue = tf.train.string_input_producer([csv_label], shuffle=False) # print(type(labelname_queue)) image_reader = tf.WholeFileReader() key_img, raw_img = image_reader.read(imagename_queue) csv_reader = tf.TextLineReader() key_txt, raw_txt = csv_reader.read(labelname_queue) jpg_image = tf.image.decode_jpeg(raw_img) csv_label = tf.decode_csv(raw_txt, record_defaults=[[0]]) jpg_image = tf.reduce_mean(jpg_image, axis=2) jpg_image = tf.reshape(jpg_image, [W_img, H_img, 1]) I got this error --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-23-6c24000e9977&gt; in &lt;module&gt;() 1 imagename_queue = tf.train.string_input_producer(images, shuffle=False) ----&gt; 2 labelname_queue = tf.train.string_input_producer([csv_label], shuffle=False) 3 4 # print(type(labelname_queue)) 5 C:\Anaconda3\lib\site-packages\tensorflow\python\training\input.py in string_input_producer(string_tensor, num_epochs, shuffle, seed, capacity, shared_name, name, cancel_op) 218 219 with ops.name_scope(name, "input_producer", [string_tensor]) as name: --&gt; 220 string_tensor = ops.convert_to_tensor(string_tensor, dtype=dtypes.string) 221 with ops.control_dependencies([ 222 control_flow_ops.Assert( C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, preferred_dtype) 609 name=name, 610 preferred_dtype=preferred_dtype, --&gt; 611 as_ref=False) 612 613 C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in internal_convert_to_tensor(value, dtype, name, as_ref…
type: UnansweredQuestion
tagged with: python
has title: TypeError: Expected string, got list containing Tensors of type '_Message' instead
has comment: http://stackoverflow.com/comment/82330626
score: 0

axios
tag name: axios
type: Tag
tags question: http://stackoverflow.com/q/47585381

http://stackoverflow.com/comment/82162193
comment on: http://stackoverflow.com/a/47601381
type: Comment
has text: Thank you for your solutions. I appreciate the time and effort you put into this.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47617030
score: 0
has body: There is no way to create a plain variable that "updates" itself when some other data structure is updated. That kind of behavior can only be achieved with kind of expression, like an attribute or item lookup. In other words, you can make an object curr_value so that evaluating curr_value[0] gives you the value of mydict[1][45] at that moment, or evaluating curr_value.value gives you the value of mydict[1][45] at that moment, but you cannot make it so that evaluating just plain curr_value gives you the value of mydict[1][45] at that moment. Doing curr_value = mydict[1][45] always sets the curr_value to what it is at the moment you assign it, and it will not be updated later if mydict[1][45] changes.
answers question: http://stackoverflow.com/q/47616887
has comment: http://stackoverflow.com/comment/82192372
type: Answer

http://stackoverflow.com/q/47649787
tagged with: plot
has answer: http://stackoverflow.com/a/47713740
accepted answer: http://stackoverflow.com/a/47713740
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/82314022
has comment: http://stackoverflow.com/comment/82338609
has comment: http://stackoverflow.com/comment/82378903
answer count: 1
has body: I am trying to plot coloured vectors onto a map in python 2.7. I can plot the vectors and their colours with no problem but as soon as I try add the coastline things go wrong. Please help import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd from mpl_toolkits.basemap import Basemap filename = 'wg_weather1_fixed.csv' readcsv = pd.read_csv(filename) temp = readcsv.Temperature_degC wind_speed_kt = readcsv.Wind_Speed_kt Wind_Direction = readcsv.Wind_Direction lat = readcsv.Latitude lon = readcsv.Longitude Wind_speed_2 = wind_speed_kt*1.852 # extract U and V components WG_wind_U = Wind_speed_2 * np.sin((360-Wind_Direction)*np.pi/180) WG_wind_V = -Wind_speed_2*np.cos((360-Wind_Direction)*np.pi/180) m = Basemap(projection='merc',llcrnrlat=-32.2,urcrnrlat=-29,\ llcrnrlon=30,urcrnrlon=33,lat_ts=5,resolution='i') # Create colour bar norm = matplotlib.colors.Normalize() norm.autoscale(temp) cm = matplotlib.cm.CMRmap sm = matplotlib.cm.ScalarMappable(cmap=cm, norm=norm) sm.set_array([]) # Plot q = m.quiver(lon,lat,WG_wind_U,WG_wind_V,color=cm(norm(temp))) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.quiverkey(q,0.9, 0.05, 30, r'$30 \frac{Kp}{h}$',labelpos='W',fontproperties={'size': 15,'weight': 'bold'}) cbar = plt.colorbar(sm) plt.show() Essentially I need to add a coastline to this plot: enter image description here
has title: Quiver plot on a map with python

superclass
type: Tag
tag name: superclass
tags question: http://stackoverflow.com/q/47628316

http://stackoverflow.com/comment/82271376
has text: @syntonym I'm relatively familiar with inheritance, but guess I don't understand it well enough. So when Controller(info='Hello world') passes the argument info='Hello world' to the parent FloatLayout, does this assign a value to FloatLayout.Controller.info or FloatLayout.info? Or am I thinking about the hierarchy wrong altogether?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47639700
type: QuestionComment

http://stackoverflow.com/a/47662957
has body: In pure Python, one way to do this is by splitting the string at '?', taking the second component, and splitting again at '='. url = 'http://mysportswebsite.com/shop/?Baseball+Bat=5' item, count = url.split('?')[1].split('=') You can use apply to run this operation over a column, however if you have a large number of URLs, it is more efficient to use the built in string methods for the same operation. The syntax is quite similar. data = pd.Series([ 'http://mysportswebsite.com/shop/?Baseball+Bat=5', 'http//memoribilia.com/checkout?autograph=1']) df = data.str.split('?', expand=True)[1].str.split('=', expand=True) df.columns = ['item', 'count']
score: 0
answers question: http://stackoverflow.com/q/47657679
type: Answer

http://stackoverflow.com/comment/82090552
comment on: http://stackoverflow.com/q/47566301
type: QuestionComment
has text: I think 'wt' implies complexity here. You may use a regular expression to ensure that the password contains a minimum or a lower case, an upper case, a special char and a number. And add a check using len to meet the minimum password length requirement.
type: Comment
score: 0

http://stackoverflow.com/a/47666125
has body: As you want to drag an image from the desktop, the path of this image provides it through a local url, to verify it uses the mimeData(). hasUrls(), and urls() to get the url, then we get the local path with the method toLocalFile(), all the above is implemented in the following code: class Button(QPushButton): def __init__(self, title, parent): super().__init__(title, parent) self.setAcceptDrops(True) def dragEnterEvent(self, e): m = e.mimeData() if m.hasUrls(): e.accept() else: e.ignore() def dropEvent(self, e): m = e.mimeData() if m.hasUrls(): self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile())) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): button = Button("",self) button.resize(100,100) button.setIcon(QIcon("gazo1.jpg")) button.setIconSize(QSize(100,100)) button.move(0, 0) self.label = QLabel(self) self.label.setPixmap(QPixmap('gazo2.png')) self.label.move(150,150) self.setWindowTitle('Simple drag &amp; drop') self.setGeometry(300, 300, 300, 300) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() app.exec_()
type: Answer
accepted answer of: http://stackoverflow.com/q/47647857
has comment: http://stackoverflow.com/comment/82335592
has comment: http://stackoverflow.com/comment/82335059
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47647857
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82335025
has comment: http://stackoverflow.com/comment/82335829

http://stackoverflow.com/q/47618826
has answer: http://stackoverflow.com/a/47619044
has answer: http://stackoverflow.com/a/47618890
has title: Basic Python Struggles
type: Question
upvote count: 0
type: UnansweredQuestion
downvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/82198951
answer count: 3
score: -2
has body: I'm making a maths skills testing program and was wondering if there's a way in which i can make random questions appear in my program instead of having to do this every single time; import time start = time.time() userinput = input("\nWhat is 11+7?") if userinput=="18": print("\nNot bad, lets try something a little harder...") print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) else: print("\nAt least you got one right") print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start)) exit() Also, how can i add a while statement into this? I would also like to add a def function in if possible. Thanks.
has comment: http://stackoverflow.com/comment/82196501
tagged with: python
has comment: http://stackoverflow.com/comment/82195731
has answer: http://stackoverflow.com/a/47620560

http://stackoverflow.com/q/47550043
has body: The following curl request works perfectly when I run it through Windows' CMD. curl -XPOST -H"Content-Type:application/json" http://my_url:8082/druid/v2/sql/ -d "{\"query\":\"SELECT DISTINCT(event) FROM programs\"}" I am trying to replicate the same call in python 3 using urllib.requests import urllib.request values = {'query':'SELECT DISTINCT(event) FROM programs'} url = 'http://my_url:8082/druid/v2/sql' data = urllib.parse.urlencode(values).encode("utf-8") req = urllib.request.Request(url, data) req.add_header("Content-Type","application/json") response = urllib.request.urlopen(req) the_page = response.read() However the python version is returning a Server Error response = urllib.request.urlopen(req) File "C:\Python\Python35\lib\urllib\request.py", line 163, in urlopen return opener.open(url, data, timeout) File "C:\Python\Python35\lib\urllib\request.py", line 472, in open response = meth(req, response) File "C:\Python\Python35\lib\urllib\request.py", line 582, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python\Python35\lib\urllib\request.py", line 510, in error return self._call_chain(*args) File "C:\Python\Python35\lib\urllib\request.py", line 444, in _call_chain result = func(*args) File "C:\Python\Python35\lib\urllib\request.py", line 590, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 500: Server Error Can someone tell me what I'm doing wrong please?
tagged with: druid
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: windows
has title: Curl post request returning 500 server error in python
tagged with: python
tagged with: curl
score: 0
has answer: http://stackoverflow.com/a/47553017
has answer: http://stackoverflow.com/a/47550131

http://stackoverflow.com/comment/82288257
score: 0
type: AnswerComment
has text: Thanks for the quick answer! Now I get no syntax error, but this: self.executables = list(executables) TypeError: 'Executable' object is not iterable
type: Comment
comment on: http://stackoverflow.com/a/47664467

http://stackoverflow.com/comment/82293733
comment on: http://stackoverflow.com/a/47665060
score: 0
type: Comment
type: AnswerComment
has text: When I try to run this, I get: Traceback (most recent call last): File "scraper.py", line 30, in <module> demo() File "scraper.py", line 25, in demo writetweets() File "scraper.py", line 15, in writetweets new.write(tweet.getText() + "\r\n") UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 33: ordinal not in range(128)

http://stackoverflow.com/a/47694463
score: 0
type: Answer
has body: you can make a list of k, v pairs to test for (doesn't have to be list of tuples) hav = [('max-threshold', True), ('zero-failcount', True)] [d for d in commands if all([d[k] == v for k, v in hav])]
answers question: http://stackoverflow.com/q/47692014

multiple-columns
tags question: http://stackoverflow.com/q/47580397
type: Tag
tags question: http://stackoverflow.com/q/47555375
tag name: multiple-columns

http://stackoverflow.com/comment/82258166
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47637504
has text: @gasman you answered my question about having all dependencies in INSTALLED_APPS. However, which admin panel will serve both applications?

http://stackoverflow.com/comment/82284777
comment on: http://stackoverflow.com/a/47662005
type: Comment
has text: @Prune I've updated the question with the code I attempted. Thx
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82145725
type: Comment
has text: the questions whether you would use a bar-chart or scatter plot should be based on what you want to visualize (your data, question) and not on whether it is possible to color it in a certain way. Perhaps ask about the measure/method to determine relations on the statistics/data analysis stackexchange: stats.stackexchange.com
type: QuestionComment
comment on: http://stackoverflow.com/q/47594244
score: 0

pyinstaller
tags question: http://stackoverflow.com/q/47610050
tags question: http://stackoverflow.com/q/47692213
tags question: http://stackoverflow.com/q/47690548
tags question: http://stackoverflow.com/q/47694335
tags question: http://stackoverflow.com/q/47611130
tags question: http://stackoverflow.com/q/47586754
type: Tag
tag name: pyinstaller
tags question: http://stackoverflow.com/q/47680063
tags question: http://stackoverflow.com/q/47671023
tags question: http://stackoverflow.com/q/47692960
tags question: http://stackoverflow.com/q/47600238
tags question: http://stackoverflow.com/q/47676319
tags question: http://stackoverflow.com/q/47545082
tags question: http://stackoverflow.com/q/47603905

http://stackoverflow.com/a/47697964
answers question: http://stackoverflow.com/q/47697749
accepted answer of: http://stackoverflow.com/q/47697749
score: 10
type: Answer
upvote count: 10
has body: Though I don't get why it has to be a one-liner, this should do what you want: listx, listy = [[x for x in alist if x != None] for alist in [listx, listy]]
has comment: http://stackoverflow.com/comment/82358340
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82122328
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47567945
has text: I tried this and it worked perfectly, thank you. However, after running it a few times it stopped working. Am I being blocked by the site as a bot? Is that going to kill my whole project?

http://stackoverflow.com/q/47684222
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: function
has body: I'm learning python, trying to figure out how does this code actually work: def func(**args): class BindArgs(object): foo = args['foo'] print 'foo is ', foo def __init__(self,args): print "hello i am here" return BindArgs(args) #return an instance of the class f = func(foo=2) Output: foo is 2 hello i am here But it's very confused that in the argument of a function func(foo=2) that takes equation mark in it. Could you please explain how the flow works?
downvote count: 0
tagged with: python
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/82328788
has answer: http://stackoverflow.com/a/47684418
tagged with: class
duplicate of: http://stackoverflow.com/q/36901
has comment: http://stackoverflow.com/comment/82344371
linked to: http://stackoverflow.com/q/36901
score: 1
answer count: 1
has title: When defining class method, why there an equals sign in argument e.g. func(foo=3)
upvote count: 1

http://stackoverflow.com/comment/99492244
comment on: http://stackoverflow.com/a/47600652
has text: Thanks. I'm just going to stick with the in-python option as that seems to be working just fine.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/74027762
score: 0
has body: Making .pack() or .grid() a separate line didn't work for me. The solution was to hide the window using root.withdraw() before running root.quit() or root.destroy() as shown below. import tkinter as tk def quit_(root): root.withdraw() root.quit() root = tk.Tk() tk.Button(root, text="Quit", command=lambda: quit_(root)).pack() root.mainloop()
answers question: http://stackoverflow.com/q/47651628
type: Answer

http://stackoverflow.com/comment/82330493
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47685214
has text: @Shadowranger made that very relevant comment. Not quite sure what you mean, we're talking about how you present dates and ISO8601 is certainly a fairly unambiguous way of doing it: 2017-12-06 is much better than 06/12/17. But arguably for an English-reading audience "6th December 2017" is completely crystal clear. However if you were exporting dates into e.g. a spreadsheet then ISO is the way to go IMO.
type: Comment

reshape
tags question: http://stackoverflow.com/q/47598968
tags question: http://stackoverflow.com/q/47599461
type: Tag
tags question: http://stackoverflow.com/q/47578571
tag name: reshape
tags question: http://stackoverflow.com/q/47560414
tags question: http://stackoverflow.com/q/47613897
tags question: http://stackoverflow.com/q/47661550
tags question: http://stackoverflow.com/q/47649690

http://stackoverflow.com/a/47660586
has comment: http://stackoverflow.com/comment/82328708
has comment: http://stackoverflow.com/comment/82286871
has comment: http://stackoverflow.com/comment/82327885
answers question: http://stackoverflow.com/q/47647282
has body: Consider using containers like list of dictionaries that are assigned within a for loop iteration through each child of entry. For attributes, if conditionals are used to parse the attribute instead of text value. OrderedDict is used to keep keys intact as they are filled in. No need for pandas as you should leave the library for actual data analysis not data wrangling. import csv import xml.etree.ElementTree as et from collections import OrderedDict doc = et.parse('LogEntryCSV.xml') csv_data = [] fields = ['logid', 'receive_time', 'type', 'src', 'dst', 'rule', 'srcuser', 'srcloc', 'dstloc', 'app', 'from', 'to', 'repeatcnt', 'sport', 'dport', 'proto', 'action', 'bytes', 'bytes_sent', 'bytes_received', 'packets', 'start', 'elapsed', 'category', 'pkts_sent', 'pkts_received', 'session_end_reason', 'action_source'] for elem in doc.findall('.//entry'): inner_dict = OrderedDict({k:None for k in fields}) # PRE-POPULATES TEMP DICT inner_dict['logid'] = elem.attrib['logid'] for item in elem.findall('.//*'): if item.tag in fields: if item.tag=='srcloc': inner_dict['scrloc code'] = item.attrib['code'] inner_dict['scr_cc'] = item.attrib['cc'] elif item.tag=='dstloc': inner_dict['dstloc code'] = item.attrib['code'] inner_dict['dst_cc'] = item.attrib['cc'] else: inner_dict[item.tag] = item.text csv_data.append(inner_dict) with open('Output.csv', 'w', newline='') as f: w = csv.DictWriter(f, csv_data[0].keys()) w.writeheader() w.writerows(csv_data)
has comment: http://stackoverflow.com/comment/82286178
has comment: http://stackoverflow.com/comment/82283301
score: 2
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82287330
downvote count: 0
has comment: http://stackoverflow.com/comment/82367126
has comment: http://stackoverflow.com/comment/82327860
has comment: http://stackoverflow.com/comment/82283483
has comment: http://stackoverflow.com/comment/82333455
accepted answer of: http://stackoverflow.com/q/47647282
type: Answer
has comment: http://stackoverflow.com/comment/82287254

http://stackoverflow.com/comment/82359453
type: AnswerComment
score: 0
type: Comment
has text: Thanks, you are a savior!
comment on: http://stackoverflow.com/a/47693327

http://stackoverflow.com/a/47665044
answers question: http://stackoverflow.com/q/47665015
has body: Instead of basename() use base = os.path.splitext(csvfile)[0]
score: 0
type: Answer

http://stackoverflow.com/comment/82053805
type: Comment
score: 0
has text: It will support eclipse versions above 4.6 I have PyDev on Oxygen Elcipse installed and it works fine.
type: QuestionComment
comment on: http://stackoverflow.com/q/47548499

http://stackoverflow.com/comment/82306446
has text: Does it eventually go back to the URLs it skipped. I believe that it doesn't work linearly, limiting the rate it will hit any one domain. Could that be your issue?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47673406
score: 0

http://stackoverflow.com/q/47619560
answer count: 2
has body: I wrote a function that calculates relativistic kinetic energy but I'm having some problems graphing it. I'm working in Python Jupyter. I'm using Taylor for very small values of v (so I don't end up with E=0 because of cancellation) and the original expression for the biggest values. I have to calculate it for v between 1e-6 and 2.88e8. m=1 c=3e8 def E(v): if (v/c) &lt;= 0.8860: return ((m*v**2)/2) + ((3*m*v**4)/(8*c**2)) + ((5*m*v**6)/(16*c**4)) + ((35*m*v**8)/(128*c**6)) else: return (m*c**2)*((1/sp.sqrt(1-(v**2/c**2)))-1) This gives me very accurate results. Now the problem is graphing E(v). I have to use matplotlib (+ numpy and scipy for everything else). Here is what I wrote for a log-log graph. xs = np.logspace(-6, 8.5) fig, ax = plt.subplots(figsize=[10,10]) ax.plot(xs, E(xs)) ax.set_xscale('log') ax.set_yscale('log') I am getting a value error : "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()", and it points at "if (v/c) &lt;= 0.8860:". what's this error means and what I did wrong. I'd be very grateful if you could help me graph or change my function.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82197366
has answer: http://stackoverflow.com/a/47620198
has title: Graphing relativistic kinetic energy
type: Question
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/47619796
score: 0

http://stackoverflow.com/comment/82096823
score: 0
has text: I thought about keeping tracking of where I change items and only change those in the end of each iteration but that would be super complicated.
comment on: http://stackoverflow.com/q/47569461
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82117910
comment on: http://stackoverflow.com/q/47579918
score: 0
has text: @juanpa.arrivillaga: Yeah, easily, but a CAS can't fix everything either. It can find exact solutions for a lot of cases, especially if the operations involved are simple enough, but eventually you'll run into limitations and either sympy will fail to simplify something, or you won't be able to express your operation in sympy at all.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82227249
has text: Btw: The error could be caused by the indent.
type: Comment
comment on: http://stackoverflow.com/q/47634812
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83893828
type: AnswerComment
has text: While this code-only answer may answer the question, please add an explanation of why it does so. This will help future users evaluate the answer for their situation.
score: 0
comment on: http://stackoverflow.com/a/48449974
type: Comment

http://stackoverflow.com/a/47634703
has comment: http://stackoverflow.com/comment/82249351
answers question: http://stackoverflow.com/q/47633803
has comment: http://stackoverflow.com/comment/82249022
has comment: http://stackoverflow.com/comment/82249298
has comment: http://stackoverflow.com/comment/82248911
type: AcceptedAnswer
has body: It seems this sever sends file with string favicon.ico if you have incorrect USER-AGENT Try with extra option which looks like correct USER-AGENT and you get HTML file. scrapy shell -s USER_AGENT="Mozilla/5.0" https://baijia.baidu.com And then response.xpath will work. In [1]: response.xpath('/html/head/title/text()').extract_first() Out[1]: '首页-百家号' You can get better USER-AGENT from your browser using page httpbin.org
has comment: http://stackoverflow.com/comment/82249394
score: 0
accepted answer of: http://stackoverflow.com/q/47633803
type: Answer

http://stackoverflow.com/a/47661478
has comment: http://stackoverflow.com/comment/82283461
score: 1
answers question: http://stackoverflow.com/q/47660537
type: AcceptedAnswer
downvote count: 0
has body: First try to create a MCVE: import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np example_data = np.array([list(range(20))]*4) cmaplist = ["red", "limegreen", "blue", "gold"]*5 fig, ax = plt.subplots() norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist)) cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist)) im = ax.matshow(example_data, cmap=cmap, norm=norm) plt.show() As can be seen, the color at positions 14 and 15 is the same, while position 15 should be yellow. This is present in matplotlib 2.1, in matplotlib 2.0.2 the issue seems not to be there. I therefore opened a bug report about it. Solution: The numbers you are mapping (which are integers here) are exactly on the edge of the boundaries. I'm not exactly sure what goes wrong here, but to be on the save side, you may use the middle between two integers as the boundary, i.e. norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist)) Complete example: import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np example_data = np.array([list(range(20))]*4) cmaplist = ["red", "limegreen", "blue", "gold"]*5 fig, ax = plt.subplots() norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist)) cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist)) im = ax.matshow(example_data, cmap=cmap, norm=norm) plt.show()
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47660537
has comment: http://stackoverflow.com/comment/82283397
type: Answer
has comment: http://stackoverflow.com/comment/82284127

http://stackoverflow.com/comment/82174617
type: AnswerComment
comment on: http://stackoverflow.com/a/47605779
type: Comment
has text: Thanks, this definitely helps. Let us say I am searching something from my notes made up of non-english words - result = semanticSearch("bahv", ["baloon", "Bhavs grape juice 8000087", "broom stick", "black swan"]) - in this I am expecting it to return the second sentence whereas it returns baloon. This works in elasticsearch (as per my understanding). Do you think we can get this working ?
score: 0

http://stackoverflow.com/q/47585195
type: Question
tagged with: python-3.x
has body: I'm trying to create a qpy plugin and I am getting an error. The part of the code I have added is below. def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() layers=self.iface.legendInterface().layers() layer_list=[] for layer in layers: layer_list.append(layer.name()) self.dlg.comboBox.addItems(layer_list) # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result==1: # Do something useful here - delete the line containing pass and index=self.dlg.comboBox.currentIndex() layer=self.dlg.comboBox.itemData(index) QMessageBox.information(self.iface.mainWindow(),"Hello world","%s has %d features."%(layer.name(),layer.featureCount())) Error:
has comment: http://stackoverflow.com/comment/82128375
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82129103
score: 0
answer count: 0
has title: Creating a plugin on qpy which counts attributes
has comment: http://stackoverflow.com/comment/82129317

http://stackoverflow.com/q/47606702
type: AnsweredQuestion
has title: Python3 "TypeError: not all arguments converted during string formatting"
has comment: http://stackoverflow.com/comment/82171796
downvote count: 1
favorite count: 0
type: Question
upvote count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/47606865
answer count: 1
has body: I'm using Flask SQLAlchemy models to make a database for my app, and I'm trying to query the database using models.Posts.query.all() This is my model: class Posts(db.Model): post_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(500), index=True) date = db.Column(db.Date) image = db.Column(db.String(500)) post_body = db.column(db.String(10000),index=True) authors = db.relationship('Users', backref='authors', lazy='dynamic') def __repr__(self): return '' % (self.post_id, self.title, self.date, self.image) And this is the error message I get: &gt;&gt;&gt; models.Posts.query.all() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/lisa-jd/Blog_platform/app/models.py", line 30, in __repr__ image = db.Column(db.String(50)) TypeError: not all arguments converted during string formatting Any help would be very appreciated.
score: 4
has answer: http://stackoverflow.com/a/47606865

http://stackoverflow.com/comment/82200966
has text: Check the [cython](https://github.com/python/cpython) source code? For performance you could use `% timeit` magic operator.
type: Comment
comment on: http://stackoverflow.com/q/47621511
type: QuestionComment
score: 0

coq
type: Tag
tags question: http://stackoverflow.com/q/47552304
tag name: coq

http://stackoverflow.com/comment/82087570
comment on: http://stackoverflow.com/q/47564648
type: Comment
type: QuestionComment
score: 0
has text: Suggest look up the differences between Python [modules](https://docs.python.org/2/tutorial/modules.html) and [packages](https://docs.python.org/2/tutorial/modules.html#packages). In general packages require an `__init__.py` file and go in sub-folder in the same place as the script(s) calling them. A module is just a single file containing Python definitions and statements - also in the same folder as the script that is importing it.

http://stackoverflow.com/comment/82214540
has text: Maybe the copying is causing the issues.
type: Comment
comment on: http://stackoverflow.com/a/47627829
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82330529
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47666505
has text: It would also be possible to use sprites and then check the collisions with `pygame.sprite.spritecollide` and [`pygame.sprite.collide_circle`](http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle) as the callback function.
type: AnswerComment

http://stackoverflow.com/a/47579961
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47569433
has comment: http://stackoverflow.com/comment/85684783
type: Answer
has comment: http://stackoverflow.com/comment/85681717
has comment: http://stackoverflow.com/comment/85687035
has comment: http://stackoverflow.com/comment/85685577
has body: The standard QComboBox uses a custom view which changes the text elide mode (amongst other things). So you must re-set it to a normal QListView to get the behaviour you want: combo = QtGui.QComboBox() view = QtGui.QListView(combo) combo.setView(view) # this must be done *after* re-setting the view view.setTextElideMode(QtCore.Qt.ElideNone) view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85687801
has comment: http://stackoverflow.com/comment/85688010
has comment: http://stackoverflow.com/comment/85685353
has comment: http://stackoverflow.com/comment/85685932
downvote count: 0
answers question: http://stackoverflow.com/q/47569433

http://stackoverflow.com/comment/82242355
comment on: http://stackoverflow.com/q/47641246
score: 0
type: Comment
has text: @AmitTripathi hi. could you email me please I would really like your help, bossanbar324@gmail.com
type: QuestionComment

http://stackoverflow.com/a/47683274
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47682621
downvote count: 0
has body: Using numpy with idxmax mm=np.triu(-df['value_a'].values[:,None]+df['value_b'].values,1) mm[np.tril_indices(mm.shape[0], 0)] = np.nan temp=pd.DataFrame(mm) df1=df.loc[df['is_case']] df1['New']=np.nan df1['New'].iloc[:4]=df['index'].iloc[(temp&gt;=0).replace(False,np.nan).idxmax(1)[df['is_case']].dropna().astype(int).values].values df1 Out[1098]: index is_case value_a value_b New 0 03/01/2005 True 0.598082 0.189099 06/01/2005 4 07/01/2005 True 0.513017 0.397304 08/01/2005 5 08/01/2005 True 0.691884 0.922642 17/01/2005 13 16/01/2005 True 0.363920 0.355211 17/01/2005 17 20/01/2005 True 0.210786 0.839850 NaN
type: Answer