http://stackoverflow.com/comment/121036736
score: 0
type: Comment
type: AnswerComment
has text: This almost drove me insane. Bless your soul for your answer.
comment on: http://stackoverflow.com/a/48434568

http://stackoverflow.com/comment/83689541
type: QuestionComment
comment on: http://stackoverflow.com/q/48351223
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thanks!
score: 0
type: Comment

http://stackoverflow.com/q/48409508
upvote count: 2
score: 1
tagged with: utc
answer count: 1
has comment: http://stackoverflow.com/comment/83808578
has comment: http://stackoverflow.com/comment/83808488
has title: Python - Convert Date string to UTC timestamp
downvote count: 1
has body: I have a string that says "Oct. 2, 2017, midnight" and want to convert it to a UTC timestamp. Is there any good way to do this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83808674
has comment: http://stackoverflow.com/comment/83808689
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48409666
tagged with: python
tagged with: date
has comment: http://stackoverflow.com/comment/83808551
has comment: http://stackoverflow.com/comment/83808719
linked to: http://stackoverflow.com/q/9637838

http://stackoverflow.com/q/48353621
has title: Python/MySqlDB - Query a database using raw_input and print the result
has answer: http://stackoverflow.com/a/48354868
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83694483
has body: I am trying to create a function that will query a database using a string (or part of a string) inserted via raw_input. The database PManDB has only one table ( accounts ) with 3 columns ( website, username, password ). Example: if in the column website I have the string 'www.website.com' I want to obtain it inserting the values 'w' or 'web' or 'com' in the raw_input. The full code of the project is here. Below an extract without the function to print the database: def SearchRecords(self): search = raw_input("Insert value to be searched in the DB:") db = MySQLdb.connect("localhost", "root", "pass", "PManDB") cursor = db.cursor() sql = """SELECT * FROM accounts WHERE website LIKE %s""" data = (search) try: # Execute the SQL command cursor.execute(sql, data) print "The research has been made with success" except: # Rollback in case there is any error print "There is an error" db.rollback() # disconnect from server The idea is to add a cursor.fetchall() after the print statement "The research has been made with success" using the following sintax result = cursor.fetchall() print result Or to add a for loop result = cursor.fetchall() for row in result: print row[0] But in both ways the code is not working. Could you please help me understanding where am I wrong and why? EDIT1: According to mata comment, I have added the error. When I launch the application in PyCharm, introducing the modification proposed by mata, I receive the following error Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) The code updated is the following (still not working with the error above): def SearchRecords(self): search = raw_input("Insert value to be searched in the DB:") db = MySQLdb.connect("localhost", "root", "studio", "PManDB") cursor = db.cursor() sql = """SELECT * FROM accounts WHERE website LIKE %s""" data = ('%' + search + '%',) cursor.execute(sql, data) result = cursor.fetchall() print result
type: AnsweredQuestion
tagged with: raw-input
score: 0
accepted answer: http://stackoverflow.com/a/48354868
has comment: http://stackoverflow.com/comment/83694356
tagged with: mysql-python
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/83694381

http://stackoverflow.com/q/48483952
has answer: http://stackoverflow.com/a/48490552
tagged with: generator
has title: recursive generator when meet string
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48485151
answer count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83960696
type: Question
tagged with: recursion
score: 0
has body: Here is my code : def flatten(nested): try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested It's the example in a book which called Beginning Python From Novice to Professional written by Magus Lie Hetland. It says ,if there is a string in this list it will be endless by recursion . Yes, It's true.But what should I do, if I use this generator? I'm a new learner.Thank you for your teaching. At last, my English is so poor, I'm so sorry,if you read hard. I'll try my best to improve.
has answer: http://stackoverflow.com/a/48493714
tagged with: python

http://stackoverflow.com/comment/83767594
comment on: http://stackoverflow.com/q/48389655
has text: Well, there you are -- your file isn't actually `|`-delimited at all. Use `line.split('\x01')` and you'll be fine.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48402613
has comment: http://stackoverflow.com/comment/83800704
type: UnansweredQuestion
answer count: 1
has body: I have a data set, obtained form the .odb file by script. I would like to change coordinates of the first point ((0, 26.7852) to (0,0)) in this data set in the same script. From .rpy file I found how to do this for the entire set (see below), but don't have idea for a single point. Please help xQuantity = visualization.QuantityType(type=DISPLACEMENT) yQuantity = visualization.QuantityType(type=FORCE) session.xyDataObjects['F_vs_U'].setValues(data=((0, 26.7852), (0.3, 26.7852), ( 0.394435, 35.446), (0.490063, 44.1067), (0.581765, 52.7674), (0.675743, 61.4282), (0.770288, 70.0889), (0.865283, 78.7497), (0.949015, 87.4104), ( 1.03486, 96.0711), (1.12699, 104.732), (1.21825, 113.393), (1.30867, 122.053), (1.38952, 130.714), (1.45982, 139.375), (1.52214, 148.036), ( 1.59321, 156.696), (1.66979, 165.357), (1.75083, 174.018), (1.83359, 182.679), (1.90974, 191.339), (1.96586, 200), ), sourceDescription='Data modified in editor', axis1QuantityType=xQuantity, axis2QuantityType=yQuantity, )
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83818297
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84003571
has title: How to add and/or modify a point in XY data set in abaqus viewer using python script
has answer: http://stackoverflow.com/a/48619814
has comment: http://stackoverflow.com/comment/83828340
tagged with: python
tagged with: abaqus

http://stackoverflow.com/q/48449997
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Modify input before executing Python class definition
has body: I am still learning how Python classes work. Here is my sample code: class StringPopped(str): def __init__(self, input): super().__init__() self.output = input[:-1] str1 = StringPopped('Alice') Then the output for &gt;&gt;&gt; str1 is Alice and str1.output is Alic. How do I make str1 have the same result as str1.output? I tried __repr__ but that only changes what is displayed and not what the value of str1 actually is. Is there a way to make a statement like self = self.output?
tagged with: python
accepted answer: http://stackoverflow.com/a/48450116
tagged with: class
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48450116
has comment: http://stackoverflow.com/comment/83896241
answer count: 1
has comment: http://stackoverflow.com/comment/83893078

tkinter
tags question: http://stackoverflow.com/q/48377577
tags question: http://stackoverflow.com/q/48466577
tags question: http://stackoverflow.com/q/48449045
tags question: http://stackoverflow.com/q/48426912
tags question: http://stackoverflow.com/q/48455042
tags question: http://stackoverflow.com/q/48398991
tags question: http://stackoverflow.com/q/48409705
tags question: http://stackoverflow.com/q/48349453
tags question: http://stackoverflow.com/q/48362010
tags question: http://stackoverflow.com/q/48389667
tags question: http://stackoverflow.com/q/48369747
tags question: http://stackoverflow.com/q/48354778
tags question: http://stackoverflow.com/q/48468536
tags question: http://stackoverflow.com/q/48392532
tags question: http://stackoverflow.com/q/48461814
tags question: http://stackoverflow.com/q/48427501
tags question: http://stackoverflow.com/q/48369080
tags question: http://stackoverflow.com/q/48358088
tags question: http://stackoverflow.com/q/48364168
tags question: http://stackoverflow.com/q/48370847
tags question: http://stackoverflow.com/q/48368509
tags question: http://stackoverflow.com/q/48368731
tags question: http://stackoverflow.com/q/48333843
tags question: http://stackoverflow.com/q/48436622
tags question: http://stackoverflow.com/q/48373632
tags question: http://stackoverflow.com/q/48404874
tags question: http://stackoverflow.com/q/48348714
tags question: http://stackoverflow.com/q/48348791
tags question: http://stackoverflow.com/q/48373128
tags question: http://stackoverflow.com/q/48432506
tags question: http://stackoverflow.com/q/48358096
tags question: http://stackoverflow.com/q/48352058
tags question: http://stackoverflow.com/q/48358929
tags question: http://stackoverflow.com/q/48384420
tags question: http://stackoverflow.com/q/48437710
tags question: http://stackoverflow.com/q/48373872
tags question: http://stackoverflow.com/q/48384986
tags question: http://stackoverflow.com/q/48339145
tags question: http://stackoverflow.com/q/48470275
tags question: http://stackoverflow.com/q/48388987
tags question: http://stackoverflow.com/q/48358084
tags question: http://stackoverflow.com/q/48352950
tag name: tkinter
tags question: http://stackoverflow.com/q/48352645
tags question: http://stackoverflow.com/q/48369351
tags question: http://stackoverflow.com/q/48426950
tags question: http://stackoverflow.com/q/48360228
tags question: http://stackoverflow.com/q/48449217
tags question: http://stackoverflow.com/q/48349169
tags question: http://stackoverflow.com/q/48395212
tags question: http://stackoverflow.com/q/48373777
tags question: http://stackoverflow.com/q/48452069
tags question: http://stackoverflow.com/q/48479924
tags question: http://stackoverflow.com/q/48407765
tags question: http://stackoverflow.com/q/48376528
tags question: http://stackoverflow.com/q/48336473
tags question: http://stackoverflow.com/q/48451144
tags question: http://stackoverflow.com/q/48389806
tags question: http://stackoverflow.com/q/48384551
tags question: http://stackoverflow.com/q/48448966
tags question: http://stackoverflow.com/q/48374484
tags question: http://stackoverflow.com/q/48469593
tags question: http://stackoverflow.com/q/48349678
tags question: http://stackoverflow.com/q/48359295
tags question: http://stackoverflow.com/q/48444246
tags question: http://stackoverflow.com/q/48352341
tags question: http://stackoverflow.com/q/48385116
tags question: http://stackoverflow.com/q/48331573
tags question: http://stackoverflow.com/q/48400158
tags question: http://stackoverflow.com/q/48472692
tags question: http://stackoverflow.com/q/48389065
tags question: http://stackoverflow.com/q/48331221
tags question: http://stackoverflow.com/q/48470478
tags question: http://stackoverflow.com/q/48343698
tags question: http://stackoverflow.com/q/48412520
tags question: http://stackoverflow.com/q/48403381
tags question: http://stackoverflow.com/q/48475960
tags question: http://stackoverflow.com/q/48388368
tags question: http://stackoverflow.com/q/48360544
tags question: http://stackoverflow.com/q/48351221

http://stackoverflow.com/q/48409363
tagged with: android
tagged with: adb
tagged with: python
has answer: http://stackoverflow.com/a/48453243
score: 2
tagged with: screen-readers
downvote count: 2
answer count: 1
has title: Using Python or adb command to read Android UI text?
favorite count: 0
type: Question
upvote count: 4
tagged with: automation
has body: I was just wondering if there was a way to read the text displayed on a Android device's UI using python or any adb commands? I have found a module for python called "UIAutomator : https://github.com/xiaocong/uiautomator", which can be used to dump the screen's contents, but it seems to be really slow and often unreliable in terms of connection to the android device. I also found google's own UIAutomator tool, but I needed something that can be used via a python script or an adb command to read the onscreen text. Any help would be appreciated. Thanks in advance :)
type: UnansweredQuestion

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

http://stackoverflow.com/a/48465414
has comment: http://stackoverflow.com/comment/83924451
score: 2
has comment: http://stackoverflow.com/comment/83924313
answers question: http://stackoverflow.com/q/48465311
has comment: http://stackoverflow.com/comment/83926460
has comment: http://stackoverflow.com/comment/83925342
has comment: http://stackoverflow.com/comment/83925929
has comment: http://stackoverflow.com/comment/83924761
upvote count: 2
downvote count: 0
type: Answer
has body: You are putting too much emphasis on public/private access. In Python every member of any instance (method, variable, etc.) is publicly available. So, you wouldn't even usually bother to write special getter or setters. Instead: c = Cla() c.var = 42 print(c.var) is perfectly acceptable. If you still would like to hint to other programmers that the variable should be private and not messed with, you would usually prefix it with a single underscore: self._var. However, this is only a convention. For more, see https://stackoverflow.com/a/1301369/1269892

http://stackoverflow.com/comment/84002273
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48503190
type: AnswerComment
has text: you should give `corpus` a value, otherwise it's not defined for the interpreter, something like: `print(query_named_params('sonnets', 10))`

http://stackoverflow.com/comment/83847995
type: QuestionComment
comment on: http://stackoverflow.com/q/48428562
has text: Essentially the solution here could be similar to [this one](https://stackoverflow.com/questions/42063542/mathplotlib-draw-triangle-with-gradient-fill). Other options would be to set the pixels outside of the area of interest to nan. Make sure to share what you have tried. Also read and understand [mcve].
score: 0
type: Comment

http://stackoverflow.com/a/48427261
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48421703
score: 1
answers question: http://stackoverflow.com/q/48421703
has body: if this '\u00e9' is actually written into the file as \ u 0 0 e 9 as normal characters by the source of the data, you need to do a string replace. the trick here is that you need to escape the \ character in the replace function first parameter s.replace('\\u00e9', 'é' ) or use a "raw string literal" by prefixing r s.replace(r'\u00e9', 'é' )
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/48336723
linked to: http://stackoverflow.com/q/18940249
has comment: http://stackoverflow.com/comment/83658699
tagged with: python-requests
has title: function missing 2 required positional arguments: 'url' and 'list'
favorite count: 0
has comment: http://stackoverflow.com/comment/83658604
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/48337579
has comment: http://stackoverflow.com/comment/83658568
has answer: http://stackoverflow.com/a/48337579
has body: I'm trying to write a python script to get the number of url used in a particuler web page: TypeErrorTraceback (most recent call last) &lt;ipython-input-7-a3136853c4b2&gt; in &lt;module&gt;() 30 return no_use 31 32 print(mining_webpage()) TypeError: mining_webpage() missing 2 required positional arguments: 'url' and 'list' This is the code: from bs4 import BeautifulSoup as bs import requests import re import pandas as pd import matplotlib as plt def mining_webpage(url,list): '''Finds the howmany websites are used in the webpage and counts its total number''' reallink=[] tokens=[] list1=[] no_use={} link=url word_list=list text=requests.get(link).text soup=bs(text) for l in soup.find_all(href=re.compile('https')): reallink.append(l.get('href').split('//')) for lists in reallink: '''print(lists[-1])''' list1.append(lists[-1].split('.')) '''print(list1)''' for l in list1: tokens.append(l[-2]) for word in tokens: if word in no_use.keys(): no_use[word]+=1 else: no_use[word]=1 return no_use print(mining_webpage()) I know this maybe has a simple solution but I really can't figure out what I am doing wrong, this is what I'm writing to practice.
upvote count: 0
score: -3
answer count: 1
downvote count: 3

http://stackoverflow.com/q/48481520
type: Question
has answer: http://stackoverflow.com/a/48482334
has comment: http://stackoverflow.com/comment/84010970
type: UnansweredQuestion
tagged with: python
has body: I have experimental data produced by different programs. One is logging the start and end time of a trial as well as the type of trial (a category). start trial type end 0 6.002987 2 c 7.574240 1 7.967054 3 b 19.084946 2 21.864419 5 b 23.298480 3 23.656995 7 c 24.087210 4 24.194764 9 c 27.960752 The other one records a continous datastream and logs the time for each observation. X Y Z 0.0000 0.324963 -0.642636 -2.305040 0.0333 0.025089 -0.480412 -0.637273 0.0666 0.364149 0.966594 0.789467 0.0999 -0.087334 -0.761769 0.399813 0.1332 0.841872 2.306711 -1.059608 I have the 2 tables as pandas DataFrames and want to retrieve only those parts of the continuous data that is between the start to end ranges found in the rows of the trials DataFrame. I managed that by using a for-loop that iterates over the rows, but I was thinking that there must be more of a "pandas way" of doing this. So I looked into apply, but what I came up with so far was even considerably slower than the loop. As I'm working on a lot of large datasets I'm looking for the most efficient way in terms of execution time to solve this. This is a slice of the expected result for the continous DataFrame: X Y Z trial type 13.6863 0.265358 0.116529 1.196689 NaN NaN 13.7196 -0.715096 -0.413416 0.696454 NaN NaN 13.7529 0.714897 -0.158183 1.735958 4.0 b 13.7862 -0.259513 0.194762 -0.531482 4.0 b 13.8195 -0.929080 -1.200593 -1.233834 4.0 b [EDIT:] Here I test performance of different approaches. I found a way using apply(), but it isn't much faster than using iterrows. import numpy as np import pandas as pd import matplotlib.pyplot as plt def create_trials_df(num_trials=360, max_start=1400.0): # First df holds start and end times (as seconds) of a trial as well as type of trial. d = {'trial': pd.Series(np.sort(np.random.choice(np.arange(1, 400), replace=False, size=(360,)))), 'type': pd.Series(np.random.choice(('a', 'b', 'c', 'd'),size=num_trials)), 'start': pd.Series(np.sort(np.random.random_sample((num_trials,)))…
tagged with: pandas
has comment: http://stackoverflow.com/comment/83977105
score: 1
has title: Efficient (fast) way to group continuous data in one DataFrame based on ranges taken from another DataFrame in Python Pandas?
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83956027
favorite count: 0

http://stackoverflow.com/comment/83960760
has text: that's the whole question? it doesn't mention anything about the implementation of `outer_function` and `inner_function`?
type: Comment
comment on: http://stackoverflow.com/q/48483960
score: 0
type: QuestionComment

http://stackoverflow.com/comment/121007982
comment on: http://stackoverflow.com/a/48468906
type: AnswerComment
score: 0
type: Comment
has text: The easiest way to perform a hassle-free dot product with two-dimensional NumPy arrays `a` and `b` is `(a * b).sum(axis=-1)`

http://stackoverflow.com/comment/83703367
comment on: http://stackoverflow.com/q/48350948
has text: Using `.loc[dt_obj]` now works as expected. I think the problem was on the fact that I didn't convert the index to datetime in the example reported. Should I edit the question pointing that out?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48430042
tagged with: pybind11
has body: I use pybind11 to add a module _cxx to existing python library liba. The liba._cxx.func doesn't exist until I compile the c++ extension and install the whole library by setup.py. When I run tests in liba/tests/test__cxx.py, it complains that it can't import liba._cxx How to solve this?
tagged with: python
possible better answer: http://stackoverflow.com/a/66104018
linked to: http://stackoverflow.com/q/41748464
answer count: 2
has answer: http://stackoverflow.com/a/48430361
accepted answer: http://stackoverflow.com/a/48430361
has title: pytest and pybind11: can't import c++ extension
has answer: http://stackoverflow.com/a/66104018
type: Question
type: AnsweredQuestion
score: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/83851180

http://stackoverflow.com/comment/83901714
type: Comment
type: QuestionComment
has text: Python does not support the [Oxford comma](https://en.m.wikipedia.org/wiki/Serial_comma).
score: 0
comment on: http://stackoverflow.com/q/48453769

http://stackoverflow.com/q/48471794
has body: I'm trying to install python and tensorflow to learn as part of a class I am taking, and am having some issues installing tensorflow. I keep getting the same set of errors: C:\Users\X\AppData\Local\Programs\Python\Python36-32\python.exe: can't find '__main__' module in 'C:\\' or Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow I've tried uninstalling and reinstalling python while adding it to my path, and that solved me not being stuck with syntax errors (most of the time), but I haven't been able to make any progress. Any advice on moving forward would be appreciated. To be clear, I am typing the following command into my command prompt: pip3 install --upgrade tensorflow As per the instructions on the TensorFlow website - I've been finding the "C:\>" raises a syntax error however.
has answer: http://stackoverflow.com/a/48472005
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83943420
type: UnansweredQuestion
has title: Pip3 installing of Tensorflow issue
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83947051
answer count: 1

http://stackoverflow.com/a/48466568
has body: You can use the tarfile module to what you are asking. Example: import tarfile tar = tarfile.open("test.tar.gz") tar.extractall() tar.close()
downvote count: 4
upvote count: 2
has comment: http://stackoverflow.com/comment/83926582
has comment: http://stackoverflow.com/comment/83927138
score: -2
type: Answer
answers question: http://stackoverflow.com/q/48466421

http://stackoverflow.com/comment/83944363
type: AnswerComment
has text: @gusa10, agreed, i think OP amended his post to clarify. in any case, the idea is there.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48475407

http://stackoverflow.com/comment/83969120
comment on: http://stackoverflow.com/a/48487716
has text: Is change views.py total_fee = int(result[0].get('total_fee')) / 100.00
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83651252
type: QuestionComment
has text: Yes Python 3.5.3 on Ubuntu Linux
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48332775

arrays
tags question: http://stackoverflow.com/q/48385082
tags question: http://stackoverflow.com/q/48353551
tags question: http://stackoverflow.com/q/48366903
tags question: http://stackoverflow.com/q/48405005
tags question: http://stackoverflow.com/q/48393640
tags question: http://stackoverflow.com/q/48360386
tags question: http://stackoverflow.com/q/48420684
tag name: arrays
tags question: http://stackoverflow.com/q/48410774
tags question: http://stackoverflow.com/q/48379965
tags question: http://stackoverflow.com/q/48355436
tags question: http://stackoverflow.com/q/48460978
tags question: http://stackoverflow.com/q/48461551
tags question: http://stackoverflow.com/q/48368855
tags question: http://stackoverflow.com/q/48419214
tags question: http://stackoverflow.com/q/48448385
tags question: http://stackoverflow.com/q/48433076
tags question: http://stackoverflow.com/q/48350320
tags question: http://stackoverflow.com/q/48349548
tags question: http://stackoverflow.com/q/48472710
type: Tag
tags question: http://stackoverflow.com/q/48405592
tags question: http://stackoverflow.com/q/48451167
tags question: http://stackoverflow.com/q/48458865
tags question: http://stackoverflow.com/q/48348131
tags question: http://stackoverflow.com/q/48384720
tags question: http://stackoverflow.com/q/48346896
tags question: http://stackoverflow.com/q/48481902
tags question: http://stackoverflow.com/q/48458104
tags question: http://stackoverflow.com/q/48379205
tags question: http://stackoverflow.com/q/48377399
tags question: http://stackoverflow.com/q/48413069
tags question: http://stackoverflow.com/q/48344065
tags question: http://stackoverflow.com/q/48331501
tags question: http://stackoverflow.com/q/48461042
tags question: http://stackoverflow.com/q/48423851
tags question: http://stackoverflow.com/q/48343244
tags question: http://stackoverflow.com/q/48351223
tags question: http://stackoverflow.com/q/48484124
tags question: http://stackoverflow.com/q/48461297
tags question: http://stackoverflow.com/q/48379243
tags question: http://stackoverflow.com/q/48444561
tags question: http://stackoverflow.com/q/48377010
tags question: http://stackoverflow.com/q/48376702
tags question: http://stackoverflow.com/q/48386293
tags question: http://stackoverflow.com/q/48373228
tags question: http://stackoverflow.com/q/48402274
tags question: http://stackoverflow.com/q/48398528
tags question: http://stackoverflow.com/q/48369864
tags question: http://stackoverflow.com/q/48386742
tags question: http://stackoverflow.com/q/48400578
tags question: http://stackoverflow.com/q/48477531
tags question: http://stackoverflow.com/q/48350916
tags question: http://stackoverflow.com/q/48348116
tags question: http://stackoverflow.com/q/48332050
tags question: http://stackoverflow.com/q/48435731
tags question: http://stackoverflow.com/q/48424990
tags question: http://stackoverflow.com/q/48466901
tags question: http://stackoverflow.com/q/48429596
tags question: http://stackoverflow.com/q/48336037
tags question: http://stackoverflow.com/q/48377506
tags question: http://stackoverflow.com/q/48447287
tags question: http://stackoverflow.com/q/48340841
tags question: http://stackoverflow.com/q/48332599
tags question: http://stackoverflow.com/q/48480510
tags question: http://stackoverflow.com/q/48406987
tags question: http://stackoverflow.com/q/48334185
tags question: http://stackoverflow.com/q/48408264
tags question: http://stackoverflow.com/q/48484358
tags question: http://stackoverflow.com/q/48339315
tags question: http://stackoverflow.com/q/48341537
tags question: http://stackoverflow.com/q/48390258
tags question: http://stackoverflow.com/q/48479750
tags question: http://stackoverflow.com/q/48354087
tags question: http://stackoverflow.com/q/48471329
tags question: http://stackoverflow.com/q/48364836
tags question: http://stackoverflow.com/q/48453620
tags question: http://stackoverflow.com/q/48367575
tags question: http://stackoverflow.com/q/48454328
tags question: http://stackoverflow.com/q/48472961

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48456900
tags question: http://stackoverflow.com/q/48359168
tags question: http://stackoverflow.com/q/48360669
tags question: http://stackoverflow.com/q/48357634
tags question: http://stackoverflow.com/q/48345887
type: Tag
tags question: http://stackoverflow.com/q/48485577
tags question: http://stackoverflow.com/q/48369148
tags question: http://stackoverflow.com/q/48446919
tags question: http://stackoverflow.com/q/48353551
tags question: http://stackoverflow.com/q/48366903
tags question: http://stackoverflow.com/q/48423935
tags question: http://stackoverflow.com/q/48405956
tags question: http://stackoverflow.com/q/48434781
tags question: http://stackoverflow.com/q/48370525
tags question: http://stackoverflow.com/q/48374825
tags question: http://stackoverflow.com/q/48383869
tags question: http://stackoverflow.com/q/48464106
tags question: http://stackoverflow.com/q/48449480
tags question: http://stackoverflow.com/q/48466139
tags question: http://stackoverflow.com/q/48476521
tags question: http://stackoverflow.com/q/48473602
tags question: http://stackoverflow.com/q/48333572
tag name: csv
tags question: http://stackoverflow.com/q/48453660
tags question: http://stackoverflow.com/q/48428743
tags question: http://stackoverflow.com/q/48485772
tags question: http://stackoverflow.com/q/48359744
tags question: http://stackoverflow.com/q/48408054
tags question: http://stackoverflow.com/q/48448472
tags question: http://stackoverflow.com/q/48476040
tags question: http://stackoverflow.com/q/48403000
tags question: http://stackoverflow.com/q/48423851
tags question: http://stackoverflow.com/q/48434430
tags question: http://stackoverflow.com/q/48444561
tags question: http://stackoverflow.com/q/48444311
tags question: http://stackoverflow.com/q/48376702
tags question: http://stackoverflow.com/q/48441790
tags question: http://stackoverflow.com/q/48340341
tags question: http://stackoverflow.com/q/48435966
tags question: http://stackoverflow.com/q/48402968
tags question: http://stackoverflow.com/q/48357177
tags question: http://stackoverflow.com/q/48434423
tags question: http://stackoverflow.com/q/48359925
tags question: http://stackoverflow.com/q/48431644
tags question: http://stackoverflow.com/q/48422730
tags question: http://stackoverflow.com/q/48472691
tags question: http://stackoverflow.com/q/48404125
tags question: http://stackoverflow.com/q/48355493
tags question: http://stackoverflow.com/q/48362976
tags question: http://stackoverflow.com/q/48377430
tags question: http://stackoverflow.com/q/48389084
tags question: http://stackoverflow.com/q/48383962
tags question: http://stackoverflow.com/q/48355680
tags question: http://stackoverflow.com/q/48464750
tags question: http://stackoverflow.com/q/48414657
tags question: http://stackoverflow.com/q/48470872
tags question: http://stackoverflow.com/q/48378866
tags question: http://stackoverflow.com/q/48435050
tags question: http://stackoverflow.com/q/48360723
tags question: http://stackoverflow.com/q/48345346
tags question: http://stackoverflow.com/q/48366030
tags question: http://stackoverflow.com/q/48478510
tags question: http://stackoverflow.com/q/48363259
tags question: http://stackoverflow.com/q/48404681
tags question: http://stackoverflow.com/q/48359354
tags question: http://stackoverflow.com/q/48436337
tags question: http://stackoverflow.com/q/48357044
tags question: http://stackoverflow.com/q/48338381
tags question: http://stackoverflow.com/q/48399871
tags question: http://stackoverflow.com/q/48389030
tags question: http://stackoverflow.com/q/48383288
tags question: http://stackoverflow.com/q/48373136
tags question: http://stackoverflow.com/q/48421506
tags question: http://stackoverflow.com/q/48408948
tags question: http://stackoverflow.com/q/48444961
tags question: http://stackoverflow.com/q/48356899
tags question: http://stackoverflow.com/q/48435033
tags question: http://stackoverflow.com/q/48471630
tags question: http://stackoverflow.com/q/48372556

http://stackoverflow.com/a/48359172
upvote count: 6
has body: When using the list form of invocation, you should not use those additional double quotes. Normally, when your command is given as a single string, quotes can be identify that the contents between the double quotes is all part of a single argument. If you use double quotes like that inside of a list item, it's understood that it should be parsed to pass the quote literally as an argument, so it is escaping your quote and passing it literally. Consequently, nothing matches your include and exclude parameters because the argument contains a literal ". So, the following should be the corrected arguments. subprocess.run(['aws', 's3', 'sync', 's3://my-bucket-1', '.', '--exclude', '*', '--include', '*2018-01-17*', '--dryrun'])
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/48358992
type: Answer
answers question: http://stackoverflow.com/q/48358992

http://stackoverflow.com/q/48399167
has body: I have this Python script that calls a SQL command through the windows command prompt UN1=str(sys.argv[1]) f_statement1 = """ set nocount on; set ansi_warnings off; SELECT c.campaign_name,ca.campaign_id,ca.product_id,p.product_name FROM [AN_MAIN].[dbo].[campaign_addon] ca JOIN product p ON p.product_id = ca.product_id JOIN campaign c ON c.campaign_id = ca.campaign_id WHERE ca.campaign_id IN""" + str(UN1) Here I'm using the 'IN' function for multiple variables meaning it must be in brackets and comma separated if there's more than one. In the command prompt I have to make my string call the file 'addon.py' and it looks like this: addon.py (45123,51241) So I'm forced to put my variables in brackets to make them one argument as far as python in concerned. Is there a way to make the python take any number of variables without having to manually put the commas and brackets in? i.e. addon.py 45123 51241
tagged with: python
has comment: http://stackoverflow.com/comment/83786153
score: 0
answer count: 2
tagged with: sql
linked to: http://stackoverflow.com/q/42123335
tagged with: windows
has title: How to allow for an undefined amount of multiple variables when calling a SQL with Python
has answer: http://stackoverflow.com/a/48401710
type: Question
has answer: http://stackoverflow.com/a/48399343
has comment: http://stackoverflow.com/comment/83786116
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4819356

http://stackoverflow.com/a/48353683
score: 0
has body: I have this program that will print the font names on console if you enter it from the command line. it is python 2.7 but easy to change for 3.x. There is a little side effect that it opens a blank window - just ignore it. I have windows 10. # show-tk-fonts.py # Sunday, December 10, 2017 4:45:00 PM -0600 import datetime import sys from Tkinter import Tk import tkFont def mysort(a,b): if a[0] == '@': a = a[1:] if b[0] == '@': b = b[1:] return cmp(a.lower(), b.lower()) root = Tk() print "# show-tk-fonts.py output" print "#", datetime.datetime.now() print i = 0 max = 1 nam = "" fnames = list(tkFont.families()) fnames.sort(mysort) for s in fnames: if len(s) &gt; max: max = len(s) nam = s ls = 32-len(s) if i == 0: sys.stdout.write(' "'+s+'"'+' '*ls) else: sys.stdout.write('"'+s+'"'+' '*ls) i += 1 if i == 3: sys.stdout.write('\n') i = 0 #print "max length = ",max #print "name = ",'"'+nam+'"' print "normal exit" root.mainloop()
has comment: http://stackoverflow.com/comment/83693981
answers question: http://stackoverflow.com/q/48352950
has comment: http://stackoverflow.com/comment/83697085
has comment: http://stackoverflow.com/comment/83705246
type: Answer

http://stackoverflow.com/q/48452206
favorite count: 0
type: Question
has title: FInding certain data from key in json output python
tagged with: python
has comment: http://stackoverflow.com/comment/83897641
has body: I am trying to get a key code from a json output. But i cannot seem to get it, I get errors left and right. Here is my code. import requests import time import threading import json def ThreadRequest(): scrape_url = "https://pastebin.com/api_scraping.php?limit=1" json_data = requests.get(scrape_url) python_obj = json.loads(json_data.text) print python_obj["key"] ThreadRequest() I either get TypeError: list indices must be integers, not str ValueError: No JSON object could be decoded TypeError: expected string or buffer I have tried many ways, different ways, even parsing by using .split() function. I cannot seem to get the understanding of how to parse in json. Here is the API output [ { "scrape_url": "https://pastebin.com/api_scrape_item.php?i=rkFbtGSj", "full_url": "https://pastebin.com/rkFbtGSj", "date": "1516914453", "key": "rkFbtGSj", "size": "3031", "expire": "0", "title": "", "syntax": "text", "user": "" } ]
has answer: http://stackoverflow.com/a/48452304
has comment: http://stackoverflow.com/comment/83897585
type: UnansweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83897757
upvote count: 1

http://stackoverflow.com/comment/83736181
type: Comment
score: 0
type: AnswerComment
has text: oh, sorry I read that incorrectly, I'll try to add an `explicit_wait` instead. thanks again @KeyurPotdar
comment on: http://stackoverflow.com/a/48373047

http://stackoverflow.com/a/48430587
type: Answer
accepted answer of: http://stackoverflow.com/q/48427922
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48427922
has body: Here is one way to do it: # Create lists column_labels = X.columns.tolist() coef = logreg.coef_.squeeze().tolist() # Zip together labels_coef = list(zip(column_labels, coef)) # Verify the result print(labels_coef)
score: 1

http://stackoverflow.com/comment/83885955
score: 0
type: Comment
type: QuestionComment
has text: Computers don't use base 10
comment on: http://stackoverflow.com/q/48446875

http://stackoverflow.com/q/48487747
has comment: http://stackoverflow.com/comment/83968735
tagged with: python
has comment: http://stackoverflow.com/comment/83968412
has title: How to take specific ip addresses from log file in shell script and convert to Python
has comment: http://stackoverflow.com/comment/83968466
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has body: I am new to python and I have a log file, which consists hundreds of destination ip, and I have taken just the destination ip addresses from log file and this is the code f = open('/Users/kiya/Desktop/webgw logs/check/1st.log', 'r') list_ip = sorted([]) for line in f: k = line.split()[3] list_ip.append(k) ips = list(set(list_ip)) for ip in ips: #print(ip,'Count',list_ip.count(ip)) print (ip) And how can I filter the IP address based on the shell script below in python cat 1st.log | grep -e "proto=6" -e "proto=17" | grep -e "srcip=10\." -e "srcip=172\." -e "srcip=192\.168" | grep -v -e "dstip=10\." -e "dstip=169\.254" -e "dstip=17\." -e "dstip=208\.91\.11[2-3]\." -e "dstip=172\." | cut -d ' ' -f 7 | sort | uniq | awk 'match($0,/[0-9]+.[0-9]+.[0-9]+.[0-9]+/){print substr($0, RSTART, RLENGTH)}' &gt; list.txt This is my basic log file, and there are many data in it #time_stamp "auth_user" dest_ip src_ip status_code "req_line" "categories" "rep_level" "media_type" bytes_to_client bytes_from_client bytes_to_server bytes_from_server "user_agent" "virus_name" block_res "application_name" [30/Dec/2017:23:59:47 +0900] "" 255.255.255.255 172.16.23.177 407 "CONNECT dapi.ds-intel.net:443 HTTP/1.1" "" "-" "" 2935 243 0 0 "Devicescape-Agent/2.0.999 (Windows 7 - 34525574-f744-a01f-f5a2-bbca6285294e) tmobile_wispr1" "" 81 "" [30/Dec/2017:23:59:47 +0900] "" 255.255.255.255 172.16.23.177 407 "CONNECT dapi.ds-intel.net:443 HTTP/1.1" "" "-" "" 2946 327 0 0 "Devicescape-Agent/2.0.999 (Windows 7 - 34525574-f744-a01f-f5a2-bbca6285294e) tmobile_wispr1" "" 81 "
has answer: http://stackoverflow.com/a/48487796
has comment: http://stackoverflow.com/comment/83968448
tagged with: pandas

http://stackoverflow.com/comment/84005834
has text: thanks, this does answer the question. but I'm realizing I think I don't fully understand what Beautifulsoup is doing. for example, i run soup.findall on another aspect of my code and it returns something of the form [div class="..." data-id="..." src="abc.com"]. this is a collection of data, what's the general way to get at something in the collection? I did try data["src"] to try and get abc.com but it didn't work. one other question: when I try and get the page title it will return <Title>XYZ . how do i just get the XYZ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48471107

http://stackoverflow.com/q/48445690
tagged with: python
tagged with: uber-api
score: -1
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
has body: Currently within the app, requesting a UberX instantly give you a exact quote price but in the Python API, I couldn't find it. I can only find the range of the cost. Where is the exact quote at?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48448078
type: Question
has answer: http://stackoverflow.com/a/48448078
has title: No exact amount estimate price for UberX

http://stackoverflow.com/comment/83754750
score: 0
comment on: http://stackoverflow.com/q/48383869
type: QuestionComment
has text: Did you already try debugging your code?
type: Comment

http://stackoverflow.com/a/48355413
has comment: http://stackoverflow.com/comment/83730942
has body: Using the code from the previous question, we simple change the any method to a sum method. The adds up all of the 1's to effectively count the number of occurrences in a gives row (axis=1). ## added and extra Jones into row 1 for 'Jan' column sales = [{'account': 'Jones LLC', 'Jan': 'Jones', 'Feb': '200', 'Mar': '140'}, {'account': 'Alpha Co', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'}, {'account': 'Blue Inc', 'Jan': '50', 'Feb': '90', 'Mar': '95' }] df = pd.DataFrame(sales) df_list = [] for search_string in ['Jones', 'Co', 'Alpha']: #use above method but rename the series instead of setting to # a columns. The append to a list. df_list.append(df.apply(lambda x: x.str.contains(search_string)) .sum(axis=1) ## HERE IS SUM in place of any .astype(int) .rename(search_string)) #concatenate the list of series into a DataFrame with the original df df = pd.concat([df] + df_list, axis=1) df Out[2]: Feb Jan Mar account Jones Co Alpha 0 200 Jones 140 Jones LLC 2 0 0 1 210 Jones 215 Alpha Co 1 1 1 2 90 50 95 Blue Inc 0 0 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83726885
downvote count: 0
answers question: http://stackoverflow.com/q/48346183
type: Answer

http://stackoverflow.com/comment/83724897
score: 0
type: QuestionComment
has text: I was just renaming the file by removing .7z from the name. Maybe that is a wrong approach. How does one decompress this file? Thank you very much.
comment on: http://stackoverflow.com/q/48357759
type: Comment

http://stackoverflow.com/a/53073300
answers question: http://stackoverflow.com/q/48390977
score: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/112356677
has body: Your __aenter__ method must return a context. class MyAsyncContextManager: async def __aenter__(self): await log('entering context') # maybe some setup (e.g. await self.setup()) return self async def __aexit__(self, exc_type, exc, tb): # maybe closing context (e.g. await self.close()) await log('exiting context') async def do_something(self): await log('doing something') usage: async with MyAsyncContextManager() as context: await context.do_something()
upvote count: 5
type: Answer

http://stackoverflow.com/comment/83806237
type: QuestionComment
has text: I find it unlikely that HDF5 is optimized for a large number of datasets. It may be better to keep a separate dictionary and rely on a single dataset for the feature vectors.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48405225

http://stackoverflow.com/comment/83757719
score: 0
comment on: http://stackoverflow.com/q/48384681
type: Comment
type: QuestionComment
has text: @LutzHorn is the incorrect json format which i'm getting from REST API ?: `{ body: [ { id:x1234 name:a1 { version:123 appname:abc } }, { id:b1234 name:b1 { appname:testapp subapp:test2 } }] } `

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48457134
tags question: http://stackoverflow.com/q/48486465
tags question: http://stackoverflow.com/q/48411672
tags question: http://stackoverflow.com/q/48428792
tags question: http://stackoverflow.com/q/48431331
tags question: http://stackoverflow.com/q/48459519
tags question: http://stackoverflow.com/q/48367943
tags question: http://stackoverflow.com/q/48433519
tags question: http://stackoverflow.com/q/48407177
tags question: http://stackoverflow.com/q/48369325
tags question: http://stackoverflow.com/q/48433682
tags question: http://stackoverflow.com/q/48454151
tags question: http://stackoverflow.com/q/48353488
tags question: http://stackoverflow.com/q/48337814
tags question: http://stackoverflow.com/q/48448095
tags question: http://stackoverflow.com/q/48363069
tags question: http://stackoverflow.com/q/48464805
tags question: http://stackoverflow.com/q/48462001
tags question: http://stackoverflow.com/q/48456322
tags question: http://stackoverflow.com/q/48427031
tags question: http://stackoverflow.com/q/48364907
tags question: http://stackoverflow.com/q/48475290
tags question: http://stackoverflow.com/q/48431871
tags question: http://stackoverflow.com/q/48346959
tags question: http://stackoverflow.com/q/48357882
tags question: http://stackoverflow.com/q/48344744
tags question: http://stackoverflow.com/q/48454755
tags question: http://stackoverflow.com/q/48476900
tags question: http://stackoverflow.com/q/48482355
tags question: http://stackoverflow.com/q/48368542
tags question: http://stackoverflow.com/q/48421297
tags question: http://stackoverflow.com/q/48404736
type: Tag
tags question: http://stackoverflow.com/q/48363179
tags question: http://stackoverflow.com/q/48333189
tags question: http://stackoverflow.com/q/48347378
tags question: http://stackoverflow.com/q/48485546
tags question: http://stackoverflow.com/q/48355897
tags question: http://stackoverflow.com/q/48358162

http://stackoverflow.com/q/48464189
type: AnsweredQuestion
has body: Let's say I have two given hex values which are str as datatype: a = 0x15 b = 0x18 Now I would like to append them so that I have as result: 0x1518 The normal way would be to cast the values to int to be able to append, like: (hex( (int(a)&lt;&lt;8) | int(b) )) I'm getting the error: ValueError:invalid literal for int() with base 10: '0x15' What I'm doing wrong here?
upvote count: 0
has comment: http://stackoverflow.com/comment/83921748
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83921667
has answer: http://stackoverflow.com/a/48464284
has comment: http://stackoverflow.com/comment/83921708
has answer: http://stackoverflow.com/a/48464389
accepted answer: http://stackoverflow.com/a/48464257
tagged with: python
linked to: http://stackoverflow.com/q/209513
has title: Append 2 hex values in python not working
score: -1
has answer: http://stackoverflow.com/a/48464249
has answer: http://stackoverflow.com/a/48464257
answer count: 4
possible better answer: http://stackoverflow.com/a/48464284

http://stackoverflow.com/a/48467866
has body: This is one way. import pandas as pd df = pd.DataFrame([[' $- '], ['1'], ['10'], ['100'], ['10000'], ['97250400'], ['98000000'], ['99000000']], columns=['A']) df['A'] = df['A'].apply(pd.to_numeric, errors='coerce') df.dtypes # A float64 # dtype: object
answers question: http://stackoverflow.com/q/48467759
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48467759
upvote count: 2
score: 2

http://stackoverflow.com/a/48514792
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/84062969
has comment: http://stackoverflow.com/comment/84067110
has comment: http://stackoverflow.com/comment/128642995
has comment: http://stackoverflow.com/comment/84106853
has comment: http://stackoverflow.com/comment/84107202
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48480009
has body: Here's a minimal example how you can do it with ScrapyRT. This is the project structure: project/ ├── scraping │ ├── example │ │ ├── __init__.py │ │ ├── items.py │ │ ├── middlewares.py │ │ ├── pipelines.py │ │ ├── settings.py │ │ └── spiders │ │ ├── __init__.py │ │ └── quotes.py │ └── scrapy.cfg └── webapp └── example.py scraping directory contains the Scrapy project. This project contains one spider quotes.py to scrape some quotes from quotes.toscrape.com: # -*- coding: utf-8 -*- from __future__ import unicode_literals import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' start_urls = ['http://quotes.toscrape.com/'] def parse(self, response): for quote in response.xpath('//div[@class="quote"]'): yield { 'author': quote.xpath('.//small[@class="author"]/text()').extract_first(), 'text': quote.xpath('normalize-space(./span[@class="text"])').extract_first() } In order to start ScrapyRT and listen to requests for scraping, go to the Scrapy project's directory scraping and issue scrapyrt command: $ cd ./project/scraping $ scrapyrt ScrapyRT will now listen on localhost:9080. webapp directory contains simple Flask app that scrapes quotes on demand (using the spider above) and simply displays them to user: from __future__ import unicode_literals import json import requests from flask import Flask app = Flask(__name__) @app.route('/') def show_quotes(): params = { 'spider_name': 'quotes', 'start_requests': True } response = requests.get('http://localhost:9080/crawl.json', params) data = json.loads(response.text) result = '\n'.join('&lt;p&gt;&lt;b&gt;{}&lt;/b&gt; - {}&lt;/p&gt;'.format(item['author'], item['text']) for item in data['items']) return result To start the app: $ cd ./project/webapp $ FLASK_APP=example.py flask run Now when you point the browser on localhost:5000, you'll the list of quotes freshly scraped from quotes.toscrape.com.
answers question: http://stackoverflow.com/q/48480009
has comment: http://stackoverflow.com/comment/84107355
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84109429

http://stackoverflow.com/comment/83864736
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48436707
type: Comment
has text: Not sure I understand the expected result. Why are there less rows in the result?

http://stackoverflow.com/a/48349469
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85652744
accepted answer of: http://stackoverflow.com/q/48338597
has comment: http://stackoverflow.com/comment/85729919
answers question: http://stackoverflow.com/q/48338597
has body: Just as a note, you're probably going to need more than a single image of each additional animal (or category) that you want the model to recognize. If you don't have a bunch of images for each category yet, you can try to find some here: http://image-net.org/synset?wnid=n01318894 The Turi Create demo you are using assumes that your all of the images for each category are saved in their own folder. So you would have separate folders for images/dog, images/cat, images/pigeon, etc. The tutorial uses this directory structure to generate a set of labels for each image. You can generalize what they have by replacing the data['label'] = ... line with: import os data['label'] = data['path'].apply( lambda path: os.path.dirname(path).split('/')[-1] ) This will look at the path of every image and use the deepest folder name as the label for training.
downvote count: 0

http://stackoverflow.com/comment/83729365
comment on: http://stackoverflow.com/a/48370973
type: Comment
score: 0
type: AnswerComment
has text: thanks alot @Andrea Corbellini . Its working fine and also thnks for explaining my mistake.

http://stackoverflow.com/q/48346403
has comment: http://stackoverflow.com/comment/83840866
type: Question
has title: Django: relation "django_site" does not exist in app with psql using sites framework
has comment: http://stackoverflow.com/comment/83842289
tagged with: django-sites
possible better answer: http://stackoverflow.com/a/48346579
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/48433080
accepted answer: http://stackoverflow.com/a/48433080
linked to: http://stackoverflow.com/q/23925726
has body: after switching from sqlite to postgres for local dev db, I am unable to run migrations for my app. Several fixes and approaches I've attempted have not resolved (ex: Django: relation "django_site" does not exist). python: 3.6.3 Django Version: 1.11.9 psql (PostgreSQL): 10.1 installed apps: DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'widget_tweaks', 'mptt', 'channels', 'honeypot', 'gunicorn', 'djangosecure', # Allauth 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) LOCAL_APPS = ( 'users.apps.UsersConfig', #because of a signal 'common', 'geo', 'community', 'objects', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS in .env file: SITE_ID=1 solutions I have attempted: Cleared all migrations and migration files and ran: $ ./manage.py makemigrations then I have attempted sequential and manual migrations of apps starting with django.contrib, such as: $ ./manage.py migrate sites (first) then applying additional migrations. but regardless of how I order app migrations does not change err or allow migration to complete. I have also tried migrations with --fake-initial. it looks like it is calling a site object before creating site model. project/utils/middleware.py: class SiteMiddleware(object): def process_request(self, request): try: current_site = Site.objects.get(domain=request.get_host()) except Site.DoesNotExist: current_site = Site.objects.get(id=settings.SITE_ID) request.current_site = current_site if current_site.domain in settings.HOST_MIDDLEWARE_URLCONF_MAP: request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[str(current_site)] .pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/utils.py: class CursorWrapper(object): def __init__…
has comment: http://stackoverflow.com/comment/83678619
tagged with: django
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48444472
has comment: http://stackoverflow.com/comment/83683120
tagged with: postgresql
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48346579
has comment: http://stackoverflow.com/comment/83678752
has comment: http://stackoverflow.com/comment/83760043

http://stackoverflow.com/q/48351338
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83690028
has comment: http://stackoverflow.com/comment/83689838
has comment: http://stackoverflow.com/comment/83690117
has comment: http://stackoverflow.com/comment/83689763
has title: Overhead in Python multiprocessing module
has comment: http://stackoverflow.com/comment/83689878
has comment: http://stackoverflow.com/comment/83690094
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83689787
has comment: http://stackoverflow.com/comment/83690330
has comment: http://stackoverflow.com/comment/83690228
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48352088
has body: I am using the multiprocessing module in Python and expect some overhead launching the process, creating a queue and putting and getting value to/from the queue. However, if the sub-process has enough work to do, I would expect that the overhead would eventually be washed out. Running a simple example (explained below), the runtime of my spawned process is about 10 times that of the same process launched from the parent process, even for very large jobs. In the following code, I compute the mean of a series of larger and larger arrays. I compare calling numpy.mean from the parent process to calling the same mean function from a single spawned process and to doing nothing in a spawned process (to get an idea of overhead cost). Initially, the results are as I expect. The total runtime is much faster when mean is called from the parent process than when called from a spawned process. For small jobs, the runtime for the spawned process is dominated by the overhead. What is surprising, however, is that for larger jobs, the runtime for the spawned process consistently exceeds the cost of calling from the parent process by about a factor of 10. Can anyone provide an explanation for this? Is this due to memory limitations in the sub-process? The largest arrays I test are 125MB, 500MB and 2GB. Here is the code : %matplotlib import numpy, multiprocessing, pandas def do_nothing(x,q): q.put(x[-1]) def my_mean(x,q): q.put(numpy.mean(x)) def test_mp(f,x): q = multiprocessing.Queue() p = multiprocessing.Process(target=f,args=(x,q)) p.start() p.join() s = q.get() return s ndata = 2**numpy.arange(10,29,2) tr1,tr2,tr3 = [[],[],[]] for n in ndata: x = numpy.random.rand(n) tresults = %timeit -n 1 -r 5 -o -q test_mp(do_nothing,x) tr1.append(tresults) tresults = %timeit -n 1 -r 5 -o -q test_mp(my_mean,x) tr2.append(tresults) tresults = %timeit -n 1 -r 5 -o -q numpy.mean(x) tr3.append(tresults) print("All done") t1,t2,t3 = map(lambda tr : pandas.Series([1000*t.best for t in tr]),[tr1,tr2,…
downvote count: 0
has comment: http://stackoverflow.com/comment/83689814
score: 1

http://stackoverflow.com/comment/83809007
comment on: http://stackoverflow.com/a/48409615
has text: so in the example what does loc=18 do?and the code in general?
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48448455
has comment: http://stackoverflow.com/comment/83890981
has comment: http://stackoverflow.com/comment/83893891
answers question: http://stackoverflow.com/q/48448240
type: Answer
has comment: http://stackoverflow.com/comment/83891097
accepted answer of: http://stackoverflow.com/q/48448240
has comment: http://stackoverflow.com/comment/83892875
score: 0
type: AcceptedAnswer
has body: Without example data, it's not absolutely clear what you want. But this should help you vectorise: numSurgeries = {shift: np.sum((OR['PATIENT_IN_ROOM_DTTM'] &gt;= df.DateTime[shift]) &amp; \ (OR['PATIENT_IN_ROOM_DTTM'] &lt; df.DateTime[shift+1])) \ for shift in range(len(df.Date))} The output is a dictionary mapping integer shift to numSurgeries.

http://stackoverflow.com/comment/83952369
has text: Granted, but is there a reason why op wouldn't want that?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48479590

http://stackoverflow.com/comment/83650909
comment on: http://stackoverflow.com/q/48332461
type: QuestionComment
score: 0
has text: Same error `SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Users\mypc\Anaconda3\envs\fenv\Scrip ts\flask.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for de tails`
type: Comment

http://stackoverflow.com/comment/83795472
has text: Did you add `F:\Python_Code` to the environment variable `PYTHONPATH` ?
comment on: http://stackoverflow.com/q/48403337
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/110477286
type: AnswerComment
comment on: http://stackoverflow.com/a/52300696
type: Comment
has text: Note: When using the 'Mount Drive' button in the file browser, no authentication codes are necessary for notebooks that have only been edited by the current user.
score: 3

http://stackoverflow.com/q/48468846
has comment: http://stackoverflow.com/comment/83931561
downvote count: 0
has answer: http://stackoverflow.com/a/53018737
has answer: http://stackoverflow.com/a/48468945
has title: How to set Spyder as default program/app to open (.py) Python file?
favorite count: 0
type: Question
has body: How to set Spyder as default program for Python file? This question has been asked over and over in here and here. I looked around, there still isn't an answer. I want to click on a .py file, and open it in Spyder. Instead of, opening Sypder from Terminal, then go to File > open. I'm using a Mac. This question was asked as early as 2013. It's now 2018!
tagged with: editor
score: 3
tagged with: python
tagged with: macos
answer count: 2
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/24643474
linked to: http://stackoverflow.com/q/33817046

http://stackoverflow.com/q/48359091
tagged with: dataframe
has answer: http://stackoverflow.com/a/48359142
has body: I have two dataframes. In dataframe1, I have a column with some Null values. I want to fill those null values using the values of another data frame i.e.,dataframe2 by comparing of values of different column of each dataframe. DataFrame 1: Col1 Col2 A Null B Null C NUll A 1000 B 1120 C 3200 Data Frame 2: Col1 Col2 A 500 B 110 C 320 Now I want to fill the null values in first dataframe with values from second dataframe where dataframe1.col1 = dataframe2.col1 The final desired output is like: Col1 Col2 A 500 B 110 C 320 A 1000 B 1120 C 3200 How can I do this in Pandas Dataframes.
accepted answer: http://stackoverflow.com/a/48359307
type: Question
score: 5
has answer: http://stackoverflow.com/a/48359307
has title: Fill Nulls with values in another dataframe in pandas
has answer: http://stackoverflow.com/a/48359147
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48359142
upvote count: 5

http://stackoverflow.com/comment/83724627
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48368298
score: 0
has text: `file_name = f'year_{year}'` syntax also works if using Python 3.6+.

http://stackoverflow.com/q/48385830
possible better answer: http://stackoverflow.com/a/48386211
has comment: http://stackoverflow.com/comment/83759064
type: AnsweredQuestion
answer count: 2
has body: I'm trying to replicate some of the examples from Neural Networks and Deep Learning with Keras, but I'm having problems training a network based on the architecture from chapter 1. The aim is to classify written digits from the MNIST dataset. The architecture: 784 inputs (one for each of the 28 * 28 pixels in MNIST images) a hidden layer of 30 neurons an output layer of 10 neurons Weights and biases are initialized from a Gaussian distribution with mean 0 and standard deviation 1. The loss/cost function is mean squared error. The optimizer is stochastic gradient descent. Hyper-parameters: learning rate = 3.0 batch size = 10 epochs = 30 My code: from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD from keras.initializers import RandomNormal # import data (x_train, y_train), (x_test, y_test) = mnist.load_data() # input image dimensions img_rows, img_cols = 28, 28 x_train = x_train.reshape(x_train.shape[0], img_rows * img_cols) x_test = x_test.reshape(x_test.shape[0], img_rows * img_cols) input_shape = (img_rows * img_cols,) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices num_classes = 10 y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) print('y_train shape:', y_train.shape) # Construct model # 784 * 30 * 10 # Normal distribution for weights/biases # Stochastic Gradient Descent optimizer # Mean squared error loss (cost function) model = Sequential() layer1 = Dense(30, input_shape=input_shape, kernel_initializer=RandomNormal(stddev=1), bias_initializer=RandomNormal(stddev=1)) model.add(layer1) layer2 = Dense(10, kernel_initializer=RandomNormal(stddev=1), bias_initializer=RandomNormal(stddev=1)) model.add(layer2…
has title: Simple Keras neural network isn't learning
upvote count: 3
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83759337
downvote count: 0
has answer: http://stackoverflow.com/a/48386211
tagged with: machine-learning
tagged with: keras
has answer: http://stackoverflow.com/a/48386081
accepted answer: http://stackoverflow.com/a/48386081
favorite count: 0
type: Question
score: 3
tagged with: mnist
tagged with: python

http://stackoverflow.com/comment/83818073
type: AnswerComment
has text: Note: If performance matters, `setdefault` with a non-constant-literal default can get kinda wasteful on large inputs (in this case it has to create the default new empty `list`s on every call, whether they're needed or not). Making `grouped = collections.defaultdict(list)`, then doing `grouped[score['subject']].append(...)` would be faster/cleaner (`defaultdict` lazily creates the default value only when the key requested doesn't exist); if you wanted to remove the defaulting behavior after, just do `grouped = dict(grouped)` at the end to convert back.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48414056

datetimeoffset
type: Tag
tags question: http://stackoverflow.com/q/48345087
tag name: datetimeoffset

http://stackoverflow.com/q/48411539
linked to: http://stackoverflow.com/q/8608587
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83813993
has comment: http://stackoverflow.com/comment/83813192
has comment: http://stackoverflow.com/comment/83814057
linked to: http://stackoverflow.com/q/37241364
has comment: http://stackoverflow.com/comment/83813422
has answer: http://stackoverflow.com/a/64632846
score: 1
has comment: http://stackoverflow.com/comment/83814261
has comment: http://stackoverflow.com/comment/83814021
answer count: 1
has title: How does Python convert data types?
has comment: http://stackoverflow.com/comment/83813108
has comment: http://stackoverflow.com/comment/83813411
has comment: http://stackoverflow.com/comment/83813291
has body: So as the title says how does converting data types work? For example in Python, when you take an intger or floating number and turn it into a string. What's going on behind the scenes that does this kind of conversion. My hypothesis was that it reads the actual bytes and then goes into memory and makes a new variable that's a string.
has comment: http://stackoverflow.com/comment/83813174
favorite count: 0
has comment: http://stackoverflow.com/comment/83812967
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83812864
has comment: http://stackoverflow.com/comment/83814352
tagged with: casting
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83814166
downvote count: 0

http://stackoverflow.com/a/48443308
downvote count: 0
has comment: http://stackoverflow.com/comment/83916361
type: Answer
answers question: http://stackoverflow.com/q/48438093
score: 4
has comment: http://stackoverflow.com/comment/83903451
upvote count: 4
has body: Subtract both variables, you can do it after sampling like: C = trace['A'] - trace['B'] or you can do it as part of your model using a deterministic variable: C = pm.Deterministic('C', A - B) Update: Now that you have posted your model I will suggest the following prices_A = [25,20,26,23,30,25] prices_B = [45,49,52,58,45,48] basic_model = pm.Model() with basic_model: mu_A = pm.Uniform('mu_A', lower=10, upper=100) sigma_A = pm.Uniform('sigma_A', lower=1, upper=10) mu_B = pm.Uniform('mu_B', lower=10, upper=100) sigma_B = pm.Uniform('sigma_B', lower=1, upper=10) A = pm.Normal('Y_1', mu=mu_A, sd=sigma_A, observed=prices_A) B = pm.Normal('Y_2', mu=mu_B, sd=sigma_B, observed=prices_B) dif = pm.Deterministic('dif', mu_A-mu_B) # diff of the means trace = pm.sample() pm.summary(trace) Basically what I am suggesting is that you do not use find_MAP(), instead sample from the posterior and then from that samples (inside trace) compute what you want. For example summary will give you the mean, standard deviation and other quantities computed from the posterior samples. You may also want to use sample_ppc to get "posterior predictive samples". ppc = pm.sample_ppc(trace, 1000, basic_model) dif_ppc = ppc['Y_1'] - ppc['Y_2'] dif_ppc represents the differences you expect to see for your stocks, including the uncertainty in the means and standard deviations of your stocks. As a side note, maybe you want to replace your Uniform distributions by other distributions like Normal for the means and HalfNormals for the sigmas.

http://stackoverflow.com/q/48397005
type: Question
score: 3
tagged with: fork
has title: Jobutil main loop protection error
tagged with: python
tagged with: jupyter-notebook
has body: I'm getting an error heeding me to protect my main loop, even though I'm protecting my main loop. The skeleton of my code: from sklearn.learning_curve import learning_curve ... def runit(): ... train_sizes, train_scores, test_scores = learning_curve( DecisionTreeClassifier(class_weight='balanced'), X, y, cv=5, train_sizes=train_sizes, n_jobs=4) ... if __name__ == '__main__': runit() I get the error for the line where I run the learning_curve: ImportError: [joblib] Attempting to do parallel computing without protecting your import on a system that does not support forking. To use parallel-computing in a script, you must protect your main loop using "if name == 'main'". Please see the joblib documentation on Parallel for more information Which is weird, because a) I am protecting the main loop and b) I'm running on a Mac, and as a UNIX-based system, forking IS supported. What am I missing? Using Python 3 in a Jupyter notebook, code does not give the error when I use n_jobs=1.
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83653994
type: QuestionComment
has text: please put your `file1` content here.
comment on: http://stackoverflow.com/q/48334347
type: Comment
score: 1

http://stackoverflow.com/a/48366106
answers question: http://stackoverflow.com/q/48365443
has body: Another way you can do using Pandas reshaping: d1 = df.T g = d1.index.str[0] df_out = d1.set_index([g,d1.groupby(g).cumcount()])\ .stack().unstack(1).reset_index(drop=True) Output: 0 1 0 17.387 17.470 1 17.680 17.896 2 17.787 17.228 3 19.930 13.290 4 21.850 14.570 5 24.460 16.300 6 19.930 19.930 7 21.860 21.860 8 24.450 24.450
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/48412688
has body: I am creating an art show with turtle graphics. This is what I have. I am able to run the code by separately entering in each line. Each separate chunk of code draws one item (sky, flower, grass, etc.) How can I put all of this into one function that will run? Or is that not possible? from turtle import * def art_show(): speed(30) penup() goto(-100,160) pensize(30) pencolor('deep sky blue') pendown() fd(500) penup() goto(-100,175) pendown() fd(500) penup() goto(-100,190) pendown() fd(500) penup() goto(60,170) pencolor('yellow') pendown() circle(10) penup() goto(-100,-100) pencolor('forest green') pendown() fd(500) penup() goto(-100,-85) pendown() fd(500) penup() goto(-100,-70) pendown() fd(500) penup() goto(-75,-75) pendown() pensize(3) pencolor('dark green') lt(90) fd(100) penup() goto(-40,-90) pendown() fd(200) penup() goto(-75, 25) pendown() for i in range(6): pencolor("slateblue") circle(25) lt(60) for i in range(6): pencolor('dodgerblue') circle(15) lt(60) for i in range(6): pencolor('deeppink') circle(5) lt(60) penup() goto(-40, 110) pendown() for i in range(6): pencolor("red") circle(25) lt(60) for i in range(6): pencolor('pink') circle(15) lt(60) for i in range(6): pencolor('yellow') circle(5) lt(60) penup() goto(20,-60) pencolor('brown') pendown() rt(90) fd(140) lt(90) fd(100) lt(45) fd(100) lt(90) fd(100) lt(45) fd(100) penup() goto(20, 40) pendown() lt(90) fd(140) penup() goto(70,-60) pendown() lt(90) pencolor('black') fd(45) rt(90) fd(30) rt(90) fd(45)
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48412881
tagged with: python
score: -1
has title: How to run a function in turtle from python 3
has comment: http://stackoverflow.com/comment/83815262
downvote count: 1
has answer: http://stackoverflow.com/a/48413993
favorite count: 0
type: Question
answer count: 2
tagged with: turtle-graphics

http://stackoverflow.com/comment/116039754
comment on: http://stackoverflow.com/a/48418225
score: 0
type: Comment
type: AnswerComment
has text: Does this also work for multi-class datasets?

http://stackoverflow.com/comment/83837965
has text: Just to check: when you say HTTP compression is closed, do you mean that it is disabled? Also, make sure that you haven't enabled Django's GZip middleware in your settings.
type: Comment
comment on: http://stackoverflow.com/q/48423643
type: QuestionComment
score: 0

http://stackoverflow.com/a/48471903
score: 3
answers question: http://stackoverflow.com/q/48471882
has body: The reason for the error is that you are attempting to return an attribute with exactly the same name as the method being decorated by property. Thus, when you call the method name, the call triggers the method again, because self.name is the method declared in the class. This triggers the non-terminating recursion. Instead, change the attribute name: class Person(object): @property def name(self): return self._name @name.setter def name(self, newname): self._name = newname
upvote count: 3
has comment: http://stackoverflow.com/comment/83937761
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83937871
type: Answer
accepted answer of: http://stackoverflow.com/q/48471882
has comment: http://stackoverflow.com/comment/83937770

python
tags question: http://stackoverflow.com/q/48433694
tags question: http://stackoverflow.com/q/48474882
tags question: http://stackoverflow.com/q/48413264
tags question: http://stackoverflow.com/q/48421712
tags question: http://stackoverflow.com/q/48373267
tags question: http://stackoverflow.com/q/48376035
tags question: http://stackoverflow.com/q/48366263
tags question: http://stackoverflow.com/q/48396554
tags question: http://stackoverflow.com/q/48373872
tags question: http://stackoverflow.com/q/48423601
tags question: http://stackoverflow.com/q/48487843
tags question: http://stackoverflow.com/q/48393985
tags question: http://stackoverflow.com/q/48366535
tags question: http://stackoverflow.com/q/48484403
tags question: http://stackoverflow.com/q/48426139
tags question: http://stackoverflow.com/q/48416982
tags question: http://stackoverflow.com/q/48363552
tags question: http://stackoverflow.com/q/48488256
tags question: http://stackoverflow.com/q/48454627
tags question: http://stackoverflow.com/q/48411141
tags question: http://stackoverflow.com/q/48448057
tags question: http://stackoverflow.com/q/48463933
tags question: http://stackoverflow.com/q/48453054
tags question: http://stackoverflow.com/q/48431498
tags question: http://stackoverflow.com/q/48344549
tags question: http://stackoverflow.com/q/48456298
tags question: http://stackoverflow.com/q/48387261
tags question: http://stackoverflow.com/q/48453212
tags question: http://stackoverflow.com/q/48379584
tags question: http://stackoverflow.com/q/48405976
tags question: http://stackoverflow.com/q/48454755
tags question: http://stackoverflow.com/q/48372873
tags question: http://stackoverflow.com/q/48443151
tags question: http://stackoverflow.com/q/48407360
tags question: http://stackoverflow.com/q/48391021
tags question: http://stackoverflow.com/q/48412510
tags question: http://stackoverflow.com/q/48408230
tags question: http://stackoverflow.com/q/48333043
tags question: http://stackoverflow.com/q/48459638
tags question: http://stackoverflow.com/q/48392761
tags question: http://stackoverflow.com/q/48468552
tags question: http://stackoverflow.com/q/48430081
tags question: http://stackoverflow.com/q/48476750
tags question: http://stackoverflow.com/q/48375484
tags question: http://stackoverflow.com/q/48469254
tags question: http://stackoverflow.com/q/48364221
tags question: http://stackoverflow.com/q/48450527
tags question: http://stackoverflow.com/q/48369222
tags question: http://stackoverflow.com/q/48347547
tags question: http://stackoverflow.com/q/48432300
tags question: http://stackoverflow.com/q/48392311
tags question: http://stackoverflow.com/q/48366708
tags question: http://stackoverflow.com/q/48377998
tags question: http://stackoverflow.com/q/48377663
tags question: http://stackoverflow.com/q/48373812
tags question: http://stackoverflow.com/q/48434732
tags question: http://stackoverflow.com/q/48374737
tags question: http://stackoverflow.com/q/48431806
tags question: http://stackoverflow.com/q/48459180
tags question: http://stackoverflow.com/q/48477153
tags question: http://stackoverflow.com/q/48431331
tags question: http://stackoverflow.com/q/48431070
tags question: http://stackoverflow.com/q/48372501
tags question: http://stackoverflow.com/q/48383916
tags question: http://stackoverflow.com/q/48484670
tags question: http://stackoverflow.com/q/48448473
tags question: http://stackoverflow.com/q/48360628
tags question: http://stackoverflow.com/q/48470466
tags question: http://stackoverflow.com/q/48446119
tags question: http://stackoverflow.com/q/48475989
tags question: http://stackoverflow.com/q/48438268
tags question: http://stackoverflow.com/q/48369463
tags question: http://stackoverflow.com/q/48409157
tags question: http://stackoverflow.com/q/48366209
tags question: http://stackoverflow.com/q/48470251
tags question: http://stackoverflow.com/q/48414538
tags question: http://stackoverflow.com/q/48359168
tags question: http://stackoverflow.com/q/48386717
tags question: http://stackoverflow.com/q/48363104
tags question: http://stackoverflow.com/q/48371188

http://stackoverflow.com/comment/83857103
comment on: http://stackoverflow.com/a/48432862
score: 0
type: Comment
has text: Thank you for the quick response! I have actually followed the steps at both of those links. When I was done with the tutorials, I went to the ip address and then the 500 internal error popped up. If I purge Apache, will this mess with anything I have setup for SSH, FTP, and MySql?
type: AnswerComment

http://stackoverflow.com/q/48376035
has comment: http://stackoverflow.com/comment/83739240
favorite count: 0
tagged with: pdb
type: Question
upvote count: 2
has body: I need pdb in almost all of my python files. Is there any way by which I can get rid of the pain of writing import pdb in every python file I create. In other words, Is there any way I can just write pdb.set_trace() and can run the program. Something like including pdb in core python libraries,or making an alias for command python etc.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4929251
tagged with: python
has comment: http://stackoverflow.com/comment/83740722
has answer: http://stackoverflow.com/a/70087290
has title: Include PDB by default in all python files
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83739564
answer count: 1

http://stackoverflow.com/q/48453474
has comment: http://stackoverflow.com/comment/83922952
upvote count: 2
has comment: http://stackoverflow.com/comment/83904150
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83922185
has comment: http://stackoverflow.com/comment/83922583
tagged with: flask
tagged with: jinja2
downvote count: 1
has title: making a table using flask
has comment: http://stackoverflow.com/comment/83922510
has body: Stuck making my table work please help me figure out this piece. python code: @app.route('/books') def result(): dict={'Series Title': 'Batman Vol.1: The Count of the Owls', 'Writers': 'Scott Snyder', 'Pencilers': 'Greg Capullo', 'Inkers': 'Jonathan Glapion', 'Volume': 1, 'Issues Contained': 1-7, 'Publisher': 'DC'} return render_template('books.html', result=dict) html/flask code: &lt;table align="center" id="comic"&gt; {% for key, value in result %} &lt;tr&gt; &lt;th&gt; {{ key }} &lt;/th&gt; &lt;td&gt; {{ value }} &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; Thanks for the help. As clarified in the comments below, the particular error I have is “function not defined” for the function “result()”
has comment: http://stackoverflow.com/comment/83934097
has comment: http://stackoverflow.com/comment/83921628
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/83922061
has answer: http://stackoverflow.com/a/48459866
score: 1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83922228
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83922338
has answer: http://stackoverflow.com/a/67744776
answer count: 2

http://stackoverflow.com/comment/83762030
type: Comment
has text: This has the disadvantage of constructing a potentially very large intermediate object.
type: AnswerComment
comment on: http://stackoverflow.com/a/48386818
score: 0

http://stackoverflow.com/q/48430886
favorite count: 0
has comment: http://stackoverflow.com/comment/83932540
type: Question
tagged with: python-3.x
has title: pandas read_csv will occasionally hang without an error message
has body: I am encountering a strange error that occurs once every few days. I have several virtual machines running on Google Cloud running a Python script. The Python file is very large, but the part that gets stuck is the following: try: f = urlopen('https://resources.lendingclub.com/SecondaryMarketAllNotes.csv') df = pd.read_csv(f) except: print('error') The first line of code always works, but the second line will occasionally stop the program. What I mean by that is that the program will not continue execution, but it does not throw any kind of error. I have logger running in my code in debug mode and it does not record anything. Again, this happens very rarely, but when it does happen my virtual machines will stop. When I look at the processes in top, I see Python running with 0% CPU, and there is still plenty of system memory available. It will continue to sit there for hours without moving on to the next line of code or returning an error. My application is very time sensitive and using urlopen is faster than using pd.read_csv to directly open the file. I notice that when this rare error occurs, it happens at the same time in all of my virtual machines which means that there is likely something about the file being downloaded that is triggering this issue. Why it doesn't cause an error is beyond me. I would greatly appreciate any ideas on what might be causing this and what workarounds might be available. I am using Python 3.5.3 and pandas 0.19.2
has comment: http://stackoverflow.com/comment/83857434
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/83894369
has comment: http://stackoverflow.com/comment/83858951
tagged with: pandas
has comment: http://stackoverflow.com/comment/83858917
downvote count: 0

http://stackoverflow.com/a/48476990
score: 0
has comment: http://stackoverflow.com/comment/83972210
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48473819
answers question: http://stackoverflow.com/q/48473819
has comment: http://stackoverflow.com/comment/83970057
type: Answer
has body: Iscrizione.objects.filter(corso1_id=fasca).values_list('fieldname', flat=True) https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values-list
has comment: http://stackoverflow.com/comment/83970958

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48468692
tags question: http://stackoverflow.com/q/48488308
tags question: http://stackoverflow.com/q/48433529
tags question: http://stackoverflow.com/q/48400593
tags question: http://stackoverflow.com/q/48430145
tags question: http://stackoverflow.com/q/48443629
tags question: http://stackoverflow.com/q/48368901
tags question: http://stackoverflow.com/q/48353398
tags question: http://stackoverflow.com/q/48349587
tags question: http://stackoverflow.com/q/48359729
tags question: http://stackoverflow.com/q/48389140
tags question: http://stackoverflow.com/q/48425316
tags question: http://stackoverflow.com/q/48433481
tags question: http://stackoverflow.com/q/48419373
tags question: http://stackoverflow.com/q/48367665
tags question: http://stackoverflow.com/q/48433383
tags question: http://stackoverflow.com/q/48400945
tags question: http://stackoverflow.com/q/48339767
tags question: http://stackoverflow.com/q/48341411
tags question: http://stackoverflow.com/q/48405646
tags question: http://stackoverflow.com/q/48451061
tags question: http://stackoverflow.com/q/48418802
tags question: http://stackoverflow.com/q/48472208
tags question: http://stackoverflow.com/q/48348622
tags question: http://stackoverflow.com/q/48381351
tags question: http://stackoverflow.com/q/48386297
tags question: http://stackoverflow.com/q/48379373
tags question: http://stackoverflow.com/q/48416936
tags question: http://stackoverflow.com/q/48461452
tags question: http://stackoverflow.com/q/48370525
tags question: http://stackoverflow.com/q/48347409
tags question: http://stackoverflow.com/q/48442442
tags question: http://stackoverflow.com/q/48487910
tags question: http://stackoverflow.com/q/48374487
tags question: http://stackoverflow.com/q/48399579
tags question: http://stackoverflow.com/q/48368856
tags question: http://stackoverflow.com/q/48441863
tag name: pyqt
tags question: http://stackoverflow.com/q/48332086
tags question: http://stackoverflow.com/q/48460935
tags question: http://stackoverflow.com/q/48379584
tags question: http://stackoverflow.com/q/48386253
tags question: http://stackoverflow.com/q/48459897
tags question: http://stackoverflow.com/q/48342313
tags question: http://stackoverflow.com/q/48447053
tags question: http://stackoverflow.com/q/48446236
tags question: http://stackoverflow.com/q/48390893
tags question: http://stackoverflow.com/q/48348491
tags question: http://stackoverflow.com/q/48343322

http://stackoverflow.com/comment/83884840
type: AnswerComment
comment on: http://stackoverflow.com/a/48443581
score: 0
type: Comment
has text: Thank you for your contribution. This snippet only works to some extent, there seems to be a bunch of UnicodeDecodeError's. Everything from invalid start bytes, to invalid continuationbyte. I'll mark your answer as the correct one. Maybe Python is not so good for this task after all.

http://stackoverflow.com/comment/83958527
type: QuestionComment
has text: you can also do: `while 1 in v: v.remove(1)`
comment on: http://stackoverflow.com/q/48482757
score: 0
type: Comment

http://stackoverflow.com/comment/83929847
type: AnswerComment
comment on: http://stackoverflow.com/a/48468011
has text: I know that it's probably a stupid error from a stupid newbie, but if I try your method I face this error message when I type defaultdict(mylistofcaptions): "Traceback (most recent call last): File " ", line 1, in <module> TypeError: first argument must be callable or None"
type: Comment
score: 0

http://stackoverflow.com/a/48367330
has comment: http://stackoverflow.com/comment/83721455
has comment: http://stackoverflow.com/comment/83721476
has body: You have your boolean logic mixed up. If command is l, then it is not equal to h or c; that makes your if statement true: False (!= l) or True (!= h) or True (!= c) == True or is True when one of the two options is true, and for your test at least 2 out of 3 options are always going to be true, possibly 3. You want to use and instead: if command != "l" and command != "h" and command != "c": or use not on 3 or tests with == equality: if not (command == "l" or command == "h" or command == "c"): or, much better and more readable, use not in to test against a set of options: if command not in {'l', 'h', 'c'}:
answers question: http://stackoverflow.com/q/48367293
has comment: http://stackoverflow.com/comment/83822060
type: Answer
has comment: http://stackoverflow.com/comment/83721738
accepted answer of: http://stackoverflow.com/q/48367293
score: 3
has comment: http://stackoverflow.com/comment/83829651
has comment: http://stackoverflow.com/comment/83822020
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83721333
has comment: http://stackoverflow.com/comment/83721408

http://stackoverflow.com/q/48471255
has title: SyntaxError in simple neural network
score: 0
has comment: http://stackoverflow.com/comment/83984736
answer count: 1
has answer: http://stackoverflow.com/a/48471281
upvote count: 1
has comment: http://stackoverflow.com/comment/84055280
downvote count: 1
favorite count: 0
type: Question
has body: line 57 in code: layer2_delta = layer2_error * nonlin(layer2, deriv=True) results in SyntaxError: invalid syntax I have checked the code multiple times and can not for the life of me find why I'm getting a syntax error. It must be in my implementation of the nonlin function call, but I can't see any issue there either. I'm lost #Simple neural network example import numpy as np # If deriv flag is False then this function returns the sigmoid function of x. # If deriv flag is passed in as True, then it calculates the derivative of the function def nonlin(x, deriv = False): if deriv == True: return(x*(1-x)) return 1/(1 + np.exp(-x)) # Input data as an array # The last column in the array is always "1" for accommodating the bias term # This simple network only has two real input nodes plus one input bias node X = np.array([[1,1,1], [3,3,3], [2,2,2], [2,2,2]]) #output data y = np.array([[1], [1], [0], [1]]) # The seed for the random generator is set so that it will return the same random # numbers each time re-running the script, which is sometimes useful for debugging. np.random.seed(1) # Now we intialize the weights to random values. syn0 are the weights between the input # layer and the hidden layer. It is a 3x4 matrix because there are two input weights # plus a bias term (=3) and four nodes in the hidden layer (=4). syn1 are the weights # between the hidden layer and the output layer. It is a 4x1 matrix because there are # 4 nodes in the hidden layer and one output. Note that there is no bias term feeding # the output layer in this example. The weights are initially generated randomly because # optimization tends not to work well when all the weights start at the same value. # synapses syn0 = 2 * np.random.random((3,4)) - 1 #3x4 matrix of weights(2 inputs +1 bias) x 4 nodes in the hidden layer) syn1 = 2 * np.random.random((4,1)) - 1 #4x1 matrix of weights(4 nodes x 1 output) # Now we start training the network # Starts with forward propogration for j in range(60000):…
type: UnansweredQuestion
tagged with: neural-network
tagged with: python

http://stackoverflow.com/comment/115312216
type: AnswerComment
comment on: http://stackoverflow.com/a/48481459
has text: what is this type in `class ModelBase(type):` ?
type: Comment
score: 0

http://stackoverflow.com/q/48431679
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48432017
tagged with: sqlite
has body: I am using a For loop to give values to three variables distance, cty, ctry. Then I want to store the values in a table in sqlite3. Unfortunately the program stores only the first row of values of the For loop in the sqlite3 database: 14004 GOROKA PAPUA NEW GUINEA Code: from math import sin, cos, sqrt, atan2, radians import sqlite3 R = 6373.0 conn = sqlite3.connect('global_airports_sqlite.db') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Ports') cur.execute(''' CREATE TABLE Ports ( Delta INTEGER, City TEXT, Country TEXT )''') coords= 'SELECT lat_decimal, lon_decimal, city, country FROM airports ORDER BY id ASC LIMIT 10' for cord in cur.execute(coords): lat2 = radians(cord[0]) lon2 = radians(cord[1]) cty = cord[2] ctry = cord[3] dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = int(R * c) cur.execute('INSERT INTO Ports (Delta, City, Country) VALUES (?,?,?)', (distance, cty, ctry)) conn.commit() How can I make it store all 10 values in my three columns: Delta, City, Country?
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: using a For loop in python3 to create a 3 columns x 10 rows table in sqlite3
tagged with: python
has answer: http://stackoverflow.com/a/48431976
answer count: 2

http://stackoverflow.com/comment/83902022
has text: Speaking of "retractable", questions on Stackoverflow should be reproducible, see [mcve]. So you may find more help when supplying some sample data or at least link to it, such that people can test this.
type: Comment
comment on: http://stackoverflow.com/a/48454470
score: 0
type: AnswerComment

http://stackoverflow.com/q/48338106
downvote count: 0
tagged with: bokeh
tagged with: updates
favorite count: 0
has body: From the last days, I have been trying to use Bokeh to plot real-time data and display on a .html in order to be embeed in a webpage. I have sucessuly adapted one of the bokeh examples to my needs. I am using a buffer of 50 elements on the plot and I am noting the following behaviour: 1) In case I run the script and go to the browser the x_range fully adapts to incomming data and everything works correctly 2) If I click on "Refresh" on the browser the x_range stops to adapt to incoming data and freezes to the last value. I tried to force the x_axis to initial and end values but the visualization behaves poorly. I think I am not correctly understanding what does the "Refresh" hit impacts my code and how I can workaround this issue. """ To view this example, first start a Bokeh server: bokeh serve --allow-websocket-origin=localhost:8000 And then load the example into the Bokeh server by running the script: python animated.py in this directory. Finally, start a simple web server by running: python -m SimpleHTTPServer (python 2) or python -m http.server (python 3) in this directory. Navigate to http://localhost:8000/animated.html """ from __future__ import print_function import io from numpy import pi, cos, sin, linspace, roll from bokeh.client import push_session from bokeh.embed import server_session from bokeh.plotting import figure, curdoc from bokeh.models import ColumnDataSource fa = open('Accelerometer.txt', 'r') source = ColumnDataSource(data=dict(x=[], y=[])) fg = figure(width=250, plot_height=250, title="RT-Test") fg.line(x='x', y='y', color="olive", source=source) fg.x_range.follow = "end" # Visualization scale and aesthetics fg.xgrid.grid_line_color = None fg.ygrid.grid_line_color = None fg.background_fill_color = "snow" # add the plot to curdoc curdoc().add_root(fg) # open a session which will keep our local doc in sync with server session = push_session(curdoc()) html = """ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; %s &lt;/body&gt; &lt;/html&gt; …
type: Question
has title: Bokeh real time update x_axis after refresh
tagged with: python
has answer: http://stackoverflow.com/a/48346793
tagged with: visualization
tagged with: real-time
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1

setup.py
tags question: http://stackoverflow.com/q/48450692
tags question: http://stackoverflow.com/q/48357817
tags question: http://stackoverflow.com/q/48454999
tags question: http://stackoverflow.com/q/48485629
tags question: http://stackoverflow.com/q/48331386
tag name: setup.py
type: Tag

http://stackoverflow.com/q/48482256
has comment: http://stackoverflow.com/comment/83957560
accepted answer: http://stackoverflow.com/a/48482831
has answer: http://stackoverflow.com/a/48482831
tagged with: dataframe
tagged with: python
has title: What is the pandas.Panel deprecation warning actually recommending?
score: 19
has body: I have a package that uses pandas Panels to generate MultiIndex pandas DataFrames. However, whenever I use pandas.Panel, I get the following DeprecationError: DeprecationWarning: Panel is deprecated and will be removed in a future version. The recommended way to represent these types of 3-dimensional data are with a MultiIndex on a DataFrame, via the Panel.to_frame() method. Alternatively, you can use the xarray package http://xarray.pydata.org/en/stable/. Pandas provides a .to_xarray() method to help automate this conversion. However, I can't understand what the first recommendation here is actually recommending in order to create MultiIndex DataFrames. If Panel is going to be removed, how am I going to be able to use Panel.to_frame? To clarify: I am not asking what deprecation is, or how to convert my Panels to DataFrames. What I am asking is, if I am using pandas.Panel and then pandas.Panel.to_frame in a library to create MultiIndex DataFrames from 3D ndarrays, and Panels are going to be deprecated, then what is the best option for making those DataFrames without using the Panel API? Eg, if I'm doing the following, with X as a ndarray with shape (N,J,K): p = pd.Panel(X, items=item_names, major_axis=names0, minor_axis=names1) df = p.to_frame() this is clearly no longer a viable future-proof option for DataFrame construction, though it was the recommended method in this question.
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/83958010
upvote count: 19
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43427189
has comment: http://stackoverflow.com/comment/83957874
tagged with: pandas
has comment: http://stackoverflow.com/comment/83957992
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83957927
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/83889900
has text: I've edited the question to spell out in more detail. In the end, we'll want the weighted average of prices, given a threshold total value.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48447641

http://stackoverflow.com/comment/83915439
has text: Are both the two columns, input?
comment on: http://stackoverflow.com/q/48461297
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48485948
has comment: http://stackoverflow.com/comment/83967393
has comment: http://stackoverflow.com/comment/83966832
downvote count: 0
has comment: http://stackoverflow.com/comment/83967027
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48485872
has comment: http://stackoverflow.com/comment/83967112
has comment: http://stackoverflow.com/comment/83967738
answers question: http://stackoverflow.com/q/48485872
has comment: http://stackoverflow.com/comment/83967444
has body: A tkinter checkbutton has 3 states: checked unchecked a "semi-checked" state, referred to as "tri-state mode". This state is useful when you have multiple checkbuttons arranged in a hierarchy - while some of the "child" checkbuttons are checked, the "parent" checkbutton should be in this 3rd state. Per default, the 3 states correspond to these 3 values: checked = 1 unchecked = 0 greyed out = anything else (These values can be changed with the onvalue and offvalue parameters, see the docs.) This explains why your checkbutton appears checked by default: A new StringVar's value is the empty string, which corresponds to the special 3rd state. To set the checkbutton's state to "unchecked", you have to set the variable to the offvalue (0 per default): eventToReturn = tk.StringVar(root) eventToReturn.set('0') Alternatively, you can use a BooleanVar or IntVar, which are set to 0 by default: eventToReturn = tk.IntVar()
has comment: http://stackoverflow.com/comment/83967643
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/48401963
type: Answer
has body: My suggestions: If you're doing something at a specified interval, you're probably better off using threading.Timer rather than checking the time yourself. As I said in the comment, you can check for an exit condition instead of brutally killing the process. This also allows to properly clean up what you need. Those time1...time6 really don't look nice, how about a list? Also, time2, time3, time4, time5, time6 are not used. You don't actually need strftime to get hour, day, month, year, etc. They're already there as attributes. You can do something like: cur_time = datetime.datetime.now() cur_hour = cur_time.hour cur_minute = cur_time.minute ...And so on, which is a bit better. In this specific case it won't matter, but if you start measuring milliseconds, the time will be slightly different after a few lines of code, so you should store it and use it from the variable. As for the rest, if you want an example, here I check that a file exists to determine whether to stop or not. It's very crude but it should give you a starting point: from threading import * from os.path import exists def hello(): print('TEST') # Instead of this, do what you need if (exists('stop_file.txt')): return t = Timer(0.5, hello) t.start() hello() Then in the other create you create the stop file when you want it to stop (don't forget to add a line to remove it before starting it again).
score: 0
answers question: http://stackoverflow.com/q/48338062

http://stackoverflow.com/a/48369906
accepted answer of: http://stackoverflow.com/q/48369864
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83728005
has body: After you read your txt, you can using following code fix it pd.DataFrame(df[0].apply(list).values.tolist()) Out[846]: 0 1 2 3 4 5 6 7 8 9 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 1 1 0 0 0 2 0 0 1 1 0 1 1 0 0 0 3 0 0 1 1 0 1 1 0 1 0 4 1 0 1 1 0 1 1 0 0 0 5 1 0 1 1 0 1 1 0 0 0 6 0 0 1 1 0 1 1 0 0 0 7 1 0 1 1 0 1 1 0 0 0 8 0 1 0 0 1 0 0 1 0 1 9 1 0 1 1 0 1 1 0 0 0
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48369864

http://stackoverflow.com/a/48423890
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48423818
score: 1
type: Answer
has body: Probably, the issue is name clutch between your file dropbox.py and module. When running dropbox.Dropbox, python tries to create instance of Dropbox class from your file (which is treated as module too), and you have no such. The motivation behind this order of imports is ability to "override" pre-installed modules with your own. TL;DR: renaming your file should help.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48423818

http://stackoverflow.com/q/48431413
has answer: http://stackoverflow.com/a/48433587
answer count: 3
has comment: http://stackoverflow.com/comment/83854059
downvote count: 0
score: 6
accepted answer: http://stackoverflow.com/a/48433768
has body: I have a service running on a Linux box that creates a named pipe character device-special file, and I want to write a Python3 program that communicates with the service by writing text commands and reading text replies from the pipe device. I don't have source code for the service. I can use os.open(named_pipe_pathname, os.O_RDWR), and I can use os.read(...) and os.write(...) to read and write it, but that's a pain because I have to write my own code to convert between bytes and strings, I have to write my own readline(...) function, etc. I would much rather use a Python3 io object to read and write the pipe device, but every way I can think to create one returns the same error: io.UnsupportedOperation: File or stream is not seekable. For example, I get that message if I try open(pathname, "r+"), and I get that same message if I try fd=os.open(...) followed by os.fdopen(fd, "r+", ...). Q: What is the preferred way for a Python3 program to write and read text to and from a named pipe character device? Edit: Oops! I assumed that I was dealing with a named pipe because documentation for the service describes it as a "pipe" and, because it doesn't appear in the file system until the user-mode service runs. But, the Linux file utility says it is in fact, a character device special file.
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48433587
tagged with: python-3.x
has title: How to open named pipe character device special file for reading and writing in Python
type: AnsweredQuestion
tagged with: linux
has answer: http://stackoverflow.com/a/48432398
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/83855675
has answer: http://stackoverflow.com/a/48433768
has comment: http://stackoverflow.com/comment/83859161
has comment: http://stackoverflow.com/comment/83859265

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

http://stackoverflow.com/a/48472946
answers question: http://stackoverflow.com/q/48472797
upvote count: 1
score: 1
downvote count: 0
type: Answer
has body: Install 64 bit version of cv2. P.S. I would recommend that you go through the guidelines for writing good questions on SO.

http://stackoverflow.com/a/48390714
score: 1
answers question: http://stackoverflow.com/q/48390615
downvote count: 0
upvote count: 1
has body: In Python, you should specify self as the first formal parameter of a definition. In your code, calculator is your first formal parameter, so when it is invoked as an object/instance method, it takes the value of the instance and there is no formal parameter self which is accessible (leading to the reported syntax errors): def optimize(self): print self.test for file in self.onlyFiles: do stuff
has comment: http://stackoverflow.com/comment/83769709
type: Answer
has comment: http://stackoverflow.com/comment/83769928
has comment: http://stackoverflow.com/comment/83769999

http://stackoverflow.com/comment/83821361
comment on: http://stackoverflow.com/q/48415862
type: Comment
type: QuestionComment
score: 2
has text: What is an "inverted coma" ?

http://stackoverflow.com/q/48372501
accepted answer: http://stackoverflow.com/a/48372547
has title: Reordering rows based on number formed by combining columns in Python
has answer: http://stackoverflow.com/a/48372547
tagged with: python
tagged with: sorting
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48372559
has body: I have a dataframe formed with pandas as seen below: a b c d e f g h i j k l m n o 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 3 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 4 0 0 0 0 0 1 0 1 0 0 1 0 0 1 0 5 0 0 1 1 0 1 0 1 0 0 1 0 0 1 0 6 1 0 0 1 0 1 0 1 0 0 1 0 0 1 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 8 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 9 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 10 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0 11 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 12 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 13 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 15 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 16 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 I want to sort the rows so that they are ordered in descending order. The value of the row is the number formed by combining the columns. For example, row 1 is 000000000000000 and row 2 is 000000101010010. The final result should have Row 6 as the first row and row 1 as the last row. I've tried dat.sort_values(by=['a'], ascending=False, axis=0) but this only sorts by the first column. Is there another way I could reorder the rows?
has answer: http://stackoverflow.com/a/48372559
type: Question
answer count: 2

http://stackoverflow.com/q/48432738
has body: When plotting a plane in Matplotlib, I do not get a solid color. I get the following with many shades of red: I am using Matplotlib version 1.5.1 in Python 3.5.2. The code that I'm running is below: import numpy as np from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xaxis = np.linspace(-3, 3, 201) yaxis = np.linspace(-3, 3, 201) X, Y = np.meshgrid(xaxis, yaxis) Z = 8 - 3*X - 3*Y ax.plot_surface(X,Y,Z,color='r') plt.savefig('not_red.png')
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48432799
has comment: http://stackoverflow.com/comment/83856803
has comment: http://stackoverflow.com/comment/83878110
type: AnsweredQuestion
score: 3
tagged with: matplotlib
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48432799
has title: Matplotlib surface color not solid
favorite count: 0
type: Question

http://stackoverflow.com/q/48457570
type: Question
has answer: http://stackoverflow.com/a/48457779
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83907872
has answer: http://stackoverflow.com/a/48457751
upvote count: 2
answer count: 5
has answer: http://stackoverflow.com/a/48466979
has comment: http://stackoverflow.com/comment/83907947
has comment: http://stackoverflow.com/comment/83908407
has comment: http://stackoverflow.com/comment/83908602
has title: How can I properly list my data?
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83908663
has comment: http://stackoverflow.com/comment/83908490
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
possible better answer: http://stackoverflow.com/a/48457733
has body: ['10', '0', '1915', '387', '1933', '402'] ['10', '0', '3350', '387', '3407', '391'] ['10', '0', '842', '505', '863', '521'] ['2', '29', '2986', '282', '3112', '300'] ['2', '29', '2753', '286', '2809', '297'] My data is a file full of these strings. The first 2 elements, let's take 10 and 0, are the characteristics of a sample, for example 10-1 is a different sample. What I want is a dictionary where these 2 elements, in this case 10 and 0, are the name under that format 10-0 and 10-0 being a list explained below: 10-0 = [ [1915, 387, 1933, 402], [3350, 387, 3407, 391], [842, 505, 863, 521], ] Same for 2-29 it would be another element of that dictionary containing 2 lists. I referred to https://docs.python.org/3/tutorial/datastructures.html but what I have to do is much more complex than their documentation.
has answer: http://stackoverflow.com/a/48457733
has answer: http://stackoverflow.com/a/48457670
downvote count: 3
has comment: http://stackoverflow.com/comment/83907930
has comment: http://stackoverflow.com/comment/83908038
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/48457751

http://stackoverflow.com/comment/83767155
has text: @georgexsh just an upgrade.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48350091

http://stackoverflow.com/q/48362180
accepted answer: http://stackoverflow.com/a/48362774
tagged with: python
has comment: http://stackoverflow.com/comment/83711668
has answer: http://stackoverflow.com/a/48362774
type: AnsweredQuestion
answer count: 2
has body: Given two functions, I would like to sort out the common tangent for both curves: The slope of the common tangent can be obtained by the following: slope of common tangent = (f(x1) - g(x2)) / (x1 - x2) = f'(x1) = g'(x2) So that in the end we have a system of 2 equations with 2 unknowns: f'(x1) = g'(x2) # Eq. 1 (f(x1) - g(x2)) / (x1 - x2) = f'(x1) # Eq. 2 For some reason I do not understand, python does not find the solution: import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt import sys from sympy import * import sympy as sym # Intial candidates for fit E0_init = -941.510817926696 V0_init = 63.54960592453 B0_init = 76.3746233515232 B0_prime_init = 4.05340727164527 # Data 1 (Red triangles): V_C_I, E_C_I = np.loadtxt('./1.dat', skiprows = 1).T # Data 14 (Empty grey triangles): V_14, E_14 = np.loadtxt('./2.dat', skiprows = 1).T def BM(x, a, b, c, d): return (2.293710449E+17)*(1E-21)* (a + b*x + c*x**2 + d*x**3 ) def P(x, b, c, d): return -b - 2*c*x - 3 *d*x**2 init_vals = [E0_init, V0_init, B0_init, B0_prime_init] popt_C_I, pcov_C_I = curve_fit(BM, V_C_I, E_C_I, p0=init_vals) popt_14, pcov_14 = curve_fit(BM, V_14, E_14, p0=init_vals) x1 = var('x1') x2 = var('x2') E1 = P(x1, popt_C_I[1], popt_C_I[2], popt_C_I[3]) - P(x2, popt_14[1], popt_14[2], popt_14[3]) print 'E1 = ', E1 E2 = ((BM(x1, popt_C_I[0], popt_C_I[1], popt_C_I[2], popt_C_I[3]) - BM(x2, popt_14[0], popt_14[1], popt_14[2], popt_14[3])) / (x1 - x2)) - P(x1, popt_C_I[1], popt_C_I[2], popt_C_I[3]) sols = solve([E1, E2], [x1, x2]) print 'sols = ', sols # Linspace for plotting the fitting curves: V_C_I_lin = np.linspace(V_C_I[0], V_C_I[-1], 10000) V_14_lin = np.linspace(V_14[0], V_14[-1], 10000) plt.figure() # Plotting the fitting curves: p2, = plt.plot(V_C_I_lin, BM(V_C_I_lin, *popt_C_I), color='black', label='Cubic fit data 1' ) p6, = plt.plot(V_14_lin, BM(V_14_lin, *popt_14), 'b', label='Cubic fit data 2') # Plotting the scattered points: p1 = plt.scatter(V_C_I, E_C_I, color='…
has title: Find common tangent line between two cubic curves
tagged with: sympy
upvote count: 3
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48498389
tagged with: numpy
tagged with: equation-solving
score: 3
has answer: http://stackoverflow.com/a/48498389

http://stackoverflow.com/q/48376093
answer count: 1
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48376165
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48376165
tagged with: pandas
has title: Split a column with different delimeters
tagged with: python
type: AnsweredQuestion
has body: Hi I have a csv dataframe in python pandas that has a column that consists of three columns. Those columns are seperated with ',' but there is a column in my dataframe that has values that looks like this: 10Bet\t\t 7.50\t5.25\t 1.34 12BET\t\t 6.90\t 4.60\t 1.38 188BET\t\t 6.00\t 5.20\t 1.38 1xBet\t\t 8.30\t 5.75\t 1.32 888sport\t\t 7.50\t 5.10\t 1.33 bet-at-home\t\t 6.64\t 5.06\t 1.35 bet365\t\t 7.50\t 5.00\t 1.36 Betclic\t\t7.50\t 4.80\t1.35 Betfair\t\t 7.50\t 4.80\t 1.36 Betsafe\t\t 7.60\t 5.25\t 1.35 Betsson\t\t 7.60\t 5.25\t 1.35 BetVictor\t\t 8.00\t 5.25\t 1.33 Betway\t\t 6.50\t 5.25\t 1.36 bwin\t\t 7.25\t 5.00\t 1.35 ComeOn\t\t 7.50\t5.25\t 1.34 Expekt\t\t7.50\t 4.80\t1.35 Interwetten\t\t8.00\t 5.30\t1.30 mybet\t\t 7.50\t 5.00\t1.35 Pinnacle\t\t 8.33 \t 5.79 \t 1.36 SBOBET\t\t 7.40\t 4.80\t 1.35 Sportingbet\t\t 7.50\t5.20\t 1.36 Tipico\t\t8.00\t 5.30\t 1.35 Unibet\t\t 7.50\t 5.10\t 1.34 William Hill\t\t 6.00\t 4.80\t 1.40 youwin\t\t 7.50\t 5.20\t 1.36 Betfair Exchange\t\t 8.41\t 5.56\t 1.37 I want to split it on tabs but there are different number of tabs that separate the values in the cell, the types are; '\t','\t\t ' there is a space in the two tab seperator. I have tried to split it by df['column'].apply(lambda x: x.split(\t)) but it popped out the error of 'float' object has no attribute 'split'. What I want to have is columns that are splitted on the delimiters '\t' or '\t\t ' How can I split this column so that it is shown like this in pandas or any other library in python?: 10Bet 7.50 5.25 1.34 12BET 6.90 4.60 1.38 ...
tagged with: split
downvote count: 0

http://stackoverflow.com/q/48359324
has title: controlling less with Popen
tagged with: less-unix
favorite count: 0
has comment: http://stackoverflow.com/comment/83706013
type: Question
has comment: http://stackoverflow.com/comment/83710457
has comment: http://stackoverflow.com/comment/83707992
has comment: http://stackoverflow.com/comment/83706668
has answer: http://stackoverflow.com/a/48361714
tagged with: python
score: 4
tagged with: unix
has comment: http://stackoverflow.com/comment/83709494
upvote count: 4
type: AnsweredQuestion
tagged with: python-3.x
has body: I'm trying to control less from a Python script on Mac OSX. Basically what I would like is to be able to forward control characters (up/down/left/right) but process other input within the Python program. I'm using Popen to start less, but less reads user input from a source other than stdin. Because of that, I'm unsure how to send any characters to less. The program opens less, waits one second, and then tries to send q to quit using two separate channels: stdin and /dev/tty (since it was mentioned in the SO question I linked above). Neither works. from subprocess import Popen, PIPE import time p1 = Popen("echo hello | less -K -R", stdin=PIPE, shell=True) time.sleep(1) p1.stdin.write(bytes('q', 'utf-8')) with open("/dev/tty", 'w') as tty: tty.write('q') p1.wait() How can I control less from a Python script?
accepted answer: http://stackoverflow.com/a/48361714
linked to: http://stackoverflow.com/q/1441251
tagged with: subprocess
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83840311
type: Comment
comment on: http://stackoverflow.com/a/48424321
type: AnswerComment
has text: Can you show me your structure of your database table!
score: 0

http://stackoverflow.com/a/48477347
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48477317
has body: You're printing the return value of functions that don't return a value. print( e1.checkLife() ) # 3 lives left... This is printed from within the function # None checkLife() returns None, and you print it here
downvote count: 0
type: Answer

http://stackoverflow.com/a/48382483
type: AcceptedAnswer
downvote count: 0
has body: Instead of modifying request, override serializer's method update. Class ItemlSerializer(serializers.ModelSerializer): class Meta: model = ItemModel fields = '__all__' read_only_fields = ('time',) def update(self, instance, validated_data): instance.time = time.time() return super().update(instance, validated_data)
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48377259
type: Answer
answers question: http://stackoverflow.com/q/48377259
score: 4

http://stackoverflow.com/comment/83799866
score: 0
has text: I am unable to see the edit history.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48392998

http://stackoverflow.com/comment/83901933
type: Comment
comment on: http://stackoverflow.com/q/48454161
score: 0
type: QuestionComment
has text: by default, NTFS paths are not case sensitive and CPython "understands" this (as it makes os path calls through win32 api). In your script, before you try to import from `requests_kerberos`, do a quick `import sys` and `print(sys.path)`, please.

http://stackoverflow.com/a/48462446
answers question: http://stackoverflow.com/q/48462226
has comment: http://stackoverflow.com/comment/83922874
downvote count: 0
has comment: http://stackoverflow.com/comment/83921352
has body: You can grab the layers and energies from the text file like this layers = [] energies = [] with open(file) as f: for line in f: linesplit = line.strip().split() # splits by whitespace layers.append(int(linesplit[1])) # 2nd index energies.append(float(linesplit[-1])) # last index Edit: if you have a header line (at say, line 1) you can skip it with: header_line = 1 # or whatever it is with open(file) as f: for line_number, line in enumerate(f, 1): if line_number &lt;= header_line: continue linesplit = line.strip().split() layers.append(int(linesplit[1])) energies.append(float(linesplit[-1])) I don't know what your file looks like because you haven't posted the full thing so I can't help you more than this without seeing the whole thing (i.e. on pastebin.com). One last try: layers = [] energies = [] with open(file) as f: for lineno, line in enumerate(f, 1): linesplit = line.strip().split() # splits by whitespace if not linesplit: # empty continue try: layers.append(int(linesplit[1])) # 2nd inde except (TypeError, IndexError): print("Skipping line {}: {!r}".format(lineno, line)) continue try: energies.append(float(linesplit[-1])) # last index except TypeError: layers.pop() print("Skipping and reverting line {}: {!r}".format(lineno, line)):
has comment: http://stackoverflow.com/comment/83989379
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83990665
score: 2
has comment: http://stackoverflow.com/comment/83921570

http://stackoverflow.com/a/48331999
has body: The first argument to linkage must be either the distances in condensed format, or the array of points being clustered. If you pass the square (N x N) distance matrix, linkage interprets it as N points in N-dimensional space. You can convert from your square matrix to the condensed form with scipy.spatial.distance.squareform. Add this to the beginning of your file from scipy.spatial.distance import squareform and replace this Z=linkage(dmat) with Z = linkage(squareform(dmat))
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48331537
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48331537

http://stackoverflow.com/a/48462317
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83920776
has body: a = [[1,0],[2,0],[3,0],[4,0]] b = [2,4,7,8] def return_common_elemens(a,b): for subval in a: if subval[0] in b: yield subval print(list(return_common_elemens(a,b))) &gt;&gt;&gt;[[2, 0], [4, 0]]
answers question: http://stackoverflow.com/q/48461770

http://stackoverflow.com/a/48436832
has comment: http://stackoverflow.com/comment/83865239
has comment: http://stackoverflow.com/comment/83865313
type: Answer
has comment: http://stackoverflow.com/comment/83865275
has comment: http://stackoverflow.com/comment/83865505
has comment: http://stackoverflow.com/comment/83865424
has comment: http://stackoverflow.com/comment/83865397
has comment: http://stackoverflow.com/comment/83865229
score: 1
answers question: http://stackoverflow.com/q/48436649
type: AcceptedAnswer
has body: def get_context_data(self, **kwargs): context = super(DirectoryClass, self).get_context_data(**kwargs) context['page'] = 'forum' context['user'] = self.request.user return context def get_queryset(self): directory = Directory.objects.filter(pk=self.kwargs['directory_id']) topics = directory.first().topic_set.all().order_by('-last_post') return topics use this only in your ListView, as Django provides pagination to all the Class Based View
downvote count: 0
has comment: http://stackoverflow.com/comment/83865529
has comment: http://stackoverflow.com/comment/83864923
upvote count: 1
has comment: http://stackoverflow.com/comment/83864951
accepted answer of: http://stackoverflow.com/q/48436649
has comment: http://stackoverflow.com/comment/83864961
has comment: http://stackoverflow.com/comment/83865296
has comment: http://stackoverflow.com/comment/83865282

http://stackoverflow.com/comment/83702083
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48357407
type: Comment
has text: sounds like a database error in the application you're making the request to

http://stackoverflow.com/comment/83899544
type: AnswerComment
has text: @sds No, there is no string conversion taking place.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48453225

http://stackoverflow.com/a/48333579
score: 0
has body: Your while loop is while True:. This will never exit unless you explicitly exit from it. You want to add a break in it like so: os.startfile('C:\\restriced access') break
type: Answer
answers question: http://stackoverflow.com/q/48333535

http://stackoverflow.com/comment/83664376
type: QuestionComment
score: 0
has text: I did that too before it didnt work
comment on: http://stackoverflow.com/q/48339641
type: Comment

http://stackoverflow.com/q/48345640
downvote count: 0
has body: I create a DataFrame from a dictionary. I want the keys to be used as index and the values as a single column. This is what I managed to do so far: import pandas as pd my_counts = {"A": 43, "B": 42} df = pd.DataFrame(pd.Series(my_counts, name=("count",)).rename_axis("letter")) I get the following: count letter A 43 B 42 The problem is I want to concatenate (with pd.concat) this with other dataframes, that have the same index name (letter), and seemingly the same single column (count), but I end up with an AssertionError: invalid dtype determination in get_concat_dtype. I discovered that the other dataframes have a different type for their columns: Index(['count'], dtype='object'). The above dataframe has MultiIndex(levels='count', labels=[[0]]). How can I ensure my dataframe has a normal index?
tagged with: python
has comment: http://stackoverflow.com/comment/83679065
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48347295
has title: How to coerce pandas dataframe column to be normal index
has comment: http://stackoverflow.com/comment/83679183
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83742838
has comment: http://stackoverflow.com/comment/83678996
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83679326
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48347295
has comment: http://stackoverflow.com/comment/83679288
upvote count: 2

http://stackoverflow.com/a/48358738
score: 2
type: Answer
upvote count: 2
downvote count: 0
has body: You can check what it does: def shuffle(self, x, random=None): """Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. """ if random is None: randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i+1) x[i], x[j] = x[j], x[i] else: _int = int for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = _int(random() * (i+1)) x[i], x[j] = x[j], x[i] The else branch applies here and the j = _int(random() * (i+1)) line in particular. This is the classic Fisher-Yates shuffle So the 'used granularity' of the random value depends on the length of the list in general, and on index of the current element in particular. Oh, and by the way: you are not supplying a seed, you are supplying the random values - which end up being a single value for each iteration. What you could do instead is using your random values for a single shuffle: from random import shuffle random_list = [ 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95 ] num_list = list(range(0, 10)) shuffle(num_list, lambda:random_list.pop()) print(num_list) Or, you could use seed-s, but they are not really expected to be floating-point numbers between 0 and 1, see def seed(self, a=None, version=2): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): x = or…
answers question: http://stackoverflow.com/q/48358500

http://stackoverflow.com/comment/83917460
type: QuestionComment
comment on: http://stackoverflow.com/q/48374039
has text: This sort of thing is generally best avoided a priori in well-designed, real programs.
score: 0
type: Comment

http://stackoverflow.com/q/48392601
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48392650
downvote count: 0
tagged with: django
tagged with: python
tagged with: django-rest-framework
has title: Returning values of a 'ReturnList' without the key in DjangoRestFramework
type: AnsweredQuestion
upvote count: 3
has body: So I have this Serializers class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') class SingleCategorySerializer(serializers.ModelSerializer): movies = MovieSerializer(many=True, read_only=True) class Meta: model = MoviesCategories fields = ('movies',) The Movie model has a relationship with the movies categories as follows category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING) Now when I try this serializer = SingleCategorySerializer(movie_category, many=True), the result of serializer.data is [ { "movies": [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] } ] I only want the values of the movies to be returned. Like this [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] Any help will be appreciated.
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48392650
has comment: http://stackoverflow.com/comment/83773157
answer count: 1

http://stackoverflow.com/a/48335572
answers question: http://stackoverflow.com/q/48332086
has body: from PyQt5 import QtWidgets,QtCore import sys import os class window(QtWidgets.QMainWindow): def __init__(self): super(window,self).__init__() self.mylineEdit = QtWidgets.QLineEdit() self.mylineEdit2 = QtWidgets.QLineEdit() self.startNew=1 #initialise to empty string on start up self.mylineEdit.setText(' ') #barcode scans here and then a returnPressed is registered #connect to a function self.mylineEdit.returnPressed.connect(self.set_sample_name) #here is where I want to delete the previous entry without backspacing by hand self.mylineEdit.textChanged.connect(self.delete_previous) centwid=QtWidgets.QWidget() lay=QtWidgets.QVBoxLayout() lay.addWidget(self.mylineEdit) lay.addWidget(self.mylineEdit2) centwid.setLayout(lay) self.setCentralWidget(centwid) self.show() #set the sample name variable def set_sample_name(self): self.sample_name = self.mylineEdit.text() print(self.sample_name) self.startNew=1 def delete_previous(self,text): if self.startNew: self.mylineEdit.setText(text[-1]) self.startNew=0 app=QtWidgets.QApplication(sys.argv) ex=window() sys.exit(app.exec_()) As soon as return pressed signal is executed you can change the flag self.startNew=1 which will ensure whenever the text will change it will check the flag and remove the complete string as soon as new barcode is entered. I have done in PyQt5 but the concept will remain the same. The functionality is achieved in self.myLineEdit.
type: Answer
accepted answer of: http://stackoverflow.com/q/48332086
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83732724

http://stackoverflow.com/q/48466139
tagged with: python
accepted answer: http://stackoverflow.com/a/48466419
possible better answer: http://stackoverflow.com/a/48466258
has answer: http://stackoverflow.com/a/48466419
type: AnsweredQuestion
has body: import pandas as pd df = pd.read_csv('admission_data.csv') df.head() female = 0 male = 0 for row in df: if df['gender']).any()=='female': female = female+1 else: male = male+1 print (female) print male The CSV file has 5 columnsHere is the picture I want to find the total number of females, males and number of them admitted, number of females admitted, males admitted Thank you. This is the code I have tried and some more iterations of the above code but none of them seem to work.
has answer: http://stackoverflow.com/a/48466491
tagged with: pandas
upvote count: 2
has answer: http://stackoverflow.com/a/48466360
has answer: http://stackoverflow.com/a/63576898
has comment: http://stackoverflow.com/comment/83925725
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83925722
type: Question
has title: I have a code here, I want to find the total number of females and males in a certain csv file.
has answer: http://stackoverflow.com/a/48466258
answer count: 5
tagged with: http://stackoverflow.com/tag/csv
score: 1

http://stackoverflow.com/a/48425586
has comment: http://stackoverflow.com/comment/83841203
answers question: http://stackoverflow.com/q/48425473
has comment: http://stackoverflow.com/comment/83886393
has comment: http://stackoverflow.com/comment/83880709
type: Answer
has comment: http://stackoverflow.com/comment/83841305
has body: Try using format() and with to open and write to the file. for i in range(0,100): with open("{}.txt".format(i), "w+") as file: file.write(str(i**2))
score: 0

http://stackoverflow.com/comment/83999742
has text: Sorry, meant to say `return g`. I've edited the above answer.
comment on: http://stackoverflow.com/a/48474842
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48334865
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48345958
accepted answer: http://stackoverflow.com/a/48345958
tagged with: javascript
tagged with: python
has title: How to disable screenshots and javascript for PhantomJS in python selenium?
type: AnsweredQuestion
tagged with: phantomjs
downvote count: 0
upvote count: 1
has body: I am scraping in a python/selenium framework using phantomJS on windows. First, I tried to disable javascript and screenhsots with selenium: driver = webdriver.PhantomJS("phantomjs.exe", desired_capabilities = dcap) webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.settings.javascriptEnabled"] = False webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.takesScreenshot"] = False webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.clearMemoryCash"] = False However, when I have a look at ghostdriver.log, Session.negotiatedCapabilities includes: browserName:phantomjs version:2.1.1 driverName:ghostdriver driverVersion:1.2.0 platform:windows-7-32bit javascriptEnabled:true # Should be false takesScreenshot:true # Should be false Therefore, I think I need to disable both parameters during onInitialized=function(), similar to the below code snippet: phantom_exc_uri='/session/$sessionId/phantom/execute' driver.command_executor._commands['executePhantomScript'] = ('POST', phantom_exc_uri) initScript=""" this.onInitialized=function() { var page=this; ### disable javascript and screenshots here ### } """ driver.execute('executePhantomScript',{'script': initScript, 'args': []}) Q1: How come I can set some phantomJS specs in webdriver.DesiredCapabilities, but others not? Is this my mistake or some bug? Q2: Is it reasonable to accomplish this during onInitialized or am I on the wrong way? Q2: If so, how to disable JS and screenshots during onInitialized?
score: 1
answer count: 1
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/comment/83842340
score: 0
has text: @bivouac0, if im understanding your post correctly, I'll setup a server with the python code that i'll start with a subprocess from Jython which will setup the server, run the calculations i need from the python file and serve that to the client, which will be implemented in Jython?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48410401

http://stackoverflow.com/q/48428115
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83847434
answer count: 5
has answer: http://stackoverflow.com/a/48429840
tagged with: python
has body: import tensorflow as tf # H(x) = Wx + b W = tf.Variable(tf.random_normal([1],name='weight')) b = tf.Variable(tf.random_normal([1],name='bias')) X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) hypothesis = X * W + b cost = tf.reduce_mean(tf.square(hypothesis - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) Weights = [] for step in range(100): sess.run([cost,hypothesis,train], feed_dict={X:x_col[0],Y:y_col[0]}) if step % 99 ==0: print(step, sess.run(cost), sess.run(W), sess.run(b)) This is the code I have. When I enter x_col[0] in Python Shell I get array([ 3., 5., 73., 33.], dtype=float32) and for y_col[0], I get array([ 3., 5., 73., 33.]). So I believe the code should work giving cost of 0 and W of 1 and 0 for b. But this error comes up. I don't know how I can fix this problem For your information, for sess.run([cost,hypothesis,train], feed_dict={X:x_col[0],Y:y_col[0]}) I get [960446.13, array([ 76.92639923, 127.70278168, 1854.09997559, 838.57220459], dtype=float32), None].
has answer: http://stackoverflow.com/a/48429843
has answer: http://stackoverflow.com/a/53920875
possible better answer: http://stackoverflow.com/a/48429843
upvote count: 2
type: AnsweredQuestion
has title: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float
has answer: http://stackoverflow.com/a/55987094
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48429639
accepted answer: http://stackoverflow.com/a/48429639
has comment: http://stackoverflow.com/comment/83846980
tagged with: tensorflow

python-2.7
tags question: http://stackoverflow.com/q/48373637
tags question: http://stackoverflow.com/q/48416696
tags question: http://stackoverflow.com/q/48468448
tags question: http://stackoverflow.com/q/48407367
tags question: http://stackoverflow.com/q/48339675
tags question: http://stackoverflow.com/q/48406991
tags question: http://stackoverflow.com/q/48368201
tags question: http://stackoverflow.com/q/48382245
tags question: http://stackoverflow.com/q/48413726
tags question: http://stackoverflow.com/q/48379584
tags question: http://stackoverflow.com/q/48391021
tags question: http://stackoverflow.com/q/48430081
tags question: http://stackoverflow.com/q/48359925
tags question: http://stackoverflow.com/q/48405330
tags question: http://stackoverflow.com/q/48350616
tags question: http://stackoverflow.com/q/48378524
tags question: http://stackoverflow.com/q/48449126
tags question: http://stackoverflow.com/q/48468524
tags question: http://stackoverflow.com/q/48433047
tags question: http://stackoverflow.com/q/48384192
tags question: http://stackoverflow.com/q/48487962
tags question: http://stackoverflow.com/q/48398726
tags question: http://stackoverflow.com/q/48375480
tags question: http://stackoverflow.com/q/48460560
tags question: http://stackoverflow.com/q/48422644
tags question: http://stackoverflow.com/q/48467087
tags question: http://stackoverflow.com/q/48487585
tags question: http://stackoverflow.com/q/48467146
tags question: http://stackoverflow.com/q/48337392
tags question: http://stackoverflow.com/q/48351725
tags question: http://stackoverflow.com/q/48366740
tags question: http://stackoverflow.com/q/48424220
tags question: http://stackoverflow.com/q/48357265
tags question: http://stackoverflow.com/q/48479848
tags question: http://stackoverflow.com/q/48419295
tags question: http://stackoverflow.com/q/48401876
tags question: http://stackoverflow.com/q/48464893
type: Tag
tags question: http://stackoverflow.com/q/48360030
tags question: http://stackoverflow.com/q/48401803
tags question: http://stackoverflow.com/q/48388459
tags question: http://stackoverflow.com/q/48355809
tags question: http://stackoverflow.com/q/48398923
tags question: http://stackoverflow.com/q/48473133
tags question: http://stackoverflow.com/q/48418843
tags question: http://stackoverflow.com/q/48346046
tags question: http://stackoverflow.com/q/48366030
tags question: http://stackoverflow.com/q/48333999
tags question: http://stackoverflow.com/q/48356623
tags question: http://stackoverflow.com/q/48368901
tags question: http://stackoverflow.com/q/48452933
tags question: http://stackoverflow.com/q/48392381
tags question: http://stackoverflow.com/q/48465368
tags question: http://stackoverflow.com/q/48399822
tags question: http://stackoverflow.com/q/48441233
tags question: http://stackoverflow.com/q/48431345
tags question: http://stackoverflow.com/q/48331164
tags question: http://stackoverflow.com/q/48371780
tags question: http://stackoverflow.com/q/48334705
tags question: http://stackoverflow.com/q/48410876
tags question: http://stackoverflow.com/q/48421675
tags question: http://stackoverflow.com/q/48357044
tags question: http://stackoverflow.com/q/48411344
tags question: http://stackoverflow.com/q/48392498
tags question: http://stackoverflow.com/q/48356440
tags question: http://stackoverflow.com/q/48394669
tags question: http://stackoverflow.com/q/48483765
tags question: http://stackoverflow.com/q/48464972
tags question: http://stackoverflow.com/q/48347331
tags question: http://stackoverflow.com/q/48368457
tags question: http://stackoverflow.com/q/48351139
tags question: http://stackoverflow.com/q/48390022
tags question: http://stackoverflow.com/q/48385340
tags question: http://stackoverflow.com/q/48362768
tags question: http://stackoverflow.com/q/48396419
tags question: http://stackoverflow.com/q/48372785
tags question: http://stackoverflow.com/q/48482031
tags question: http://stackoverflow.com/q/48464607
tags question: http://stackoverflow.com/q/48462928
tags question: http://stackoverflow.com/q/48388368

http://stackoverflow.com/q/48353415
has body: While experimenting with list insertion/concatenation by slicing, I entered this typo at Python 3.6.4 interactive prompt: x:[-9999] = [-1, 0], intending x[:-9999] = [-1, 0] as an exploratory way of inserting [-1, 0] at the beginning of a list. My typo caused x to be assigned the list [-1, 0]. Surprised, I tried similar expressions, like x:5=1, which assigns 1 to x, and x:’hello’=‘goodbye’, which assigns ‘goodbye’ to x. This is either obscure syntax or very simple, but why does this expression work, as if the colon and what immediately follows it weren’t there at all? I’m guessing it’s some kind of mapping or substitution prior to assignment?
has comment: http://stackoverflow.com/comment/83693343
duplicate of: http://stackoverflow.com/q/48323493
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83693350
tagged with: python-3.x
type: UnansweredQuestion
tagged with: variable-assignment
tagged with: python
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/48323493
answer count: 0
has title: Python variable assignment with colon?
downvote count: 0

http://stackoverflow.com/q/48355960
upvote count: 2
type: AnsweredQuestion
score: 2
has body: I have a function that loops through a list containing found registry key paths. I now need to find the date each registry key was last changed from that list of keys. def get_values(subkeylist): try: x = 0 nanos = [] while x &lt; len(subkeylist): keypath = subkeylist[x] key = OpenKey(HKEY_CURRENT_USER, keypath, 0, KEY_ALL_ACCESS) secs = QueryInfoKey(key)[2] / 1e9 dt = datetime.fromtimestamp(secs) dt.strftime('%Y-%m-%dT%H:%M:%S.%f') print(dt) x += 1 except WindowsError: pass I feel like I have either done something wrong here, or the value being held in the key is incorrect. The output in the shell is as follows: 1974-03-04 05:54:37.481353 1974-03-04 05:54:37.481433 1974-03-04 05:54:37.481443 And here is the actual output before conversion in nanoseconds since EPOCH 1601.(QueryInfoKey: An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601). 131608477481353446 131608477481433451 131608477481443451
tagged with: windows
answer count: 1
has answer: http://stackoverflow.com/a/48356655
accepted answer: http://stackoverflow.com/a/48356655
favorite count: 0
has title: Winreg Python, QueryInfoKey giving incorrect date/times for the last changed?
type: Question
tagged with: python-3.x
downvote count: 0
tagged with: winreg
tagged with: registry
tagged with: python

http://stackoverflow.com/comment/83949117
has text: I am ready to post it, but I realized the problem may be connected to other thing: 1) first, .copy() throws `<HttpError 404 ... "File not found: 12vQQwYK5bkg-6UKoNrXpsU1C1-fiYeTX.">` (although the dot in the end is not present in code - rather it seems that service account has no permissions to access the folder) 2) Everything works fine without `"parents": [folder]` part, but when I try to open the returned file id I see: "You need permission, request access..." thing. So I think my service account doesen't have permissions to manage files on my drive. But don't know how to fix it either =\
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48471127
type: Comment

http://stackoverflow.com/a/48449158
has comment: http://stackoverflow.com/comment/83892357
type: Answer
upvote count: 2
score: 2
has body: Using fillna Originaldf=Originaldf.set_index(['Pclass','Sex']).Age.fillna(piv.Age).reset_index()
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48449087
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48449087

http://stackoverflow.com/q/48347827
has title: Why do I keep getting a float division by zero in Python?
has comment: http://stackoverflow.com/comment/83681885
downvote count: 1
favorite count: 0
type: Question
has body: I have written the following code: import math import scipy def steffensen(equation, f_prime, x, er, N): for i in range(1, N): y1 = x r = equation(x) dx = (-r)/(f_prime(x)) y2 = y1 + dx y3 = y2 + dx x = y1-(((y2-y1)**2)/(y3-2*y2+y1)) z = abs(equation(x)) print("|f(x)| = %e"%z) if z &lt; e: print("Converged!") break return x #This will be used for testing def equation(x): return math.exp(-x**2 + x)-(0.5*x) def f_prime(x): return (1-2*x)*math.exp(x-(x**2))-0.5 #def main(): x0 = 1 N = 5 er = 1e-6 x = steffensen(equation, f_prime, x0, er, N) print("Finished!") When compiled, the code returns saying that there is a zero division error: float division by zero on the line that says: x = y1-(((y2-y1)**2)/(y3-2*y2+y1)). When computed by hand, I don't get 0. Please help me find the bug.
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: math
score: -1
has answer: http://stackoverflow.com/a/48347959
has comment: http://stackoverflow.com/comment/83681732

http://stackoverflow.com/comment/83796786
type: Comment
comment on: http://stackoverflow.com/a/48402787
type: AnswerComment
has text: I was indeed using 0.91 under Debian (ie should be same as your Ubuntu).ii freetds-common 0.91-6 all configuration files for FreeTDS SQL client libraries ii tdsodbc:amd64 0.91-6+b1 amd64 ODBC driver for connecting to MS SQL and Sybase SQL servers
score: 0

http://stackoverflow.com/comment/83935749
has text: Thank you! I know it's tough to give much advice without me being more specific..I've just been trying random stuff (i.e. guessing), so I don't know if sharing would help? I'm trying to above methods and what I keep getting as output is just one sku or the other. For example: filter1 = 'blue-shirt' filter2 = 'white-socks' df_items_of_interest1 = df[(df['sku'] == filter1) | (df['sku'] == filter2)] is returning orders that have either blue-shirt or white-socks in them, but what I want is to see orders that have blue-shirt AND white-socks in them. Probably something I'm missing.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48453814

http://stackoverflow.com/a/48392575
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83773059
upvote count: 2
downvote count: 0
type: Answer
has body: I am not sure how you are retrieving the data from the API, but I would reccomend using the Python requests library. You would send off the request: import requests r = requests.get('https://www.cryptopia.co.nz/api/GetMarkets/BTC/12') From there you want JSON data back, so convert the data to JSON like so: data = r.json() Then you can just parse the attributes you want from the API. If you wanted the label attribute for the 1st object in the Data array, you would do something like this: &gt;&gt;&gt; data['Data'][0]['Label'] &gt;&gt;&gt; '$$$/BTC' Hope that helps
answers question: http://stackoverflow.com/q/48392514
has comment: http://stackoverflow.com/comment/83773122
has comment: http://stackoverflow.com/comment/83773092
score: 2
accepted answer of: http://stackoverflow.com/q/48392514

http://stackoverflow.com/comment/83650182
type: AnswerComment
has text: Interesting, did not think of this way. Only the thing is that both `question` and `answer ` have to be str. For this case it's ok though.
score: 0
comment on: http://stackoverflow.com/a/48331967
type: Comment

http://stackoverflow.com/a/48478574
answers question: http://stackoverflow.com/q/48478562
downvote count: 0
has body: I think you need str.strip: df['order_number'] = df['order_number'].str.strip('"').astype(float) Or add parameter regex=True for replace substrings: df['order_number'] = df['order_number'].replace('"','', regex=True).astype(float) Last convert values to floats.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48478562
upvote count: 2
score: 2

http://stackoverflow.com/comment/83896131
type: QuestionComment
has text: You named your new script `ssl.py`; you are *masking the built-in library*. Rename the script.
score: 3
comment on: http://stackoverflow.com/q/48451546
type: Comment

http://stackoverflow.com/q/48459897
score: 0
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/48498064
answer count: 1
tagged with: macos
type: Question
has body: I Have an issue on Mac OS when I try to click on my menubar, nothing happend. I have two menus on named File and Load/Save but when I click on these the submenu don't show up. Although it works on windows and linux OS. So I'm suspecting something must be done for MAC, but I don't uberstand what? Even clicking on the 'python' button don't do anything. Here is a screenshot to better see what I meant: [![enter image description here][1]][1] and here the begining of the soft: class SurfViewer(QMainWindow): def __init__(self, parent=None): super(SurfViewer, self).__init__() self.parent = parent ############variable utiles########### self.height_per_line = 20 self.height_add = 30 self.width_per_col =155 self.List_Stim = [] self.NewStim = None self.List_ParamEvol = [] self.NewParamEvol = None ####################################### ####################################### self.centralWidget = QWidget() self.color = self.centralWidget.palette().color(QPalette.Background) # toolbarmenu extractAction = QAction("ScreenShot", self) extractAction.triggered.connect(self.screenshot) extractLoadmodelparam = QAction("Load Model parameters", self) extractSavemodelparam = QAction("Save Model parameters", self) extractLoadStimparam = QAction("Load Stimulation parameters", self) extractSaveStimparam = QAction("Save Stimulation parameters", self) extractLoadparamEvol = QAction("Load parameters evolution", self) extractSaveparamEvol = QAction("Save parameters evolution", self) self.extractLoadResult = QAction("Load Result signals", self) self.extractLoadResult.setEnabled(True) self.extractSaveResult = QAction("Save Result signals", self) self.extractSaveResult.setEnabled(False) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(extractAction) fileLoad = menubar.addMenu('&amp;Load/Save') fileLoad.addAction(extractSavemodelparam) fileLoad.addAction(extractLoadmodelparam) fileLoad.addAction(extractSaveStimparam) fileLoad.addAction(extractLoadStimparam) fileLoa…
has title: Click on Python and File in MenuBar of a Qt windows not working on Mac OS
has comment: http://stackoverflow.com/comment/83915285
has comment: http://stackoverflow.com/comment/83912641
has answer: http://stackoverflow.com/a/48498064
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48365433
accepted answer of: http://stackoverflow.com/q/48365377
has body: To quote the great uncle bob, author of 'Clean Code' and famed engineer, 'never let the readers of your code scroll sideways', and 'your code should read like well written prose'. Instead of placing the if statement within the with block, why not separate them. if src_name: with open(src_name, 'r') as f: pass #do something else: pass # do something else Also, consider using better names for your variables, i.e. instead of src_name use file_path > makes more sense. I highly recommend 'Clean Code' by Robert C. Martin - it changed my life.
has comment: http://stackoverflow.com/comment/83717472
has comment: http://stackoverflow.com/comment/83717513
type: Answer
has comment: http://stackoverflow.com/comment/83717482
answers question: http://stackoverflow.com/q/48365377
has comment: http://stackoverflow.com/comment/83717502
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83745203
has comment: http://stackoverflow.com/comment/83748375
type: AcceptedAnswer

http://stackoverflow.com/comment/127100609
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/61029093
has text: **_"tkinter elements do not have names."** This statement is completely false. Check https://stackoverflow.com/a/71906287/16187613
type: Comment

http://stackoverflow.com/q/48348361
has body: Consider the following dataframe df: Address City State Zip Code Query Result 0 55 W Waterloo Rd Akron OH 44319 {'field1': 'street_number', 'longname1': '55', 'field2': 'route', 'longname2': 'West Waterloo Road'} 1 1120 Hwy 20 Correctionville IA 51016 {'field1': 'street_number', 'longname1': '1120', 'field2': 'route', 'longname2': 'U.S. 20'} 2 Hwy 12 and Bonito Dr Fort Defiance AZ 86504 {'field1': 'route', 'longname1': 'Indian Route 7', 'field2': 'locality', 'longname2': 'Fort Defiance'} 3 2661 County Hwy I Chippewa Falls WI 54729 {'field1': 'street_number', 'longname1': '2661', 'field2': 'route', 'longname2': 'County Highway I'} 4 301 US Rt 1 Ste A Scarborough ME 4074 {'field1': 'subpremise', 'longname1': 'a', 'field2': 'street_number', 'longname2': '301'} 5 500 W Broadway St Ste 5 Missoula MT 59807 {'field1': 'subpremise', 'longname1': '5', 'field2': 'street_number', 'longname2': '500'} I would like to populate column df['street_number'] using the dict in df['Query Result'] such that: Address City State Zip Code Query Result street_number 0 55 W Waterloo Rd Akron OH 44319 {'field1': 'street_number', 'longname1': '55', 'field2': 'route', 'longname2': 'West Waterloo Road'} 55 1 1120 Hwy 20 Correctionville IA 51016 {'field1': 'street_number', 'longname1': '1120', 'field2': 'route', 'longname2': 'U.S. 20'} 1120 2 Hwy 12 and Bonito Dr Fort Defiance AZ 86504 {'field1': 'route', 'longname1': 'Indian Route 7', 'field2': 'locality', 'longname2': 'Fort Defiance'} 3 2661 County Hwy I Chippewa Falls WI 54729 {'field1': 'street_number', 'longname1': '2661', 'field2': 'route', 'longname2': 'County Highway I'} 2661 4 301 US Rt 1 Ste A Scarborough ME 4074 {'field1': 'subpremise', 'longname1': 'a', 'field2': 'street_number', 'longname2': '301'} 301 5 500 W Broadway St Ste 5 Missoula MT 59807 {'field1': 'subpremise', 'longname1': '5', 'field2': 'street_number', 'longname2': '500'} 500 Can someone help me undertstand how to do this? Please let me know if I need to make my example cl…
favorite count: 0
type: Question
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48348955
type: AnsweredQuestion
has title: Assigning to dataframe column based on dict value
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48348930
has answer: http://stackoverflow.com/a/48348930
accepted answer: http://stackoverflow.com/a/48348955

http://stackoverflow.com/comment/83850544
comment on: http://stackoverflow.com/q/48429104
type: Comment
type: QuestionComment
score: 0
has text: @DYZ, when '-o' is used in conjunction with the cProfile module, it specifies the output file to write the profile results, .e.g `python -m cProfile [-o output_file] [-s sort_order] myscript.py` [cProfile docs](https://docs.python.org/2/library/profile.html)

http://stackoverflow.com/q/48399116
tagged with: list
answer count: 2
downvote count: 2
tagged with: return-value
has answer: http://stackoverflow.com/a/48399351
has body: from collections import deque def muladd(f1,f2_inv): global ans for j in f1: ans = f1[j]*f2_inv[j] f1 = [2,3,7,5,4,0,0,0,0,0,0,0,0] f2 = [0,0,0,0,8,7,6,5,9,0,0,0,0] conv = [0,0,0,0,0,0,0,0,0] f2_inv = f2.reverse() for i in conv: conv[i]= muladd(f1,f2_inv) print conv[i] f1.rotate(1) ​ I am not able to run the code. When I run this code I get the error: 'NoneType' object has no attribute '__getitem__'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83786805
has answer: http://stackoverflow.com/a/48399166
favorite count: 0
has comment: http://stackoverflow.com/comment/83786166
tagged with: reverse
score: -2
has comment: http://stackoverflow.com/comment/83786594
has comment: http://stackoverflow.com/comment/83786633
tagged with: python
has comment: http://stackoverflow.com/comment/83785964
has title: 'NoneType' object has no attribute '__getitem__' 4
has comment: http://stackoverflow.com/comment/83786079
has comment: http://stackoverflow.com/comment/83786251
type: Question
upvote count: 0

apache-spark
tags question: http://stackoverflow.com/q/48396550
tags question: http://stackoverflow.com/q/48434771
tags question: http://stackoverflow.com/q/48427095
tags question: http://stackoverflow.com/q/48451271
tags question: http://stackoverflow.com/q/48423534
tags question: http://stackoverflow.com/q/48359436
tags question: http://stackoverflow.com/q/48367110
tags question: http://stackoverflow.com/q/48433297
tags question: http://stackoverflow.com/q/48435479
tags question: http://stackoverflow.com/q/48406749
tags question: http://stackoverflow.com/q/48432348
tags question: http://stackoverflow.com/q/48397543
tags question: http://stackoverflow.com/q/48448473
tags question: http://stackoverflow.com/q/48354342
tags question: http://stackoverflow.com/q/48377469
tags question: http://stackoverflow.com/q/48460956
tags question: http://stackoverflow.com/q/48350722
tags question: http://stackoverflow.com/q/48467215
tags question: http://stackoverflow.com/q/48387221
type: Tag
tags question: http://stackoverflow.com/q/48447554
tags question: http://stackoverflow.com/q/48386996
tags question: http://stackoverflow.com/q/48379377
tags question: http://stackoverflow.com/q/48443837
tags question: http://stackoverflow.com/q/48442024
tags question: http://stackoverflow.com/q/48416385
tag name: apache-spark
tags question: http://stackoverflow.com/q/48408004
tags question: http://stackoverflow.com/q/48375747
tags question: http://stackoverflow.com/q/48364037
tags question: http://stackoverflow.com/q/48349048
tags question: http://stackoverflow.com/q/48450352
tags question: http://stackoverflow.com/q/48456191

http://stackoverflow.com/comment/83903504
type: Comment
score: 0
type: QuestionComment
has text: How you start the execution. From IDLE with "Run Module" or from your OS shell with `python mymodule.py` for example.
comment on: http://stackoverflow.com/q/48455129

http://stackoverflow.com/comment/83911115
type: Comment
comment on: http://stackoverflow.com/a/48458781
has text: @PythonMan What do you mean, it does not work in PyCharm? That's just an IDE, and even if the builtin console does not support curses, the program you create in that IDE will ultimately run as a regular Python script, right?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48476521
favorite count: 0
has comment: http://stackoverflow.com/comment/83946669
type: Question
has comment: http://stackoverflow.com/comment/83947284
has body: I have a list of strings like the following orig = ["a1 2.3 ABC 4 DEFG 567 b890", "a2 3.0 HI 4 5 JKL 67 c65", "b1 1.2 MNOP 3 45 67 89 QR 987 d64 e112"] Context here is that this is a CSV file and certain columns are omitted. I don't think that the pandas csv reader can handle these cases. The idea is now to inject na for the missing values, so the output becomes corr = ["a1 2.3 ABC 4 na na na DEFG 567 b890", "a2 3.0 HI 4 5 na na JKL 67 c65", "b1 1.2 MNOP 3 45 67 89 QR 987 d64 e112"] to align the second column with capitalised words later on, when imported in pandas. The structure is the following: Delimiters between columns are two or more whitespaces and between the two upper case columns have to be four values. In the original file, there are always only two upper case columns, there is at least one and maximal four numbers in between them and there are only number values between these upper case words. I can write without problem a script in native Python, so please no suggestions for this. But I thought, this might be a case for regex. As a regex beginner, I only managed to extract the string between the two upper case columns with for line in orig: a = re.findall("([A-Z]+[\s\d]+[A-Z]+)", line)) print(a) &gt;&gt;&gt;'ABC 4 DEFG' #etc pp Is there now an easy way in regex to determine, how many numbers are between the upper case words and insert 'na' values to have always four values in between? Or should I do it in native Python? Of course, if there is a way to do this with the pandas csv reader, that would be even better. But I studied pandas csv_reader docs and haven't found anything useful.
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/24366449
has comment: http://stackoverflow.com/comment/83947683
has comment: http://stackoverflow.com/comment/83946225
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83946434
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/48487087
has title: String substitution with regex or regular Python?
has comment: http://stackoverflow.com/comment/83947177
score: 1
has answer: http://stackoverflow.com/a/48487087
possible better answer: http://stackoverflow.com/a/48476665
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83947009
has answer: http://stackoverflow.com/a/48476665

http://stackoverflow.com/a/48414527
score: 2
upvote count: 2
downvote count: 0
has body: My answer is inspired by this accepted answer. Code: from bs4 import BeautifulSoup, NavigableString data = ''' Details about item name goes here ''' soup = BeautifulSoup(data, 'html.parser') inner_text = [element for element in soup.h1 if isinstance(element, NavigableString)] print(inner_text) Output: ['item name goes here']
answers question: http://stackoverflow.com/q/48414407
type: Answer

http://stackoverflow.com/q/48355055
has title: Access azure cosmosdb emulator from ubuntu using python script
tagged with: python
tagged with: azure
score: 0
tagged with: azure-cosmosdb
answer count: 1
has body: I have got azure cosmos db emulator installed and running on windows 10. I'm successful in performing operations on db using .net sdk on windows(Visual Studio) (Used windows certificate manager (certmgr.msc) for authorization). The issue is, I want to access cosmosdb emulator from a python script which is running on ubuntu 16.04. Initially my script threw SSl certificate verification failed error. I solved it using below commands sudo cp documentdbemulatorcert.pem /usr/local/share/ca-certificates/documentdbemulatorcert.crt sudo update-ca-certificates and added below code in my python script os.environ['REQUESTS_CA_BUNDLE'] = os.path.join( '/usr/local/share/ca-certificates', 'documentdbemulatorcert.crt') Now the ssl error is not coming so certificates maybe verified, But when I call find collection method it gives me below error Top level Error: args:([],), message:[] Below is full python script which I've used from samples of python documentdb sdk import pydocumentdb.documents as documents import pydocumentdb.document_client as document_client import pydocumentdb.errors as errors import os import config as cfg try: os.environ['REQUESTS_CA_BUNDLE'] = os.path.join( '/usr/local/share/ca-certificates', 'documentdbemulatorcert.crt') except Exception as error: print "****os**",error # ---------------------------------------------------------------------------------------------------------- # Prerequistes - # # 1. An Azure Cosmos DB account - # https://azure.microsoft.com/en-us/documentation/articles/documentdb-create-account/ # # 2. Microsoft Azure DocumentDB PyPi package - # https://pypi.python.org/pypi/pydocumentdb/ # ---------------------------------------------------------------------------------------------------------- # Sample - demonstrates the basic CRUD operations on a Collection resource for Azure Cosmos DB # # 1. Query for Collection # # 2. Create Collection # 2.1 - Basic Create # 2.2 - Create collection with custom IndexPolicy # 2.3 - Create collection with o…
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83860500
has answer: http://stackoverflow.com/a/48417508

http://stackoverflow.com/a/60451355
score: 13
type: Answer
upvote count: 13
has body: The easiest way to increase the contrast (i.e. pull apart darker and brighter pixels), is just to "stretch out" the current existing range (144 to 216) over the entire spectrum (0 to 255): Setup, same way as in this answer. import numpy as np from PIL import Image pixvals = np.array(Image.open("image.png").convert("L")) And then expand the range pixvals = ((pixvals - pixvals.min()) / (pixvals.max()-pixvals.min())) * 255 Image.fromarray(pixvals.astype(np.uint8)) The result is effectively the same as in this answer, just with slightly less code: Now, in this image, that might be enough. However some images might have a few pixels that are really close to 0 or 255, which would render this method ineffective. Here numpy.percentile() comes to the rescue. The idea is to "clip" the range in which pixels are allowed to exist. minval = np.percentile(pixvals, 2) maxval = np.percentile(pixvals, 98) pixvals = np.clip(pixvals, minval, maxval) pixvals = ((pixvals - minval) / (maxval - minval)) * 255 Image.fromarray(pixvals.astype(np.uint8)) Which results in a little bit higher contrast, since all values below 2% and above 98% are effectively removed. (Play with these values as you see fit)
downvote count: 0
answers question: http://stackoverflow.com/q/48406578

http://stackoverflow.com/comment/83916107
type: Comment
comment on: http://stackoverflow.com/q/48460332
type: QuestionComment
has text: simply put it in codingground : Execute Python Online (Python v2.7.13) shows same results
score: 0

http://stackoverflow.com/q/48452041
linked to: http://stackoverflow.com/q/430079
has answer: http://stackoverflow.com/a/48452661
has title: Separating words from numbers in Python
favorite count: 0
type: Question
has body: I have to search a string for words that have a number as prefix or suffix (Example, "abc21" or "943xyz". Then, I need to split the number from the word. For example, "abc12" has to converted to "abc 12" or "12abc" has to be converted to "12 abc" However, if the number lies in between letters, for example, "a12bc", then it should be left as it is. How can we do this? Is there a simpler way than regex?
has comment: http://stackoverflow.com/comment/83897530
has comment: http://stackoverflow.com/comment/83897160
has comment: http://stackoverflow.com/comment/83897199
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83897178
has comment: http://stackoverflow.com/comment/83897488
tagged with: python
has comment: http://stackoverflow.com/comment/83897630
downvote count: 5
tagged with: regex
has comment: http://stackoverflow.com/comment/83897647
has comment: http://stackoverflow.com/comment/83897465
score: -5
answer count: 3
has answer: http://stackoverflow.com/a/48458422
has comment: http://stackoverflow.com/comment/83897333
has answer: http://stackoverflow.com/a/48452519
has comment: http://stackoverflow.com/comment/83897695

http://stackoverflow.com/comment/109948505
type: Comment
type: QuestionComment
has text: Hey @TomaszWojcik did you end up finding a solution to this in the end for PyCharm? The question marked as a duplicate uses the console, not PyCharm
comment on: http://stackoverflow.com/q/48342503
score: 0

http://stackoverflow.com/q/48335699
score: 3
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83663320
tagged with: tensorflow-serving
tagged with: python
tagged with: tensorflow
has body: I trained a Wide &amp; Deep model using the pre-made Estimator class (DNNLinearCombinedClassifier), by essentially following the tutorial on tensorflow.org. I wanted to do inference/serving, but without using tensorflow-serving. This basically comes down to feeding some test data to the correct input tensor and retrieving the output tensor. However, I am not sure what the input nodes/layer should be. In the tensorflow graph (graph.pbtxt), the following nodes seem relevant. But they are also related to the input queue which is mainly used during training, but not necessarily inference (I can just send one instance at a time). name: "enqueue_input/random_shuffle_queue" name: "enqueue_input/Placeholder" name: "enqueue_input/Placeholder_1" name: "enqueue_input/Placeholder_2" ... name: "enqueue_input/Placeholder_84" name: "enqueue_input/random_shuffle_queue_EnqueueMany_1" name: "enqueue_input/random_shuffle_queue_EnqueueMany_2" name: "enqueue_input/random_shuffle_queue_EnqueueMany_3" name: "enqueue_input/random_shuffle_queue_EnqueueMany_4" name: "enqueue_input/random_shuffle_queue_EnqueueMany" name: "enqueue_input/sub/y" name: "enqueue_input/sub" name: "enqueue_input/Maximum/x" name: "enqueue_input/Maximum" name: "enqueue_input/Cast" name: "enqueue_input/mul/y" name: "enqueue_input/mul" Does anyone know the answer? Thanks in advance!
type: Question
has answer: http://stackoverflow.com/a/51063972
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
has title: TensorFlow: What are the input nodes for tf.Estimator models
tagged with: tensorflow-estimator

http://stackoverflow.com/q/48412868
has answer: http://stackoverflow.com/a/50455375
score: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52627707
type: Question
answer count: 2
type: UnansweredQuestion
has body: I want to profile my tensorflow application using tfprof. I have a running tensorflow 1.3 installation where the the tfprof command line tool is missing. I also tried the provided pip packages locally, but there I also can't find tfprof. Is there a way to compile and link the tfprof command line tool agains my running tensorflow application? I already git-cloned the tensorflow repository and tried to build it with bazel 0.5.2 $ bazel build --config opt tensorflow/core/profiler/... WARNING: Output base '/home/USERNAME/.cache/bazel/_bazel_USERNAME/e5cce820cc082410b4fcc604db349066' is on NFS. This may lead to surprising failures and undetermined behavior. WARNING: Config values are not defined in any .rc file: opt ERROR: /tmp/tensorflow/tensorflow/core/BUILD:1416:1: no such target '//tensorflow/tools/git:gen/spec.json': target 'gen/spec.json' not declared in package 'tensorflow/tools/git' defined by /tmp/tensorflow/tensorflow/tools/git/BUILD and referenced by '//tensorflow/core:version_info_gen'. ERROR: /tmp/tensorflow/tensorflow/core/BUILD:1416:1: no such target '//tensorflow/tools/git:gen/head': target 'gen/head' not declared in package 'tensorflow/tools/git' defined by /tmp/tensorflow/tensorflow/tools/git/BUILD and referenced by '//tensorflow/core:version_info_gen'. ERROR: /tmp/tensorflow/tensorflow/core/BUILD:1416:1: no such target '//tensorflow/tools/git:gen/branch_ref': target 'gen/branch_ref' not declared in package 'tensorflow/tools/git' defined by /tmp/tensorflow/tensorflow/tools/git/BUILD and referenced by '//tensorflow/core:version_info_gen'. ERROR: Analysis of target '//tensorflow/core/profiler:profiler' failed; build aborted. INFO: Elapsed time: 167.083s or just copy the command mentioned here bazel build --config opt third_party/tensorflow/core/profiler/... WARNING: Output base '/home/USERNAME/.cache/bazel/_bazel_USERNAME/e5cce820cc082410b4fcc604db349066' is on NFS. This may lead to surprising failures and undetermined behavior. WARNING: Config values are…
downvote count: 0
has title: Installing tfprof command line
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/48416445
score: 0
answer count: 2
has body: I have created a graph using networkx in Python. import networkx as nx G = createGraph ('abc.csv') #My function that returns graph from file. connected_components = nx.connected_components(G) print (connected_components) &lt;generator object connected_components at 0x00000000221EF1A8&gt; nbr_cc = nx.number_connected_components(G) print (nbr_cc) 57215 I want to convert every connected component into a clique and then write a csv file in following manner: node1_id node2_id connected_component_id 1 2 1 1 3 1 1 4 1 2 1 1 . . . . . . 500 600 9 How to do that? Is there any way to achieve that in notworkx or using any other python library?
has title: Creating cliques from connected components using networkx
has answer: http://stackoverflow.com/a/48418009
tagged with: networkx
type: Question
tagged with: graph
accepted answer: http://stackoverflow.com/a/48416818
has answer: http://stackoverflow.com/a/48416818
tagged with: python
possible better answer: http://stackoverflow.com/a/48418009
type: AnsweredQuestion

http://stackoverflow.com/a/48417508
score: 1
answers question: http://stackoverflow.com/q/48355055
has comment: http://stackoverflow.com/comment/84111133
has comment: http://stackoverflow.com/comment/83870612
has body: I tried to use Ubuntu Subsystem on my Windows System to run python documentdb SDK and it works for me. My sample code hello.py: import pydocumentdb.document_client as document_client config = { 'ENDPOINT': 'https://localhost:8081', 'MASTERKEY': 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==', 'DOCUMENTDB_DATABASE': 'test', 'DOCUMENTDB_COLLECTION': 'testcoll' }; def find_collection(client, id): collections = list(client.QueryCollections( "dbs/test", { "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ {"name": "@id", "value": id} ] } )) if len(collections) &gt; 0: print('Collection with id \'{0}\' was found'.format(id)) else: print('No collection with id \'{0}\' was found'. format(id)) client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']}) find_collection(client,'testcoll') print ("done........") Output: Depending on the error trace you provided, I can only know that an exception was caught and thrown but I cannot determine the specific cause. I suggest you check if the transmission parameters are correctly, and try other methods except QueryCollection method. Any concern ,please let me know.
has comment: http://stackoverflow.com/comment/83910083
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83875110
has comment: http://stackoverflow.com/comment/84110895
has comment: http://stackoverflow.com/comment/83870292

http://stackoverflow.com/comment/83740298
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48374468
has text: @Chan Ahh I see, the hyperlink should be attached to the image instead. That's tricky since `docx` doesn't seem to support adding hyperlink relations to a picture according to their [official docs](https://python-docx.readthedocs.io/en/latest/api/document.html#docx.document.Document.add_picture) and their [github issue discussion](https://github.com/python-openxml/python-docx/issues/74#issuecomment-261169410). Even after studying some discussions online, I can't come up with a suitable solution for this. Hopefully, this answer would still be of use to anyone who's looking for a solution.

http://stackoverflow.com/q/48391579
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83771267
has answer: http://stackoverflow.com/a/48404611
has title: How can I concatenate multiple lists in one dictionary in Python?
tagged with: for-loop
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: dictionary
answer count: 1
has body: I have an OrderedDict with multiple values for the same city that I need to merge in one single dictionary. The OrderedDict goes as follows: print(OrderedDict) OrderedDict([('UF' , 'New York'), ('Total', 44.13), ('DEF', 9.5)]) OrderedDict([('UF' , 'LA'), ('Total', 54.13), ('DEF', 1.0)]) OrderedDict([('UF' , 'New York'), ('Total', 12.01), ('DEF', 0.4)]) ... So I need a new dictionary where all the values for "New York" are summed into a single entry: for data in OrderedDict: newDict = {"UF": data['UF'], 'DEF' : data["DEF"] , 'N_DEF' : (data["Total"] - data["DEF"]) , 'Total' : data["Total"] } Here I'm not even doing the sum yet and I already having trouble, the for loop here is only returning 1 entry in the newDict, seem like it's not iterating through the hole OrderedDict. print(newDict) {"DEF" : 9.5, "N_DEF" : 34,63 , "Total" : 44.13 , "UF" : "New York"} Please help!!!! Thanks people!!
has comment: http://stackoverflow.com/comment/83771174
has comment: http://stackoverflow.com/comment/83797218
downvote count: 1
has comment: http://stackoverflow.com/comment/83771461

http://stackoverflow.com/comment/83905908
score: 0
has text: Why not also have your code create the directory structure? You can call list() again on `prefix + response['prefixes'][0]`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48450359

dataframe
tags question: http://stackoverflow.com/q/48429367
tags question: http://stackoverflow.com/q/48482256
tags question: http://stackoverflow.com/q/48483787
tags question: http://stackoverflow.com/q/48351575
tags question: http://stackoverflow.com/q/48420684
tags question: http://stackoverflow.com/q/48431483
tags question: http://stackoverflow.com/q/48410032
tags question: http://stackoverflow.com/q/48382122
tags question: http://stackoverflow.com/q/48409128
tags question: http://stackoverflow.com/q/48467759
tags question: http://stackoverflow.com/q/48460589
tags question: http://stackoverflow.com/q/48446408
tags question: http://stackoverflow.com/q/48422642
tags question: http://stackoverflow.com/q/48346156
tags question: http://stackoverflow.com/q/48448091
tags question: http://stackoverflow.com/q/48364134
tags question: http://stackoverflow.com/q/48421703
tags question: http://stackoverflow.com/q/48480766
tags question: http://stackoverflow.com/q/48364619
tags question: http://stackoverflow.com/q/48463459
tags question: http://stackoverflow.com/q/48358837
tags question: http://stackoverflow.com/q/48338811
tags question: http://stackoverflow.com/q/48380425
tags question: http://stackoverflow.com/q/48450332
tags question: http://stackoverflow.com/q/48453376
tags question: http://stackoverflow.com/q/48484333
tags question: http://stackoverflow.com/q/48416481
tags question: http://stackoverflow.com/q/48431774
tags question: http://stackoverflow.com/q/48399718
tags question: http://stackoverflow.com/q/48351637
tags question: http://stackoverflow.com/q/48341948
tags question: http://stackoverflow.com/q/48462012
tags question: http://stackoverflow.com/q/48365315
tags question: http://stackoverflow.com/q/48409694
tags question: http://stackoverflow.com/q/48488335
tags question: http://stackoverflow.com/q/48385525
tags question: http://stackoverflow.com/q/48356052
tags question: http://stackoverflow.com/q/48442024
tags question: http://stackoverflow.com/q/48449249
tags question: http://stackoverflow.com/q/48421509
tags question: http://stackoverflow.com/q/48382663
tags question: http://stackoverflow.com/q/48458330
tags question: http://stackoverflow.com/q/48364037
tags question: http://stackoverflow.com/q/48413388
tags question: http://stackoverflow.com/q/48462326
tags question: http://stackoverflow.com/q/48344958
tags question: http://stackoverflow.com/q/48458706
tags question: http://stackoverflow.com/q/48437196
tags question: http://stackoverflow.com/q/48369984
tags question: http://stackoverflow.com/q/48419589
tags question: http://stackoverflow.com/q/48445012
tags question: http://stackoverflow.com/q/48363342
tags question: http://stackoverflow.com/q/48424891
tags question: http://stackoverflow.com/q/48465765
tags question: http://stackoverflow.com/q/48487822
tags question: http://stackoverflow.com/q/48408592
tags question: http://stackoverflow.com/q/48351197
tags question: http://stackoverflow.com/q/48487688
tags question: http://stackoverflow.com/q/48452774
tags question: http://stackoverflow.com/q/48393301
tags question: http://stackoverflow.com/q/48340341
tags question: http://stackoverflow.com/q/48369864
tags question: http://stackoverflow.com/q/48396321
tags question: http://stackoverflow.com/q/48373226
tags question: http://stackoverflow.com/q/48370708
tags question: http://stackoverflow.com/q/48372735
tags question: http://stackoverflow.com/q/48339263
tags question: http://stackoverflow.com/q/48433275
tags question: http://stackoverflow.com/q/48463174
tags question: http://stackoverflow.com/q/48336175
tags question: http://stackoverflow.com/q/48448647
tags question: http://stackoverflow.com/q/48445505
tags question: http://stackoverflow.com/q/48382219
tags question: http://stackoverflow.com/q/48359925
tags question: http://stackoverflow.com/q/48392311
tags question: http://stackoverflow.com/q/48452274
tags question: http://stackoverflow.com/q/48454720
tags question: http://stackoverflow.com/q/48447812
tags question: http://stackoverflow.com/q/48362692
tags question: http://stackoverflow.com/q/48404268

http://stackoverflow.com/comment/83754860
score: 0
type: Comment
type: QuestionComment
has text: Hi Bryan, because before I created an item in the list. This new item in the list has a button associated with it that is what I need to press.
comment on: http://stackoverflow.com/q/48381258

http://stackoverflow.com/comment/83730305
type: Comment
type: QuestionComment
has text: @hpaulj `alpha` can be an array of arbitrary shape, and is typically much larger than `arr`.
comment on: http://stackoverflow.com/q/48367575
score: 0

http://stackoverflow.com/comment/83712703
comment on: http://stackoverflow.com/q/48362903
type: QuestionComment
has text: How did you run your first line of code and get a different error if `x` isn't even iterable?
score: 1
type: Comment

http://stackoverflow.com/a/48365456
type: Answer
answers question: http://stackoverflow.com/q/48364941
score: 0
has body: Ok to answer your questions in order. As @GalAbra mentions above, it is dependent on the design of the tool. From the sounds of it though, if index.html forces the browser to post data to tool.py then the IP of where tool.py is located will be the one that requests the page. The ideal way would be to have a queing system built into the tool. You could have the client add their request to the queue (possibly in a database) and then have the tool.py monitor the queue for new entries and have it then request. Possibly using threading where there are multiple new requests in the queue, depending on how much activity you think this tool will see. Hope this helps

http://stackoverflow.com/a/48375645
score: 4
type: AcceptedAnswer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48375618
has body: It looks like you have a dictionary where the key(s) is JSON data. Try parsing it with a JSON parser. &gt;&gt;&gt; json.loads(list(data)[0]) {'auth': {'user_id': '2'}, 'data': {'collection': 'master-services'}} If you have many such keys, you can iterate over data (or, data.keys()), like this: &gt;&gt;&gt; new_data = [json.loads(d) for d in data] This gives you a list of dictionaries.
downvote count: 0
answers question: http://stackoverflow.com/q/48375618
type: Answer

http://stackoverflow.com/comment/83701044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48357213
has text: Possible duplicate of [Is there a difference between \`==\` and \`is\` in Python?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python)
score: 3

http://stackoverflow.com/comment/131582971
has text: What is the time complexity for `Counter(D.values())[0]` ?
comment on: http://stackoverflow.com/a/48371896
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/83850898
type: Comment
has text: Related: https://stackoverflow.com/questions/27033823/how-to-overwrite-the-output-directory-in-spark
type: AnswerComment
comment on: http://stackoverflow.com/a/48430033
score: 0

http://stackoverflow.com/q/48429880
has answer: http://stackoverflow.com/a/63979102
tagged with: python
has body: How with google text-to-speech I can save to the MP3 file 2 Variables with different languages? Please help me. Everywhere is written only for 1 language. This is my code: from gtts import gTTS import os import pickle import pandas as pd frame = pd.read_csv('file.csv', header=0, sep = '\t', encoding='cp1251') print(frame) text1 = list() text2 = list() for a, b in zip(frame['English'], frame['Русский']): text1.append(a) text2.append(b) print(text1, text2) text1 = str(text1) text2 = str(text2) tts1 = gTTS(text=text1, lang='en') tts2 = gTTS(text=text2, lang='ru') # tts2.save("from_file.mp3") it work just for one Variable! with open('from_file.mp3', 'wb') as pickle_file: pickle.dump([tts1, tts2], pickle_file) # with pickle it doesn't work! os.system("from_file.mp3") file content: English Русский tell говорить fly летать sit сидеть act действовать As a solution: I can loop every word with gTTS and add in mp3 file, but how can I add data in mp3 without delete past data ?? I want to create an audio dictionary.
has title: How with google text-to-speech (gTTS) I can save to the MP3 file 2 Variables with different languages? (Python)
linked to: http://stackoverflow.com/q/4581417
score: 0
has comment: http://stackoverflow.com/comment/83859423
tagged with: text-to-speech
answer count: 1
tagged with: http://stackoverflow.com/tag/mp3
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/48461814
favorite count: 0
type: Question
tagged with: tkinter
has body: When I compile this code: def compileF(): file = text.get('1.0', END) print(file) text = Text(root, height=40, width=60, fg="black", font="Helvetica 12") I get an ERROR: Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\MIK\Desktop\GranitePad\GranitePad.pyw", line 16, in compileF file = text.get('1.0', END) UnboundLocalError: local variable 'text' referenced before assignment What is going on?
has comment: http://stackoverflow.com/comment/83930918
type: UnansweredQuestion
downvote count: 5
tagged with: python
has title: Error: UnboundLocalError: local variable referenced before assignment
has answer: http://stackoverflow.com/a/48461881
score: -5
upvote count: 0
linked to: http://stackoverflow.com/q/41369408
answer count: 1
has comment: http://stackoverflow.com/comment/83932329

http://stackoverflow.com/comment/83932195
type: QuestionComment
has text: @Darkonaut yes. Everything works fine outside of environment
comment on: http://stackoverflow.com/q/48468975
score: 0
type: Comment

http://stackoverflow.com/q/48486465
has answer: http://stackoverflow.com/a/48486680
score: 3
upvote count: 3
has body: class Jornal(models.Model): url = models.URLField(unique = True,blank=True) name = models.CharField(max_length=100) def __str__(self): return self.name @property def domain(self): return urlparse(self.url).netloc How to I get the Jornal object through its domain? I was trying this in the shell: domain = "www.example.com" obj = Jornal.objects.get_domain(domain) and then this: domain = "www.example.com" obj = Jornal.objects(domain = domain) But none works. EDIT I was trying with a get method because I want DoesNotExist in case it is not found.
downvote count: 0
has answer: http://stackoverflow.com/a/48486794
favorite count: 0
has answer: http://stackoverflow.com/a/48486504
has answer: http://stackoverflow.com/a/48486477
type: Question
has title: How to get a property from a Django model?
type: UnansweredQuestion
tagged with: python
tagged with: django
tagged with: django-models
answer count: 4

http://stackoverflow.com/q/48452933
has comment: http://stackoverflow.com/comment/83903101
tagged with: pandas
has comment: http://stackoverflow.com/comment/83899089
has title: Python comparison ignoring nan
linked to: http://stackoverflow.com/q/4187185
has comment: http://stackoverflow.com/comment/83899900
tagged with: equality
score: 17
has comment: http://stackoverflow.com/comment/83903139
has answer: http://stackoverflow.com/a/48453042
possible better answer: http://stackoverflow.com/a/48453042
has comment: http://stackoverflow.com/comment/83899019
has answer: http://stackoverflow.com/a/66049516
downvote count: 1
tagged with: nan
favorite count: 0
has comment: http://stackoverflow.com/comment/83899661
type: Question
has comment: http://stackoverflow.com/comment/83899155
has comment: http://stackoverflow.com/comment/83903031
has body: While nan == nan is always False, in many cases people want to treat them as equal, and this is enshrined in pandas.DataFrame.equals: NaNs in the same location are considered equal. Of course, I can write def equalp(x, y): return (x == y) or (math.isnan(x) and math.isnan(y)) However, this will fail on containers like [float("nan")] and isnan barfs on non-numbers (so the complexity increases). So, what do people do to compare complex Python objects which may contain nan? PS. Motivation: when comparing two rows in a pandas DataFrame, I would convert them into dicts and compare dicts element-wise. PPS. When I say "compare", I am thinking diff, not equalp.
has comment: http://stackoverflow.com/comment/83899031
upvote count: 18
tagged with: python
has comment: http://stackoverflow.com/comment/83899158
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48455242
answer count: 3
accepted answer: http://stackoverflow.com/a/48455242

http://stackoverflow.com/a/48386818
has comment: http://stackoverflow.com/comment/83782198
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83762030
type: Answer
has body: You can use broadcasting to do all the comparisons at once: In [23]: np.where(terms1[:, None] == vocab)[1] Out[23]: array([5, 2, 0, 3, 3, 3]) In [24]: np.where(terms2[:, None] == vocab)[1] Out[24]: array([4, 2, 1, 3])
answers question: http://stackoverflow.com/q/48386742
score: 2

http://stackoverflow.com/comment/83900215
score: 0
has text: [Flask Debugger Traceback](https://i.imgur.com/nIHgC1V.png)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48453558

http://stackoverflow.com/comment/103315117
has text: @ahbon have a look at this [MNIST example](https://github.com/pytorch/examples/blob/master/mnist/main.py) The ``Net`` class is where the model is defined and then initialized in the line 105 as follows `model = Net().to(device)`
type: Comment
comment on: http://stackoverflow.com/a/57342167
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83960605
comment on: http://stackoverflow.com/q/48434733
score: 0
has text: Removing spaces didn't work. I added code in the post. To elaborate; for many sites I get a 2FA key like "ABCDEFGHIJKLM123" and for those the code works fine and generates the correct code. But from Amazon I get a different format shared key ("ABCD EFGH IJKL MNOP QRST UVWX YZ01 1234 5678 9ABC DEFG HIJK LMNO"), but I"m ont sure how to use this key with above code.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83731513
score: 0
comment on: http://stackoverflow.com/q/48368635
type: Comment
type: QuestionComment
has text: @KlausD. Thank, noted.

http://stackoverflow.com/a/51033930
type: Answer
answers question: http://stackoverflow.com/q/48434843
downvote count: 0
has body: PyCharm passes a blank value for the LC_CTYPE environment variable: Please see: PyCharm is changing the default encoding in my Django app
upvote count: 3
score: 3

http://stackoverflow.com/q/48355172
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: popen
has body: I'm trying to execute tshark in python as follows: class ARPSniffer: def testTshark(self, iface): print("Testing if tshark works. Using {}".format(iface)) cmd = "tshark -i " + iface args = shlex.split(cmd) tshark = subprocess.Popen(args, stdout=PIPE) for line in io.TextIOWrapper(tshark.stdout, encoding="utf-8"): print(line) def run(self, iface): try: t = Thread(target=self.testTshark, args=(iface, )) t.daemon = True t.start() t.join except KeyboardInterrupt: print("\nExiting ARP monitor...") sys.exit(0) if __name__ == '__main__': iface = 'wlan1' arps = ARPSniffer() arps.run(iface) It prints "Testing if tshark works. Using wlan1" but tshark doesn't start. I checked it using top and there is not any process running. What am I doing wrong? I'm running it using sudo. Thank you all of you.
has comment: http://stackoverflow.com/comment/83697499
tagged with: python
has title: Tshark not executing through subprocess.Popen
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83697290
tagged with: subprocess
upvote count: 2
accepted answer: http://stackoverflow.com/a/48355520
tagged with: tshark
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48355520
has comment: http://stackoverflow.com/comment/83696987
has comment: http://stackoverflow.com/comment/83697554

http://stackoverflow.com/comment/83683161
has text: If you are not sure of the answer , Please add comments
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48348399

http://stackoverflow.com/comment/83735188
score: 1
comment on: http://stackoverflow.com/a/48373959
has text: Do you mean that I will have to create a random variable noise when I am loading the trained model ? `noise` in my training keeps on changing hence affecting the loss value
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48517485
type: Answer
has body: Closing the thread for future reference. As was pointed out in the comment to my question the problem here is that Python is (currently) packaged differently on different Linux distributions. In order to fix the issue one must ensure that the Python symbols are visible to libraries that are loaded within the python plugin. As far as I can tell there are three ways of dealing with it: Link the main executable to Python. Set the RTDL_GLOBAL option (only possible when using dlopen, dlopen("lib.so", RTDL_NOW | RTDL_LAZY | RTDL_GLOBAL), and is not guaranteed to be supported on all systems). Set the environment variable LD_PRELOAD, export LD_PRELOAD="/path/to/libpython2.7.so.1.0", to enforce certain libraries to be loaded before any other library. For me this worked for my little example plugin, but caused harmful interactions when dealing with a larger software framework.
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48462792
downvote count: 0
answers question: http://stackoverflow.com/q/48462792
score: 3

http://stackoverflow.com/q/48474503
tagged with: markdown
score: 0
has comment: http://stackoverflow.com/comment/83963358
tagged with: python
type: Question
has title: django-markdown cannot support bold or italic？
has comment: http://stackoverflow.com/comment/83953935
answer count: 0
has body: I use the django-markdown module to make the comments support the markdown, but there is a problem. The bold and italic are not supported. Others, such as pre, title and so on, work well. why? django user-define templatetags from django import template import markdown register = template.Library() @register.filter def markdown_change(content): content = markdown.markdown(content,extensions=['markdown.extensions.extra','markdown.extensions.codehilite','markdown.extensions.toc',]) return content template &lt;p&gt;&lt;/p&gt; views.py def contact(request): if request.method == 'POST': if request.user.username: form = CommentForm(request.POST) if form.is_valid(): form.save() form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) &gt; 5: data,comment_list=comment_paginator(request,comment_list) else: data='' response = True context = {'form':form,'comment_list':comment_list,'response':response,'data':data} return render(request,'contact.html',context=context) else: form = CommentForm() comment_list = Comment.objects.all().filter(public = True).order_by('id').reverse() if len(comment_list) &gt; 5: (data,comment_list)=comment_paginator(request,comment_list) else: data='' context = {'form':form,'comment_list':comment_list,'data':data} return render(request,'contact.html',context=context)
type: UnansweredQuestion
tagged with: django
tagged with: javascript

http://stackoverflow.com/comment/83937436
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48471648
has text: [Here](https://github.com/pandas-dev/pandas/issues/17594) is an issue with Jeff's answer but I cannot follow his logic.

http://stackoverflow.com/q/48340974
tagged with: wordnet
tagged with: preprocessor
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47769818
has body: When I'm trying to run this code to preprocess a text, I get the error below, someone is having a similar problem but the post did not have enough details. I am putting everything in context here hoping to help reviewer to help us better. Here is the function; def preprocessing(text): #text=text.decode("utf8") #tokenize into words tokens=[word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] #remove stopwords stop=stopwords.words('english') tokens=[token for token in tokens if token not in stop] #remove words less than three letters tokens=[word for word in tokens if len(word)&gt;=3] #lower capitalization tokens=[word.lower() for word in tokens] #lemmatization lmtzr=WordNetLemmatizer() tokens=[lmtzr.lemmatize(word for word in tokens)] preprocessed_text=' '.join(tokens) return preprocessed_text calling the function here; #open the text data from disk location sms=open('C:/Users/Ray/Documents/BSU/Machine_learning/Natural_language_Processing_Pyhton_And_NLTK_Chap6/smsspamcollection/SMSSpamCollection') sms_data=[] sms_labels=[] csv_reader=csv.reader(sms,delimiter='\t') for line in csv_reader: #adding the sms_id sms_labels.append(line[0]) #adding the cleaned text by calling the preprocessing method sms_data.append(preprocessing(line[1])) sms.close() result; --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-38-b42d443adaa6&gt; in &lt;module&gt;() 8 sms_labels.append(line[0]) 9 #adding the cleaned text by calling the preprocessing method ---&gt; 10 sms_data.append(preprocessing(line[1])) 11 sms.close() &lt;ipython-input-37-69ef4cd83745&gt; in preprocessing(text) 12 #lemmatization 13 lmtzr=WordNetLemmatizer() ---&gt; 14 tokens=[lmtzr.lemmatize(word for word in tokens)] 15 preprocessed_text=' '.join(tokens) 16 return preprocessed_text ~\Anaconda3\lib\site-packages\nltk\stem\wordnet.py in lemmatize(self, word, pos) 38 39 def lemmatize(self, word, pos=NOUN): --…
tagged with: lemmatization
upvote count: 2
has comment: http://stackoverflow.com/comment/83690924
tagged with: nltk
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48341103
has comment: http://stackoverflow.com/comment/83668202
has answer: http://stackoverflow.com/a/48341103
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83667258
has title: how to resolve the error: AttributeError: 'generator' object has no attribute 'endswith'
has comment: http://stackoverflow.com/comment/83690927
answer count: 1

http://stackoverflow.com/q/48337949
upvote count: 1
has answer: http://stackoverflow.com/a/48339616
possible better answer: http://stackoverflow.com/a/48339616
has body: I would like to resize an image using TKinter. Please note that I will not be using PIL for this. How can I currently have this image, which works fine. logo = PhotoImage(file="logo_dribbble-01_1x.PNG") label = Label(f1,image=logo, borderwidth=0, highlightthickness=0) label.pack() I would like to resize this image so that the logo looks smaller. I tried doing this, which was suggested here smallLogo = PhotoImage(file="logo_dribbble-01_1x.PNG") smallLogo = smallLogo.subsample(2, 2) smallLabel = Label(f1,image=smallLogo, borderwidth=0, highlightthickness=0) smallLabel.pack() But this creates an empty label without displaying the image. I tried to resize the image using Photoshop and use that image and then use that .png image to display the smaller image like so: logo = PhotoImage(file="logo_dribbble-01_1xsmall.PNG") smallLabel = Label(f1,image=smallLogo, borderwidth=0, highlightthickness=0) smallLabel.pack() But, I get this error when I try to run the code _tkinter.TclError: encountered an unsupported criticial chunk type "mkBF" How can I resolve this issue?
favorite count: 0
has comment: http://stackoverflow.com/comment/83665132
has comment: http://stackoverflow.com/comment/83664464
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48341483
accepted answer: http://stackoverflow.com/a/48341483
has answer: http://stackoverflow.com/a/48343403
has comment: http://stackoverflow.com/comment/83675057
tagged with: photoimage
has comment: http://stackoverflow.com/comment/83665288
has comment: http://stackoverflow.com/comment/83664398
tagged with: python
has comment: http://stackoverflow.com/comment/83674913
has comment: http://stackoverflow.com/comment/83674752
tagged with: image
linked to: http://stackoverflow.com/q/3177969
has title: TKinter python 3.x resizing an image
has comment: http://stackoverflow.com/comment/83665267
type: AnsweredQuestion
tagged with: tkinter
answer count: 3
downvote count: 0
score: 1

http://stackoverflow.com/a/48488458
has comment: http://stackoverflow.com/comment/83971396
has comment: http://stackoverflow.com/comment/83971353
has comment: http://stackoverflow.com/comment/83972054
has comment: http://stackoverflow.com/comment/83972075
answers question: http://stackoverflow.com/q/48488047
has comment: http://stackoverflow.com/comment/83971295
score: 1
downvote count: 0
upvote count: 1
has body: Just do this: import pandas as pd from datetime import datetime df = pd.read_csv("yourdataframe.csv") df["Bill_Date"] = df["Bill_Date"].map(lambda x: datetime.fromordinal(datetime(1900, 1, 1).toordinal() + x - 2)) df["Bill_Date"] = df["Bill_Date"].map(lambda x: x.strftime("%Y-%m-%d")) print df.head()
has comment: http://stackoverflow.com/comment/83972157
type: Answer

http://stackoverflow.com/a/48413574
type: Answer
has body: You seem unclear what lambda does: Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". In the example you have given you have not created any anonymous function so therefore they are totally unnecessary. Just remove them and everything should work. def no(): PlaySound('wrong.wav', SND_FILENAME) def yes(): PlaySound('right.wav', SND_FILENAME) Remember however winsound is Windows only (so no cross platform development) and to use these functions you need from winsound import *
answers question: http://stackoverflow.com/q/48389263
score: 0

http://stackoverflow.com/comment/83721830
score: 0
type: AnswerComment
has text: The covariance matrix should be 2x2. The dependent features only have 2 features. Fixing the independent feature, you get the Gaussian distibution of the dependent feature which follows the mean (i.e. one of the column of your conditional mean) and the 2 x 2 covariance matrix.
type: Comment
comment on: http://stackoverflow.com/a/48360790

http://stackoverflow.com/q/48409610
has comment: http://stackoverflow.com/comment/83912050
has answer: http://stackoverflow.com/a/48564734
has answer: http://stackoverflow.com/a/48412109
has comment: http://stackoverflow.com/comment/83809666
accepted answer: http://stackoverflow.com/a/48473953
has answer: http://stackoverflow.com/a/48409996
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83939587
answer count: 8
has answer: http://stackoverflow.com/a/48573920
has comment: http://stackoverflow.com/comment/83810916
has comment: http://stackoverflow.com/comment/83911424
linked to: http://stackoverflow.com/q/48459493
linked to: http://stackoverflow.com/q/4060772
has answer: http://stackoverflow.com/a/48480292
has comment: http://stackoverflow.com/comment/83911369
has body: I'd like a unique dict (key/value) database to be accessible from multiple Python scripts running at the same time. If script1.py updates d[2839], then script2.py should see the modified value when querying d[2839] a few seconds after. I thought about using SQLite but it seems that concurrent write/read from multiple processes is not SQLite's strength (let's say script1.py has just modified d[2839], how would script2.py's SQLite connection know it has to reload this specific part of the database?) I also thought about locking the file when I want to flush the modifications (but it's rather tricky to do), and use json.dump to serialize, then trying to detect the modifications, use json.load to reload if any modification, etc. ... oh no I'm reinventing the wheel, and reinventing a particularly inefficient key/value database! redis looked like a solution but it does not officially support Windows, the same applies for leveldb. multiple scripts might want to write at exactly the same time (even if this is a very rare event), is there a way to let the DB system handle this (thanks to a locking parameter? it seems that by default SQLite can't do this because "SQLite supports an unlimited number of simultaneous readers, but it will only allow one writer at any instant in time.") What would be a Pythonic solution for this? Note: I'm on Windows, and the dict should have maximum 1M items (key and value both integers).
tagged with: key-value-store
has comment: http://stackoverflow.com/comment/83932895
score: 13
tagged with: python
linked to: http://stackoverflow.com/q/186202
possible better answer: http://stackoverflow.com/a/48474132
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83809518
has answer: http://stackoverflow.com/a/48473953
upvote count: 14
has comment: http://stackoverflow.com/comment/83810459
has answer: http://stackoverflow.com/a/48474132
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48535999
has comment: http://stackoverflow.com/comment/83941723
has comment: http://stackoverflow.com/comment/84119657
has title: Share a dict with multiple Python scripts
has comment: http://stackoverflow.com/comment/83809861
has comment: http://stackoverflow.com/comment/83809768
linked to: http://stackoverflow.com/q/48083405
tagged with: sqlite
downvote count: 1
has comment: http://stackoverflow.com/comment/84149621

http://stackoverflow.com/q/48377413
has comment: http://stackoverflow.com/comment/83741939
tagged with: azure
upvote count: 2
has answer: http://stackoverflow.com/a/48377951
has comment: http://stackoverflow.com/comment/83741702
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/48376092
has comment: http://stackoverflow.com/comment/83741733
favorite count: 0
type: Question
has body: How can I use the Python SDK and execute a script stored in Blob inside a VM? Is it possible to do it at the time of creation? I've looked at this, and I'm not able to make it work. This is my existing template. Where am I going wrong?
has comment: http://stackoverflow.com/comment/83742550
tagged with: python
tagged with: azure-virtual-machine
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48377951
has title: Execute script inside azure VM programmatically

http://stackoverflow.com/q/48340392
has answer: http://stackoverflow.com/a/60097398
downvote count: 0
has comment: http://stackoverflow.com/comment/84107310
upvote count: 49
has answer: http://stackoverflow.com/a/49611074
has comment: http://stackoverflow.com/comment/106284349
has comment: http://stackoverflow.com/comment/91018829
has answer: http://stackoverflow.com/a/49503311
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83844325
has answer: http://stackoverflow.com/a/50458125
score: 49
has title: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated
has answer: http://stackoverflow.com/a/49264739
accepted answer: http://stackoverflow.com/a/48544614
has comment: http://stackoverflow.com/comment/106289401
has answer: http://stackoverflow.com/a/48774337
has answer: http://stackoverflow.com/a/48750592
tagged with: python
has answer: http://stackoverflow.com/a/48544614
has answer: http://stackoverflow.com/a/58339792
answer count: 11
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49890475
has comment: http://stackoverflow.com/comment/87106362
has answer: http://stackoverflow.com/a/48486720
possible better answer: http://stackoverflow.com/a/48774337
has body: After updating my Numpy and Tensorflow I am getting these kind of warnings. I had already tried these, but nothing works, every suggestion will be appreciated. FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters 2018-01-19 17:11:38.695932: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

http://stackoverflow.com/a/48348046
has body: Use a supported Python version.
score: 0
answers question: http://stackoverflow.com/q/48348025
type: Answer

http://stackoverflow.com/q/48461700
upvote count: 1
has body: I generally try to avoid code duplication, even in single rows. However, I find myself writing lines like this in R a lot: # R code my_long_vector_var_name &lt;- append(my_long_vector_var_name, new_var) my_long_int_name &lt;- my_long_int_name + 1 In Python, not only are there way less letters in a row - I also do not have to write the same variable twice, which potentially reduces errors: my_long_vector_var_name.append(new_var) my_long_int_name += 1 For the second one, this question indicates that there truely is no comparable "short" way in R. The question, however, is more than 6 years old. Is there still no better way to do this in R?
linked to: http://stackoverflow.com/q/5738831
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48461898
has comment: http://stackoverflow.com/comment/83916595
tagged with: python
accepted answer: http://stackoverflow.com/a/48461882
has answer: http://stackoverflow.com/a/48461882
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83916424
answer count: 2
possible better answer: http://stackoverflow.com/a/48461898
has comment: http://stackoverflow.com/comment/83918060
has title: In-place assignment in R without writing the variable name twice?
score: 1
downvote count: 0

http://stackoverflow.com/comment/83951350
has text: Found this useful to get rid of those 2 issues. But the main issue still exists. Might be a cluster service-specific problem, as it works for me locally too.
type: Comment
comment on: http://stackoverflow.com/a/48465147
type: AnswerComment
score: 0

http://stackoverflow.com/q/48344958
has answer: http://stackoverflow.com/a/48366330
tagged with: dataframe
linked to: http://stackoverflow.com/q/23586510
accepted answer: http://stackoverflow.com/a/48366330
score: 8
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/83675841
has comment: http://stackoverflow.com/comment/83690688
linked to: http://stackoverflow.com/q/26886653
has answer: http://stackoverflow.com/a/48350336
possible better answer: http://stackoverflow.com/a/48350336
tagged with: python
has body: What I have: A dataframe with many rows, and several existing columns (python, pandas). Python 3.6, so a solution that relies on that particular version is fine with me (but obviously solutions that also work for earlier versions are fine too) What I want to do: Add multiple additional columns to the dataframe, where the values in these new columns all depend on some way on values in existing columns in the same row. The original order of the dataframe must be preserved. If a solution changes the ordering, I could restore it afterwards by manually sorting based on one of the existing columns, but obviously this introduces extra overhead. I already have the following code, which does work correctly. However, profiling has indicated that this code is one of the important bottlenecks in my code, so I'd like to optimize it if possible, and I also have reason to believe that should be possible: df["NewColumn1"] = df.apply(lambda row: compute_new_column1_value(row), axis=1) df["NewColumn2"] = df.apply(lambda row: compute_new_column2_value(row), axis=1) # a few more lines of code like the above I based this solution on answers to questions like this one (which is a question similar to mine, but specifically about adding one new column, whereas my question is about adding many new columns). I suppose that each of these df.apply() calls is internally implemented with a loop through all the rows, and I suspect it should be possible to optimize this with a solution that only loops through all the loops once (as opposed to once per column I want to add). In other answers, I have seen references to the assign() function, which does indeed support adding multiple columns at once. I tried using this in the following way: # WARNING: this does NOT work df = df.assign( NewColumn1=lambda row: compute_new_column1_value(row), NewColumn2=lambda row: compute_new_column2_value(row), # more lines like the two above ) The reason why this doesn't work is because the lambda's actually don't re…
favorite count: 0
has answer: http://stackoverflow.com/a/48366522
has answer: http://stackoverflow.com/a/48349742
linked to: http://stackoverflow.com/q/23330654
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83675591
linked to: http://stackoverflow.com/q/16575868
downvote count: 0
tagged with: pandas
answer count: 5
has title: How to efficiently add multiple columns to pandas dataframe with values that depend on other columns
has answer: http://stackoverflow.com/a/48358097

http://stackoverflow.com/q/48389141
has comment: http://stackoverflow.com/comment/83765990
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83766977
has title: pandas dataframe from dict preserves string indices (which mis-orders)
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
has body: I am loading data from a json file which, via json.load, returns a dict such as this: a = {'0': 0, '1': 1, '10': 10, '2': 2, '3': 3 ... etc.} When I turn this into a pandas dataframe (b = pd.DataFrame(a)), the DataFrame preserves indices with strings: print b.index Index([u'0', u'1', u'10', u'11', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9'], dtype='object') Is there a straightforward/pythonic way to sort this into 0:12 order? I feel like this should be trivial but my attempts with sort_index haven't worked (yet?)
tagged with: python
has comment: http://stackoverflow.com/comment/83766166
has comment: http://stackoverflow.com/comment/83765971
has comment: http://stackoverflow.com/comment/83766378
score: 2
has answer: http://stackoverflow.com/a/48389354
accepted answer: http://stackoverflow.com/a/48389354
upvote count: 2

http://stackoverflow.com/q/48403619
favorite count: 0
type: Question
tagged with: apache-spark-sql
upvote count: 2
tagged with: pyspark
tagged with: python
accepted answer: http://stackoverflow.com/a/48405450
has title: PySpark - Join dataframe by time intervals
score: 2
tagged with: left-join
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48405450
has body: I have two dataframes df_fruit= spark.createDataFrame([("Apple", "10:00"),("Orange", "12:35"),("Apple", "11:36"),("Apple","12:48"),("Pear","11:00")], ["Fruit", "Time"]) This dataframe stores when a fruit should be eaten. I have an additional dataframe which stores when exactly a fruit was eaten by a person as well as how many cals, and kg's was ingested. df_calories= spark.createDataFrame([("Apple", "10:02", "86g", "1cal"),("Orange", "12:39", "75g", "14cal"),("Apple", "10:04", "9g", "47cal"),("Apple","12:46", "25g", "9cal"),("Orange","12:33", "75g", "2cal")], ["Fruit", "Time", "Weight", "Calories"]) I need to join both tables by Fruit but also in time intervals of 5 mins. Since ingestion is flexible 5 mins either way from recommended time. This is the expected result. +------+-----+-----+------+--------+ | Fruit| Time| Time|Weight|Calories| +------+-----+-----+------+--------+ | Apple|10:00|10:02| 86g| 1cal| | Apple|10:00|10:04| 9g| 47cal| |Orange|12:35|12:39| 75g| 14cal| |Orange|12:35|12:33| 75g| 2cal| | Apple|11:36| null| null| null| | Apple|12:48|12:46| 25g| 9cal| | Pear|11:00| null| null| null| +------+-----+-----+------+--------+ The join type should be a left join i.e. all of df_fruit must be maintained
tagged with: join
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48451909
possible better answer: http://stackoverflow.com/a/48453422
score: 0
has title: Find index number for identical elements in a list
tagged with: string
type: Question
tagged with: indexing
has body: I have a list made of lists and strings. I want to find the index position of every element in the list which is a string. The problem is that the strings are identical to 'Error'. I tried with the following code: err = [bayesian_prices.index(i) for i in bayesian_prices if i == 'Error'] Unfortunately, from the initial list composed by 252 elements, the output is the following: [39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39] This is exactly the position of the first element which is not a list, but a string. Then the other string positions are registered with the same index number. Probably is due to the fact that all the strings are equal. How it is possible to obtain the correct index numbers?
has answer: http://stackoverflow.com/a/48452080
has answer: http://stackoverflow.com/a/48453422
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48452080
tagged with: list
answer count: 2

http://stackoverflow.com/comment/83715293
has text: I don't understand your *** operation. Also, can you post the data you use? You can use `to_dict` to get data that we can use immediately.
comment on: http://stackoverflow.com/q/48364134
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83730573
type: Comment
type: QuestionComment
score: 0
has text: read the error message. What could 'indention error' possibly mean?
comment on: http://stackoverflow.com/q/48371782

http://stackoverflow.com/comment/83726767
comment on: http://stackoverflow.com/a/48349031
score: 0
type: AnswerComment
has text: now it works so this great. But I have an additional issue : when I send the request the server put itslef in "TIME_WAIT" and then stop listenning the port. How could I do to make it listen all the time ?
type: Comment

http://stackoverflow.com/q/48374761
tagged with: arguments
tagged with: python
has answer: http://stackoverflow.com/a/48374881
score: 0
tagged with: oop
answer count: 1
tagged with: methods
has title: How do I define an argument in a method only if it isn't defined in __init__()?
tagged with: initialization
type: Question
type: UnansweredQuestion
has body: For example, I want to create a class that can do different things with or without an initialized variable, but I want to keep it flexible, so that if the class is created without that argument, it can be added in with a method later. I have: class Kickass(object): def __init__(self, website=None) if website: self.website = website def kick_butt(self): # Can do stuff even if website == None return stuff def web_scrape(self, site=None): if site: try: self.website == None except ValueError: print('Class instance already has a website!') # Do operations with method's argument if not site: if self.website == None: raise ValueError('Neither method nor instance have defined a website!') else: # Do operations with instance's variable I'm still terrible at classes and handling exceptions. Thanks in advance for your input.

http://stackoverflow.com/comment/83761784
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48378081
has text: There is nothing wrong with your answer from a stand point of "this code works". All the down votes came after your answer was the accepted answer. I believe people are down voting it because it was accepted and it doesn't use fancy python syntax like some of the other answers here, which would make your answer "not very pythonic". Yep, the dogma around this language is all too real unfortunately. The op probably understood your answer better than the other answers because they probably aren't that familiar with python. I didn't down vote, but some explanation from down voters would be nice.
score: 1

http://stackoverflow.com/q/48389065
has comment: http://stackoverflow.com/comment/83765816
has comment: http://stackoverflow.com/comment/83765873
tagged with: python
has comment: http://stackoverflow.com/comment/83765967
has comment: http://stackoverflow.com/comment/83857104
score: 0
has body: so i recently asked about, and then created a pretty simple Login system using files. the code basically works by saving your imputed username as a '.txt' file, and then your password is saved in the file. when logging in the code takes your input ( username)and opens the corresponding '.txt' file . the consent of the file is then checked to make sure it matches your password in put and it then allows you to log in. import sys import os str1=(ent.get()+".txt") password=ent3.get() name1=os.path.abspath(str1) myfile = open(name1, 'w') fh=open(str1,'w') fh.write(password) fh.close() window.destroy() import project.py and the logging in code def logging_in(): u = ent.get() password=(ent1.get()) file1=open((u)+'.txt','r') stored=file1.read() if stored == password: window.destroy() import mainmenu.py else: print('sorry something went wrong') my question is whether i can save the '.txt' file to a specific path and be able to open it it from the same path. i am relatively new to coding and am aware that it is most likely something very easy that i am missing. please bear in mind that my code is integrated with tkinter.
answer count: 0
has comment: http://stackoverflow.com/comment/83857055
has comment: http://stackoverflow.com/comment/83765979
has comment: http://stackoverflow.com/comment/83765890
has comment: http://stackoverflow.com/comment/83773315
has comment: http://stackoverflow.com/comment/83766749
has title: writng a file path for a login system
type: Question
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83765837

http://stackoverflow.com/comment/83859883
comment on: http://stackoverflow.com/q/48434117
type: Comment
type: QuestionComment
score: 0
has text: can you use `for param, values in param_list: for val in values: thisCuboid = Cuboid(param, val)`?

http://stackoverflow.com/q/48434487
answer count: 1
tagged with: unicode
accepted answer: http://stackoverflow.com/a/48436960
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48436960
tagged with: python-unicode
tagged with: python
tagged with: unicode-string
type: Question
has body: This question relates to Construct python library although that is not really important. I am writing a piece of code that needs to parse UTF16/32 encoded strings, there is no prefix (alike PascalString) and there is arbitrary data that follows it. I need someone to confirm my understanding oh these encodings. I know how to write a parser if these assumptions hold. UTF16 must be multiple of 2 bytes, last chunk (and only last) must be \x00\x00 UTF32 must be multiple of 4 bytes, last chunk (and only last) must be \x00\x00\x00\x00 I realise that some codepoints are not necessarily 2 bytes (UTF16).
has comment: http://stackoverflow.com/comment/83860934
has title: UTF16 and UTF32 decoder schema assumptions

http://stackoverflow.com/comment/83895779
score: 0
type: Comment
has text: Also I tried this on my DataFrame and im getting this error:
type: AnswerComment
comment on: http://stackoverflow.com/a/48451101

http://stackoverflow.com/comment/83822440
type: Comment
has text: @unknown121 it will depend on the path that you are in. Try to search on import on relative/absolute path. Like this one https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
comment on: http://stackoverflow.com/a/48416126
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83964262
has text: csv data is big (90 mb) and on windows environment. but still it just became 10 times slower!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48484615
score: 0

http://stackoverflow.com/a/48446536
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48446233
has comment: http://stackoverflow.com/comment/83885298
has body: You need to convert all your dictionary values to integers as an error TypeError: unsupported operand type(s) for +: 'int' and 'str' will be raised with the current code. When the latter error is corrected, the code achieves the correct result in Python2: import matplotlib.pyplot as plt D = { 'GCF_000416945.1': '450', 'GCF_001294115.1': '451', 'GCF_000245395.1': '416', 'GCF_002318825.1': '451', 'GCF_001401215.1': '450', 'GCF_000935735.1': '450' } plt.bar(range(len(D)), map(int, D.values()), align='center') plt.xticks(range(len(D)), D.keys())
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83885669
type: Answer
has comment: http://stackoverflow.com/comment/83885419
has comment: http://stackoverflow.com/comment/83885579
answers question: http://stackoverflow.com/q/48446233
upvote count: 1

http://stackoverflow.com/q/48452267
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48452469
type: Question
has body: foo = ['123','123','123] I am attempting to turn foo into: revisedfoo = ['111', '222', '333'] This in effect is turning the "rows" into "columns": 111 222 333 I have attempted something along these lines: for j in range(len(foo)): for i in range(len(foo)): revisedfoo.append(foo[i][j]) But it leaves me with: revisedfoo = ['1','1','1','2','2','2','3','3','3'] Any help would be appreciated!
has answer: http://stackoverflow.com/a/48452469
tagged with: python
tagged with: python-3.x
has title: Turning a list of rows into columns
type: AnsweredQuestion

http://stackoverflow.com/comment/83712858
comment on: http://stackoverflow.com/a/48362933
has text: Sorry If I failed to explain. As I mentioned "grouping based on first words" , so as you see on the sample output, lines start with "XZZ" and "DEF" are altogether. That's what I meant about grouping by first value. Line would be intact, but similar word that start the line would also be "grouped"
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48427095
tagged with: spark-submit
upvote count: 4
answer count: 2
tagged with: apache-spark
has answer: http://stackoverflow.com/a/57119197
has body: I'm new to Spark and having trouble replicating the example in the EMR docs for submitting a basic user application with spark-submit via AWS CLI. It seems to run without error but produces no output. Is something wrong with my syntax for add-steps in the below workflow? Example script The objective is to count words in a document in S3, for this example 1000 words of lorem-ipsum: $ aws s3 cp s3://projects/wordcount/input/some_document.txt - | head -n1 Lorem ipsum dolor sit amet, consectetur adipiscing [... etc.] Copying from the docs, the python script looks like: $ aws s3 cp s3://projects/wordcount/wordcount.py - from __future__ import print_function from pyspark import SparkContext import sys if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: wordcount ", file=sys.stderr) exit(-1) sc = SparkContext(appName="WordCount") text_file = sc.textFile(sys.argv[1]) counts = text_file.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b) counts.saveAsTextFile(sys.argv[2]) sc.stop() The destination folder (currently empty): $ aws s3 ls s3://projects/wordcount/output PRE output/ create-cluster Working from doc, I have a running cluster with logging, as produced by: aws emr create-cluster --name TestSparkCluster \ --release-label emr-5.11.0 --applications Name=Spark \ --enable-debugging --log-uri s3://projects/wordcount/log \ --instance-type m3.xlarge --instance-count 3 --use-default-roles with return message showing created {"ClusterID": "j-XXXXXXXXXXXXX"} add-steps Looking directly at the example, I submit add-steps as: aws emr add-steps --cluster-id j-XXXXXXXXXXXXX \ --steps Type=spark,Name=SparkWordCountApp,\ Args=[--deploy-mode,cluster,--master,yarn,\ --conf,spark.yarn.submit.waitAppCompletion=false,\ --num-executors,2,--executor-cores,2,--executor-memory,1g,\ s3://projects/wordcount/wordcount.py,\ s3://projects/wordcount/input/some_document.txt,\ s3://projects/wordcount/output/],\ ActionOnFailure=CONTINUE which lau…
downvote count: 0
has title: launch Python app with spark-submit in AWS EMR
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: amazon-emr
has answer: http://stackoverflow.com/a/48430033
tagged with: pyspark
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/27033823

travis-ci
tags question: http://stackoverflow.com/q/48464972
type: Tag
tag name: travis-ci

http://stackoverflow.com/a/48377311
accepted answer of: http://stackoverflow.com/q/48376724
has comment: http://stackoverflow.com/comment/83742172
answers question: http://stackoverflow.com/q/48376724
score: 0
has body: You should implement your second suggestion. Cross-validation should be used to tune the parameters of your approach. Among others, such parameters in your example are the value of the C parameter and the class_weight='balanced' of Logistic Regression. So you should: split in 50% training, 50% test use the training data to select the optimal values of the parameters of your model with cross-validation Refit the model with the optimal parameters on the training data Predict for the test data and report the score of the evaluation measure you selected Notice, you should use the test data only for reporting the final score and not for tuning the model, otherwise you are cheating. Imagine, that in reality you may not have access to them until the last moment, so you can not use them.
has comment: http://stackoverflow.com/comment/83744829
type: Answer
has comment: http://stackoverflow.com/comment/83748127
has comment: http://stackoverflow.com/comment/83747748
has comment: http://stackoverflow.com/comment/83745331
type: AcceptedAnswer

http://stackoverflow.com/comment/83792151
type: Comment
comment on: http://stackoverflow.com/q/48401550
type: QuestionComment
score: 0
has text: @VikasDamodar This scripts has no error. It spits out the filenames and extensions only, as I described in the text. :) Only I can't figure out how to do the rest.

http://stackoverflow.com/comment/83901335
score: 1
has text: I am using JS. When I tried to use that kind of code, it returns null, which is why I was suspecting it is a closed kind of shadow DOM vs open, which I also tested on and it works. So user-agent shadow DOMs are created by the browser itself and can not be accessed at this time.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48451806

http://stackoverflow.com/q/48448206
has comment: http://stackoverflow.com/comment/83889262
linked to: http://stackoverflow.com/q/509211
has title: Python use of a:[1,3]?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83889065
has comment: http://stackoverflow.com/comment/83889418
downvote count: 8
has comment: http://stackoverflow.com/comment/83890438
tagged with: python
has answer: http://stackoverflow.com/a/48448476
answer count: 4
has comment: http://stackoverflow.com/comment/83889274
has comment: http://stackoverflow.com/comment/83888853
has comment: http://stackoverflow.com/comment/83889397
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48448400
has comment: http://stackoverflow.com/comment/83888803
accepted answer: http://stackoverflow.com/a/48448434
has answer: http://stackoverflow.com/a/48448400
has body: What does this line mean in python 3.x? a:[1,3] Source : https://www.youtube.com/watch?v=yX8KuPZCAMo Time: 17:40
has answer: http://stackoverflow.com/a/48448411
has answer: http://stackoverflow.com/a/48448434
upvote count: 1
score: -7

http://stackoverflow.com/comment/83708817
has text: Possible duplicate of [Python dynamic instantiation from string name of a class in dynamically imported module](https://stackoverflow.com/questions/4821104/python-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported)
comment on: http://stackoverflow.com/q/48361026
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48449847
favorite count: 0
tagged with: deep-learning
tagged with: convolution
score: 1
tagged with: python
has title: Calculating output_shape when using 3d transpose convolutions in Tensorflow
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48450385
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: computer-vision
has body: I have a 4D tensor h0 from a previous layer with shape [10, 1, 1, 1, 10] and I want to upsample using conv3d_transpose to a tensor h1 with shape, lets say, [10, 4, 4, 4, 20]. I do not understand how my choice of filter, strides and padding effect output_shape, given h0, and hence whether [10, 4, 4, 4, 20] is possible for h1? Is there a rule of thumb or formula? For example, if I run the following: import tensorflow as tf sess = tf.Session() # Input (previous layer) [batch, depth, height, width, in_channels] h0 = tf.constant(0.1, shape=[10, 1, 1, 1, 10]) # Filter [depth, height, width, output_channels, in_channels] w1 = tf.constant(0.1, shape=[5, 5, 5, 20, 10]) # Strides [1, depth, height, width, 1] strides1 = [1, 4, 4, 4, 1] # Output shape [batch, depth, height, width, in_channels] output_shape1 = [10, 4, 4, 4, 20] # Current layer h1 = tf.nn.conv3d_transpose(value = h0, filter = w1, output_shape = output_shape1, strides = strides1, padding = 'VALID') sess.close() I get the error: InvalidArgumentError: Conv3DBackpropInput: Number of planes of out_backprop doesn't match computed: actual = 1, computed = 0 But if I change padding = 'SAME' then I get no error. I have read about convolutional arithmetic but do not understand how the formulas apply to Tensorflow specifically.

http://stackoverflow.com/q/48441336
has comment: http://stackoverflow.com/comment/84138349
has answer: http://stackoverflow.com/a/48448805
favorite count: 0
has comment: http://stackoverflow.com/comment/84137282
type: Question
has comment: http://stackoverflow.com/comment/83876814
has comment: http://stackoverflow.com/comment/84138859
has body: I'm using scrapy to scrape the adidas site: http://www.adidas.com/us/men-shoes. But it always shows error: User timeout caused connection failure: Getting http://www.adidas.com/us/men-shoes took longer than 180.0 seconds.. It retries for 5 times and then fails completely. I can access the url on chrome but it's not working on scrapy. I've tried using custom user agents and emulating header requests but It's still doesn't work. Below is my code: import scrapy class AdidasSpider(scrapy.Spider): name = "adidas" def start_requests(self): urls = ['http://www.adidas.com/us/men-shoes'] headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Host": "www.adidas.com", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" } for url in urls: yield scrapy.Request(url, self.parse, headers=headers) def parse(self, response): yield(response.body) Scrapy log: {'downloader/exception_count': 1, 'downloader/exception_type_count/twisted.web._newclient.ResponseNeverReceived': 1, 'downloader/request_bytes': 224, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'finish_reason': 'shutdown', 'finish_time': datetime.datetime(2018, 1, 25, 10, 59, 35, 57000), 'log_count/DEBUG': 2, 'log_count/INFO': 9, 'retry/count': 1, 'retry/reason_count/twisted.web._newclient.ResponseNeverReceived': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 2, 'scheduler/enqueued/memory': 2, 'start_time': datetime.datetime(2018, 1, 25, 10, 58, 39, 550000)} Update After looking at the request headers using fiddler and doing some tests I found what was causing the issue. Scrapy is sending a Connection: close header by default due to which I'm not getting any response from…
has comment: http://stackoverflow.com/comment/84136710
answer count: 5
tagged with: twisted
has comment: http://stackoverflow.com/comment/84137104
possible better answer: http://stackoverflow.com/a/48459677
has comment: http://stackoverflow.com/comment/84114241
linked to: http://stackoverflow.com/q/4981440
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/48559453
score: 4
has title: Scrapy error:User timeout caused connection failure
has answer: http://stackoverflow.com/a/48459677
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84120800
downvote count: 0
has answer: http://stackoverflow.com/a/48555404
tagged with: python
has answer: http://stackoverflow.com/a/48482101
has answer: http://stackoverflow.com/a/48559453
upvote count: 4

http://stackoverflow.com/q/48455689
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/74500705
score: 7
has answer: http://stackoverflow.com/a/74500705
tagged with: python
has title: Flask validate_on_submit always False
type: Question
has answer: http://stackoverflow.com/a/48456053
accepted answer: http://stackoverflow.com/a/48456053
has answer: http://stackoverflow.com/a/71101422
answer count: 3
downvote count: 0
upvote count: 7
has body: I know that there are similar problems which have been answered. The csrf_enabled is not an issue now if the Form inheriting FlaskForm, and the template has the form.hidden_tag(). I have the following flask app. ## Filenname: app.py from flask import Flask, render_template, redirect, url_for, flash, request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, SelectField from wtforms.validators import DataRequired app = Flask(__name__) app.config["SECRET_KEY"] = "secret" class DataForm(FlaskForm): name = StringField("Name", validators=[DataRequired()]) gender = SelectField("Gender", validators=None, choices=[(1, 'M'), (2, "F")]) submit = SubmitField("Submit", validators=None) @app.route('/index', methods=["GET", "POST"]) def index(): form = DataForm(request.form) print(form.validate_on_submit()) if form.validate_on_submit(): print(form.validate()) print(form.name) flash("THIS IS FLASH") title="hello" return redirect(url_for('output')) return render_template('index.html', form=form) @app.route('/output', methods=["GET", "POST"]) def output(): title = "hello" form = DataForm() print(form.validate()) return render_template('output.html', title=title) app.run(debug=False) The following is index.html template: &lt;html&gt; &lt;body&gt; {% with messages = get_flashed_messages() %} {{ messages }} {% endwith %} &lt;form action="" method="GET"&gt; {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name() }} {% for error in form.name.errors %} &lt;span style="color: red;"&gt;[{{ error }}]&lt;/span&gt; {% endfor %} &lt;hr&gt; {{ form.gender.label }} {{ form.gender() }} {{ form.submit() }} &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; After clicking the submit button the execution never goes in the if form.validate_on_submit() block in the index function. I also removed all the validators, the code inside validate_on_submit block is still unreachable. Printing form.validate_on_submit() is always false.
tagged with: flask
tagged with: jinja2
has comment: http://stackoverflow.com/comment/83904511
favorite count: 0
linked to: http://stackoverflow.com/q/18716920

http://stackoverflow.com/a/48337228
downvote count: 0
has body: This is because the widget does not have the variable "text". Instead, the options for the widget are stored in a dictionary. When you use button["text"], you're accessing the item "text" in the dictionary, and so it returns the value of the "text" key. You could also use the cget method to get the option. This dictionary of values is best accessed from the configure method. Using said method with no parameters will return a dictionary of all options for the widget.
upvote count: 1
has comment: http://stackoverflow.com/comment/83668057
has comment: http://stackoverflow.com/comment/83691369
answers question: http://stackoverflow.com/q/48336473
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83670737

http://stackoverflow.com/comment/83704362
has text: @Sean: I'm not sure what you are asking. Pass your hand-picked seed value to `random.seed()` to set it.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48358698

http://stackoverflow.com/q/48331883
tagged with: python
has comment: http://stackoverflow.com/comment/83649613
type: Question
has comment: http://stackoverflow.com/comment/83660226
has title: Sending message on Facebook using Python
upvote count: 0
type: UnansweredQuestion
has body: Trying to send a message on Facebook using Python. All the step works until putting the text in textarea to send. Getting error code: Unable to locate element: {"method":"css selector","selector":"div textarea.uiTextareaNoResize"} Here is the whole code: from selenium import webdriver from selenium.webdriver.common.keys import Keys import sched, time, timeit import random import getpass import sys driver = webdriver.Chrome('C:\path\chromedriver.exe') driver.get('https://www.facebook.com/') username_box = driver.find_element_by_id('email') username_box.send_keys("USEREMAIL") passElem = driver.find_element_by_id("pass") passElem.send_keys("USERPASS") passElem.send_keys(Keys.RETURN) userTargetUrl = "https://www.facebook.com/messages/t/" + "USERTARGET NAME" driver.get(userTargetUrl) elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize") elem.send_keys("Test") elem.send_keys(Keys.RETURN) driver.find_element_by_id("u_0_t").click() Error occurs here: elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize") elem.send_keys("Test") elem.send_keys(Keys.RETURN) driver.find_element_by_id("u_0_t").click() Getting this message on the console: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div textarea.uiTextareaNoResize"} (Session info: chrome=63.0.3239.132) (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.15063 x86_64) This code here fails: elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize") In this picture you can see where I want my message to be written.
tagged with: message
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83650681
tagged with: facebook-messages
favorite count: 0
score: -2
has answer: http://stackoverflow.com/a/48332342
tagged with: facebook
tagged with: facebook-messenger

http://stackoverflow.com/q/48407730
answer count: 0
downvote count: 0
tagged with: machine-learning
upvote count: 1
score: 1
tagged with: keras
has body: my theano version is 1.0.1+unknown. my keras version is 2.1.3 i'm implementing stacked LSTM autoencoder in keras and this is my code: timesteps = x_train.shape[1] input_dim = 1 inputs = Input(batch_shape=(1,timesteps, input_dim)) encoded = LSTM(7,return_sequences = True)(inputs) encoded = LSTM(5,return_sequences = True)(encoded) encoded = LSTM(3)(encoded) decoded = RepeatVector(timesteps)(encoded) decoded = LSTM(5,return_sequences = True)(decoded) decoded = LSTM(7,return_sequences = True)(decoded) decoded = LSTM(input_dim,return_sequences = True)(decoded) sequence_autoencoder = Model(inputs, decoded) encoder = Model(inputs,encoded) sequence_autoencoder.compile(loss='mean_squared_error', optimizer='Adam') sequence_autoencoder.fit(x_train, x_train, epochs=100, batch_size=1, shuffle=True, ) It gives me the following error: TypeError: The broadcast pattern of the output of scan (TensorType(float32, 3D)) is inconsistent with the one provided in output_info (TensorType(float32, col)). The output on axis 1 is False, but it is True on axis 2 in output_info. This can happen if one of the dimension is fixed to 1 in the input, while it is still variable in the output, or vice-verca. You have to make them consistent, e.g. using theano.tensor.{patternbroadcast,unbroadcast,addbroadcast}.
favorite count: 0
type: Question
tagged with: theano
has comment: http://stackoverflow.com/comment/83811851
has comment: http://stackoverflow.com/comment/83808408
tagged with: python
type: UnansweredQuestion
has title: a TypeError in fit function when using keras with theano backend
tagged with: neural-network

http://stackoverflow.com/comment/140264736
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79535780
type: AnswerComment
has text: Don’t add code-only answers. Explain what your code does, why it works, and how it helps to solve the problem. Remember, answers should be useful for future visitors, even if they don’t have the exact same code as the OP.

http://stackoverflow.com/a/48378999
type: AcceptedAnswer
has body: Python has a way of dealing with complex numbers; it actually has a type for them (&lt;class 'complex'&gt;). As a result, and to avoid having to re-invent the wheel I would strongly recommend using that. To do that, we must first sanitise our input (convert the values from strings to complex). To do that we must first adhere to Python's conventions for the imaginary unit for which 'j' is used and not 'i'. l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i'] l1 = [complex(x.replace('i', 'j')) for x in l1] # if you are curious how they look like print(l1) # -&gt; [(13+1j), (1+4j), ...] With the values now in a proper format, we can take advantage of the .real and .imag attributes of variables of type complex and built our result lists using list-compehensions. real_parts = [value.real for value in l1] print(real_parts) # -&gt; [13.0, 1.0, 3.0, 11.0, 5.0, 10.0, 5.0] imaginary_parts = [value.imag for value in l1] print(imaginary_parts) # -&gt; [1.0, 4.0, 2.0, 4.0, 1.0, 2.0, 4.0] Note that by default, they are all real numbers (real as in not-integer). Casting them to int could easily be achieved with [int(value.real) for value in l1]. Probably the nicest thing about using existing functionality is that you do not have to worry about edge cases which you might have not though possible and as a result might have caused your code to break. For instance 4j (no real part) or 1-j (negative imaginary part so .split('+')[0] would not work) and so on.
answers question: http://stackoverflow.com/q/48378851
has comment: http://stackoverflow.com/comment/83744774
type: Answer
has comment: http://stackoverflow.com/comment/83744852
downvote count: 0
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48378851

http://stackoverflow.com/comment/83760154
type: Comment
type: QuestionComment
has text: It looks like what you want is a nested for loop: for url in urls: for pattern in patterns: re.search(pattern, url) Have you thought about what you want to do if a url matches more than one pattern?
comment on: http://stackoverflow.com/q/48386339
score: 0

http://stackoverflow.com/comment/83884578
has text: I want to get a JSON object containing the info from the latest Page revision. Fortunately this part is done. Based on the results of the conditional statement, I want to change one of the value of one of the keys. This part is also done. I now have a JSON object with all the correct values. So @gasman, how do I save this updated JSON object as the latest revision, so after the page refresh the values show in the browser? I tried passing the JSON to the save_revisions() method and ran into issues. Using save_revisions.publish() saves the key values to the model and not to the last revision.
score: 0
comment on: http://stackoverflow.com/q/48432006
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86705135
comment on: http://stackoverflow.com/q/48462011
has text: Did you figure this out?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48391078
downvote count: 0
has body: Here is the direct way of exploiting csr format. Your matmul solution probably does similar things under the hood. But we save one lookup (from the .data attribute) by also exploiting that it is an adjacency matrix; also, diffing .indptr should be more efficient than summing the equivalent amount of ones. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy import sparse &gt;&gt;&gt; # create mock data &gt;&gt;&gt; A = np.random.random((100, 100)) &lt; 0.1 &gt;&gt;&gt; A = (A | A.T).view(np.uint8) &gt;&gt;&gt; AS = sparse.csr_matrix(A) &gt;&gt;&gt; X = np.random.random((100, 3)) &gt;&gt;&gt; # dense solution for reference &gt;&gt;&gt; Xa = A @ X / A.sum(axis=-1, keepdims=True) # sparse solution &gt;&gt;&gt; XaS = np.add.reduceat(X[AS.indices], AS.indptr[:-1], axis=0) / np.diff(AS.indptr)[:, None] &gt;&gt;&gt; # check they are the same &gt;&gt;&gt; np.allclose(Xa, XaS) True
type: Answer
has comment: http://stackoverflow.com/comment/84347244
accepted answer of: http://stackoverflow.com/q/48390268
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48390268
type: AcceptedAnswer

http://stackoverflow.com/a/48375736
answers question: http://stackoverflow.com/q/48374911
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: QMenu has the triggered signal, this returns the QAction associated to the item pressed, to obtain the text we use the text() method of the QAction: def create_actions(self): # filters menu self.menu_filters = QtWidgets.QMenu(self) filters = ['Asphalt','Ceramic','Concrete','Fabric','Ground','Granite','Leather'] for x in filters: action = self.menu_filters.addAction(x) self.ui_filters.setMenu(self.menu_filters) self.ui_filters.setPopupMode(QtWidgets.QToolButton.InstantPopup) self.menu_filters.triggered.connect(self.onTriggered) def onTriggered(self, action): print(action.text())
type: Answer
accepted answer of: http://stackoverflow.com/q/48374911

http://stackoverflow.com/q/48454484
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/48454541
has comment: http://stackoverflow.com/comment/83902036
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has title: How to turn array of vectors into dataframe?
has comment: http://stackoverflow.com/comment/83902088
score: 1
has answer: http://stackoverflow.com/a/48454543
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83901974
accepted answer: http://stackoverflow.com/a/48454543
has answer: http://stackoverflow.com/a/48454541
has body: I have the following list with arrays: [array([2, 1, 4, 1]), array([2, 4, 4, 2]), array([2, 2, 4, 0])] I would like to turn it into a dataframe with a title "Vectors" that looks like this: "1x4 Vectors" 0 [2, 1, 4, 1] 1 [2, 4, 4, 2] 3 [2, 2, 4, 0] I tried using pd.DataFrame(name_of_data_with_vectors, columns = "4x1 Vectors") But, I get the following error: AssertionError: 1 columns passed, passed data had 4 columns

http://stackoverflow.com/comment/83770486
comment on: http://stackoverflow.com/q/48390412
type: Comment
type: QuestionComment
score: 1
has text: The solution is [here](https://projecteuler.chat/viewtopic.php?t=1572)

http://stackoverflow.com/comment/121399899
score: 4
has text: It seems it's related to this Click issue https://github.com/pallets/click/issues/2012 and simply defining declaring `type=tuple` on the click option fixes it.
type: AnswerComment
comment on: http://stackoverflow.com/a/48394004
type: Comment

http://stackoverflow.com/q/48386070
downvote count: 1
favorite count: 0
type: Question
has body: I have a python list e with ~11,000 elements. I then have a list of indexes p of ~3,000 elements. I want to filter e to keep only the elements at the indexes specified in p. So far, I'm using simple list comprehension: f = [x for i,x in enumerate(e) if i in p] However, this implementation takes ~1s. This might not be much, but as I have to do it for 10,000 lists, it becomes over 2 hours. I then have to repeat this again for 200 batches of 10,000 lists, so it's really too slow. Any idea of how I can achieve the same result in a quicker manner?
duplicate of: http://stackoverflow.com/q/5993621
tagged with: algorithm
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48386103
has title: Faster way of getting elements in list by index
score: 0
has comment: http://stackoverflow.com/comment/83759466
has answer: http://stackoverflow.com/a/48386103
linked to: http://stackoverflow.com/q/5993621
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/83665244
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48339961
has text: you should be able to use `Workbooks.Open(Filename:= "C:\....", Password:="pw")`, when you open it through python, but im not really understanding what you are trying to ask.
type: Comment

http://stackoverflow.com/comment/83788841
comment on: http://stackoverflow.com/q/48398706
has text: Following this method [My answer in another post](https://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces-in-path/48382727#48382727)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83890144
type: Comment
type: AnswerComment
has text: thanks for the quick answer, this works but I'd like to understand what's different between your approach and my approach? In your code you convert each RDD item into a Row and my code didn't do that, is that way my code failed?
comment on: http://stackoverflow.com/a/48448673
score: 0

http://stackoverflow.com/comment/83960095
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48482750
has text: Right, I understand that NaN and Inf cant be int, which is why line notna= floats.columns[floats.notna().any()].tolist() is collecting the names of the columns that do not have NaNs in them. And then the next line is meant to convert only those columns that are floats and dont have NaNs in them

http://stackoverflow.com/comment/83875791
comment on: http://stackoverflow.com/q/48441705
has text: I a bit modify answer if multiple max dates per group. Is possible check output from R code? I have no R studio, so cannot do it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48485672
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: sockets
has body: I'm working with socket and try to understand how we can find the good format character to unpack Ethernet Frame. For example, to unpack Ethernet frame we can do this: struct.unpack("! 6s 6s H", data[0:14]) How we know it's "6s 6s H"?
has title: How unpack frame ethernet works
tagged with: python
has answer: http://stackoverflow.com/a/48485734
has comment: http://stackoverflow.com/comment/83964238
upvote count: 0
has comment: http://stackoverflow.com/comment/83964122
answer count: 1
downvote count: 1
score: -1

http://stackoverflow.com/a/48389822
type: Answer
has body: Opening an in-memory database with shared-cache mode requires a URI filename. Your Python version does not support this; it always treats the entire string as the file name. URI filenames are supported in Python 3.4 and later: db = sqlite3.connect("file::memory:?cache=shared", uri=True)
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48388624
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48388624
downvote count: 0
score: 1

http://stackoverflow.com/comment/83685760
comment on: http://stackoverflow.com/a/48349601
type: Comment
score: 0
type: AnswerComment
has text: @Nahuatl_19650 Be that as it may, the `Answer = a + b` returns an `int` and `myAnswer.get()` returns a `str`. If you want to compare them you need to convert one or the other in the most simplistic of the solutions.

http://stackoverflow.com/comment/120964437
has text: You can also try custom_objects. something like model = load_model(model_path, custom_objects={ 'weighted_binary_crossentropy': weighted_binary_crossentropy(y_true, y_pred, weight=[1.,2.]) }) this is just an example that my loss name was weighted_binary_crossentropy and I had added weight. so I needed to give some weight when loading as well. I'm not sure how you have defined your loss, but you can just give some arbitrary variable when loading in the test time; I could give weight=[1.,1.]. Please search more for it and let me know if any issues.
comment on: http://stackoverflow.com/a/67010429
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48450311
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83896114
has comment: http://stackoverflow.com/comment/83896634
has comment: http://stackoverflow.com/comment/83896555
type: Answer
has comment: http://stackoverflow.com/comment/83896522
score: 0
has comment: http://stackoverflow.com/comment/83896440
answers question: http://stackoverflow.com/q/48450244
has body: df['freq'] = 1 df.groupby(['starttime','hour', as_index=False]).count()

http://stackoverflow.com/comment/83927814
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48466839
type: Comment
has text: The format of the floating-point type was is not determined by whether the machine is “32-bit” or “64-bit”. You can have both 32-bit and 64-bit floating-point formats on a 32-bit machine or a 64-bit machine.

http://stackoverflow.com/comment/83675571
type: Comment
has text: Not familiar with *pandas*, but the `freq` value shouldn't have been `'3333333ns'` (7 digits instead of 9) as *3333333ns* =~ *3ms* =~ *1/(300Hz)*?
score: 0
comment on: http://stackoverflow.com/q/48344540
type: QuestionComment

http://stackoverflow.com/comment/83754777
score: 0
comment on: http://stackoverflow.com/a/48383804
type: Comment
has text: `itr_split_overlap()` doesn't return the correct result
type: AnswerComment

http://stackoverflow.com/q/48396321
downvote count: 0
duplicate of: http://stackoverflow.com/q/53645882
answer count: 1
favorite count: 0
type: Question
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/83780236
has comment: http://stackoverflow.com/comment/83780376
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83780335
linked to: http://stackoverflow.com/q/53645882
accepted answer: http://stackoverflow.com/a/48396375
upvote count: 2
has body: I have two data frames, df1=pd.DataFrame({"Req":["Req 1","Req 2","Req 3"],"Count":[1,2,1]}) Req Count 0 Req 1 1 1 Req 2 2 2 Req 3 1 df2=pd.DataFrame({"Req":["Req 1","Req 2"],"Count":[0,1]}) Req Count 0 Req 1 0 1 Req 2 1 I am trying to merge these df's based on "Req" column My desired output is, Req total from_1 from_2 Req 1 1 1 0 Req 2 3 2 1 Req 3 1 1 0 I tried pd.merge(df1, df2, on = "Req", ) but it is not giving my desired output, please help, thanks in advance!
tagged with: pandas
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48396375
has title: how to merge two dataframes based on a column in pandas

http://stackoverflow.com/comment/107554458
comment on: http://stackoverflow.com/a/48421507
has text: https://stackoverflow.com/questions/42490368/pythonappending-to-the-same-list-from-different-processes-using-multiprocessing
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83934226
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48466886
score: 0
has text: Hello again, I have noticed now that it also matches paths like: c:\windows\system32\tasks\microsoft\windows\shell\windowsparentalcontrolsmigration and turns them into: c:\windows\system32\tasks\microsoft\windows\shell\##HASH## How can I improve the re to say that it should have at least a digit in the name or k digits. Thanks.

http://stackoverflow.com/q/48440803
tagged with: spss
score: 1
has title: SPSS print to output on start
tagged with: python
has answer: http://stackoverflow.com/a/48448871
has comment: http://stackoverflow.com/comment/83907954
type: Question
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83911650
answer count: 1
has body: I am looking for a way to print to the SPSS output on start of program. By looking in the python documentation for SPSS I cannot seem to find any instance for doing stuff on start. Or am I missing something here? So after reading eli-k's comment (startup scripts) it should be as easy to place StartClient_.py in the /extensions directory but this does not seem to work as well.. #StartClient_.py import SpssClient SpssClient.StartClient() print "whatever" SpssClient.StopClient()
favorite count: 0

http://stackoverflow.com/q/48350299
upvote count: 0
has comment: http://stackoverflow.com/comment/83687211
favorite count: 0
type: Question
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/83687333
has answer: http://stackoverflow.com/a/48350798
type: UnansweredQuestion
score: -4
tagged with: python
has answer: http://stackoverflow.com/a/48350689
has title: Why is my while statement not working
has comment: http://stackoverflow.com/comment/83687236
linked to: http://stackoverflow.com/q/39983695
has comment: http://stackoverflow.com/comment/83687201
has body: I am relatively new to programming and am having trouble with a simple while loop. I am attempting to write a program that outputs all multiples of 3 between 0 and 100. Here is what I have: counter3 = 1 theList = [] while counter3 &lt;= 1000: if 3 % counter3 : True theList.append(counter3) counter3 = counter3+1 print(theList) The while loop I am using has a syntax error, but I am not sure where it is. Any help would be appreciated

http://stackoverflow.com/comment/84003038
has text: Perfect, please edit the answer with adding the comment text.
type: Comment
comment on: http://stackoverflow.com/a/48474134
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83969184
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48488124
has text: Replace `msg` with `messenger()` ?

http://stackoverflow.com/comment/83902871
has text: my implementation is also solving things with FD. Its very possible, I was just saying that in theory you could use post optimality sensitivities, but to do so would mean posing things as an ImplicitComponent. You'd also need access to the Lagrange multipliers though, which most optimizers don't provide.
type: AnswerComment
comment on: http://stackoverflow.com/a/48393288
score: 0
type: Comment

http://stackoverflow.com/q/48346752
type: Question
has comment: http://stackoverflow.com/comment/83679586
answer count: 2
linked to: http://stackoverflow.com/q/15203829
has comment: http://stackoverflow.com/comment/83679616
has answer: http://stackoverflow.com/a/48346880
accepted answer: http://stackoverflow.com/a/48346880
has answer: http://stackoverflow.com/a/48347938
tagged with: python
has body: The argparse package does a great job when dealing with command line arguments. I'm wondering however if there is any way to ask argparse to check for file extension (e.g ".txt"). The idea would be to derived one the class related to argparse.FileType. I would be interested in any suggestion. Keep in mind that I have more than 50 subcommands in my program all having there own CLI. Thus, I would be interest in deriving a class that could be imported in each of them more than adding some uggly tests in all my commands. Thanks a lot. # As an example one would be interested in turning this... parser_grp.add_argument('-o', '--outputfile', help="Output file.", default=sys.stdout, metavar="TXT", type=argparse.FileType('w')) # Into that... from somewhere import FileTypeWithExtensionCheck parser_grp.add_argument('-o', '--outputfile', help="Output file.", default=sys.stdout, metavar="TXT", type=FileTypeWithExtensionCheck('w', '.[Tt][Xx][Tt]$'))
upvote count: 7
has comment: http://stackoverflow.com/comment/83680377
has comment: http://stackoverflow.com/comment/83679572
has comment: http://stackoverflow.com/comment/83679715
type: AnsweredQuestion
tagged with: argparse
has title: python argparse.FileType('w') check extension
score: 7
downvote count: 0
possible better answer: http://stackoverflow.com/a/48347938
tagged with: file-type
favorite count: 0

http://stackoverflow.com/a/52919794
has comment: http://stackoverflow.com/comment/137807822
type: Answer
score: 12
upvote count: 12
has comment: http://stackoverflow.com/comment/137805620
answers question: http://stackoverflow.com/q/48409128
downvote count: 0
has body: loc is specially useful when the index is not numeric (e.g. a DatetimeIndex) because you can get rows with particular labels from the index: df.loc['2010-05-04 07:00:00'] df.loc['2010-1-1 0:00:00':'2010-12-31 23:59:59 ','Price'] However [] is intended to get columns with particular names: df['Price'] With [] you can also filter rows, but it is more elaborated: df[df['Date'] &lt; datetime.datetime(2010,1,1,7,0,0)]['Price']

http://stackoverflow.com/q/48412424
has comment: http://stackoverflow.com/comment/83833883
has answer: http://stackoverflow.com/a/56851539
has comment: http://stackoverflow.com/comment/83825474
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83814917
answer count: 1
tagged with: keras
type: Question
score: 0
has title: AttributeError: 'Tensor' object has no attribute 'exp'
tagged with: attributeerror
has body: I am trying to train a LSTM NN using Keras on a self-defined evaluation_metric that I use as loss function. The structure of my Neural Network is: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 15, 1) 0 _________________________________________________________________ lstm_2 (LSTM) (None, 20) 1760 _________________________________________________________________ dense_3 (Dense) (None, 10) 210 _________________________________________________________________ dense_4 (Dense) (None, 1) 11 ================================================================= Let me give you some context: my NN produces an array of numerical values. These values have been scaled by some mathematical function. In order to compare it with the actual values, I need to first undo the scaling to transform it back to the original context. For this, I have created the function decode_output_values: import numpy as np [....] def decode_output_values(pred_scaled,Y_train): #Decodes the output values back to the original context Y_min = np.nanmin(Y_train) Y_max = np.nanmax(Y_train) Y_pred = np.exp(pred_scaled*(np.log(Y_max)-np.log(Y_min))+np.log(Y_min)) return Y_pred Now that the output values are decoded, I make another change in order to be able to compare it with the real output values in the test set that are known. These real output values in the test set have a lot of NA values and only numerical values on some rows. Therefore, I only look at the corresponding indices of the rows that have non-NA values and calculate the RMSE between these values, using a function "evaluation_metric" that I have created: I have created my own function evaluation_metric: from sklearn.metrics import mean_squared_error from math import sqrt [....] def evaluation_metric(y_true, y_pred_scaled): #Convert predictions back to original scale y_pred = decode_output_values(y_pred…
has comment: http://stackoverflow.com/comment/83842058
has comment: http://stackoverflow.com/comment/83833859
tagged with: python

http://stackoverflow.com/q/48354887
score: 1
has title: Difference in List
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48355036
has answer: http://stackoverflow.com/a/48355036
has answer: http://stackoverflow.com/a/48355192
has comment: http://stackoverflow.com/comment/83696339
has answer: http://stackoverflow.com/a/48355004
tagged with: python
has body: I want to write a function which gives difference between lists. For example, list1 = ['a','a','a','b','c','d','d'] list2 = ['a','a','a','b','c','a','d'] list = diff(list1, list2) print(list) list should be ['d','a'], the elements which don't match in both. I thought of using set but it won't work as it'll eliminate repeating characters.
answer count: 4
has comment: http://stackoverflow.com/comment/83696398
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48355159
possible better answer: http://stackoverflow.com/a/48355004
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83782189
comment on: http://stackoverflow.com/q/48394638
type: Comment
score: 0
has text: dude..setting up django on hostgator is headache.. i struggled a lot doing that.
type: QuestionComment

http://stackoverflow.com/a/48437773
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: You can calculate Structural Similarity Index (SSIM) using scikit-image module, from skimage.measure import compare_ssim import cv2 ###convert you images to grayscale gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) ###compute the similarity and difference (score, diff) = compare_ssim(gray1, gray2, full=True) diff = (diff * 255).astype("uint8") print("Similarity: {}".format(score))
answers question: http://stackoverflow.com/q/48437443

http://stackoverflow.com/comment/83704157
type: QuestionComment
has text: Your function has the character ← in it? That's obviously not going to work.
score: 0
comment on: http://stackoverflow.com/q/48358723
type: Comment

http://stackoverflow.com/a/48333592
has comment: http://stackoverflow.com/comment/83662915
answers question: http://stackoverflow.com/q/48333517
score: 0
has comment: http://stackoverflow.com/comment/83653168
has body: This is where your problem lies: dictionary = response.data[j] You declare the dictionary and at the same time, you the existing value with the latest value in the loop. By the time the loop exits, The dictionary would contain only one result (The last one in the loop) you should declare it outside the loop and then call dict.update something like this: dictionary = {} for j in range(0,len(response.data)): dictionary.update(response.data[j]) That solves your problem. But there's no point generating a this new dictionary. You can just iterate once on response.data if you need to customize the response. since response.data is a list of users you can do this instead dictionary = {'messages': []} for user in response.data: dictionary['messages'].append({'text': user['id']}) dictionary['messages'].append({'text': user['username']}) Also since you're using django rest framework and the APIView you don't need json.dumps django framework has a Response class that takes care of that and it also sets the appropriate headers. from rest_framework.response import Response and then change your return statement to: return Response(dictionary)
has comment: http://stackoverflow.com/comment/83653626
has comment: http://stackoverflow.com/comment/83653572
type: Answer
has comment: http://stackoverflow.com/comment/83652803

http://stackoverflow.com/comment/83890181
score: 0
type: AnswerComment
has text: @Alex, good point. I noted this was true in lookup_table provided, but important to note that it is a requirement.
comment on: http://stackoverflow.com/a/48448721
type: Comment

http://stackoverflow.com/q/48382515
has body: I have a python function that prints some stuff. I am gonig to put that to AWS Lambda and would like to print these stuff directly to a file in S3 bucket. So something to redirect stdout in S3 bucket file. This is how I call the fuction: recurse_for_values(top_vault_prefix, top_level_keys)
downvote count: 1
has comment: http://stackoverflow.com/comment/83752687
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83754490
tagged with: python
has title: python to write directly to S3 bucket
tagged with: boto3
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/48418300
score: 0
tagged with: amazon-s3
upvote count: 1
has comment: http://stackoverflow.com/comment/83752782
has answer: http://stackoverflow.com/a/48383094

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

http://stackoverflow.com/comment/83897570
score: 0
type: Comment
has text: Which part is actually slow? Is it the page loading or your code scraping it?
type: QuestionComment
comment on: http://stackoverflow.com/q/48452155

django
tags question: http://stackoverflow.com/q/48435534
tags question: http://stackoverflow.com/q/48424866
tags question: http://stackoverflow.com/q/48362679
tags question: http://stackoverflow.com/q/48461074
tags question: http://stackoverflow.com/q/48342826
tags question: http://stackoverflow.com/q/48379434
tags question: http://stackoverflow.com/q/48460087
tags question: http://stackoverflow.com/q/48463566
tags question: http://stackoverflow.com/q/48414202
tags question: http://stackoverflow.com/q/48369467
tags question: http://stackoverflow.com/q/48363942
tags question: http://stackoverflow.com/q/48364586
tags question: http://stackoverflow.com/q/48472546
tags question: http://stackoverflow.com/q/48439532
tags question: http://stackoverflow.com/q/48432241
tags question: http://stackoverflow.com/q/48442002
tags question: http://stackoverflow.com/q/48407790
tags question: http://stackoverflow.com/q/48365904
tags question: http://stackoverflow.com/q/48397608
tags question: http://stackoverflow.com/q/48415467
tags question: http://stackoverflow.com/q/48465870
tags question: http://stackoverflow.com/q/48485522
tags question: http://stackoverflow.com/q/48361131
tags question: http://stackoverflow.com/q/48405270
tags question: http://stackoverflow.com/q/48348210
tags question: http://stackoverflow.com/q/48483514
tags question: http://stackoverflow.com/q/48486325
tags question: http://stackoverflow.com/q/48367591
tags question: http://stackoverflow.com/q/48429234
tags question: http://stackoverflow.com/q/48476529
tags question: http://stackoverflow.com/q/48428023
tags question: http://stackoverflow.com/q/48405674
tags question: http://stackoverflow.com/q/48345011
tags question: http://stackoverflow.com/q/48433882
tags question: http://stackoverflow.com/q/48352586
tags question: http://stackoverflow.com/q/48461168
tags question: http://stackoverflow.com/q/48375006
tags question: http://stackoverflow.com/q/48344744
tags question: http://stackoverflow.com/q/48416351
tags question: http://stackoverflow.com/q/48349025
tags question: http://stackoverflow.com/q/48374927
tags question: http://stackoverflow.com/q/48453248
tags question: http://stackoverflow.com/q/48431498
tags question: http://stackoverflow.com/q/48454755
tags question: http://stackoverflow.com/q/48408230
tags question: http://stackoverflow.com/q/48438765
tags question: http://stackoverflow.com/q/48367192
tags question: http://stackoverflow.com/q/48431331
tags question: http://stackoverflow.com/q/48475071
tags question: http://stackoverflow.com/q/48405330
tags question: http://stackoverflow.com/q/48415210
tags question: http://stackoverflow.com/q/48414352
tags question: http://stackoverflow.com/q/48402868
tags question: http://stackoverflow.com/q/48351756
tags question: http://stackoverflow.com/q/48412871
tags question: http://stackoverflow.com/q/48464803
tags question: http://stackoverflow.com/q/48364817
tags question: http://stackoverflow.com/q/48419372
tags question: http://stackoverflow.com/q/48397761
tags question: http://stackoverflow.com/q/48482420
tags question: http://stackoverflow.com/q/48422473
tags question: http://stackoverflow.com/q/48483889
tags question: http://stackoverflow.com/q/48337324
tags question: http://stackoverflow.com/q/48465788
tags question: http://stackoverflow.com/q/48422533
tags question: http://stackoverflow.com/q/48350196
tags question: http://stackoverflow.com/q/48433519
tags question: http://stackoverflow.com/q/48403728
tags question: http://stackoverflow.com/q/48396103
tags question: http://stackoverflow.com/q/48462571
tags question: http://stackoverflow.com/q/48474503
tags question: http://stackoverflow.com/q/48334951
tags question: http://stackoverflow.com/q/48483627
tags question: http://stackoverflow.com/q/48444800
tags question: http://stackoverflow.com/q/48476900
tags question: http://stackoverflow.com/q/48333517
tags question: http://stackoverflow.com/q/48468069
tags question: http://stackoverflow.com/q/48421692
tags question: http://stackoverflow.com/q/48482355
tags question: http://stackoverflow.com/q/48482899

http://stackoverflow.com/q/48364447
tagged with: python
possible better answer: http://stackoverflow.com/a/48364689
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48364502
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53268516
has answer: http://stackoverflow.com/a/48364689
answer count: 3
tagged with: matrix
upvote count: 3
has body: I need to generate a tall-and-thin random column-orthonormal matrix in SciPy; that is, the number of rows n is far greater than the number of columns of p by many orders of magnitude (say n = 1e5 and p = 100. I know that scipy.stats.ortho_group generates a square orthogonal matrix. However, in my case it's simply infeasible to generate an n-by-n random orthogonal matrix and then keep the first p columns... Is there a more time- and space- efficient approach?
downvote count: 0
has comment: http://stackoverflow.com/comment/83715701
tagged with: orthogonal
has comment: http://stackoverflow.com/comment/83727900
tagged with: scipy
favorite count: 0
type: Question
score: 3
has title: Generating a tall-and-thin random orthonormal matrix in SciPy
has answer: http://stackoverflow.com/a/48364502

iteration
tags question: http://stackoverflow.com/q/48426505
tags question: http://stackoverflow.com/q/48469454
type: Tag
tags question: http://stackoverflow.com/q/48392386
tags question: http://stackoverflow.com/q/48356122
tags question: http://stackoverflow.com/q/48486784
tags question: http://stackoverflow.com/q/48484525
tags question: http://stackoverflow.com/q/48429361
tags question: http://stackoverflow.com/q/48405312
tags question: http://stackoverflow.com/q/48432557
tag name: iteration

http://stackoverflow.com/q/48374603
score: -2
downvote count: 2
has body: I want to obtain the top 3 cities and items based on their sales, but the only thing I can do now is return the all cities and items with their respective sales. Without using dict, can I obtain my desired output? Or if I use dict, how do I obtain the desired output? purchases.txt 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex 2012-01-01 09:00 Fort Worth Women's Clothing 153.57 Visa 2012-01-01 09:00 San Diego Music 66.08 Cash 2012-01-01 09:00 Pittsburgh Pet Supplies 493.51 Discover 2012-01-01 09:00 Omaha Children's Clothing 235.63 MasterCard 2012-01-01 09:00 Stockton Men's Clothing 247.18 MasterCard 2012-01-01 09:00 Austin Cameras 379.6 Visa 2012-01-01 09:00 New York Consumer Electronics 296.8 Cash 2012-01-01 09:00 Corpus Christi Toys 25.38 Discover 2012-01-01 09:00 Fort Worth Toys 213.88 Visa test.py f = open ("purchases.txt") def separator(): str = ("="*48) print (str) return; city_seen = set() item_seen = set() citysaleslist = [] itemsaleslist= [] for line in open(sys.argv[1]): sales=float(line.split()[-2]) strsales=line.split()[-2] city=line.split('\t')[2] item=line.split('\t')[3] if city not in city_seen: # if city is not a duplicate, add to city_seen set city_seen.add(city) #Pressing tab for the bottom 2 lines will remove duplicate but combining the sales for the duplicates is impossible here. citysales="{0:&lt;29}{1:&gt;18}".format(city,strsales) citysaleslist.append(citysales) if item not in item_seen: # if item is not a duplicate, add to item_seen set item_seen.add(item) #Pressing tab for the bottom 2 lines will remove duplicate but combining the sales for the duplicates is impossible here. itemsales = "{0:&lt;29}{1:&gt;18}".format(item,strsales) itemsaleslist.append(itemsales) print("Top Three Cities \n") separator() for i in citysaleslist: print(i) separator() print("Bottom Three Cities \n") separator() separator() print("Top Three Item Categories") separator() for i in itemsaleslist: print(i) separator() print("\nBottom Three Item Categories") sepa…
has comment: http://stackoverflow.com/comment/83736394
has comment: http://stackoverflow.com/comment/83736449
linked to: http://stackoverflow.com/q/3730019
has title: Obtaining values from columns in python
type: Question
has answer: http://stackoverflow.com/a/48374788
has comment: http://stackoverflow.com/comment/83736511
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48378674
answer count: 2
has comment: http://stackoverflow.com/comment/83736533
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48415814
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48415782
has comment: http://stackoverflow.com/comment/83821350
has comment: http://stackoverflow.com/comment/83821325
type: Answer
has body: You can't change a tuple as you are in the following two lines: merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) # here merged_meetings.append((current_meeting_start, current_meeting_end)) # and here Tuples are immutatable. Not only are you using a tuple, you are unpacking more values than you should be.
downvote count: 0

http://stackoverflow.com/a/48359808
has comment: http://stackoverflow.com/comment/83706390
downvote count: 0
has comment: http://stackoverflow.com/comment/121027841
has comment: http://stackoverflow.com/comment/121012701
has body: Nice catch! It would seem that the issue linked in the comment above by Dennis Soemers, Keras Dropout layer changes results with dropout=0.0, has not been fully resolved, and it somehow blunders when faced with a dropout rate of 1.0 [see UPDATE at the end of post]; modifying the model shown in the Keras MNIST MLP example: model = Sequential() model.add(Dense(512, activation='relu', use_bias=False, input_shape=(784,))) model.add(Dropout(1.0)) model.add(Dense(512, activation='relu')) model.add(Dropout(1.0)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) model.fit(x_train, y_train, batch_size=128, epochs=3, verbose=1, validation_data=(x_test, y_test)) gives indeed a model being trained, despite all neurons being dropped, as you report: Train on 60000 samples, validate on 10000 samples Epoch 1/3 60000/60000 [==============================] - 15s 251us/step - loss: 0.2180 - acc: 0.9324 - val_loss: 0.1072 - val_acc: 0.9654 Epoch 2/3 60000/60000 [==============================] - 15s 246us/step - loss: 0.0831 - acc: 0.9743 - val_loss: 0.0719 - val_acc: 0.9788 Epoch 3/3 60000/60000 [==============================] - 15s 245us/step - loss: 0.0526 - acc: 0.9837 - val_loss: 0.0997 - val_acc: 0.9723 Nevertheless, if you try a dropout rate of 0.99, i.e. replacing the two dropout layers in the above model with model.add(Dropout(0.99)) then indeed you have effectively no training taking place, as it should be the case: Train on 60000 samples, validate on 10000 samples Epoch 1/3 60000/60000 [==============================] - 16s 265us/step - loss: 3.4344 - acc: 0.1064 - val_loss: 2.3008 - val_acc: 0.1136 Epoch 2/3 60000/60000 [==============================] - 16s 261us/step - loss: 2.3342 - acc: 0.1112 - val_loss: 2.3010 - val_acc: 0.1135 Epoch 3/3 60000/60000 [==============================] - 16s 266us/step - loss: 2.3167 - acc: 0.1122 - val_loss: 2.3010 - val_acc: 0.1135 UPDATE (after…
has comment: http://stackoverflow.com/comment/83706341
accepted answer of: http://stackoverflow.com/q/48355700
has comment: http://stackoverflow.com/comment/83706431
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48355700
score: 5
type: AcceptedAnswer

http://stackoverflow.com/a/48457030
accepted answer of: http://stackoverflow.com/q/48445776
type: Answer
answers question: http://stackoverflow.com/q/48445776
has body: Assuming, the elements in CO2_t correspond to the elements in timers, then you just enumerate your timers list and where there is an element in date, you append the element at the enumerated index of CO2_t to CO2_tt. CO2_tt = [] for i, j in enumerate(timers): if j in date: CO2_tt.append(CO2_t[i])
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/48423769
downvote count: 2
answer count: 1
tagged with: neural-network
has title: How to use a trained neural network model?
has body: I can not understand how to use the already trained neural network model. I program on python, I use library keras. I analyze the time series. The neural network is trained, the model is saved. As described in the keras documentation, you need to call the model_name.predict () method. Good. I do this: model.predict (dataset), where dataset are the values ​​for the last 90 days. And I need to get a prediction forward for, say, 10 days. But the forecast is made only for the specified data set for 90 days! That is, you can only compare the original data and forecast. So how do make a forecast for 10 days in advance from today?
tagged with: keras
favorite count: 0
type: Question
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48453724
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48345920
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83850827
tagged with: localization
downvote count: 0
has title: Pepper Cartography and Navigation using SoftBank libraries
tagged with: python
favorite count: 0
score: 3
has comment: http://stackoverflow.com/comment/83747145
has answer: http://stackoverflow.com/a/48378692
tagged with: pepper
has body: I am currently working on a Pepper Robot. The project aims to welcome visitors in a laboratory and to guide them to the office/teacher he wants to see. To do that, i need to make Pepper create her map of the environment and to localize herself. I have encountered two problems: the quality of the map, the navigation with this map. A good navigation implies a good map, but even though when there is only free space around, Pepper is not able to navigate on it. I use the SoftBank's : qi library (http://doc.aldebaran.com/2-4/dev/python/install_guide.html), functions (http://doc.aldebaran.com/2-5/naoqi/motion/alnavigation-api.html) Below are the maps I have (note that the floor reflects light) : Black is free space - White is obstacle when the lights are turned on, Environment with lights On when the lights are turned off Environment with lights Off To better the map i went in a room with no reflexion on the floor (carpet floor) and here are the map i had Carpet Floor Carpet Floor Lights On (the environment changed but it is quiet recognizable with some imagination) For now I couldn't test the navigation on a carpet floor but on the first two maps, Pepper movements are completely incorrect. Moreover, the localization gives me ellipse errors 2 meters wide and 3 meters long on an exploration of 5 meters. So my questions are : am I doing something incorrect? how could i solve my problems? it is my first experience with navigation, am I expecting too much of it? or are the softbank's functions not efficient? My code to explore : PepperSpeech = session.service("ALTextToSpeech") PepperSpeech.say("Connexion") PepperNavig = session.service("ALNavigation") PepperMvt = session.service("ALMotion") PepperMvt.wakeUp() PepperSpeech.say("Lancement de l'exploration") state = PepperNavig.explore(5.0) print(state) PepperSpeech.say("Exploration terminee") time.sleep(2) PepperNavig.stopExploration() path = PepperNavig.saveExploration() print(path) time.sleep(2) PepperSpeech.say("sauvegarde t…
has comment: http://stackoverflow.com/comment/83751312
has answer: http://stackoverflow.com/a/48380400
tagged with: navigation
type: Question
answer count: 2
upvote count: 3

http://stackoverflow.com/comment/83789766
has text: @ThomasKühn: Thanks for the suggestion. Just tried to do: `python parent_script_v01.py --display ssd1351 --width 128 --height 128 --interface spi --gpio-data-command 20` on terminal but got the same error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48400740
score: 0

if-statement
tags question: http://stackoverflow.com/q/48390005
tag name: if-statement
type: Tag
tags question: http://stackoverflow.com/q/48408062
tags question: http://stackoverflow.com/q/48384720
tags question: http://stackoverflow.com/q/48413215
tags question: http://stackoverflow.com/q/48357213
tags question: http://stackoverflow.com/q/48462928
tags question: http://stackoverflow.com/q/48423865
tags question: http://stackoverflow.com/q/48336692
tags question: http://stackoverflow.com/q/48465536
tags question: http://stackoverflow.com/q/48473706
tags question: http://stackoverflow.com/q/48364407
tags question: http://stackoverflow.com/q/48372888
tags question: http://stackoverflow.com/q/48410563
tags question: http://stackoverflow.com/q/48431481
tags question: http://stackoverflow.com/q/48397061
tags question: http://stackoverflow.com/q/48464958
tags question: http://stackoverflow.com/q/48475118
tags question: http://stackoverflow.com/q/48347002
tags question: http://stackoverflow.com/q/48453769
tags question: http://stackoverflow.com/q/48357372
tags question: http://stackoverflow.com/q/48473778
tags question: http://stackoverflow.com/q/48445012
tags question: http://stackoverflow.com/q/48482801

http://stackoverflow.com/comment/83863102
type: Comment
comment on: http://stackoverflow.com/a/48435869
type: AnswerComment
has text: for some reason it is still outputting as follows `[79, 321, 240, 223, 190, 164, 134, 62, 54, None]` 240,223,190 is not in the triangle, so there is still some concatenation going on
score: 0

http://stackoverflow.com/a/48337072
has comment: http://stackoverflow.com/comment/83660399
upvote count: 1
has comment: http://stackoverflow.com/comment/83659395
downvote count: 0
answers question: http://stackoverflow.com/q/48336658
has comment: http://stackoverflow.com/comment/83659995
has body: The proper way to achieve this is to provide LOGIN_URL and LOGIN_URL_REDIRECT in settings.py file of your project. And then provide some logic in confirmation, something like: def confirmation(request): if request.method == 'POST': form = ConfirmationForm(request.POST, instance=request.user) if form.is_valid(): user.first_login = False user.save() return redirect('some_page') else: if not user.first_login: login(request, request.user) return redirect('some_page') form = ConfirmationForm(instance=request.user) context = { 'form': form, } return render(request, 'confirmation.html', context)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83659700
has comment: http://stackoverflow.com/comment/83660443

http://stackoverflow.com/a/48425592
answers question: http://stackoverflow.com/q/48425473
type: Answer
score: 0
has body: You can do it and are on the right track; you just need to format the filename string properly ("%s.txt" % i, "w+" or use str.format).

http://stackoverflow.com/q/48335039
score: 0
answer count: 0
has body: Let me allow to describe my problem: I have created socket server in python and client in java, from java I am sending multiple objects to server by using : ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream append = new ByteArrayOutputStream(); ObjectOutput out = null; byte finalarr[]=null; try { out = new ObjectOutputStream(bos); out.writeObject(object); out.flush(); byte[] objByte = bos.toByteArray(); bos.close(); out.close(); append.write(objByte.length); append.write(objByte); bos = new ByteArrayOutputStream(); out = new ObjectOutputStream(bos); out.writeObject(value); out.flush(); append.write(bos.toByteArray()); finalarr = append.toByteArray( ); os = sChannel.socket().getOutputStream(); oos = new ObjectOutputStream(os); oos.write(finalarr); } finally { try { bos.close(); } catch (IOException ex) { } } Now, finalarr contains byte length of object then actual byte[] of object and then byte[] of value. Now in python after receiving this First I want to read length of byte which is written in first position of finalarr then whatever length I get I want to read received array upto that length so that I will get object separately then the remaining part separately. In python I have done upto this: total_data=b'' while True: data = self.clientsocket.recv(1024) if not data: break total_data += data In total_data I am getting entire bytearray, but I don't know how I can read it so that I can get two objects separately as explained.
has comment: http://stackoverflow.com/comment/83691927
tagged with: java
has comment: http://stackoverflow.com/comment/83655190
type: Question
has comment: http://stackoverflow.com/comment/83697509
type: UnansweredQuestion
tagged with: python
has title: reading bytearray upto specified location

http://stackoverflow.com/a/48440601
has comment: http://stackoverflow.com/comment/83873279
accepted answer of: http://stackoverflow.com/q/48440081
type: Answer
answers question: http://stackoverflow.com/q/48440081
has comment: http://stackoverflow.com/comment/83874489
has body: I'm mostly replying to the title of your question since the question itself is formulated pretty confusingly. From the title: I think what you want is to find all dicts in a list of dicts which have the same id, and get a list of them? Assuming I am right and that is your question, this should help: &gt;&gt;&gt; dictlist [{'id': 1, 'value': 'foo'}, {'id': 2, 'value': 'foo'}, {'id': 1, 'value': 'bar'}] &gt;&gt;&gt; filtered_list = [d for d in dictlist if d['id']==1] &gt;&gt;&gt; filtered_list [{'id': 1, 'value': 'foo'}, {'id': 1, 'value': 'bar'}]
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48422288
has comment: http://stackoverflow.com/comment/83843024
has body: If you make use of Python's CSV library, you can easily test to ensure a given row has values in it, that way it does not matter if there are empty lines are not, they will be skipped over when writing the master files: import csv import glob def merge_csvs(target_filename, csv_list): with open(target_filename, 'w', newline='') as f_master_target: csv_master_target = csv.writer(f_master_target) write_header = True for csv_filename in csv_list: with open(csv_filename, 'r', newline='') as f_single: csv_single = csv.reader(f_single) header = next(csv_single) if write_header: csv_master_target.writerow(header) write_header = False for row in csv_single: if row: csv_master_target.writerow(row) path = 'directory' Enviro_Files = glob.glob(path + "**/*enviro.csv") Total_Files = glob.glob(path + "**/*TOTAL.csv") merge_csvs('Master_enviro.csv', Enviro_Files) merge_csvs('Master_TOTAL.csv', Total_Files)
has comment: http://stackoverflow.com/comment/83842518
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48408948
accepted answer of: http://stackoverflow.com/q/48408948
has comment: http://stackoverflow.com/comment/83845974
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48349325
has answer: http://stackoverflow.com/a/50714078
downvote count: 0
has comment: http://stackoverflow.com/comment/117863570
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83685749
has title: Download full anaconda distribution in a new environment
tagged with: python
has body: I am using the Anaconda python 2.x distribution. I wanted to have python 3 installed, keeping python 2. I used the conda environment feature: conda create --name py3 python=3 That worked great, and I am able to switch between the two seamlessly. The problem is that on my python3 install I don't have all the packages that the anaconda distribution comes with (such as numpy, pandas, the continuum analytics ones..) Is there an easy way to get them all from the command line?
score: 2
has answer: http://stackoverflow.com/a/75545688
has comment: http://stackoverflow.com/comment/83685026
answer count: 2
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83685039

http://stackoverflow.com/q/48401148
has answer: http://stackoverflow.com/a/48793049
tagged with: machine-learning
tagged with: scikit-learn
tagged with: document-classification
favorite count: 0
tagged with: logistic-regression
type: Question
has title: Document Classification with scikit-learn: most efficient way to get the words (token) that impacted more on the classification
upvote count: 2
has answer: http://stackoverflow.com/a/48416893
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83844688
has body: I have built a document binomial classifier using a tf-idf representation of a training set of documents and applying Logistic Regression to it: lr_tfidf = Pipeline([('vect', tfidf),('clf', LogisticRegression(random_state=0))]) lr_tfidf.fit(X_train, y_train) I have saved the model in pickle format and used it to classify new documents, getting as a result the probability the document is in class A and the probability the model is in class B. text_model = pickle.load(open('text_model.pkl', 'rb')) results = text_model.predict_proba(new_document) Which is the best way to also get the words (or, in general, the tokens) that impacted more in the classification? I would expect to get: The N tokens contained in the document which had the higher coefficient as a feature in the Logistic Regression model The N tokens contained in the document which had the lower coefficient as a feature in the Logistic Regression model I am using sklearn v 0.19
tagged with: python
has comment: http://stackoverflow.com/comment/83838590
has comment: http://stackoverflow.com/comment/83845817
score: 2
answer count: 3
has comment: http://stackoverflow.com/comment/83790949
has answer: http://stackoverflow.com/a/48956310
downvote count: 0

http://stackoverflow.com/comment/83897792
type: Comment
type: QuestionComment
has text: @PaulPanzer Thank you so much!! That is exactly what I was looking for.
comment on: http://stackoverflow.com/q/48450781
score: 1

http://stackoverflow.com/q/48379846
type: Question
tagged with: python-3.x
has body: Navigate to the directory that contains the .whl file and type: pip install Twisted-17.9.0-cp27-cp27m-win32.whl and I got: Twisted-17.9.0-cp27-cp27m-win32.whl is not a supported wheel on this platform. I also tried 64 bit version had the same error message: pip install Twisted-17.9.0-cp27-cp27m-win_amd64.whl I have checked: pip install wheel Requirement already satisfied: wheel in c:\users\yang\appdata\local\programs\python\python36\lib\site-packages My OS: Windows 7, 64 bit
type: UnansweredQuestion
tagged with: python-wheel
tagged with: python
has answer: http://stackoverflow.com/a/48381055
tagged with: twisted
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has title: Twisted is not a supported wheel on this platform
favorite count: 0

http://stackoverflow.com/comment/83752094
type: Comment
type: QuestionComment
score: 0
has text: The udf must have a type unfortunately and by default, if you do not specify it, it will be "StringType" [src](http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.UDFRegistration)
comment on: http://stackoverflow.com/q/48382546

http://stackoverflow.com/comment/83950410
type: Comment
has text: Why call `dict(d)` anew every time?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48478606

http://stackoverflow.com/q/48332599
favorite count: 0
has title: Access a list index after introducing words using input
type: Question
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/252703
has comment: http://stackoverflow.com/comment/83651192
has body: I want to know why I cant access a list index. I have a list full of words(input) but then t try to acces for example: list[2] and I get an error. words=[] n =input().split() words.append(n) print (words]) Intput: Hi internet what up Output: 'hello', 'internet', 'what', 'up' print(words[0]) Output:['hello', 'internet', 'what', 'up'] print(words[1]) Output: IndexError: list index out of range
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/48332611
duplicate of: http://stackoverflow.com/q/252703
type: UnansweredQuestion
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/83650955
upvote count: 1
tagged with: string
downvote count: 1

http://stackoverflow.com/comment/83937936
has text: @anna where did you see that pythonnet cannot be used for embedding python in .net? here is tutorial: https://github.com/pythonnet/pythonnet/blob/master/README.md
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48463842

http://stackoverflow.com/q/48404484
type: AnsweredQuestion
tagged with: list
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/83797493
has answer: http://stackoverflow.com/a/48404761
has answer: http://stackoverflow.com/a/48404684
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83797450
has comment: http://stackoverflow.com/comment/83798045
has answer: http://stackoverflow.com/a/48404639
possible better answer: http://stackoverflow.com/a/48404639
has comment: http://stackoverflow.com/comment/83797507
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48404712
accepted answer: http://stackoverflow.com/a/48404712
tagged with: dictionary
has body: data = ['ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:a@b.c ST:VIC', ' ID:b22 EM:b@d.c ST:VIC GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215', ' ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:d@b.c'] I was wondering how to count how many IDs that contain digits only. Do I need to convert this list to a dictionary to do so or is there a simpler way? thanks
answer count: 4
has title: How to count the number of values that has digits only in a list python?

http://stackoverflow.com/q/48413264
upvote count: 8
has answer: http://stackoverflow.com/a/48413382
type: UnansweredQuestion
tagged with: k-means
tagged with: cluster-analysis
score: 6
tagged with: python
tagged with: centroid
has title: M nearest points to centroid in K-Means clustering
answer count: 2
downvote count: 2
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/77948584
type: Question
has body: I have implemented a function to find the nearest data point to each centroid calculated after running the K-Means clustering algorithm. I wanted to know if there's a sklearn function that allows me to find the M nearest points to each of the centroids.

http://stackoverflow.com/comment/83688674
type: Comment
type: QuestionComment
has text: What are you trying to achieve here? You may want to read up a bit more on OOP because this construction you have doesn't make sense: https://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep
score: 1
comment on: http://stackoverflow.com/q/48350971

http://stackoverflow.com/a/48407736
type: AcceptedAnswer
has body: In the SQL grammer, DISTINCT does not belong to any values (expressions), but to the SELECT or the aggregate function (here: COUNT). So you have to write it directly after the SELECT or the opening parenthesis: SELECT ..., COUNT(DISTINCT CASE ... END) ...
answers question: http://stackoverflow.com/q/48406018
type: Answer
accepted answer of: http://stackoverflow.com/q/48406018
score: 0

http://stackoverflow.com/a/48462788
has comment: http://stackoverflow.com/comment/84006792
has comment: http://stackoverflow.com/comment/84007217
answers question: http://stackoverflow.com/q/48462326
has comment: http://stackoverflow.com/comment/84007019
has comment: http://stackoverflow.com/comment/83921642
has comment: http://stackoverflow.com/comment/83921775
has body: Here is an example with dataframe definition, you can do the same by replacing Null with np.NaN: import pandas as pd import numpy as np df = pd.DataFrame({'A': [10, None, None, None, 29], 'B': [15, 20, 10, None, 35], 'C': [20, 11, None, None, 40]}, index = range(1,6)) vars = df.columns.tolist() df.reset_index(inplace=True) df = df.melt(id_vars=['index'], value_vars=vars, var_name='ColumnName') df = df[df['value'].isnull()].groupby(['ColumnName'], as_index=False)['index'].agg({'StartIndex': 'first', 'EndIndex': 'last'}).assign(Comment=lambda x: np.NaN) df # ColumnName EndIndex StartIndex Comment #0 A 4 2 NaN #1 B 4 4 NaN #2 C 4 3 NaN
type: Answer
score: 0

http://stackoverflow.com/q/48360729
has title: Concurrency in processing multiple files
has answer: http://stackoverflow.com/a/48361531
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83708440
tagged with: python
has body: I have two files. File A contains 1 million records. File B contains approximately 2,000 strings, each on a separate line. I have a Python script that takes each string in File B in turn and searches for a match in File A. The Logic is as follows: For string in File B: For record in File A: if record contains string: # I use regex for this write record to a separate file This is currently running as a single thread of execution and takes a few hours to complete. I’d like to implement concurrency to speed up this script. What is the best way to approach it? I have looked into multi-threading but my scenario doesn’t seem to represent the producer-consumer problem as my machine has an SSD and I/O is not an issue. Would multiprocessing help with this?
linked to: http://stackoverflow.com/q/481970
score: 0
answer count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/83711531
has answer: http://stackoverflow.com/a/48360840
type: Question

http://stackoverflow.com/comment/85983230
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48470466
type: QuestionComment
has text: What is your task timeout?

http://stackoverflow.com/comment/83865239
has text: Could it be because it doesn't have access to the arguments?
type: Comment
comment on: http://stackoverflow.com/a/48436832
type: AnswerComment
score: 0

http://stackoverflow.com/a/74452716
has comment: http://stackoverflow.com/comment/135727330
has body: With Result.scalars() you can create a ScalarResult to receive single objects instead of Rows. With the Core-style querying syntax your example could look like this: &gt;&gt;&gt; from sqlalchemy import select &gt;&gt;&gt; from sqlalchemy.orm import sessionmaker &gt;&gt;&gt; session = sessionmaker(...) &gt;&gt;&gt; result = session.execute(select(MyModel.id)) &gt;&gt;&gt; result.scalars().all() [1, 2, 3, ...] Careful: If you select multiple columns .scalars().all() returns the first column only. So select(MyModel.id, MyModel.something) has the same ScalarResult as select(MyModel.id). However, to select all columns using select(MyModel), the ScalarResult is helpful again, as it returns a list of MyModel-objects.
upvote count: 13
answers question: http://stackoverflow.com/q/48466959
type: Answer
has comment: http://stackoverflow.com/comment/137233732
has comment: http://stackoverflow.com/comment/138104151
downvote count: 0
score: 13

http://stackoverflow.com/a/48410791
has body: I think you are just close, you just need to process the results of tds. I would do the following: from bs4 import BeautifulSoup b = BeautifulSoup(html, 'lxml') html = """ song artist|album """ tds = b.find_all('td') data = tds[0] t = data.text.split('\n') song = t[1] artist_album = t[2].split('|') artist = artist_album[0] album = artist_album[1] print("Song:", song) print("Artist:", artist) print("Album:", album) This should give you: Song: song Artist: artist Album: album
score: 2
accepted answer of: http://stackoverflow.com/q/48410479
type: Answer
answers question: http://stackoverflow.com/q/48410479
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48360030
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83707474
accepted answer: http://stackoverflow.com/a/48360337
has comment: http://stackoverflow.com/comment/83707237
has comment: http://stackoverflow.com/comment/83707600
has body: I recently discovered that the round function available in future does not support negative digit rounding, which is incompatible with builtin round: &gt;&gt;&gt; from builtins import round &gt;&gt;&gt; round(4781, -2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/future/builtins/newround.py", line 33, in newround raise NotImplementedError('negative ndigits not supported yet') NotImplementedError: negative ndigits not supported yet This somewhat limits the usefulness of the Python-Future quick-start recommendation: The easiest way is to start each new module with these lines: from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * Then write standard Python 3 code. I can't find the round incompatibility documented anywhere, and wonder what other functions or types behave differently or have non-implemented features. What other gotchas are there? Where are these incompatibilities documented?
has answer: http://stackoverflow.com/a/48360337
tagged with: python
has comment: http://stackoverflow.com/comment/83707639
has comment: http://stackoverflow.com/comment/83707231
has comment: http://stackoverflow.com/comment/83707691
tagged with: incompatibility
has comment: http://stackoverflow.com/comment/83707053
type: Question
upvote count: 3
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83707623
has title: Where can I find documentation of Python-Future imports that are incompletely implemented?
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48356398
linked to: http://stackoverflow.com/q/61216402
type: Question
has answer: http://stackoverflow.com/a/48356640
linked to: http://stackoverflow.com/q/48384516
has comment: http://stackoverflow.com/comment/83699379
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/42294109
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
score: 3
answer count: 1
tagged with: python
tagged with: image-processing
has body: I am using Opencv and python to detect shapes and then crop them. I have succeeded to do that, however now I am trying to take the cropped images and remove their backgrounds. The image has a circle inside and surrounded by gray color. (It can be gray or can be even more than one color). How can I remove the colors surrounding the circle border (which is black) - we can convert the gray color to black - as the border color or even remove it at all and make that transparent. The result image should contain only the circle.
tagged with: image
accepted answer: http://stackoverflow.com/a/48356640
has title: OpenCV : Remove background of an image

http://stackoverflow.com/q/48374076
has body: I try to extract the "1 min" from the HTML code below using BeautifulSoup 1 min 30 min For this, I write the code below in Python: # import libraries import urllib2 from bs4 import BeautifulSoup # specify the url quote_page = 'http://beta.stm.info/fr/infos/reseaux/bus/reseau-local/ligne-51-est/56184' page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, 'html.parser') # EXTRACT FIELD 1 name_titre = soup.find('div', attrs={'class': 'label not-accessible'}) name_t = name_titre.text.strip() print name_t # EXTRACT FIELD 2 time_passage = soup.find('div', attrs={'class': "date-list--time"}) t_passage = time_passage print t_passage It worked well for other data I wanted to extract (EXTRACT 1), but here I just get "None" as a print output for EXTRACT 2. Could please someone tell me what I am doing wrong? I guess the issue is that the HTML includes a list of items for EXTRACT 2, but not sure... Thanks!
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48374177
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83735632
favorite count: 0
has comment: http://stackoverflow.com/comment/83735419
tagged with: beautifulsoup
type: Question
has title: Expected to extract a string from HTML page with BeautifulSoup, but got "None"
has comment: http://stackoverflow.com/comment/83735495
has comment: http://stackoverflow.com/comment/83735646
has comment: http://stackoverflow.com/comment/83735728
has comment: http://stackoverflow.com/comment/83735698
tagged with: python
has comment: http://stackoverflow.com/comment/83735670
linked to: http://stackoverflow.com/q/17597424
has comment: http://stackoverflow.com/comment/83735573
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83735885
accepted answer: http://stackoverflow.com/a/48374177
has comment: http://stackoverflow.com/comment/83735848

http://stackoverflow.com/comment/87082302
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48376732
has text: Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas)

http://stackoverflow.com/comment/83938145
score: 0
has text: Would you add an edit with the full urls.py file please?
type: Comment
comment on: http://stackoverflow.com/a/48472062
type: AnswerComment

http://stackoverflow.com/q/48390451
has comment: http://stackoverflow.com/comment/83768962
type: Question
has title: Python - Accessing dictionary inside of list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83769493
has comment: http://stackoverflow.com/comment/83769061
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83769410
has comment: http://stackoverflow.com/comment/83768868
answer count: 0
score: 0
tagged with: selenium
has body: Following instructions from more advanced programmers here (see my previous questions if you want background) I stored my information in a dictionary that is INSIDE a list. (sorry for my confusion, I am learning as I go along) The problem is that I want to have access to it now through Pandas, but it does not work. What am I doing wrong and what code do I need to make it work? Thank you from selenium import webdriver import pandas as pd import time from bs4 import BeautifulSoup driver = webdriver.Firefox() driver.implicitly_wait(10) #driver.get("https://coinmunity.co/") url = 'file:///C:/Users/nique/PycharmProjects/untitled/test1.html' driver.get(url) html = driver.page_source.encode('utf-8') #html = driver.page_source.encode('utf-8') soup = BeautifulSoup(html, 'lxml') results = [] row = driver.find_elements_by_xpath('/html/body/app-root/app-home/div/div/table/tbody/tr') for el in row[1:4]: symbol = el.find_element_by_class_name('coin-link') print('I am symbol &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;', symbol.text) followers = el.find_element_by_class_name('stats') print('I am followers &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;', followers.text) results.append({'Symbol': symbol.text, 'TFollowers': followers.text}) df = pd.DataFrame(results) df.head() Everything is being recorded inside the dictionary as it should, but the last two lines of code to show the results on Pandas, do nothing at all! PS/ Could it be because I am coding over PyCharm, or something is wrong with the code?

http://stackoverflow.com/a/48355334
has comment: http://stackoverflow.com/comment/85620042
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/134094244
answers question: http://stackoverflow.com/q/48354933
score: 3
has body: You can make your own implementation of the nursery interface: class ExceptionLoggingNursery: def __init__(self, nursery): self.nursery = nursery @property def cancel_scope(self): return self.nursery.cancel_scope async def _run_and_log_errors(self, async_fn, *args): # This is more cumbersome than it should be # See https://github.com/python-trio/trio/issues/408 def handler(exc): if not isinstance(exc, Exception): return exc logger.error("Unhandled exception!", exc_info=exc) with trio.MultiError.catch(handler): return await async_fn(*args) def start_soon(self, async_fn, *args, **kwargs): self.nursery.start_soon(self._run_and_log_errors, async_fn, *args, **kwargs) async def start(self, async_fn, *args, **kwargs): return await self.nursery.start(self._run_and_log_errors, async_fn, *args, **kwargs) @asynccontextmanager async def open_exception_logging_nursery(): async with trio.open_nursery() as nursery: yield ExceptionLoggingNursery(nursery) Note that we only catch Exception subclasses, and allow other exceptions to continue propagate. This means that if one of your child tasks raises a KeyboardInterrupt (because you hit control-C), or a trio.Cancelled (because you, well, cancelled it... maybe because you hit control-C and the nursery that the parent is living in got cancelled), then those exceptions are allowed to propagate out and still cause all of the other tasks to be cancelled, which is almost certainly what you want. It's a bit of code, but it can easily be put in a reusable library. (If I were doing this for real I might make the exception-handling code an argument passed to open_exception_logging_nursery, instead of hard-coding that call to logger.error.) And I'd love to see a library with this kind of "smart supervisor" in it -- the basic trio nursery was always intended as a building block for such things. You can imagine other even more interesting policies too, like "if a task exits with an unhandled exception, log something and then restart it, with an ex…
has comment: http://stackoverflow.com/comment/85594327
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48354933

http://stackoverflow.com/q/48401060
tagged with: windows
tagged with: mxnet
tagged with: python
has title: mxnet regression divide by zero error
has comment: http://stackoverflow.com/comment/83790056
type: AnsweredQuestion
score: 0
answer count: 1
has body: Try to edit the example of https://mxnet.incubator.apache.org/tutorials/python/linear-regression.html to develop a machine learning solution for solving quadratic equations. I am now getting divide by zero error: INFO:root:Epoch[0] Train-mse=49.961319 INFO:root:Epoch[0] Time cost=0.030 INFO:root:Epoch[0] Validation-mse=58229.367065 INFO:root:Epoch[1] Batch [2] Speed: 2000.14 samples/sec mse=361.597036 INFO:root:Epoch[1] Batch [4] Speed: 2000.14 samples/sec mse=1903.920013 INFO:root:Epoch[1] Batch [6] Speed: 2000.14 samples/sec mse=6117.729675 INFO:root:Epoch[1] Batch [8] Speed: 1999.67 samples/sec mse=4203.171875 INFO:root:Epoch[1] Batch [10] Speed: 2000.14 samples/sec mse=31765.921204 INFO:root:Epoch[1] Batch [12] Speed: 2000.14 samples/sec mse=6946.003112 Traceback (most recent call last): File "C:\Users\ibraheem\.vscode\extensions\ms-python.python-0.9.1\pythonFiles\PythonTools\visualstudio_py_launcher_nodebug.py", line 74, in run _vspu.exec_file(file, globals_obj) File "C:\Users\ibraheem\.vscode\extensions\ms-python.python-0.9.1\pythonFiles\PythonTools\visualstudio_py_util.py", line 119, in exec_file exec_code(code, file, global_variables) File "C:\Users\ibraheem\.vscode\extensions\ms-python.python-0.9.1\pythonFiles\PythonTools\visualstudio_py_util.py", line 95, in exec_code exec(code_obj, global_variables) File "c:\Users\ibraheem\Desktop\OtherProjects\python_AI_ML\Untitled-1.py", line 37, in &lt;module&gt; batch_end_callback = mx.callback.Speedometer(batch_size, 2)) File "C:\Python27amd64\lib\site-packages\mxnet\module\base_module.py", line 506, in fit callback(batch_end_params) File "C:\Python27amd64\lib\site-packages\mxnet\callback.py", line 159, in __call__ speed = self.frequent * self.batch_size / (time.time() - self.tic) ZeroDivisionError: float division by zero Entire source: import mxnet as mx import numpy as np import math import logging logging.getLogger().setLevel(logging.DEBUG) train_size = 50 train_data = np.random.uniform(0.1, 1, [train_size, 3]) fo…
tagged with: python-2.x
type: Question
has answer: http://stackoverflow.com/a/48401555
tagged with: time
accepted answer: http://stackoverflow.com/a/48401555
has comment: http://stackoverflow.com/comment/83790025

http://stackoverflow.com/q/48448611
upvote count: 3
tagged with: winapi
accepted answer: http://stackoverflow.com/a/48453929
has comment: http://stackoverflow.com/comment/83899281
has answer: http://stackoverflow.com/a/48453929
has body: I'm using following code to execute some file system operations (copy/move/rename of files and folders) on windows. This code requires pywin32. from win32com.shell import shell, shellcon from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL, WORD from ctypes import c_void_p, Structure, windll, POINTER, byref src = unicode(os.path.abspath(_src_) + '\0', 'utf-8') dest = unicode(os.path.abspath(_dest_) + '\0', 'utf-8') class SHFILEOPSTRUCTW(Structure): _fields_ = [("hwnd", HWND), ("wFunc", UINT), ("pFrom", LPCWSTR), ("pTo", LPCWSTR), ("fFlags", WORD), ("fAnyOperationsAborted", BOOL), ("hNameMappings", c_void_p), ("lpszProgressTitle", LPCWSTR)] SHFileOperationW = windll.shell32.SHFileOperationW SHFileOperationW.argtypes = [POINTER(SHFILEOPSTRUCTW)] args = SHFILEOPSTRUCTW(wFunc=UINT(op), pFrom=LPCWSTR(src), pTo=LPCWSTR(dest), fFlags=WORD(flags), fAnyOperationsAborted=BOOL()) result = SHFileOperationW(byref(args)) aborted = bool(args.fAnyOperationsAborted) if not aborted and result != 0: # Note: raising a WindowsError with correct error code is quite # difficult due to SHFileOperation historical idiosyncrasies. # Therefore we simply pass a message. raise WindowsError('SHFileOperationW failed: 0x%08x' % result) flags are always: shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_NOCONFIRMMKDIR op is for e.g.: shellcon.FO_COPY The problem I have is that sometimes this function gives me error: ArgumentError: argument 1: &lt;type 'exceptions.TypeError'&gt;: expected LP_SHFILEOPSTRUCTW instance instead of pointer to SHFILEOPSTRUCTW especially when dealing with very long paths (e.g. len(dest)=230) What I'm I doing wrong here? [edit] There is a shell.SHFileOperation but we need to use custom wrapper SHFileOperationW to support unicodes. [edit2] As Barmak Shemirani wrote, in python3 you can just simply use shell.SHFileOperation and it will work with any special unicode chars. If I will find a solution to fix this in python2, I'll share it he…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83897934
tagged with: ctypes
has comment: http://stackoverflow.com/comment/83896882
has comment: http://stackoverflow.com/comment/83891235
answer count: 1
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83890698
has title: expected LP_SHFILEOPSTRUCTW instance instead of pointer to SHFILEOPSTRUCTW (python ctypes)
has comment: http://stackoverflow.com/comment/83891184
has comment: http://stackoverflow.com/comment/83927974
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83925449
has comment: http://stackoverflow.com/comment/83926845
tagged with: win32com

http://stackoverflow.com/q/48374049
has body: setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy extensions = [ Extension("word2vec_inner", ["word2vec_inner.pyx"], include_dirs=[numpy.get_include()]) ] setup( name="word2vec_inner", ext_modules=cythonize(extensions), ) error: Warning: Extension name 'word2vec_inner' does not match fully qualified name 'TWE-1.gensim.models.word2vec_inner' of 'word2vec_inner.pyx' Compiling word2vec_inner.pyx because it changed. [1/1] Cythonizing word2vec_inner.pyx Error compiling Cython file: ------------------------------------------------------------ ... #!/usr/bin/env cython ^ ------------------------------------------------------------ word2vec_inner.pyx:1:0: 'TWE-1.gensim.models.word2vec_inner' is not a valid module name Traceback (most recent call last): File "D:\PyCharm 2017.3\helpers\pydev\pydevd.py", line 1668, in &lt;module&gt; main() File "D:\PyCharm 2017.3\helpers\pydev\pydevd.py", line 1662, in main globals = debugger.run(setup['file'], None, None, is_module) File "D:\PyCharm 2017.3\helpers\pydev\pydevd.py", line 1072, in run pydev_imports.execfile(file, globals, locals) # execute the script File "D:/pycharm/TWE/TWE-1/gensim/models/setup.py", line 11, in &lt;module&gt; ext_modules=cythonize(extensions), File "E:\Python27\lib\site-packages\cython-0.27.3-py2.7- win32.egg\Cython\Build\Dependencies.py", line 1039, in cythonize cythonize_one(*args) File "E:\Python27\lib\site-packages\cython-0.27.3-py2.7- win32.egg\Cython\Build\Dependencies.py", line 1161, in cythonize_one raise CompileError(None, pyx_file) Cython.Compiler.Errors.CompileError: word2vec_inner.pyx I have install the Microsoft Visual C++ Compiler for Python 2.7 and cython, but it can't compile. It always appears this problem. how to solve this problem? Thank you very much!
answer count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48374128
score: 0
accepted answer: http://stackoverflow.com/a/48374128
tagged with: cythonize
tagged with: cython
linked to: http://stackoverflow.com/q/42102656
type: Question
has title: Error compiling Cython file:word2vec_inner.pyx:1:0: 'TWE-1.gensim.models.word2vec_inner' is not a valid modu le name

http://stackoverflow.com/q/48464062
has comment: http://stackoverflow.com/comment/83921442
accepted answer: http://stackoverflow.com/a/48464437
has comment: http://stackoverflow.com/comment/83921647
has answer: http://stackoverflow.com/a/48464395
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83921496
has answer: http://stackoverflow.com/a/48464437
has title: Regex to find if a string contains all numbers 0-9 be it in any order
has comment: http://stackoverflow.com/comment/83921308
has answer: http://stackoverflow.com/a/48464186
has comment: http://stackoverflow.com/comment/83921246
duplicate of: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/83921309
score: -3
tagged with: python
possible better answer: http://stackoverflow.com/a/48464395
tagged with: regex
linked to: http://stackoverflow.com/q/15111420
answer count: 4
downvote count: 6
has comment: http://stackoverflow.com/comment/83922146
has comment: http://stackoverflow.com/comment/83921301
linked to: http://stackoverflow.com/q/4289331
has comment: http://stackoverflow.com/comment/83923450
type: AnsweredQuestion
has body: Regex to find if a string contains all numbers 0-9 be it in any order. Can anyone help? Suppose I have a string- "01230912747238507156" This has all characters from 0-9. So I should get True.
has comment: http://stackoverflow.com/comment/83921331
upvote count: 3
has answer: http://stackoverflow.com/a/48464239
has comment: http://stackoverflow.com/comment/83921465
has comment: http://stackoverflow.com/comment/83921411
linked to: http://stackoverflow.com/q/22937618

http://stackoverflow.com/comment/83890481
type: Comment
comment on: http://stackoverflow.com/q/48448473
type: QuestionComment
has text: Your code failed because schema doesn't match the data. As per question linked above.
score: 1

http://stackoverflow.com/q/48483560
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83971871
has comment: http://stackoverflow.com/comment/83972034
tagged with: pandas
has answer: http://stackoverflow.com/a/48483598
possible better answer: http://stackoverflow.com/a/48483598
tagged with: python
accepted answer: http://stackoverflow.com/a/48483639
has title: Using isin() to determine what should be printed
has body: Right now I have two dataframes (data1 and data2) I would like to print a column of string values in the dataframe called data1, based on whether the ID exists in both data2 and data1. What I am doing now gives me a boolean list (True or False if the ID exists in the both dataframes but not the column of strings). print(data2['id'].isin(data1.id).to_string()) yields 0 True 1 True 2 True 3 True 4 True 5 True Any ideas would be appreciated. Here is a sample of data1 'user_id', 'id', 'rating', 'unix_timestamp' 196 242 3 881250949 186 302 3 891717742 22 377 1 878887116 And data2 contains something like this 'id', 'title', 'release_date', 'video_release_date', 'imdb_url' 37|Nadja (1994)|01-Jan-1994||http://us.imdb.com/M/title-exact?Nadja%20(1994)|0|0|0|0|0|0|0|0|1|0|0|0|0|0|0|0|0|0|0 38|Net, The (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Net,%20The%20(1995)|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|1|0|0 39|Strange Days (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Strange%20Days%20(1995)|0|1|0|0|0|0|1|0|0|0|0|0|0|0|0|1|0|0|0
tagged with: numpy
has comment: http://stackoverflow.com/comment/83959951
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48483639
favorite count: 0
has comment: http://stackoverflow.com/comment/83972295
type: Question
has comment: http://stackoverflow.com/comment/83972082

http://stackoverflow.com/q/48450016
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83893636
answer count: 1
has title: PHP how to use data posted from Python script?
type: Question
has body: I have a python script that does pa POST request to my php page (json format). After posting I see from the response that the data is sent at PHP through print(r.text) in python script. The problem is that I can't use the data from PHP side - I cannot print it or write to files etc. What could I be doing wrong here? Part of python script: data_json = { "measurementTime" : first_line.split(',')[0], "windSpeed" : first_line.split(',')[1], "windGust" : first_line.split(',')[2], "windSpeedCount" : first_line.split(',')[3], "rain" : first_line.split(',')[12], "windDirection" : first_line.split(',')[13], "inputVoltage" : first_line.split(',')[14], "solarRadiation" : first_line.split(',')[15], "temperature" : first_line.split(',')[16], "windSpeed" : first_line.split(',')[18], "humidity" : first_line.split(',')[19], "barPressure" : first_line.split(',')[20] } url = 'http://localhost/index.php' r = requests.post(url, data=json.dumps(data_json)) print(r.text) # here I can see that data has been sent print(r.status_code) PHP (index.php): &lt;?php $json = file_get_contents('php://input'); print_r($json); ?&gt; Python script output: ... &lt;body&gt; {"measurementTime": "2018-01-25 17:52:25", "windSpeed": "9.0", "windGust": "0.0", "windSpeedCount": "0", "rain": "1.50", "windDirection": "0", "inputVoltage": "13.51", "solarRadiation": "", "temperature": "0.00", "humidity": "87.5", "barPressure": "1004.473"} &lt;/body&gt; &lt;/html&gt;
has comment: http://stackoverflow.com/comment/83893682
has comment: http://stackoverflow.com/comment/83893286
tagged with: python
has answer: http://stackoverflow.com/a/48451572
tagged with: php
has comment: http://stackoverflow.com/comment/83893742
tagged with: post
score: 0

http://stackoverflow.com/q/48397514
type: AnsweredQuestion
has body: I know how to use .groupby over more than one column, namely: df.groupby(['col5', 'col2']).size() I also know how to use .groupby using a list that is distinct/separate from the dataframe I am working with, namely: df.groupby(aList).size() But how can I use .groupby using, simultaneously, a separate list and one (or some) of the columns of the dataframe I am working with. I.e, what is the correct way to write: df.groupby(aList, aColumnName).size() ? Thanks.
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
has title: pd.groupby by column + list
tagged with: pandas-groupby
type: Question
tagged with: pandas
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/48397528
has answer: http://stackoverflow.com/a/48397528

http://stackoverflow.com/a/48433904
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/48433872
downvote count: 0
has body: Your code is a bit misleading, it should read: text = text.replace(word, "*" * len(word)) The asterisk is the multiplication operator - it's multiplying the string "*" by the length of the word you're censoring to build up the censored string.
upvote count: 4
answers question: http://stackoverflow.com/q/48433872
type: AcceptedAnswer

http://stackoverflow.com/q/48485442
has answer: http://stackoverflow.com/a/48486534
has answer: http://stackoverflow.com/a/55271661
has answer: http://stackoverflow.com/a/71199516
tagged with: tws
type: Question
accepted answer: http://stackoverflow.com/a/48486534
has body: I am trying out this new python package ib_insync. https://github.com/erdewit/ib_insync I ran the python script below; from ib_insync import * ib = IB() ib.connect('127.0.0.1', 7496, clientId=1) contract = Forex('EURUSD') bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='30 D', barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True) # convert to pandas dataframe: df = util.df(bars) print(df'date', 'open', 'high', 'low', 'close') I encountered the error IB API from http://interactivebrokers.github.io is required. I have already installed IB API ver 9.73.06 under C:\TW_API folder. I am using Windows 10 and anaconda python v3.6 . Here is a snapshot of my TWS API settings;
tagged with: ib-api
has title: Encounter error "IB API required" when IB API is installed
possible better answer: http://stackoverflow.com/a/53547277
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/53547277
answer count: 4
favorite count: 0
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/48390934
upvote count: 1
has body: K found the answer. I was supposed to indicate the path in the GET request sent to the server. In www.python.org/about/, the www.python.org is the hostname, and the /about/ is the path. So, the string to be sent would be "GET /about HTTP...". Something like: import socket from urllib import parse # for separating path and hostname s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) url = parse.urlparse(link) s.connect((url[1], 80)) msg = "GET " + link[2] + " HTTP/1.0\r\n\r\n" s.sendall(msg) s.recv(4096)
type: Answer
answers question: http://stackoverflow.com/q/48370348
score: 1
downvote count: 0

http://stackoverflow.com/comment/83709077
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48361026
type: Comment
has text: @roganjosh But as the other classes can grow up to a hundred files, it's very uninteresting to import them all hard coded in the main class file. The main class should load only load one other class per object because it only needs one of them per object.

http://stackoverflow.com/a/48421502
answers question: http://stackoverflow.com/q/48421426
has body: Add all processes to a list, and join() each of them in turn: processes = [] for i in range(1, processes + 1): hup = MyURLParser() //A class I made p = Process(target = hup.run) p.start() processes.append(p) for p in processes: p.join() The join() call blocks until the process is finished. It doesn't matter in which order you call them; calling join() on a process that's already complete will just return immediately. You may also want to check out the other functionality in the multiprocessing module; in particular the Pool class might help you simplify this code.
type: Answer
downvote count: 0
score: 5
upvote count: 5

amazon-web-services
tags question: http://stackoverflow.com/q/48347269
tags question: http://stackoverflow.com/q/48476742
tags question: http://stackoverflow.com/q/48454628
tags question: http://stackoverflow.com/q/48483612
tags question: http://stackoverflow.com/q/48339675
tags question: http://stackoverflow.com/q/48467575
tags question: http://stackoverflow.com/q/48480390
tags question: http://stackoverflow.com/q/48368466
tags question: http://stackoverflow.com/q/48477832
tags question: http://stackoverflow.com/q/48412401
tags question: http://stackoverflow.com/q/48415441
tags question: http://stackoverflow.com/q/48375881
tags question: http://stackoverflow.com/q/48470644
tags question: http://stackoverflow.com/q/48476161
tags question: http://stackoverflow.com/q/48476977
tags question: http://stackoverflow.com/q/48364250
tags question: http://stackoverflow.com/q/48392841
tags question: http://stackoverflow.com/q/48433297
tags question: http://stackoverflow.com/q/48438202
tags question: http://stackoverflow.com/q/48351518
tags question: http://stackoverflow.com/q/48428838
tags question: http://stackoverflow.com/q/48486757
tags question: http://stackoverflow.com/q/48389406
tags question: http://stackoverflow.com/q/48341413
tags question: http://stackoverflow.com/q/48373967
tags question: http://stackoverflow.com/q/48446367
tags question: http://stackoverflow.com/q/48409989
type: Tag
tags question: http://stackoverflow.com/q/48363510
tags question: http://stackoverflow.com/q/48441982
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/48385803
tags question: http://stackoverflow.com/q/48373044
tags question: http://stackoverflow.com/q/48367110
tags question: http://stackoverflow.com/q/48422765
tags question: http://stackoverflow.com/q/48382515
tags question: http://stackoverflow.com/q/48458377
tags question: http://stackoverflow.com/q/48335721
tags question: http://stackoverflow.com/q/48407365

http://stackoverflow.com/a/48373079
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48373044
has body: Follow their recommendation to put your credentials at ~/.aws/credentials, or run aws configure as Taylor Wood's answer, but never put credentials in your code. It's a big security risk.
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/48423159
has answer: http://stackoverflow.com/a/48423293
accepted answer: http://stackoverflow.com/a/48423293
has answer: http://stackoverflow.com/a/53577162
possible better answer: http://stackoverflow.com/a/53577162
favorite count: 0
type: Question
answer count: 2
has body: I have a dataframe A: 's' 'S' 'T' 0 'abc' 'a' 12 1 'def' 'b' 15 2 'abc' 'b' 1.4 Now I want to have the value of 'T' where 's' == 'abc' and 'S' == 'b' So I tried: idx = (A['s'] == 'abc') &amp; (A['S'] == 'b') but I see .get_value() is depricated and: number = A.at[idx,'T'] gives this error: ValueError: At based indexing on an integer index can only have integer indexers EDIT: number = A.loc[idx, 'T'] returns a dataframe and not the value (integer or float) print(number) 2 1.4 Name: T, dtype: float64 When doing this: number2 = 1.3 if (number != number2): I get: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
has title: Get single value from dataframe pandas
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/48443236
upvote count: 2
has comment: http://stackoverflow.com/comment/83881674
has comment: http://stackoverflow.com/comment/83889850
tagged with: python
has comment: http://stackoverflow.com/comment/83889460
type: AnsweredQuestion
has title: Scrapy: Running multiple spider at scrapyd - python logical error
score: 2
tagged with: scrapyd
linked to: http://stackoverflow.com/q/10801093
has comment: http://stackoverflow.com/comment/83922924
has comment: http://stackoverflow.com/comment/83944325
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83923031
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/48481981
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21345092
has body: Scrapy 1.4 I am using this script (Run multiple scrapy spiders at once using scrapyd) to schedule multiple spiders at Scrapyd. Before I was using Scrapy 0.19 and was running fine. I am receiving the error: TypeError: create_crawler() takes exactly 2 arguments (1 given) So now I dont know if the problem is in Scrapy version or a simple python logical problem (I am new with python) I did some modifications to check before if the spider is active on the database. class AllCrawlCommand(ScrapyCommand): requires_project = True default_settings = {'LOG_ENABLED': False} def short_desc(self): return "Schedule a run for all available spiders" def run(self, args, opts): cursor = get_db_connection() cursor.execute("SELECT * FROM lojas WHERE disponivel = 'S'") rows = cursor.fetchall() # Coloco todos os dominios dos sites em uma lista # La embaixo faco uma verificacao para rodar somente os # que estao disponiveis e somente os que batem o dominio do site sites = [] for row in rows: site = row[2] print site # adiciono cada site na lista sites.append(site) url = 'http://localhost:6800/schedule.json' crawler = self.crawler_process.create_crawler() crawler.spiders.list() for s in crawler.spiders.list(): #print s if s in sites: values = {'project' : 'esportifique', 'spider' : s} r = requests.post(url, data=values) print(r.text)
has answer: http://stackoverflow.com/a/48481981

http://stackoverflow.com/a/78267477
score: 7
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/48334853
has body: 2024 update - looks like the settings menus are slightly different these days, so the current solution (at least for PyCharm 2023.3.2) is: File --> Settings --> Tools --> Python Plots --> Uncheck "Show plots in tool window"
downvote count: 0

http://stackoverflow.com/comment/83783513
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48385256
type: QuestionComment
has text: Some performance Tests regarding chunk-size with continous reading. https://stackoverflow.com/a/44961222/4045774 In your case (random access) i would put each row in an extra chunk. Only whole chunks can be read or written!! Another performance bottleneck is usually the very small default value for the chunk-cache-size. Regarding the fancy indexing i would try to manually read the data row for row without fancy indexing (accessing a continous 2D-Array. (even data=dataset[i,:] is a kind of fancy indexing, data=dataset[i:i+1,:] would be much faster)

http://stackoverflow.com/a/48430651
has comment: http://stackoverflow.com/comment/83926822
answers question: http://stackoverflow.com/q/48430023
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48430023
has comment: http://stackoverflow.com/comment/83894786
has comment: http://stackoverflow.com/comment/83891838
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83927039
score: 2
has body: def fill_missing(x): """x is a group after group by `number`""" return x.reindex( list((x.name, v) for v in range(x.index[0][1], x.index[-1][1]+1)) ).fillna(0) ret = df.groupby("number", as_index=False)["val1", "val2"].apply(fill_missing) The method is modified from the example in the documentation. Basically, the method uses reindex method to add the indexes that did not exist. The new indexes are created with the following line: list((x.name, v) for v in range(x.index[0][1], x.index[-1][1]+1)) This list comprehension takes the first month index x.index[0][1] and the last x.index[-1][1]+1 to create all months in between. For example, when number is 1, the first month index is 3 and the last is 9. Then, the list compreshension creates [(1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9)]. Here you see that the new indeces are created by the list comprehension. (We use x.name to locate the group name. so here the x.name is 1.) This list will be the new indices that we put into reindex. Now, for the indexes that do not exist part, {(1,6), (1,7), (1,8)}, reindex will fill in nan. (reindex added these indices in.) We then fill nan part with 0 via fillna(0).
has comment: http://stackoverflow.com/comment/83924836
downvote count: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/48447812
tags question: http://stackoverflow.com/q/48475687
tag name: merge
tags question: http://stackoverflow.com/q/48338811
tags question: http://stackoverflow.com/q/48371569
tags question: http://stackoverflow.com/q/48427118
tags question: http://stackoverflow.com/q/48457984
tags question: http://stackoverflow.com/q/48425964
tags question: http://stackoverflow.com/q/48432889
tags question: http://stackoverflow.com/q/48467833

http://stackoverflow.com/a/48460864
upvote count: 1
has body: Might be worth to check what os.path.join('results', filename).replace('\\','/') evaluates to. Have you tried a (little safer) approach using send_from_directory? (Didn't check if it actually works): @app.route('/results/&lt;path:filename&gt;', methods=['GET']) def serve_static(filename): return send_from_directory(os.path.dirname(os.getcwd()), filename)
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48460337
downvote count: 0

http://stackoverflow.com/a/48358193
score: 1
has body: seems like a crazy question but why not &gt;&gt;&gt; myval = 'ObjectId("5a60a394ac73c233ba1acc55")' &gt;&gt;&gt; myval.split("(")[1] '"5a60a394ac73c233ba1acc55")' &gt;&gt;&gt; myval.split("(")[1].split(")")[0] '"5a60a394ac73c233ba1acc55"' &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall('[a-zA-z0-9]', myval.split("(")[1].split(")")[0]) ['5', 'a', '6', '0', 'a', '3', '9', '4', 'a', 'c', '7', '3', 'c', '2', '3', '3', 'b', 'a', '1', 'a', 'c', 'c', '5', '5'] &gt;&gt;&gt; "".join(re.findall('[a-zA-z0-9]', myval.split("(")[1].split(")")[0])) '5a60a394ac73c233ba1acc55'
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48357988
answers question: http://stackoverflow.com/q/48357988
type: Answer

http://stackoverflow.com/q/48447147
score: 3
has body: I'm trying to bin data and apply a float value based on the bin. I thought pandas.cut was the tool for this, but apparently it requires unique values for each bin label. values = [0.6, 0.5, 0.5, 0.6, 0.8, 0.9] bins = [0, 2, 5, 10, 15, 25, 200] binned = pd.cut(original_table[field], bins, labels=values) &gt;&gt;&gt; ValueError: Categorical categories must be unique My data (original_table) is very large and doing anything iteratively is quite slow, which is why cut was an appealing tool. Is there a workaround to make pd.cut work for this?
answer count: 3
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/83887111
downvote count: 0
has title: Pandas cut with non-unique labels
accepted answer: http://stackoverflow.com/a/48447871
possible better answer: http://stackoverflow.com/a/61086556
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48447871
has comment: http://stackoverflow.com/comment/83886681
has answer: http://stackoverflow.com/a/61086556
tagged with: python
has answer: http://stackoverflow.com/a/48447347
has comment: http://stackoverflow.com/comment/83886578
type: AnsweredQuestion

http://stackoverflow.com/comment/83956866
comment on: http://stackoverflow.com/q/48481883
type: QuestionComment
has text: please provide code that works. More likely to get a helpful response with a [mcve]
score: 1
type: Comment

http://stackoverflow.com/comment/83810969
has text: @mehD something like this? infile = "/Users/project/results_1.csv" #myResults1 = np.genfromtxt([infile.encode('utf-8)], delimiter=",", names=columns, dtype=dtypes) error generated: ValueError: could not assign tuple of length 1 to structure with 3 fields.
score: 0
comment on: http://stackoverflow.com/q/48410063
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83818930
type: AnswerComment
has text: Would doing `fin.read(fin._CHUNK_SIZE)` be beneficial here? Ever since I noticed files have a `_CHUNK_SIZE` attribute, I've had a hunch that this value might be optimized for optimal disk read operations but never really could mentally justify it since it means more iterations in python-land.
type: Comment
comment on: http://stackoverflow.com/a/48414150
score: 0

bokeh
tags question: http://stackoverflow.com/q/48437451
tags question: http://stackoverflow.com/q/48454388
tags question: http://stackoverflow.com/q/48359806
tags question: http://stackoverflow.com/q/48451710
tags question: http://stackoverflow.com/q/48463514
tags question: http://stackoverflow.com/q/48464465
tags question: http://stackoverflow.com/q/48441861
tags question: http://stackoverflow.com/q/48452103
tags question: http://stackoverflow.com/q/48440929
type: Tag
tags question: http://stackoverflow.com/q/48338106
tags question: http://stackoverflow.com/q/48405055
tags question: http://stackoverflow.com/q/48435996
tags question: http://stackoverflow.com/q/48357663
tags question: http://stackoverflow.com/q/48331950
tags question: http://stackoverflow.com/q/48470627
tags question: http://stackoverflow.com/q/48397330
tag name: bokeh
tags question: http://stackoverflow.com/q/48401579
tags question: http://stackoverflow.com/q/48439142
tags question: http://stackoverflow.com/q/48333820
tags question: http://stackoverflow.com/q/48389481
tags question: http://stackoverflow.com/q/48386862

http://stackoverflow.com/comment/83746997
score: 0
type: Comment
has text: My present config is same as above.
type: AnswerComment
comment on: http://stackoverflow.com/a/48380050

http://stackoverflow.com/comment/83695317
comment on: http://stackoverflow.com/q/48354359
type: Comment
type: QuestionComment
has text: No need to *... manually recompile .py files into .pyc files every time I make a change to the code in the other folder.*. Just use a package that is what they are for.
score: 0

http://stackoverflow.com/comment/83710098
type: QuestionComment
comment on: http://stackoverflow.com/q/48360675
score: 0
type: Comment
has text: What is `self.game.spritesPlayer`? It seems to be an `OrderedDict`. However, the `Sprite.__init__` method needs a Pyglet image or animation as its first parameter.

http://stackoverflow.com/comment/83911417
comment on: http://stackoverflow.com/q/48458865
has text: Thank you for the suggestion @kazemakase. I tried but this doesn't result in any change in memory consumption.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48480667
has comment: http://stackoverflow.com/comment/83954393
has body: I'm looking to encrypt a string (using a password or key) in Python, without installing any modules. I can work with the default modules included when you download Python (2.7), but I can't install anything like PyCrypto. I've tried looking at Simple way to encode a string according to a password?, but the Base64 answer doesn't seem safe, and the others require an external module. Can anyone offer any help? I don't have any code to show because I haven't found anything to try.
tagged with: encryption
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83955000
has comment: http://stackoverflow.com/comment/83954434
favorite count: 0
has title: Encrypt string with password without external modules
has comment: http://stackoverflow.com/comment/83954241
type: Question
has comment: http://stackoverflow.com/comment/83956338
accepted answer: http://stackoverflow.com/a/48482295
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48482295
linked to: http://stackoverflow.com/q/2490334
has comment: http://stackoverflow.com/comment/83966309
has comment: http://stackoverflow.com/comment/83955386
has comment: http://stackoverflow.com/comment/83954732
has comment: http://stackoverflow.com/comment/83954527
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83955166
has comment: http://stackoverflow.com/comment/83955059
has comment: http://stackoverflow.com/comment/83954280
has comment: http://stackoverflow.com/comment/83954857

http://stackoverflow.com/a/48386103
has comment: http://stackoverflow.com/comment/83761866
score: 5
upvote count: 5
has body: Turn p into a set. The i in p containment test against a list takes O(length_of_list) linear time, whilst testing against a set takes O(1) constant time: p_set = set(p) f = [x for i, x in enumerate(e) if i in p_set] This makes filtering a O(length_of_e) operation, so 11k steps. With p a list, you made up to O(length_of_e * length_of_p) steps, so 33 million. However, if p is a sorted list, you already have your indices in the correct order, and you can just loop over p to select the elements: f = [e[i] for i in p] Now you are taking only 3k steps. If p is not sorted, the second version will produce the items in a different order from what they were listed in in e. That could be fine, or you could sort p first. However, sorting takes O(N log N) steps; with 3k items in p that’d take 3k times log(3k) == 3k times 8 == 24k steps, so not worth your time here over the first approach which is more than twice as efficient here.
type: Answer
has comment: http://stackoverflow.com/comment/83761942
accepted answer of: http://stackoverflow.com/q/48386070
answers question: http://stackoverflow.com/q/48386070
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83667959
comment on: http://stackoverflow.com/q/48339956
type: Comment
score: 0
type: QuestionComment
has text: @Piinthesky I usually have to say it, but you said it for me this time. Thanks! :-)

http://stackoverflow.com/q/48463868
has comment: http://stackoverflow.com/comment/83920775
has body: I'm working with my dataframe in Python. Dataframe looks like this: Timestamp cpu_system Host 2018-01-09 20:03:22 1.3240749835968018 pwp2 2017-09-30 21:03:22 2.0 pwp2 ................................................... When I check on dtypes on this dataframe, I get this: timestamp object cpu_system object host object dtype: object I want to change cpu_system into float. Running this code: df'cpu_system' = df'cpu_system'.astype(float) Getting this error: ValueError: could not convert string to float: value How should I fix it?
has answer: http://stackoverflow.com/a/48463908
has title: How to convert a string to a float in my dataframe? (Python)
tagged with: python
type: Question
score: 0
tagged with: pandas
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/48458635
tagged with: keras
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/83913074
has answer: http://stackoverflow.com/a/48460486
accepted answer: http://stackoverflow.com/a/48460486
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83914984
linked to: http://stackoverflow.com/q/48234586
tagged with: machine-learning
tagged with: python
linked to: http://stackoverflow.com/q/48476830
has comment: http://stackoverflow.com/comment/83921329
favorite count: 0
type: AnsweredQuestion
has title: Getting very bad prediction with KerasRegressor
score: 1
answer count: 1
has body: I used KerasRegressor on a dummy dataset and tried to predict the training values itself. It is giving me an output far from satisfactory. The training data is not random at all. Could anyone help me out? from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor import numpy as ny X = ny.array([[1,2], [3,4], [5,6], [7,8], [9,10]]) Y = ny.array([3, 4, 5, 6, 7]) N = 5 def brain(): #Create the brain br_model=Sequential() br_model.add(Dense(3, input_dim=2, kernel_initializer='normal',activation='relu')) br_model.add(Dense(2, kernel_initializer='normal',activation='relu')) br_model.add(Dense(1,kernel_initializer='normal')) #Compile the brain br_model.compile(loss='mean_squared_error',optimizer='adam') return br_model estimator = KerasRegressor(build_fn=brain, nb_epoch=1000000, batch_size=5,verbose=1) print "Done" estimator.fit(X,Y) prediction = estimator.predict(X) print Y print prediction The output is [3 4 5 6 7] [0.001 0.001 0.001 0.001 0.001] Basically, the prediction is 0.001 while actual value is not. I've tried with other network configs but I face the same issue. What must I do/(not do) to get an accurate output??
downvote count: 0

http://stackoverflow.com/comment/83898566
has text: It's still not clear. There is no indication of which is the left/right child, and the node 0 has only one child.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48451129

http://stackoverflow.com/a/48438759
has body: Your code with the elif part fixed import socket import time serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'localhost' port = 9999 serversocket.bind((host, port)) serversocket.listen(5) while True: clientsocket, addr = serversocket.accept() task = clientsocket.recv(1024) if not task: break if task.decode() == 't': stime = time.strftime('%H:%M:%S', time.localtime()) clientsocket.send(('Server time: ' + stime).encode()) elif task.decode() == 'off': clientsocket.close() else: pass serversocket.close() The problem being here while True: clientsocket, addr = serversocket.accept() After having processed your 1st command, you go again to accept a connection, but your client is working with the existing connection. The server has gone. You need a 2nd inner loop: while True: task = clientsocket.recv(1024) if not task: break if task.decode() == 't': stime = time.strftime('%H:%M:%S', time.localtime()) clientsocket.send(('Server time: ' + stime).encode()) elif task.decode() == 'off': clientsocket.close() break else: pass Loop from which you break out when closing the connection after getting the off command. After breaking out you are fit again for accept
answers question: http://stackoverflow.com/q/48438463
score: 1
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48438463
type: AcceptedAnswer

http://stackoverflow.com/comment/83924608
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48445144
type: Comment
has text: I tried, but it doesn't change anything.

desktop-application
tags question: http://stackoverflow.com/q/48343698
tag name: desktop-application
type: Tag

http://stackoverflow.com/q/48346046
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83680786
accepted answer: http://stackoverflow.com/a/48351121
score: 7
has answer: http://stackoverflow.com/a/48351121
tagged with: python
has comment: http://stackoverflow.com/comment/83681816
has title: How do I unpack a SQL Server DATETIME in a pyodbc Output Converter function?
type: Question
has body: I am adding output converters to pyodbc connection objects to handle date types returned from SQL Server. I was able to unpack a datetime.time struct with: tuple = struct.unpack("HHHI", dateObj) which works well. I cannot figure out the secret sauce for the datetime.datetime object, though, which according to the pyodbc docs is a TIMESTAMP_STRUCT, defined here: typedef struct tagTIMESTAMP_STRUCT { SQLSMALLINT year; SQLUSMALLINT month; SQLUSMALLINT day; SQLUSMALLINT hour; SQLUSMALLINT minute; SQLUSMALLINT second; SQLUINTEGER fraction; } TIMESTAMP_STRUCT; A datum from that column in the db is 2018-01-11 11:50:16.000, and without the add_output_convert trap pyodbc returns: TypeError: datetime.datetime(2018, 1, 11, 11, 50, 16) is not JSON serializable Looks like pyodbc silently drops the fraction, which is fine. Shouldn't the unpack() format be one of: tuple = struct.unpack("hHHHHHI", dateObj) # with missing fraction tuple = struct.unpack("hHHHHH", dateObj) ? The latter simply returns: error: unpack requires a string argument of length 12 For the record, according to sys.getsizeof dateObj is 41 bytes. Any suggestions for the format? This is Windows 10 64-bit, as well as Linux 64-bit.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83681870
upvote count: 7
tagged with: pyodbc
favorite count: 0
tagged with: sql-server

http://stackoverflow.com/comment/83711160
type: Comment
comment on: http://stackoverflow.com/q/48362041
score: 0
type: QuestionComment
has text: Of your predetermined choosing?

http://stackoverflow.com/comment/83716579
comment on: http://stackoverflow.com/q/48364969
type: QuestionComment
has text: Seems duplicate of this https://stackoverflow.com/questions/18721066/execute-python-in-a-php-script-using-shell-exec?lq=1
score: 0
type: Comment

http://stackoverflow.com/a/48481981
type: AcceptedAnswer
upvote count: 1
has body: Based on parik suggested link, here's what I did: from scrapy.utils.project import get_project_settings from scrapy.crawler import CrawlerProcess import requests setting = get_project_settings() process = CrawlerProcess(setting) url = 'http://localhost:6800/schedule.json' cursor = get_db_connection() cursor.execute("SELECT * FROM lojas WHERE disponivel = 'S'") rows = cursor.fetchall() # Coloco todos os dominios dos sites em uma lista # La embaixo faco uma verificacao para rodar somente os # que estao disponiveis e somente os que batem o dominio do site sites = [] for row in rows: site = row[2] print site # adiciono cada site na lista sites.append(site) for spider_name in process.spiders.list(): print ("Running spider %s" % (spider_name)) #process.crawl(spider_name,query="dvh") #query dvh is custom argument used in your scrapy if spider_name in sites: values = {'project' : 'esportifique', 'spider' : spider_name} r = requests.post(url, data=values)
accepted answer of: http://stackoverflow.com/q/48443236
downvote count: 0
answers question: http://stackoverflow.com/q/48443236
type: Answer
score: 1

http://stackoverflow.com/a/48357020
upvote count: 1
has comment: http://stackoverflow.com/comment/83701169
score: 1
has comment: http://stackoverflow.com/comment/83701250
has body: You can try this: lines = ["abnormal /Users/alex/Documents/X-ray-classification/data/images/1.png","normal /Users/alex/Documents/X-ray-classification/data/images/3.png","normal /Users/alex/Documents/X-ray-classification/data/images/4.png"] maxvalue = 4 # or any other maximum value missing = [] i = 0 for num in range(1, maxvalue+1): if str(num) not in lines[i]: missing.append(num) else: i += 1 print(missing) Or if you want to check for the line ending with XXX.png: lines = ["abnormal /Users/alex/Documents/X-ray-classification/data/images/1.png","normal /Users/alex/Documents/X-ray-classification/data/images/3.png","normal /Users/alex/Documents/X-ray-classification/data/images/4.png"] maxvalue = 4 # or any other maximum value missing = [] i = 0 for num in range(1, maxvalue+1): if not lines[i].endswith(str(num) + ".png"): missing.append(num) else: i += 1 print(missing) Example: here
type: Answer
answers question: http://stackoverflow.com/q/48356973
downvote count: 0

http://stackoverflow.com/q/48387466
tagged with: numpy
linked to: http://stackoverflow.com/q/46657885
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83806508
has comment: http://stackoverflow.com/comment/83814937
tagged with: python
has comment: http://stackoverflow.com/comment/83814698
has comment: http://stackoverflow.com/comment/83815148
has body: This is a follow-up question for my solution to the question below: How to apply a function in parallel to multiple images in a numpy array? My suggested solution works fine if the function process_image() has to return the result and then we can cache that to some list for later processing. Since I want to do this type of preprocessing for more than 100K images (with array shape (100000, 32, 32, 3)), I want my solution to be very efficient. But, my list based approach will hog up lot of memory and thus it will also be inefficient (for further processing). So, I want the array to be updated in-place inside the process_image() function, when this function is called several times using joblib. But, I'm having issues with updating the original batched image array in-place. I tried the suggestion by Eric but it fails to update the original array in-place. I verified whether the array memory is indeed shared among the worker processes by printing the flags of the array inside the process_image function. Here is my code for doing so: import numpy as np from skimage import exposure from joblib import Parallel, delayed # number of processes nprocs = 10 # batched image array img_arr = np.random.randint(0, 255, (1000, 32, 32, 3)).astype(np.float32) # for verification img_arr_copy = img_arr.copy() # function to be applied on all images (in parallel) # note: this function fails to update the original array in-place # but, I want in-place updation of original array with the result of `equalize_hist` def process_image(img, idx): """ update original array in-place since all worker processes share original memory! i.e. they don't make copy while processing it. """ print("\n processing image: ", idx) img[...] = exposure.equalize_hist(img) print("array metadata: \n", img.flags) print("======================= \n") # run `process_image()` in parallel Parallel(n_jobs=nprocs)(delayed(process_image)(img_arr[idx], idx) for idx in range(img_arr.shape[0])) I even tried initializing an empty …
has comment: http://stackoverflow.com/comment/83815324
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/83805899
answer count: 0
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83805861
has title: Updating batch image array in-place when using joblib
linked to: http://stackoverflow.com/q/48373944
tagged with: joblib
favorite count: 0
tagged with: multiprocessing
type: Question

http://stackoverflow.com/a/48482640
score: -1
has comment: http://stackoverflow.com/comment/83973445
answers question: http://stackoverflow.com/q/48481022
has comment: http://stackoverflow.com/comment/83961903
upvote count: 1
downvote count: 2
has body: How about: my_list = ['room', 10, 'chamber', 23, 'kitchen', 8] max_index = max(range(len(mylist)), key=lambda i: my_list[i] if isinstance(my_list[i], int) else float('-inf')) max_name = my_list[max_index-1] I'd recommend changing your data format though, if you can. A dictionary mapping number to name would (or name to number) would be a lot more natural. Even a list of lists might be easier to deal with.
type: Answer

http://stackoverflow.com/comment/83878928
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48405348
type: Comment
has text: Use a variable you set in local.conf. ie DEBUG_MYSTUFF="1" in local.conf and then skip if d.getVar("DEBUG_MYSTUFF")=="1".

http://stackoverflow.com/comment/83852072
comment on: http://stackoverflow.com/q/48430052
has text: Thanks for the response. I'm new in Linux and I'm not sure how to run the default python version. Any help is appreciated.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48339157
has comment: http://stackoverflow.com/comment/83663680
score: 3
has body: You can use transform and duplicated i.e df['g'] = df['values'].astype(str).str.contains('[A-z]').cumsum() df['is_dup'] = df.groupby('g')['C_rows'].transform(lambda x : x.duplicated().any()) C_rows values g is_dup 0 C1 customer1 1 True 1 C2 4321 1 True 2 C3 1266 1 True 3 C2 5671 1 True 4 C1 customer2 2 False 5 C2 123 2 False 6 C3 7344 2 False 7 C1 customer3 3 False 8 C2 4321 3 False 9 C3 4444 3 False 10 C4 5674 3 False 11 C1 customer4 4 False In case you want to find only duplicated rows then remove the any() df['is_dup'] = df.groupby('g')['C_rows'].transform(lambda x : x.duplicated())
has comment: http://stackoverflow.com/comment/83663555
upvote count: 3
answers question: http://stackoverflow.com/q/48338971
has comment: http://stackoverflow.com/comment/83663585
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83704660
type: Comment
has text: `return 'p=' in list(map(lambda x: x[:2], lst))` this is not valid python syntax. Unless you put this in a function
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48358832

http://stackoverflow.com/comment/83855998
comment on: http://stackoverflow.com/q/48430297
type: Comment
type: QuestionComment
has text: This really isn't a discussion forum or a tutorial. You should take the time to read [ask] and the other links on that page. There is a lot being left unsaid regarding the design of your classes which might make a difference in implementation. If you are using Python 2, you should really switch to Python 3.6+ while you are still learning.
score: 0

http://stackoverflow.com/q/48373038
type: Question
has answer: http://stackoverflow.com/a/48373502
tagged with: int
score: 0
has title: NA cost function for tensorflow
tagged with: dataframe
tagged with: python
has body: Here is my code: import pandas as pd import tensorflow as tf import numpy #download csv data sheet of all cell lines input_data = pd.read_csv( 'C:xxxxxxxxxxxxxxxxxx/xxx/xxx.csv', index_col=[0, 1], header=0, na_values='---') matrix_data = input_data.as_matrix() #user define cell lines of interest for supervised training group1 = input("Please enter cell lines that makes up the your cluster of interest with spaces in between(case sensitive):") group_split1 = group1.split(sep=" ") #assign label of each: input cluster = 1 # rest of cluster = 0 #extract data of input group g1 = input_data.loc[:,group_split1] g2 = input_data.loc[:,[x for x in list(input_data) if x not in group_split1]] regroup = pd.concat([g1,g2], axis=1, join_axes=[g1.index]) regroup = numpy.transpose(regroup.as_matrix()) labels = numpy.zeros(shape=[len(regroup),1]) labels[0:len(group_split1)] = 1 #define variables trainingtimes = 1000 #create model x = tf.placeholder(tf.float32, [None, 54781]) w = tf.Variable(tf.zeros([54781,1])) b = tf.Variable(tf.zeros([1])) #define linear regression model, loss function y = tf.nn.sigmoid((tf.matmul(x,w)+b)) #define correct training group ytt = tf.placeholder(tf.float32, [None, 1]) #define cross optimizer and cost function mse = tf.reduce_mean(tf.losses.mean_squared_error(y, ytt)) #train step train_step = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(mse) sess = tf.InteractiveSession() tf.global_variables_initializer().run() for i in range(trainingtimes): sess.run(train_step, feed_dict={x: regroup, ytt:labels}) if i%100 == 0: print(sess.run(mse, feed_dict={x:regroup, ytt:labels})) My input x and y data: x is a 141*54871 matrix with each row representing a cell and each 54871 column as a gene expression level of a gene of the cell (of that row). y is a 141*1 one column label that distinguishes group1 from group2 by labeling a cell either as 0 or 1 for group 1 or 2. my cost function mse only prints nan. Is there something wrong with having too many neuro…
type: UnansweredQuestion
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/84011067
score: 1
type: Comment
type: AnswerComment
has text: Ok... that error is indeed memory shortage. It's not related to this question.
comment on: http://stackoverflow.com/a/48500993

http://stackoverflow.com/comment/83853566
comment on: http://stackoverflow.com/q/48409924
score: 1
type: Comment
type: QuestionComment
has text: Yeah so you should be able to keep it set in `default_args` so all your other tasks have the alert, then override it when you define your one task, i.e. `BashOperator(task_id='foo', dag=dag, on_failure_callback=None)`.

http://stackoverflow.com/a/48465223
score: 1
type: Answer
has body: You can do a simple backtrack and explore an implicit graph like this: (comments explain most of it) def explore(r, c, n, memo): """ explore right and down from position (r,c) report a rout once position (n,n) is reached memo is a matrix which saves how many routes exists from each position to (n,n) """ if r == n and c == n: # one path has been found return 1 elif r &gt; n or c &gt; n: # crossing the border, go back return 0 if memo[r][c] is not None: return memo[r][c] a= explore(r+1, c, n, memo) #move down b= explore(r, c+1, n, memo) #move right # return total paths found from this (r,c) position memo[r][c]= a + b return a+b if __name__ == '__main__': n= 20 memo = [[None] * (n+1) for _ in range(n+1)] paths = explore(0, 0, n, memo) print(paths)
answers question: http://stackoverflow.com/q/48464979
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/89347846
type: AnswerComment
comment on: http://stackoverflow.com/a/48493272
score: 1
has text: In tensorflow 1.8, from_tensor_slices and zip are static methods now, so the flat_map line should be:ds = ds.flat_map(lambda mystr, myint: tf.data.Dataset.zip(( tf.data.Dataset.from_tensor_slices(mystr), tf.data.Dataset.from_tensor_slices(myint)) ))"
type: Comment

http://stackoverflow.com/a/48398398
has comment: http://stackoverflow.com/comment/83832060
has body: I tried to rewrite your code in places where a different approach leads to better results, while keeping the overall idea that you had. If anything is beyond recognition, feel free to ask. The main points are these: Bubble sort works best if you work with classic for-loops instead of for-each loops as python favors (classical in the sense of iterating over list indices instead of the actual objects) Swap operations need a temporary object to store the object you will overwrite during the first swap Use loops instead of recursion whenever possible, in particular for sorting algorithms that don't use a tree Use if..else instead of try..except whenever possible As a side note, try not to re-use existing names like list and sorted, it can lead to very weird and hard to debug errors. students = [ ('tiffany', 'A', 15), ('jane', 'B', 10), ('ben', 'C', 8), ('simon', 'A', 15), ('john', 'A', 21), ('jimmy', 'F', 1), ('charles', 'C', 9), ('freddy', 'D', 4), ('dave', 'B', 12)] def bubble_sort(to_sort): def swap(index_1, index_2): # just use indices directly temp = to_sort[index_1] # this step was missing to_sort[index_1] = to_sort[index_2] to_sort[index_2] = temp we_are_done = False # slightly more obvious than keeping a count while not we_are_done: we_are_done = True # this looks weird, but sadly we don't have do..while in python for index in range(len(to_sort) - 1): # this also avoids the checking-if-next-exists if to_sort[index][2] &gt; to_sort[index+1][2]: we_are_done = False swap(index, index+1) bubble_sort(students) # this function sorts in-place, nothing to return print (students) Prints: [('jimmy', 'F', 1), ('freddy', 'D', 4), ('ben', 'C', 8), ('charles', 'C', 9), ('jane', 'B', 10), ('dave', 'B', 12), ('tiffany', 'A', 15), ('simon', 'A', 15), ('john', 'A', 21)]
type: Answer
accepted answer of: http://stackoverflow.com/q/48397745
has comment: http://stackoverflow.com/comment/83785079
score: 0
has comment: http://stackoverflow.com/comment/83793620
has comment: http://stackoverflow.com/comment/83831891
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83790085
has comment: http://stackoverflow.com/comment/83830286
answers question: http://stackoverflow.com/q/48397745
has comment: http://stackoverflow.com/comment/83789937
has comment: http://stackoverflow.com/comment/83788807

http://stackoverflow.com/q/48356416
answer count: 1
has title: Not able to display time on X-Axis using Matplotlib
has answer: http://stackoverflow.com/a/48358223
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/83699810
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83701898
tagged with: python
has body: I am reading some data from the file, and then I have to plot this data for visual representation. The data in the file is present in the following format: 16:08:45,64,31.2 16:08:46,60,29.3 16:08:47,60,29.3 16:08:48,60,29.3 16:08:49,60,29.3 . . This data is present in a file with the current date. The file consist of time (Hour:Minute:Second), Adc Counts, Temperature Value I used the following code to read the data from the file using Pandas. from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates year = 2018 # For 2018 ''' month = input ('Enter Month : ') date = input ('Enter Date : ') month = int(month) date = int(date) ''' # Hardcoded Values for Testing Purpose month = 1 date = 20 headers = ['Time', 'ADC', 'Temperature'] filename = '%.2d-%.2d-%.2d.txt' % (month, date, year-2000) print (filename) try: df = pd.read_table( filename, ',', names=headers,\ engine='python', header=None) except: print ('No Such File in Database') print ('Exiting Program') exit() FMT = '%H:%M:%S' df['Time'] = df['Time'].map(lambda x: datetime.strptime(str(x), FMT)) df['Time'] = df['Time'].map(lambda x: x.replace(day=date, month=month, year=year)) plt.plot( df['Time'], df['ADC']) plt.ylim( [0,200]) #plt.gcf().autofmt_xdate() plt.show() I didn't get why the x-axis doesn't have correct values. Is it due to the reason, that samples are too close ( 1sec) apart? I only want time information on X-Axis. Please suggest how I can get that. Thanks in advance. Update: From comments, I am able to find the reason, why this is happening. Pandas is treating my Date and Time as timestamp object while for plotting it with Matplotlib, it should be datetime object. My problem will get solved if I am able to convert df['Time'] from Timestamp to datetime. I searched online and found the pd.to_datetime, will do this work for me, but unfortunately, it doesn't work. The following commands will list what I have done. &gt;&gt;&gt; x = pd.Timestamp( "2018-0…
accepted answer: http://stackoverflow.com/a/48358223
favorite count: 0
type: Question
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83699535

http://stackoverflow.com/comment/83699913
type: QuestionComment
score: 0
type: Comment
has text: Possible duplicate of [pygame: player fire delay](https://stackoverflow.com/questions/24042420/pygame-player-fire-delay)
comment on: http://stackoverflow.com/q/48356638

http://stackoverflow.com/q/48426950
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/83847399
has title: How to get a correct scrolling using TkInter's text widget?
has comment: http://stackoverflow.com/comment/83844553
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83847314
has comment: http://stackoverflow.com/comment/83844486
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48428574
has comment: http://stackoverflow.com/comment/83846782
accepted answer: http://stackoverflow.com/a/48428574
has comment: http://stackoverflow.com/comment/83847210
tagged with: textbox
favorite count: 0
type: Question
tagged with: tkinter
has body: I'm trying to program a simple GUI using the Text widget of TkInter and I'm stuck with a strange behavior when I scroll within it. When I reach the end of the text, sometime, I get a blank line at the bottom of the widget (and sometime not)... Here you can see the blank line : And this time, there's no... Or course I don't want to see this blank line. Here is a simple snippet that illustrate my issue. Play with it : scroll up and down using the up/down arrows, the home/end/pageup/pagedown keys. At one time, you should see the blank line... import sys,Tkinter escape,up,down,home,end,pageup,pagedown = 27,38,40,36,35,33,34 class HText ( Tkinter.Text ): def __init__(self,parent,lines,w,h ): Tkinter.Text.__init__( self,parent ) self.config( takefocus=True,width=w,height=h ) self._len = len( lines ) self._index = 0 self.config( state=Tkinter.NORMAL ) for i,t in enumerate( lines ): self.insert( Tkinter.END,'%-4d : %s\n'%(i,t),'#%d'%i ) self.focus( 1 ) def focus (self,on): self.tag_config( '#%d'%self._index,background='#daf' if on else 'white' ) def move (self,keycode): delta = { up:-1,down:+1,home:-self._len,end:self._len,pageup:-20,pagedown:+20 }.get( keycode,0 ) index = max( 0,min( self._index+delta,self._len-1 )) if index != self._index : self.focus( 0 ) self._index = index self.see( '#%d.first'%self._index ) self.focus( 1 ) def Gui ( text ): self = Tkinter.Tk() self.bind('&lt;Escape&gt;',lambda e : self.quit()) self.bind('&lt;Key&gt;' ,lambda e : htext.move( e.keycode )) htext = HText( self,text.split('\n'),120,30 ) htext.pack() self.mainloop() self.destroy() Gui( open( sys.argv[0] ).read()*10 ) Do you see what I'm doing wrong ? Is it a bug in TkInter ? By the way, I'm using python 2.7 under Windows 7 x64. Thank in advance for your time. Hadrien
upvote count: 0

http://stackoverflow.com/q/48468536
tagged with: image
has comment: http://stackoverflow.com/comment/83930781
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83930964
type: UnansweredQuestion
upvote count: 0
answer count: 1
tagged with: image-processing
has body: I want to import a png using tkinter. I have seen many tutorials to use PhotoImage but it does not accept the .png file format. Moreover, I cannot use Pillow as this program is for use in my school and my school only has the modules that come with python. Can someone suggest a way to do this?
has comment: http://stackoverflow.com/comment/83932213
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48468898
tagged with: python
score: -1
has title: Is there any way to import a png into python using only modules that come with python 3?
has comment: http://stackoverflow.com/comment/83931792

recursion
type: Tag
tags question: http://stackoverflow.com/q/48364107
tags question: http://stackoverflow.com/q/48483368
tags question: http://stackoverflow.com/q/48474723
tags question: http://stackoverflow.com/q/48344936
tags question: http://stackoverflow.com/q/48372808
tags question: http://stackoverflow.com/q/48483952
tags question: http://stackoverflow.com/q/48407582
tag name: recursion
tags question: http://stackoverflow.com/q/48360056
tags question: http://stackoverflow.com/q/48453373
tags question: http://stackoverflow.com/q/48397280
tags question: http://stackoverflow.com/q/48443462
tags question: http://stackoverflow.com/q/48375342
tags question: http://stackoverflow.com/q/48364221
tags question: http://stackoverflow.com/q/48359714
tags question: http://stackoverflow.com/q/48359150

http://stackoverflow.com/a/48457779
score: -1
has body: You can do something like this data = [ ['10', '0', '1915', '387', '1933', '402'], ['10', '0', '3350', '387', '3407', '391'], ['10', '0', '842', '505', '863', '521'], ['2', '29', '2986', '282', '3112', '300'], ['2', '29', '2753', '286', '2809', '297'], ] output = dict() for d in data: key = str(d[0]) + "-" + str(d[1]) if key not in output: output[key] = list() output[key].append(d[2:]) print(output)
answers question: http://stackoverflow.com/q/48457570
downvote count: 2
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83907714
has text: There are information about [super](https://docs.python.org/3/library/functions.html?highlight=super#super)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48457475

http://stackoverflow.com/comment/83790238
score: 0
has text: @ArpitSolanki: it's hardly a typographical mistake. I'd call it 'inexperience', not ignorance.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48401102

http://stackoverflow.com/a/48381101
has body: The error occurs because you're reading the masks in RGB color mode. The default color_mode in flow_from_directory is 'rgb'. So without specifying color_mode, your masks are loaded into (batch_size, 400, 400, 3) arrays. That's why y_true_f is 3 times larger than y_pred_f in your error message. To read the masks in grayscale, use color_mode='grayscale': mask_generator = generator_y.flow_from_directory( 'masks', target_size=(400, 400), class_mode=None, color_mode='grayscale', seed=seed)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48377289
answers question: http://stackoverflow.com/q/48377289
type: Answer
has comment: http://stackoverflow.com/comment/83749389

http://stackoverflow.com/a/48339768
has comment: http://stackoverflow.com/comment/102686774
downvote count: 7
has comment: http://stackoverflow.com/comment/83666312
has comment: http://stackoverflow.com/comment/122724777
answers question: http://stackoverflow.com/q/48338847
upvote count: 48
score: 41
has body: Yes you can make a copy of class instance using deepcopy: from copy import deepcopy c = C(4,5,'r'=2) d = deepcopy(c) This creates the copy of class instance 'c' in 'd' .
has comment: http://stackoverflow.com/comment/95711699
type: Answer

http://stackoverflow.com/comment/83739667
comment on: http://stackoverflow.com/a/48372937
has text: no, you are altering the goodList and add an additional label badList. goodList and badList are both pointing to the same data structure in memory. Just add `print(goodList, badList) badList.append("demo") print(goodList, badList)` for a quick demonstration of the effect.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/65421959
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: Accepted answer is correct, but having similar issue I opted for creating a property which is also a context manager. So the idea is to use the attribute as a context manager always. In your case: @property def hangar(self): return pandas.HDFStore(...) then you use with: with self.hangar as hangar: res = some_function(hangar) This allows you to change hangar definition (e.g. in a subclass) for something that is not a context manager. In that case, you need to decorate your method: @property @contextmanager def hangar(self): yield self._hangar and it still be working. Keep in mind that decorator order matters, as yield instead of return.
answers question: http://stackoverflow.com/q/48470053

http://stackoverflow.com/q/48355181
type: Question
has answer: http://stackoverflow.com/a/48355232
has comment: http://stackoverflow.com/comment/83697426
type: UnansweredQuestion
has title: Pass more/multiple argument to Python subprocess.call
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/13332268
tagged with: subprocess
has body: I can run ps aux | grep python_script.py and get the details of the process running the script. I want to be able to run the same command from python script. from subprocess import call call(["ps", "aux"]) works well, however tried these lines but both returns error, call(["ps", "aux", "|", "grep", "python_script.py"]) call(["ps", "aux", "| grep python_script.py"]) Returns error, can someone please advise me on how to run ps aux | grep python_script.py from command line
upvote count: 2
answer count: 1
downvote count: 0
tagged with: shell
duplicate of: http://stackoverflow.com/q/13332268
has comment: http://stackoverflow.com/comment/83697016
favorite count: 0

http://stackoverflow.com/a/48388766
answers question: http://stackoverflow.com/q/48387391
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48387391
score: 2
has body: The group by is not performing the desired counts due to the null values. Try this: dataframes['BoxType1'].fillna("NaN").groupby(["version", "boxCode", "bla"]).size().reset_index(name="count")
has comment: http://stackoverflow.com/comment/83765235
has comment: http://stackoverflow.com/comment/83765226
upvote count: 2

python-3.x
tags question: http://stackoverflow.com/q/48378524
tags question: http://stackoverflow.com/q/48474811
tags question: http://stackoverflow.com/q/48356148
tags question: http://stackoverflow.com/q/48352587
tags question: http://stackoverflow.com/q/48430902
tags question: http://stackoverflow.com/q/48409042
tags question: http://stackoverflow.com/q/48432737
tags question: http://stackoverflow.com/q/48481606
tags question: http://stackoverflow.com/q/48384192
tags question: http://stackoverflow.com/q/48446168
tags question: http://stackoverflow.com/q/48365594
tags question: http://stackoverflow.com/q/48480192
tags question: http://stackoverflow.com/q/48353544
tags question: http://stackoverflow.com/q/48453469
tags question: http://stackoverflow.com/q/48476810
tags question: http://stackoverflow.com/q/48476900
tags question: http://stackoverflow.com/q/48352480
tags question: http://stackoverflow.com/q/48353415
tags question: http://stackoverflow.com/q/48445554
tags question: http://stackoverflow.com/q/48459574
tags question: http://stackoverflow.com/q/48371259
tags question: http://stackoverflow.com/q/48359692
tags question: http://stackoverflow.com/q/48355493
tags question: http://stackoverflow.com/q/48332599
tags question: http://stackoverflow.com/q/48457866
tags question: http://stackoverflow.com/q/48447053
tags question: http://stackoverflow.com/q/48406362
tags question: http://stackoverflow.com/q/48448453
tags question: http://stackoverflow.com/q/48331983
tags question: http://stackoverflow.com/q/48455460
tags question: http://stackoverflow.com/q/48452782
tags question: http://stackoverflow.com/q/48361637
tags question: http://stackoverflow.com/q/48386113
tags question: http://stackoverflow.com/q/48470241
tags question: http://stackoverflow.com/q/48372903
tags question: http://stackoverflow.com/q/48342671
tags question: http://stackoverflow.com/q/48372508
tags question: http://stackoverflow.com/q/48427802
tags question: http://stackoverflow.com/q/48485583
tags question: http://stackoverflow.com/q/48466199
tags question: http://stackoverflow.com/q/48448410
tags question: http://stackoverflow.com/q/48416850
tags question: http://stackoverflow.com/q/48383963
tags question: http://stackoverflow.com/q/48455290
tags question: http://stackoverflow.com/q/48359581
tags question: http://stackoverflow.com/q/48432880
tags question: http://stackoverflow.com/q/48394076
tags question: http://stackoverflow.com/q/48382380
tags question: http://stackoverflow.com/q/48373181
tags question: http://stackoverflow.com/q/48452267
tags question: http://stackoverflow.com/q/48391777
tags question: http://stackoverflow.com/q/48343583
tags question: http://stackoverflow.com/q/48433578
tags question: http://stackoverflow.com/q/48367293
tags question: http://stackoverflow.com/q/48487032
tags question: http://stackoverflow.com/q/48375425
tags question: http://stackoverflow.com/q/48409068
tags question: http://stackoverflow.com/q/48427915
tags question: http://stackoverflow.com/q/48379846
tags question: http://stackoverflow.com/q/48471826
tags question: http://stackoverflow.com/q/48348803
tags question: http://stackoverflow.com/q/48414657
tags question: http://stackoverflow.com/q/48388511
tags question: http://stackoverflow.com/q/48395051
tags question: http://stackoverflow.com/q/48365001
tags question: http://stackoverflow.com/q/48377146
tags question: http://stackoverflow.com/q/48462927
tags question: http://stackoverflow.com/q/48360650
tags question: http://stackoverflow.com/q/48406442
tags question: http://stackoverflow.com/q/48451546
tags question: http://stackoverflow.com/q/48347728
tags question: http://stackoverflow.com/q/48449895
tags question: http://stackoverflow.com/q/48346861
tags question: http://stackoverflow.com/q/48360056
tags question: http://stackoverflow.com/q/48474681
tags question: http://stackoverflow.com/q/48435050
tags question: http://stackoverflow.com/q/48416016
tags question: http://stackoverflow.com/q/48360723
tags question: http://stackoverflow.com/q/48354887
tags question: http://stackoverflow.com/q/48407765

http://stackoverflow.com/q/48393019
upvote count: 0
tagged with: seaborn
answer count: 1
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/10998621
has title: How to resize x labels in a chart for display purposes
linked to: http://stackoverflow.com/q/10998621
downvote count: 1
score: -1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48393378
type: Question
tagged with: charts
has answer: http://stackoverflow.com/a/48393378
has body: Is there a way to autofit x labels on a chart so they are viewable by the users? Either rotate the labels down 90 degrees or make the chart wider? My Sales departments have at least 15 characters in their name. Image attached. sns.countplot(x='sales_dept', data=df) Sample chart Peter

http://stackoverflow.com/q/48344566
tagged with: date
has comment: http://stackoverflow.com/comment/83676051
type: Question
has comment: http://stackoverflow.com/comment/83677437
has comment: http://stackoverflow.com/comment/83675139
type: UnansweredQuestion
has body: I had searched for how to change the format of my axis x from 'Y-m-d' to 'd/m/Y' using pandas and matplotlib, but I couldn't find anything that works for me. So, here is my code: import matplotlib.dates as mdates df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d') ax = df[df_w].plot(kind='bar',x='week'); _fmt = mdates.DateFormatter('%d/%m/%Y') ax.xaxis.set_major_formatter(_fmt) I got this error: ValueError: DateFormatter found a value of x=0, which is an illegal date. This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()
answer count: 1
has comment: http://stackoverflow.com/comment/83674951
downvote count: 0
has comment: http://stackoverflow.com/comment/83676094
upvote count: 1
tagged with: plot
favorite count: 0
has title: How to format axis x date ('dd/mm/yyyy')?
tagged with: pandas
has answer: http://stackoverflow.com/a/48345863
score: 1
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/83675569

http://stackoverflow.com/q/48413762
has body: I am using this code to split a string at \.*[\s$], but preserving the split characters as an item in the list: import re markup = r"\{caption Figure 1: Leaf shapes\} \image:leaf_shapes.tiff" tokens = re.split(r'(\.*[\s$])', markup) I expected it to return this list: ['\\caption ', 'Figure 1: Leaf shapes', '\\} ', '\\image:leaf_shapes.tiff'] But instead I get this: ['\\{caption', ' ', 'Figure', ' ', '1:', ' ', 'Leaf', ' ', 'shapes\\}', ' ', '\\image:leaf_shapes.tiff'] Why are white spaces returned as separate items in the list? Edit I was supposed to escape the backslash, not the period, so I've changed my code to this: markup = r"\{caption Figure 1: Leaf shapes\} \image:leaf_shapes.tiff" tokens = re.split(r'(\\.*[\s$])', markup) But now I get this result: ['', '\\{caption Figure 1: Leaf shapes\\} ', '\\image:leaf_shapes.tiff'] Please look at my expected result so you know what I'm trying to achieve.
type: Question
has comment: http://stackoverflow.com/comment/83817606
tagged with: split
has title: Why does this re.split() return white space as separate items in the list?
upvote count: 0
answer count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83817605
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83817645
has comment: http://stackoverflow.com/comment/83817519
linked to: http://stackoverflow.com/q/22444
accepted answer: http://stackoverflow.com/a/48414435
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/48414435
has comment: http://stackoverflow.com/comment/83817559
duplicate of: http://stackoverflow.com/q/22444
favorite count: 0

http://stackoverflow.com/comment/83856700
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. Your given code doesn't run (undefined variable); when repaired, it doesn't exhibit the problem you describe.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48432564

http://stackoverflow.com/q/48439745
downvote count: 0
possible better answer: http://stackoverflow.com/a/48439859
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/48439859
favorite count: 0
accepted answer: http://stackoverflow.com/a/48439873
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48439873
has comment: http://stackoverflow.com/comment/83870648
has title: How objects are sorted in Python
type: Question
has body: Suppose that I have a list lst of some objects. What value of an object is used to perform sorted(lst) if key function is not provided? Is it hash or some id?
answer count: 2
upvote count: 3

http://stackoverflow.com/comment/83903656
type: QuestionComment
score: 0
has text: I'm running windows 10 so i'll look it up right now. Also, when I type python in my search bar I see that it is 3.63, but on python.org the newest version (from 10/12/20170 is 3.64. Could that be causing these issues?
type: Comment
comment on: http://stackoverflow.com/q/48455129

http://stackoverflow.com/a/48373254
answers question: http://stackoverflow.com/q/48372758
score: 3
upvote count: 3
downvote count: 0
has body: You get 2 legend entries, because you plot a vector with two columns, i.e. you get one legend entry per column. Usually one would plot 1D arrays, and hence get a single legend entry. At least in the case of the question there is no reason to plot a 2D array, so a solution would be to use a single dimension. import numpy as np import matplotlib.pyplot as plt t = np.arange(0,1,0.001) td = np.arange(0,1,0.1) td = np.repeat(td,2) N = len(td) x1 = t x1r = td + 0.1*np.random.randn(N) x2 = 2-t x2r = 2-td + 0.1*np.random.randn(N) plt.plot(t,x1,color='red') plt.plot(td,x1r,'.',color='red',label='A') plt.plot(t,x2,color='green') plt.plot(td,x2r,'x',color='green',label='B') plt.legend() plt.show() If for any reason you need to have 2D arrays (e.g. because they come from some other part of the code), you can simply plot their flattened version. plt.plot(td.flatten(),x1r.flatten(),'.',color='red',label='A') Lastly it seems that the newest matplotlib release (2.1.1) actually does not have 2 legend entries, even if 2 columns are plotted, so updating may be a solution as well.
type: Answer
has comment: http://stackoverflow.com/comment/131436188

http://stackoverflow.com/q/48338609
type: UnansweredQuestion
has body: I am having a problem with PyCharm (Community Edition) in that, when I open a .py file in the program, I can happily read and write in the file as usual, however when I click out of PyCharm (to look my emails for example) and then click back into it to carry on with my code, the file automatically closes and the project tree structure collapses (so I have to re-open it every time). So far I have tried changing the tab limit to a high number, but this doesn't seem to help (and it shouldn't be related, since this happens when I open just one file).
answer count: 1
has title: Can you stop PyCharm from automatically closing script files when you click out of the program?
favorite count: 0
type: Question
upvote count: 10
score: 10
tagged with: python
has answer: http://stackoverflow.com/a/48353664
tagged with: pycharm
downvote count: 0

http://stackoverflow.com/q/48384720
score: -1
tagged with: numpy
type: AnsweredQuestion
has body: My code returns an image for every number .e.g if x==0 then it will create an image and save it in a particular folder but the issue is numbers are from 0 to lets say up to infinity how do i avoid multiple if conditions in such problem. Please ask if question is not clear. Here i posted only two if condition but it is increasing. Zero=np.zeros(shape=(100, 100),dtype=np.uint8) count=0 count1=0 for (x, y) in labels: component = uf.find(labels[(x, y)]) labels[(x, y)] = component if labels[(x, y)]==0: Zero[y][x]=int(255) count=count+1 if count&lt;=32: continue elif count&gt;32: Zeroth = Image.fromarray(Zero) Zeroth.save(os.path.join(dirs, file_+'_Zero.png'), 'png') if labels[(x, y)]==1: One[y][x]=int(255) count1=count1+1 if count1&lt;=32: continue elif count1&gt;32: First = Image.fromarray(One) First.save(os.path.join(dirs, file_+'_First.png'),'png')
has comment: http://stackoverflow.com/comment/83756838
has title: If conditions for unknown range of number
upvote count: 0
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/83756800
accepted answer: http://stackoverflow.com/a/48384905
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83758254
has answer: http://stackoverflow.com/a/48384905
tagged with: if-statement
has comment: http://stackoverflow.com/comment/83756744
tagged with: python

http://stackoverflow.com/comment/83918158
comment on: http://stackoverflow.com/a/48461406
type: Comment
score: 0
type: AnswerComment
has text: I validate your answer because you provided the one-liner I asked for, but I'll settle for using a simple `for` loop instead then. :)

http://stackoverflow.com/comment/83943806
type: AnswerComment
has text: Any negative side effects using `itertools.zip_longest` with `fillvalue = ''` instead of `zip`?
score: 0
comment on: http://stackoverflow.com/a/48473765
type: Comment

http://stackoverflow.com/q/48351308
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/127695065
has title: How to specify ca_bundle in Kubernetes Python client
tagged with: kubernetes
tagged with: ssl
tagged with: python
has body: I am trying to use the Kubernetes Python client to connect to my Kubernetes cluster. The API is behind an SSL certificate signed by my CA. If I try to access any API, I get an SSL error about certificate verification failing. I found a v1beta1_api_service_spec.py library that has a parameter for ca_bundle to verify the certificate, but the core_v1_api.py and api_client.py do not have parameter options for ca_bundle. How do I pass the CA certificate so I can access the API over HTTPS? ** Solution ** Based on Matthew's pointer, I was able to figure out the problem. Initially, I was using the Kubernetes config module to load the configuration from the ~/.kube/config file. from kubernetes import client, config config.load_kube_config() This wasn't working on the client I was testing on, but kubectl was working from my PC, so I checked, and found that the .kube/config file did not specify the CA cert. I added it in, and then it worked. apiVersion: v1 clusters: - cluster: api-version: v1 certificate-authority: /path/to/ca_chain.crt server: "https://my-kubernetes-cluster" ... I also was able to figure out how to manually build the configuration if you do not want to create the .kube/config file on the host. from kubernetes import client from kubernetes.client import Configuration, ApiClient config = Configuration() config.api_key = {'authorization': 'Bearer &lt;api_key&gt;'} config.host = 'https://my-kubernetes-cluster' config.ssl_ca_cert = "/path/to/ca_chain.crt" api_client = ApiClient(configuration=config) v1 = client.CoreV1Api(api_client) v1.list_pod_for_all_namespaces(watch=False)
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/127664464
answer count: 1
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/48353513
accepted answer: http://stackoverflow.com/a/48353513
favorite count: 0

http://stackoverflow.com/q/48373991
type: Question
has comment: http://stackoverflow.com/comment/83747977
type: AnsweredQuestion
has body: I'm trying to submit form data to a handler function I wrote but Flask keeps automatically redirecting to '/' which is causing a 400 Bad Request error. Within I have and createacc is @app.route('/createacc', methods=['GET', 'POST']) def createacc(): if request.method == 'POST': name = request.form.get['nameinput'] print("This is from the main file") username = request.form['usernameinput'] passwd = request.form['passwdinput'] email = request.form['emailinput'] credentialhandler.add_user(name, username, email, passwd) return redirect(url_for(login()), code=302) return render_template("createacc.html") Thanks for the help! EDIT : It might help if I add the website HTML so Name Username Email Address Password Submit
tagged with: http://stackoverflow.com/tag/html
has title: Flask Automatically Redirecting To /
tagged with: python
accepted answer: http://stackoverflow.com/a/48383086
score: -1
favorite count: 0
upvote count: 0
answer count: 1
tagged with: request
tagged with: flask
downvote count: 1
tagged with: backend
has answer: http://stackoverflow.com/a/48383086

http://stackoverflow.com/q/48409989
has answer: http://stackoverflow.com/a/48821075
score: 0
has body: I found this guide on the AWS blog that illustrates an example of what I am trying to accomplish. I currently have a workflow that looks like Kinesis Stream --> Kinesis Firehose --> S3 bucket, and I want to introduce a Lambda where I can transform the data before it reaches the final destination. First, the links for the Lambda blueprints don't work on that article. Nor the official documentation for the data transformation in Firehose. Does anyone have a working Python blueprint for this case? Secondly, the guide shows that when creating a Firehose Delivery Stream in the AWS Console, there is an option to "Enable" data transformation in Lambda. However, I do not see any property for AWS::KinesisFirehose::DeliveryStream in the CloudFormation documentation that would accomplish the same thing. How would I enable this in my CloudFormation template? Thanks!
answer count: 1
tagged with: amazon-web-services
tagged with: aws-lambda
type: Question
has title: Transforming data in AWS Kinesis Firehose with AWS Lambda / CloudFormation
tagged with: amazon-kinesis-firehose
type: UnansweredQuestion
tagged with: aws-cloudformation
tagged with: python

http://stackoverflow.com/comment/83890624
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48448935
has text: Do you want `Rational(501, 1250)` instead of `Rational(501/1250)`, maybe?

http://stackoverflow.com/comment/83844281
has text: You don't need to "unlock" Python 3 by learning Python 2.7 first. Better start with Python 3 right away.
comment on: http://stackoverflow.com/q/48426622
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/48457346
has comment: http://stackoverflow.com/comment/83907975
has comment: http://stackoverflow.com/comment/83907844
has comment: http://stackoverflow.com/comment/83907281
has body: You can use str.extract by regex - ^ for start of string, \d{6} for 6 digits and $ for end of string: data['Cleaned_Post_Code'] = data['Post_Code'].str.extract('^(\d{6})$', expand=False) print (data) Post_Code Cleaned_Post_Code 0 629785 629785 1 588778 588778 2 760-3 NaN 3 76063 NaN 4 76063 NaN 5 S4P2Z6 NaN 6 NP443HO NaN 7 999999999 NaN 8 8 NaN 9 4 NaN 10 3 NaN 11 3 NaN 12 460803 460803 13 460803 460803 14 460803 460803 15 760439 760439 16 569139 569139 17 ABVCD NaN If want replace NaNs add fillna: data['Cleaned_Post_Code'] = (data['Post_Code'].str.extract('^(\d{6})$', expand=False) .fillna('Nill')) print (data) Post_Code Cleaned_Post_Code 0 629785 629785 1 588778 588778 2 760-3 Nill 3 76063 Nill 4 76063 Nill 5 S4P2Z6 Nill 6 NP443HO Nill 7 999999999 Nill 8 8 Nill 9 4 Nill 10 3 Nill 11 3 Nill 12 460803 460803 13 460803 460803 14 460803 460803 15 760439 760439 16 569139 569139 17 ABVCD Nill
answers question: http://stackoverflow.com/q/48457321
upvote count: 3
score: 1
downvote count: 2
has comment: http://stackoverflow.com/comment/83908906
has comment: http://stackoverflow.com/comment/83908670
has comment: http://stackoverflow.com/comment/83908016
has comment: http://stackoverflow.com/comment/83907906
type: Answer

http://stackoverflow.com/comment/83857751
has text: Has the proposed answer solved your problem? If it has, please accept so others can see it's been tested.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48413388
score: 0

http://stackoverflow.com/comment/108615898
type: AnswerComment
has text: Still for @realDonaldTrump sometimes this code returns 160 tweets, sometimes 220 tweets
score: 0
comment on: http://stackoverflow.com/a/48363194
type: Comment

http://stackoverflow.com/comment/83774556
type: QuestionComment
has text: Welcome to StackOverflow! It's a little difficult to understand exactly what you're struggling with, so in order for us to help you better, can you please update your question to clearly state where you are struggling. It would also be helpful if you could let us know what you have [**tried so far**](http://meta.stackoverflow.com/questions/261592). For further information, please refer to the help article regarding [**how to ask good questions**](http://stackoverflow.com/help/how-to-ask), and take the [**tour of the site**](http://stackoverflow.com/tour) :)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48393355

http://stackoverflow.com/q/48368457
has comment: http://stackoverflow.com/comment/83724251
tagged with: python
tagged with: state-machine
tagged with: artificial-intelligence
tagged with: python-2.7
score: 0
has title: Python AttributeError: 'FSM' object has no attribute 'AddState'
answer count: 0
has comment: http://stackoverflow.com/comment/83723659
type: UnansweredQuestion
tagged with: fsm
type: Question
has body: I am trying to create a very basic Finite State Machine in Python and keep getting the following error/s: Traceback (most recent call last): File "C:\Python27\RobotMaid_FSM.py", line 143, in &lt;module&gt; r = RobotMaid() File "C:\Python27\RobotMaid_FSM.py", line 129, in __init__ self.FSM.AddState("Sleep", Sleep(self.FSM)) AttributeError: 'FSM' object has no attribute 'AddState' I've tried many suggestions I've read from here and other places and searched for a long time for a solution but nothing seems to work, and I know it's probably some simple piece of code I haven't included or haven't implemented properly. My code is as follows: from random import randint from time import clock class Transition(object): def __init__(self, toState): self.toState = toState def Execute(self): print "Transitioning..." class State(object): def __init__(self, FSM): self.FSM = FSM self.timer = 0 self.startTime = 0 def Enter(self): self.timer = randint(0, 5) self.startTime = int(clock()) def Execute (self): pass def Exit(self): pass class CleanDishes(State): def __init__(self, FSM): super(CleanDishes, self).__init__(FSM) def Enter(self): print "Preparing to clean dishes." super(CleanDishes, self).Enter() def Execute (self): print "Cleaning dishes" if (self.startTime + self.timer &lt;= clock()): if not (randint(1, 3) %2): self.FSM.ToTransition else: self.FSM.ToTransition def Exit(self): print "Finished cleaning dishes." class Vacuum(State): def __init__(self, FSM): super(Vacuum, self).__init__(FSM) def Enter(self): print "Starting to Vacuum" super(Vacuum, self).Enter() def Execute(self): print "Vacuuming" if (self.startTime + self.timer &lt;= clock()): if not (randint(1, 3) %2): self.FSM.ToTransition("toSleep") else: self.FSM.ToTransition("toCleanDishes") def Exit(self): print "Finished Vacuuming" class Sleep(State): def __init__(self, FSM): super(Sleep, self).__init__(FSM) self.sleepAmount = 0 self.startTime = 0 def Enter(self): print "Starting to Sleep" super(Sleep, self).Enter() de…

http://stackoverflow.com/a/48378392
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48377469
has body: Please see raj's answer as it is more complete. I provided my solution as it might be easier to understand for a beginner. sc.textfile reads the entire line and therefore there is only one column in your inputRDD. You will need to split your input lines first by your delimitation character(either a space or a tab). Once you have done that, you can select the relevant column you are after inputRDD1 = sc.parallelize(['a b','1 1','2 3']) newrdd = inputRDD1 .map(lambda x: x.split( )[1]) newrdd.collect() gives ['b', '1', '3']
has comment: http://stackoverflow.com/comment/83743745
type: Answer
accepted answer of: http://stackoverflow.com/q/48377469
score: 3

http://stackoverflow.com/a/48369126
downvote count: 0
score: 13
accepted answer of: http://stackoverflow.com/q/48369104
has comment: http://stackoverflow.com/comment/83729606
answers question: http://stackoverflow.com/q/48369104
has body: You're passing a list to where() function not a Numpy array. Use an array instead: In [20]: a = np.array([5,1,3,0,2]) In [21]: np.where(a == 2) Out[21]: (array([4]),) Also as mentioned in comments, in this case the value of a == 2 is False, and this is the value passed to where. If a is a numpy array, then the value of a == 2 is a numpy array of bools, and the where function will give you the desire results.
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/83725655
has comment: http://stackoverflow.com/comment/83725463
type: AcceptedAnswer

http://stackoverflow.com/comment/83846077
type: AnswerComment
comment on: http://stackoverflow.com/a/48427456
has text: So that means `tkinter` just threw in the constants so that it may match the users' coding style? And there is no such thing as performance improvement?
type: Comment
score: 0

http://stackoverflow.com/comment/84109771
type: Comment
comment on: http://stackoverflow.com/a/48378190
type: AnswerComment
has text: I didn't understand what to replace in the template, sorry
score: 0

http://stackoverflow.com/comment/84062702
comment on: http://stackoverflow.com/a/48471281
has text: You're welcome. Please remember to accept the answer :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83886131
has text: What John Coleman said. BTW, on modern versions of Python you should use [`time.perf_counter`](https://docs.python.org/3/library/time.html#time.perf_counter) for high resolution timing info.
type: Comment
comment on: http://stackoverflow.com/q/48446875
score: 1
type: QuestionComment

http://stackoverflow.com/q/48344907
tagged with: python-3.x
downvote count: 0
has title: python chatroom with sockets not working as expected
tagged with: sockets
has answer: http://stackoverflow.com/a/48345776
accepted answer: http://stackoverflow.com/a/48345776
answer count: 1
favorite count: 0
score: 2
type: AnsweredQuestion
has body: I'm creating a chatroom program with sockets and threads where one client is intended to send a message to the server. The server is then suppose to send that message back to every client. The problem seems to be in server.py where reciever() doesn't seem to be recieving any messages when the client sends the message. I've tried debugging and it seems that if i remove the while loop in the listening() function, reciever() works again however then listening() is broken. Any ideas? server.py import socket, sys, os from threading import Thread listOfUsers = [] IP = '192.168.1.128' listeningPort = 5000 recievingPort = 5001 sendingPort = 5002 listeningSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) recievingSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sendingSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) listeningSocket.bind((IP, listeningPort)) recievingSocket.bind((IP, recievingPort)) def listening(): '''Waits for the a client to send its data( the IP address) which is added to listOfUsers''' global listOfUsers while True: print('sdfg') data, addr = listeningSocket.recvfrom(4096) data = data.decode('utf-8') if data not in listOfUsers: listOfUsers.append(data) else: pass def reciever(): '''Waits to recieve incoming messages. Once a message is recieved, this function sends the message to every IP address in listOfUsers''' while True: data, addr = recievingSocket.recvfrom(4096) data = data.decode('utf-8') with open('E:\\log.txt', 'a') as file: file.write(data) print(data) print(listOfUsers) data = data.encode() for ip in listOfUsers: sendingSocket.sendto(data, (ip, sendingPort)) def main(): t1 = Thread(target= listening(), args=()) t2 = Thread(target= reciever(), args=()) t1.start() t2.start() if __name__ == '__main__': print('Starting server... \n') main() client.py import socket, sys, os, datetime from threading import Thread name = os.getlogin() ServerIP = '192.168.1.128' hostIP = socket.gethostbyname(socket.gethostname()) initialisati…
tagged with: python
has comment: http://stackoverflow.com/comment/83675520
type: Question
upvote count: 2

http://stackoverflow.com/q/48421970
tagged with: indexing
tagged with: time
has body: i have data frames belows, and i wanna select time range. for example i have below data, and i wanna select 06:00~08:00 every day . Date, Time is multi indexed index Date Time a b c 2018-01-09 5:15:00 20.55 0 -3.07 2018-01-09 5:30:00 20.57 0 -3.07 2018-01-09 5:45:00 20.33 0 -3.44 2018-01-09 6:00:00 20.31 0 -2.95 2018-01-09 6:15:00 20.76 26738 -2.88 2018-01-09 6:30:00 21.4 22462 -2.77 2018-01-09 6:45:00 21.84 20033 -3 2018-01-09 7:00:00 22.17 20010 -3.28 2018-01-09 7:15:00 22.38 18133 -2.82 2018-01-09 7:30:00 22.75 18254 -3.14 2018-01-09 7:45:00 22.93 17039 -3.22 2018-01-09 8:00:00 23.13 15934 -3.27 2018-01-09 8:15:00 23.25 15438 -3.48 2018-01-09 8:30:00 23.44 16218 -3.65 2018-01-09 8:45:00 23.65 14666 -3.14 2018-01-09 9:00:00 24.01 14686 -3.1 ..... so result should be belows Date Time a b c 2018-01-09 6:00:00 20.31 0 -2.95 2018-01-09 6:15:00 20.76 26738 -2.88 2018-01-09 6:30:00 21.4 22462 -2.77 2018-01-09 6:45:00 21.84 20033 -3 2018-01-09 7:00:00 22.17 20010 -3.28 2018-01-09 7:15:00 22.38 18133 -2.82 2018-01-09 7:30:00 22.75 18254 -3.14 2018-01-09 7:45:00 22.93 17039 -3.22 2018-01-09 8:00:00 23.13 15934 -3.27 2018-01-10 6:00:00 20.31 0 -2.95 2018-01-10 6:15:00 20.76 26738 -2.88 2018-01-10 6:30:00 21.4 22462 -2.77 2018-01-10 6:45:00 21.84 20033 -3 2018-01-10 7:00:00 22.17 20010 -3.28 2018-01-10 7:15:00 22.38 18133 -2.82 2018-01-10 7:30:00 22.75 18254 -3.14 2018-01-10 7:45:00 22.93 17039 -3.22 2018-01-10 8:00:00 23.13 15934 -3.27 how can i select data on time range(06:00~08:00) ?
tagged with: range
tagged with: python
accepted answer: http://stackoverflow.com/a/48422054
has answer: http://stackoverflow.com/a/48422054
score: 2
type: AnsweredQuestion
has title: how can i select data on time range in pandas
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question

parallel-processing
tags question: http://stackoverflow.com/q/48423270
tags question: http://stackoverflow.com/q/48349980
tags question: http://stackoverflow.com/q/48475858
tags question: http://stackoverflow.com/q/48401876
tags question: http://stackoverflow.com/q/48480870
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/48349563
tags question: http://stackoverflow.com/q/48456081
tags question: http://stackoverflow.com/q/48387466
tags question: http://stackoverflow.com/q/48440541
tags question: http://stackoverflow.com/q/48415348
tags question: http://stackoverflow.com/q/48438790
tags question: http://stackoverflow.com/q/48349085
tags question: http://stackoverflow.com/q/48373944
tags question: http://stackoverflow.com/q/48367882
tags question: http://stackoverflow.com/q/48354342

http://stackoverflow.com/comment/83849476
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48425515
has text: Paul, your comment and the documentation for the Python Imaging Library helped point me in the right direction. After placing the data into a StringIO object, PIL was able to import it, and numpy was able to generate an array out of that PIL object. I'd like to encourage you to make an answer, rather than a comment, so I can select it.

http://stackoverflow.com/comment/83806775
has text: Thanks @Gavin Gray. I did set the drop_path_keep_prob to 1 and I launched a training. This time I got very good accuracy on the validation set as for the other networks. But now the question is: what does this param means? I'm asking for more clarification before accepting your answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48399165
type: Comment

http://stackoverflow.com/q/48360377
has comment: http://stackoverflow.com/comment/83708021
type: Question
has comment: http://stackoverflow.com/comment/83707766
answer count: 0
has body: I have a merge sort implemented in Python ... def mergesort(z): if len(z) &gt; 1: mid = len(z)//2 leftPortion = z[:mid] rightPortion = z[mid:] mergesort(leftPortion) mergesort(rightPortion) l = 0 # Next position in rightPortion r = 0 # Next position in leftPortion i = 0 # Next position in z while l &lt; len(leftPortion) and r &lt; len(rightPortion): if leftPortion[l] &lt;= rightPortion[r]: z[i] = leftPortion[l] l = l + 1 else: z[i] = rightPortion[r] r = r + 1 i = i + 1 while l &lt; len(leftPortion): z[i] = leftPortion[l] l = l + 1 i = i + 1 while r &lt; len(rightPortion): z[i] = rightPortion[r] r = r + 1 i = i + 1 ... and I want to 'record' the state of the original list, z, as the sort executes so I can use Matplotlib to graph an animation of the sort. I have implemented this method for a Bubble sort and for an Insertion sort but can't figure out how to do it because of the recursion in the merge. Can anyone help please? This is the way I did it with Bubble Sort ... import matplotlib.pyplot as plot from time import sleep from random import shuffle from copy import copy from time import time plot.ion() def generatecolours(w): max = 16581375 # 255**3 interval = int(max/len(w)) r = range(0,max,interval) return ['#{0}'.format(hex(r[i])[2:].zfill(6)) for i in w] def plotchart(x,y,title): plot.clf() plot.title(title) plot.axis('off') plot.bar(x,y,color=generatecolours(y)) plot.pause(0.0001) sleep(pause) def bubblesort(): n = len(z) trace = [copy(z)] while True: swap = False for i in range(n-1): if z[i] &gt; z[i+1]: z[i],z[i+1] = z[i+1],z[i] swap = True trace.append(copy(z)) n = n - 1 if not swap or n == 1: break return trace # Define number of items in the list items = 16 # Pause between iterations (s) pause = 0.2 # Define coordinates and shuffle y x = [i for i in range(1,items+1)] y = [i for i in range(1,items+1)] shuffle(y) # Time sort operation for copies of y print('Bubble sort') print('-----------') z = copy(y) print('Unsorted list : {0}'.format(','.join(map(str,z))…
type: UnansweredQuestion
tagged with: mergesort
tagged with: sorting
score: 0
tagged with: visualization
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/83707593
has title: Record execution of a merge sort

http://stackoverflow.com/a/48479267
answers question: http://stackoverflow.com/q/48479234
type: Answer
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83951576
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83951558
has body: Very close, but I think you want split instead of strip, and extend instead of append You can also iterate directly over the lines with a for loop. list1=[] filepath="words.txt" with open(filepath, encoding="utf8") as fp: for line in fp: list1.extend(line.strip().split(', '))
accepted answer of: http://stackoverflow.com/q/48479234
downvote count: 0

http://stackoverflow.com/comment/83892614
type: QuestionComment
has text: It seem s that with mpz it's much faster (see the EDIT)
comment on: http://stackoverflow.com/q/48447427
score: 0
type: Comment

http://stackoverflow.com/comment/83690025
comment on: http://stackoverflow.com/q/48351460
score: 0
type: Comment
has text: @Anlinyang Can you add it to the question and have one that matches? Your example does not work with the desired input.
type: QuestionComment

http://stackoverflow.com/a/48355724
score: 0
answers question: http://stackoverflow.com/q/48355680
has comment: http://stackoverflow.com/comment/83698272
type: Answer
has body: JSON data must be a single object, whereas you have an object every line. It's better to store it as an array of objects as that is considered valid JSON. eg [{"created_at"...}, {"created_at"...}, {"created_at"...}]

http://stackoverflow.com/comment/83895223
type: QuestionComment
has text: I am sure it is! How come it is possible to instantiate like this: a = Template('template-text')? Is there an actual Template class? With a method render? I can see no information on either one of those questions on the website you linked. Please correct me if I am wrong!
score: 0
comment on: http://stackoverflow.com/q/48450284
type: Comment

http://stackoverflow.com/q/48446367
favorite count: 0
type: Question
tagged with: python
tagged with: boto3
has body: I have an SNS topic on AWS, can I connect to it from my local computer using boto3? I can't find the right doc to clear this up.
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/48449028
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48449028
score: 1
has comment: http://stackoverflow.com/comment/83884688
tagged with: amazon-sns
answer count: 1
downvote count: 0
has title: Connect to AWS SNS using boto3 from local computer.
upvote count: 1
has comment: http://stackoverflow.com/comment/83884868

http://stackoverflow.com/a/48345547
downvote count: 0
type: AcceptedAnswer
has body: Another way: df_out = df[df.groupby('GroupID')'Tests','Size'.transform('count').sum(1).eq(0)] And the same logic as below to get GroupID or ID Note: count does not count NaN values so we check the count equal to zero and sum to see if all in that group are NaN. On way is to use: df_out = df.groupby('GroupID').filter(lambda x: x'Tests','Size'.isnull().all().all()) ID Details Tests Size GroupID 1 601 85 NaN NaN 2 2 601 338 NaN NaN 2 3 383 332 NaN NaN 3 Then, df_out.ID.unique().tolist() Output: [601, 383] OR df_out.GroupID.unique().tolist() Output: [2, 3]
accepted answer of: http://stackoverflow.com/q/48345290
has comment: http://stackoverflow.com/comment/83677109
answers question: http://stackoverflow.com/q/48345290
type: Answer
has comment: http://stackoverflow.com/comment/83676815
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83677018

http://stackoverflow.com/a/48373366
type: Answer
score: 2
has body: How could I force buffer to flush before going back to the event loop? You can't, because the sending can only be done asynchronously, not synchronously. But we can queue a flush the same way the packets are queued. Namely: send each packet after the previous one has been sent. Thus we shall send it every time the event loop has processed all other work. The idiom for that is zero-duration timers - note that this has nothing at all to do with timers, it's a weird overloading of the timer concept that really makes no sense otherwise. int i = 10; while (i--) QTimer::singleShot(0, this, [this]{ m_btSocket.write("&lt;some payload&gt;"); }); m_btSocket must be a member of the class, and must be a value member - otherwise the code will be unsafe. If you wish to ensure that stale packets are dumped in case of a disconnection and won't affect any subsequent connections, keep track of their generation and send only if it's current: class Foo : public QObject { unsigned int m_generation = {}; // unsigned: modulo math w/o overflows QBluetoothSocket m_btSocket{QBluetoothServiceInfo::L2CAP}; ... bool isBtConnected() const { return m_btSocket::state() == QBluetoothSocket::ConnectedState; } void sendSinglePacket(const QByteArray &amp; data) { if (!isBtConnected()) return; auto gen = m_generation; QTimer::singleShot(0, this, [this, gen, data] { if (m_generation == gen) m_btSocket.write(data); }); } Foo(QObject * parent = {}) : QObject(parent) { connect(&amp;m_btSocket, &amp;QBluetoothSocket::Disconnected, this, [this]{ m_generation++; // drops all in-flight packets }); ... } };
downvote count: 0
answers question: http://stackoverflow.com/q/48367819
upvote count: 2

http://stackoverflow.com/q/48413900
has answer: http://stackoverflow.com/a/48415008
has title: How to automate Python Dash app data pull?
tagged with: ethereum
tagged with: python
score: 2
has body: I am building a Dash app (screenshots of UI are also available at the github link) that is used to identify large buy / sell-walls on the cryptocurrency exchange GDAX thanks to the python API they have set up. My 2 big questions are as follows (calling all Python / Dash coders for their advice): 1 - How do I go about automating the data pull so that it doens't require manual refresh. I essentially just need some code that automates the data pull every second (or, if that's too hard, does it whenever there is a manual refresh via the browser). 2 - How do I host this publicly so that everyone else can use it? (I don't have experience publishing Dash apps, so any advice would be great.) https://github.com/pmaji/eth_python_tracker/blob/master/app.py
tagged with: plotly-dash
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/48432195
has body: Assume I have model like this: class Account(models.Model): balance = models.IntegerField() debt = models.IntegerField() history = HistoricalRecords() I'm using django-simple-history to get instance of the model as it would have existed at the provided date and time: inst = Account.history.as_of(datetime.datetime.now().date) It's working fine, but I want to get instance where balance field is represented as it would have existed at the provided date and time, and then debt field will be most recent of that date. I don't know if this is possible, didn't find anything about that.
type: Question
answer count: 1
tagged with: django
tagged with: django-simple-history
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48432543
has answer: http://stackoverflow.com/a/48432543
tagged with: python
has title: Django model history by date and datetime

http://stackoverflow.com/comment/83707435
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48349409
has text: It appears that the answer here is no, there is tf.py_func which provides this functionality for the map functions, but tf.py_func doesn't work with generators. I'll leave this open a while longer in case any more information comes to light. This seems to be a tough limitation of the Dataset pipeline process.
score: 0

http://stackoverflow.com/comment/83913205
type: AnswerComment
has text: The method by @ImportanceOfBeingErnest is a lot more elegant. Mine is a hack that works. I think you should reconsider. Also, he gave you a whole class that you just need to drop into your code and it will do the thing (whatever `func` ends up doing). There is nothing left for you to implement.
comment on: http://stackoverflow.com/a/48447538
score: 1
type: Comment

http://stackoverflow.com/a/48404768
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48404618
has body: Use input() server = input("Server :") ssh_command = "ssh admin@{} switchshow".format(server) subprocess.call(["sudo", "su", "switchadm", "-c", ssh_command], stdout=f)
type: Answer
downvote count: 0

http://stackoverflow.com/q/48370918
tagged with: python
has answer: http://stackoverflow.com/a/48370973
tagged with: binaryfiles
upvote count: 1
score: 1
has body: &gt;&gt;&gt; def qrcodegenerate(nbr): ... res = requests.get("https://chart.googleapis.com/chart?cht=qr&amp;chs=300x330&amp;choe=UTF-8&amp;chl="+str(nbr)) ... print(res.url) ... data =res.text ... with open("C:\wamp\www\Paymentapi\qrcode\qr_"+str(nbr)+'.png','w',encoding="utf-8") as f: ... f.write(data) ... &gt;&gt;&gt; qrcodegenerate(5697) Here I am calling API to generate a QR code and I want to save into a PNG file. The QR code is being generated, but it's not being saved correctly.
answer count: 1
downvote count: 0
has title: How can i store raw data into a PNG file in Python?
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: encoding
type: UnansweredQuestion

http://stackoverflow.com/comment/83945236
has text: Why would you need exact names when you can use `'#048cf0'`?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48475960
type: Comment

http://stackoverflow.com/q/48454612
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2
has body: Consider the following code a = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) a[[True,True,False],[True,True,False]] What I expect is a submatrix array([[1, 2], [4, 5]]) but what I get is array([1, 5]) I have figured out a method to retrieve the submatrix a[np.ix_([True,True,False],[True,True,False])] My question: Any other way we can do this more elegantly?
answer count: 0
has comment: http://stackoverflow.com/comment/83902352
favorite count: 0
type: Question
tagged with: numpy
has title: Use masks to retrieve submatrix in numpy

http://stackoverflow.com/comment/83734270
type: Comment
type: QuestionComment
has text: I do not (that's why I said "apparently"). But it is apparent from what we see.
score: 0
comment on: http://stackoverflow.com/q/48373506

http://stackoverflow.com/a/48454041
answers question: http://stackoverflow.com/q/48453509
type: Answer
has body: Method 1 (Original) import numpy as np def transform(matrix): mat = np.asarray(matrix) mat[np.logical_not(np.not_equal(mat, 0).cumprod(axis=0))] = 0 # Alternatively: # mat[~(mat != 0).cumprod(axis=0, dtype=np.bool)] = 0 # or, # mat[~((mat != 0).cumprod(axis=0, dtype=np.bool))] = 0 return mat Then with your sample data, I get the following mat: In [195]: matrix = [[1, 1, 1, 0], ...: [0, 5, 0, 1], ...: [2, 1, 3, 10]] In [196]: transform(matrix) Out[196]: array([[1, 1, 1, 0], [0, 5, 0, 0], [0, 1, 0, 0]]) Method 2 (further optimized) def transform2(matrix): mat = np.asarray(matrix) mat *= (mat != 0).cumprod(axis=0, dtype=np.bool) return mat Method 3 (even more optimized) def transform3(matrix): mat = np.asarray(matrix) mat *= mat.cumprod(axis=0, dtype=np.bool) return mat Explanation Let's look at the main statement (in Method 1): mat[np.logical_not(np.not_equal(mat, 0).cumprod(axis=0))] = 0 We can split it into several "elementary" operations: Create a boolean mask containing False (numerically 0) where elements of mat are 0 and True (numerically 1) where they are non-zero: mask1 = np.not_equal(mat, 0) Using the fact that numerically False is 0, use cumprod() function (a good explanation can be found here: https://www.mathworks.com/help/matlab/ref/cumprod.html) mask2 = mask1.cumprod(axis=0) Since 1*1==1 and 0*0 or 0*1 is 0, all elements of this "mask" will be either 0 or 1. They will be 0 only in locations for which mask1 is zero and below (!) because of the "cumulative nature" of the product along the columns (hence axis=0). Now, we want set those elements of mat that correspond to 0 in mask2 to 0. To do this we create a boolean mask that is True where mask2 is 0 and False elsewhere. This can be easily achieved by applying logical (or binary) NOT to mask2: mask3 = np.logical_not(mask2) Using "logical" NOT here creates a boolean array thus we avoid explicit type conversion. Finally we use Boolean Indexing to select those elements of mat that need to be set to 0 and set …
has comment: http://stackoverflow.com/comment/83901830
accepted answer of: http://stackoverflow.com/q/48453509
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83903108
downvote count: 0
has comment: http://stackoverflow.com/comment/83901911
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83902432
has comment: http://stackoverflow.com/comment/83902530
has comment: http://stackoverflow.com/comment/83901794

http://stackoverflow.com/comment/83901618
has text: I've stripped (what I assumed) the non-relevant fields. Please say if you think I'm missing something crucial to solve this.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48454151

http://stackoverflow.com/a/48396488
accepted answer of: http://stackoverflow.com/q/48395485
has body: This is how it can work with Select: select = Select(driver.find_element_by_css_selector('.stats-table- pagination__select')) select.select_by_visible_text("All") or by index: select.select_by_index(0)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48395485
type: Answer

http://stackoverflow.com/comment/83810314
type: QuestionComment
has text: Thanks for your comment. I think you're right about the cookies; however, adding them doesn't seem to fix the problem. When printing results.cookies I get: <RequestsCookieJar[]>... suppose there should be cookies in them?
comment on: http://stackoverflow.com/q/48410064
score: 0
type: Comment

http://stackoverflow.com/q/48361363
type: Question
tagged with: django
tagged with: django-1.11
tagged with: python
has comment: http://stackoverflow.com/comment/83709518
has title: Django middleware: UnboundLocalError: local variable 'background_color' referenced before assignment
has comment: http://stackoverflow.com/comment/83709562
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: django-middleware
has body: I'm trying to randomise certain elements of my theme across a website I'm building. I thought it might be quite nice to experiment with defining some custom middleware to handle this. But it looks like I've gone wrong somewhere: middleware.py: class RandomThemeAppearanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): theme = { background_color: '#266040', contrast: '#3bbfad', color: '#ffffff', } background_colors = ['#266040', '#009a16', '#015e85', '#d6006d'] background_color = random.choice(background_colors) if background_color == '#266040': theme['contrast'] = '#3bbfad' elif background_color == '#009a16': theme['contrast'] = '#fedf21' elif background_color == '#015e85': theme['contrast'] = '#0590b3' elif background_color == '#d6006d': theme['contrast'] = '#f97fb5' else: pass theme['background_color'] = background_color request.background_color = theme['background_color'] request.contrast = theme['contrast'] request.color = theme['color'] return self.get_response(request) Django debug is telling me the following: UnboundLocalError at / local variable 'background_color' referenced before assignment Can anyone shed any light on why this is error is being thrown?

http://stackoverflow.com/comment/83868887
type: Comment
score: 0
has text: your 2nd attached link has helped me a lot. I will write the final solution and if you'd like you can copy pasta it and I'll accept it as the answer. Otherwise, I'll accept it as the answer because it will make things much more clean and straight forward.
type: AnswerComment
comment on: http://stackoverflow.com/a/48369364

http://stackoverflow.com/q/48382621
linked to: http://stackoverflow.com/q/48331211
has answer: http://stackoverflow.com/a/48383316
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: I am trying to use OpenCV watershed algorithm (https://docs.opencv.org/3.1.0/d3/db4/tutorial_py_watershed.html) but with one little change. There is this line of code in the docs: ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0) I need to replace this thresholding with Otsu's thresholding method if it's possible. Most of the code I use I got from the OpenCV watershed docs: img = np.load('file.npy') kernel = np.ones((3,3), np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations = 2) sure_background = cv2.dilate(opening, kernel, iterations = 50) dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5) ret, sure_foreground = cv2.threshold(dist_transform, 0, dist_transform.max(), cv2.THRESH_BINARY + cv2.THRESH_OTSU) The last line causes the error: /tmp/build/80754af9/opencv_1512687413662/work/modules/imgproc/src/thresh.cpp:1402: error: (-215) src.type() == (((0) &amp; ((1 &lt;&lt; 3) - 1)) + (((1)-1) &lt;&lt; 3)) in function threshold I know that in the watershed documentation there is no Otsu's thresholding in this step, but I have to set up a script to be executed on very many images and it is important to me that it does not require the threshold value to be set up for explicitly every image. Is there a way to run this method (cv2.threshold) on this object (the result of cv2.distanceTransform) with Otsu's thresholding? EDIT To be honest I did not look for similar solution in other libraries, but now I found watershed algorithm in scikit-image library (http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_watershed.html). It seems to be a little bit less complicated in use, probably will fit my needs. But the I asked may be useful to me (or someone else) later, so if anyone has the solution then please share it :) EDIT 2 When I normalized the values by adding this line: dist_transform = cv2.normalize(dist_transform, None, 255,0, cv2.NORM_MINMAX, cv2.CV_8UC1) it worked, but unfortunately, there is anothe…
tagged with: opencv
has answer: http://stackoverflow.com/a/48383443
answer count: 2
tagged with: watershed
has title: OpenCV watershed + otsu with distanceTransform
score: 1

http://stackoverflow.com/q/48462023
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83917078
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
answer count: 1
has body: I was trying to come up with a way to isolate variables that have been defined after a certain point in my code. For this task, I wrote the following: from copy import deepcopy beginning = deepcopy(dict(globals())) # getting the current stand a = 5 # new variable gets defined # possibly more code with other definitions here end = {k: v for k, v in dict(globals()).items() if k not in beginning} Upon printing end I was expecting to see {'a': 5} only, but that was not the case. Instead, I got the entire scope all over again. As a result, it is clear that the if condition on the dictionary comprehension fails. So I have two questions: What am I doing wrong? How can my desired result be achieved? P.S: I am using Python 3.6.1
tagged with: global-variables
has comment: http://stackoverflow.com/comment/83917114
has title: How to get newly defined variables
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48462422
has answer: http://stackoverflow.com/a/48462422
tagged with: python

http://stackoverflow.com/q/48389750
tagged with: sympy
has answer: http://stackoverflow.com/a/48428446
downvote count: 0
has title: Sympy with Cython produces singular matrix when attempting to find roots
tagged with: cython
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83770903
has comment: http://stackoverflow.com/comment/83768655
type: Question
has comment: http://stackoverflow.com/comment/83767922
type: UnansweredQuestion
tagged with: python
has body: I am trying to solve a set of nonlinear equations using Sympy. This is my code with a few numbers changed and only one input value (the real code runs through 170,000 lines of data): import sympy as sp K0 = 2.00*10**-4 x2, y2 = sp.symbols('x2, y2') x0 = 500 y0 = 500 R1 = ((x2 - x0)**2 + (y2 - y0)**2)**0.5 R2 = K0 * R1 H2 = sp.atan(R2 * (x2 - x0)/R1) V2 = sp.atan(R2 * (y2 - y0)/R1) x, y = sp.symbols('x, y') x0 = 1.0 y0 = 2.0 x = R1 * H2 y = R1 * V2 dat = sp.nsolve([x - x0, y - y0], [x2, y2], [512, 512]) # This line is the problem print "dat = %f, %f" % (dat[0], dat[1]) Purely with Python, the code runs fine and produces a good output - but it's very slow. To speed up the process, I used Cython to compile a .pyx file with the exact same code (in a definition, def test()), yet during run-time I'm met with: File "test.py", line 3, in &lt;module&gt; demo.test() File "demo.pyx", line 17, in demo.test dat = sp.nsolve([x - x0, y - y0], [x2, y2], [512, 512]) File "C:\...\site-packages\sympy\utilities\decorator.py", line 91, in func_wrapper return func(*args, **kwargs) File "C:\...\site-packages\sympy\solvers\solvers.py", line 2847, in nsolve x = findroot(f, x0, J=J, **kwargs) File "C:\...\site-packages\mpmath\calculus\optimization.py", line 960, in findroot for x, error in iterations: File "C:\...\site-packages\mpmath\calculus\optimization.py", line 658, in __iter__ s = self.ctx.lu_solve(Jx, fxn) File "C:\...\site-packages\mpmath\matrices\linalg.py", line 227, in lu_solve A, p = ctx.LU_decomp(A) File "C:\...\site-packages\mpmath\matrices\linalg.py", line 137, in LU_decomp raise ZeroDivisionError('matrix is numerically singular') ZeroDivisionError: matrix is numerically singular I have narrowed down the problem to the x - x0 and y - y0 part. For some reason, the compiled code cannot handle finding the roots when they're not equal to 0. Can nsolve simply not be converted to C using Cython? Is there something I'm missing that I have to do with Cython?
has comment: http://stackoverflow.com/comment/83767543

http://stackoverflow.com/q/48421988
upvote count: 1
downvote count: 1
tagged with: caffe2
linked to: http://stackoverflow.com/q/45831255
favorite count: 0
type: Question
has title: In a Anaconda virtual environment，what‘s the difference between "conda install package_name", "pip install package_name"?
type: UnansweredQuestion
has body: The default PyThon environment in my linux is: Python 3.6.2 :: Anaconda custom (64-bit), I created the virtual environment: Python 2.7.14 :: Anaconda custom (64-bit) First, I enter the Aanconda virtual envirenment: source activate python27 Then, I installed caffe2, there is an error: ImportError:No module named google.protobuf.internal so, I use conda to install protobuf: conda install protobuf, but the error still exists。 when I use pip install protobuf， the error disappeared. What's the difference: conda install package_name pip install package_name /opt/anaconda3/envs/python27/bin/pip install package_name apt install package_name Is pip install package_name the same as /opt/anaconda3/envs/python27/bin/pip install package_name ? When I which pip, it shows: /opt/anaconda3/envs/python27/bin/pip Thank you!
has comment: http://stackoverflow.com/comment/83833584
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/83834284
score: 0
tagged with: linux
answer count: 0
linked to: http://stackoverflow.com/q/20994716
has comment: http://stackoverflow.com/comment/83833535

http://stackoverflow.com/q/48480523
type: Question
has body: SSH to a VPS running ubuntu and installed flask, Apache, and WSGI with the following: sudo apt-get update sudo apt-get install python-pip pip install --user Flask sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi cloned git repo that had the hello.py program with the following code: from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello World!" if __name__ == '__main__': app.run(port=5000, debug=True) created hello.wsgi file in VPS by running the following: nano hello.wsgi import sys sys.path.insert(0, "/var/www/firstapp") from hello import app as application created apache configuration pointing to above .wsgi by running the following in VPS: cd /etc/apache2/sites-available nano hello.conf &lt;VirtualHost *&gt; ServerName example.com WSGIScriptAlias / /var/www/firstapp/hello.wsgi WSGIDaemonProcess hello &lt;Directory /var/www/firstapp&gt; WSGIProcessGroup hello WSGIApplicatioinGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; Configured Apache to serve Flask application by doing the following in VPS: sudo a2dissite 000-default.conf sudo a2ensite hello.conf sudo servive apache2 reload if I go to the VPS public IP the application fails with Error 500, when i run "sudo tail -f /var/log/apache2/error.log" I get the error "from flask import Flask ImportError:No module named flask
linked to: http://stackoverflow.com/q/31252791
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83980357
tagged with: flask
tagged with: mod-wsgi
score: 0
has title: Configuring Apache to server fails with Error 500. error.log says "ImportError: No module named flask"
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83953915
downvote count: 1
has answer: http://stackoverflow.com/a/48480922
favorite count: 0

http://stackoverflow.com/a/48397198
accepted answer of: http://stackoverflow.com/q/48385954
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48385954
has body: I actually found the answer. Thanks to LittleFoot and Christopher Jones. After removing the exception handler, I got ORA-12516: TNS:listener could not find available handler with matching protocol stack, I have to increase the database process and session. alter system set processes=1000 scope=spfile; alter system set sessions=2248 scope=spfile; startup and it worked. Thanks
type: Answer

http://stackoverflow.com/comment/83713272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48363104
has text: You assign `balance = balance0`, but `balance0` is set outside of your loop.
score: 1

http://stackoverflow.com/q/48448682
type: Question
has body: I'm trying to open up my chrome profile which is signed into google however am not having any luck. from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument(r'user-data- dir=G:\Users\Kareem\AppData\Local\Google\Chrome\User Data\Profile 10') chrome_path= r"G:\Users\Kareem\Documents\Work\Computer Science\Selenium\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get("https://www.google.co.uk/webhp?source=search_app")
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48448849
score: 0
answer count: 1
tagged with: selenium
has title: Open a chrome profile in python that is already signed into google

http://stackoverflow.com/a/48366721
has body: Using the zipped-transpose idiom, zip upto the longest list with itertools.zip_longest. Then iterate over each item in the sub-lists, filtering out None values. from itertools import zip_longest for i in zip_longest(*data.values()): for j in filter(None, i): print(j) cup one five pen two Here, data is your input dictionary. Don't use dict to name variables, it shadows the builtin class with the same name. Note that this order is not guaranteed on python versions below python-3.6, since dictionaries are not ordered in these older versions of python. Final note, for python-2.x, the appropriate function to be used is itertools.izip_longest. The output of zip_longest looks like this: print(list(zip_longest(*data.values()))) [('cup', 'one', 'five'), ('pen', 'two', None)] These None values are inserted in place of missing values due to the "zip longest' behaviour of the function. These Nones are removed with filter. You can use this to get creative using itertools.chain and a print statement, accomplishing this in one line: from itertools import chain print(*filter(None, chain.from_iterable(zip_longest(*data.values()))), sep='\n') cup one five pen two Re-written a little more clearly: print( *filter( # `filter` out None (iterable unpacking) None, chain.from_iterable( # flatten an iterable of iterables zip_longest(*data.values()) # zip-longest transpose ) ), sep='\n' # separate unpacked arguments with newline ) One more option, for homework submission without zip_longest. This just cycles over the keys, popping one element at a time from each list. while any(bool(v) for v in data.values()): for k in data: try: print(data[k].pop(0)) except IndexError: pass cup one five pen two This empties data of its contents, so you may want to make a copy of your data beforehand.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48366684
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83720144
accepted answer of: http://stackoverflow.com/q/48366684
has comment: http://stackoverflow.com/comment/83720128
has comment: http://stackoverflow.com/comment/83720176

http://stackoverflow.com/q/48332461
has body: I get the following error for encoding when I activate DEBUG mode: set FLASK_DEBUG=1 For some reason, the debug mode does not get activated by app.debug=True. Here is the error: Non-UTF-8 code starting with '\x90' in file C:\Users\mypc\Anaconda3\envs\fenv\Scrip ts\flask.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for de tails I tried the solution in the this link but it didn't help! Working with utf-8 encoding in Python source Then I tried the following command: python -m flask run And I got the following error: handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread This is my code : #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, url_for, request, render_template, jsonify import requests, json from urllib.request import quote from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/flask' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '&lt;User %r&gt;' % self.username @app.route('/') def Index(): return render_template('add_user.html') @app.route('/postuser', methods=['POST']) def post_user(): user = User(request.form['username'], request.form['email']) db.session.add(user) db.session.commit()
type: UnansweredQuestion
tagged with: python
tagged with: flask
has title: signal only works in main thread, no encoding declared
has comment: http://stackoverflow.com/comment/83650909
linked to: http://stackoverflow.com/q/6289474
has comment: http://stackoverflow.com/comment/94441017
answer count: 0
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/48225473
upvote count: 1
has comment: http://stackoverflow.com/comment/83650765
favorite count: 0
type: Question

http://stackoverflow.com/comment/83801960
has text: Only alternative would be to create an object on demand each time the attributes `users` or `posts` are requested but this would need CPU instead of memory.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48406389
score: 0

http://stackoverflow.com/q/48358686
has answer: http://stackoverflow.com/a/48358848
has comment: http://stackoverflow.com/comment/83704168
type: Question
has answer: http://stackoverflow.com/a/48358866
upvote count: 2
has answer: http://stackoverflow.com/a/48358932
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83704163
has body: This is my code : #Choose Report def chooseReport(): print "Choose a report." while True: choice = raw_input("Enter A or B: ") if choice == 'a' or choice == 'A': reportA() break elif choice == 'b' or choice == 'B': reportB() break else: continue When I input either a or b, it just asks me to "Enter A or B" again. It doesn't go to the functions its supposed to. Any idea why is this?
tagged with: python
answer count: 6
downvote count: 1
has answer: http://stackoverflow.com/a/48358790
favorite count: 0
has answer: http://stackoverflow.com/a/48358757
has comment: http://stackoverflow.com/comment/83704088
tagged with: while-loop
has comment: http://stackoverflow.com/comment/83704255
has comment: http://stackoverflow.com/comment/83704247
score: 1
has answer: http://stackoverflow.com/a/48358851
has comment: http://stackoverflow.com/comment/83704133
has title: "while loop" not breaking (using Python)

http://stackoverflow.com/comment/83860338
comment on: http://stackoverflow.com/q/48434175
has text: If you are learning Python at your school I don't see how they can deny you downloading it.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83689297
score: 1
type: QuestionComment
has text: Indent the the function after your class. It needs to be indented to be part of your class.
comment on: http://stackoverflow.com/q/48351221
type: Comment

http://stackoverflow.com/q/48351223
type: Question
has comment: http://stackoverflow.com/comment/83689541
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has title: How can I get the day of the year from datetime64 array?
score: 0
answer count: 0
has body: I have an array: array(['1980-01-01T00:00:00.000000000', '1980-01-02T00:00:00.000000000', '1980-01-03T00:00:00.000000000', ..., '1989-12-29T00:00:00.000000000', '1989-12-30T00:00:00.000000000', '1989-12-31T00:00:00.000000000'], dtype='datetime64[ns]' And I want to get another array with day of the year. I am not sure how to use timetuple().tm_yday with it. Or something else.
linked to: http://stackoverflow.com/q/18215317
tagged with: arrays
duplicate of: http://stackoverflow.com/q/18215317
has comment: http://stackoverflow.com/comment/83689528

http://stackoverflow.com/comment/83691470
comment on: http://stackoverflow.com/a/48352342
has text: VARIABLE calls in every class every time in a new way again? Do not know it, thanks
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83707731
comment on: http://stackoverflow.com/q/48360390
type: Comment
type: QuestionComment
score: 0
has text: okay I am sorry is my very first question in here!

http://stackoverflow.com/q/48360571
has title: Treatment of large size packets at Twisted
type: Question
has answer: http://stackoverflow.com/a/48360676
type: UnansweredQuestion
tagged with: python
tagged with: serve
score: 0
has body: I am currently building a TCP server (the server is going to be used by my company so it must be at a high production level) My requirements are: The server will be fast (it can handle a large number of requests simultaneously because our clients send large files regularly and this will create Bottleneck). The server will be easy to maintain. Support as many users as possible at the same time. That the server will be a TCP server because it receives protocol messages that our company has developed and I need to parse it myself. After checking the options, I chose Python Twisted because he seems to be meeting the first requirement (and since he is in Python then the second demand is solved by itself). After reading Twisted's documentation I thought of a problem I had not yet found an elegant answer , my clients send me pretty large packets and I make decisions based sub sequence within these packets. Let's say if I got 1000 first bytes that are all zeros and then another 5,000 bytes that all of them 0x10, I will send back "Hello world" and if I get instead 2000 bytes that all of them 0x50 I will answer "Hello everyone". My problem with Twisted is that the data eventually comes to "protocol.Protocol" and they are treated with the "dataReceived (self, data)" function, and this instant is a one-time instant, which means that if I only get some of the bytes for the first time and I'm going to get the rest of the bytes at the second time I do not have how to save the data from the first time... I can not save the data in the protocol.Factory because I will talk with multiple clients simultaneously and then one will use the data of the other, for the same reason I can not use the Globals. I'm pretty sure I'm not the first to come across this problem, I've seen several online solutions that included re-implementation of "protocol.Protocol" and they really were not elegant .. Is there a simple and elegant way to solve this problem? (The solution must be elegant because I add…
tagged with: twisted
tagged with: tcp
tagged with: multithreading
answer count: 1

http://stackoverflow.com/a/48487886
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83968998
has body: If I understand you correctly, you want something like the pcolormesh plot, but with only the outlines. One way to achieve this is to extend (or widen) your array such that it contains the same value many times in x and y direction. This basically means that your z consists of many plateaus with very steep gradients in between. You can do this easily with np.repeat. Below I show an example where each point in the original data is expanded to a 20x20 plateau. The colours of the plots can be fixed by creating a custom colormap. In your case, using a ListedColormap should be enough. When using contour, you also have to specify the levels at which the contours should be drawn in order to make it work correctly. import matplotlib.pyplot as plt import numpy as np from matplotlib import colors cmap = colors.ListedColormap([ 'royalblue', 'cyan','yellow', 'orange', 'red', 'green' ]) np.random.seed(1234) num = 5 x = np.linspace(-1.0, 1.0, num=num) xx, yy = np.meshgrid(x, x) z = np.random.randint(low=0, high=6, size=xx.shape) levels = np.arange(0, 6) fig, axes = plt.subplots(nrows=2, ncols=2) axes[0, 0].contourf(xx, yy, z) axes[0, 1].contour(xx, yy, z, colors='k') axes[1, 0].scatter(xx, yy, marker='.', c=z) axes[1, 1].pcolormesh(xx, yy, z, cmap=cmap) ##I added here the custom colormap for reference ##expanding the arrays N = 20 x1 = np.linspace(-1.0, 1.0, num=N*num) xx1, yy1 = np.meshgrid(x1,x1) z1 = np.repeat(np.repeat(z, N,axis=0),N).reshape(xx1.shape) fig2, ax2 = plt.subplots() ax2.contour(xx1, yy1, z1, cmap=cmap, levels = levels) plt.show() produces this kind of plot: As you can see, the lines are still not quite straight and sometimes two lines next to each other can be seen. This is because the gradients between different plateaus are not equal. I ran another example using N=200, in which case the lines are much straighter: Hope this helps.
has comment: http://stackoverflow.com/comment/83968906
type: Answer
has comment: http://stackoverflow.com/comment/83968939
answers question: http://stackoverflow.com/q/48487346

http://stackoverflow.com/q/48345658
has answer: http://stackoverflow.com/a/48345769
has title: Trying to upload multiple files, but getting str error
score: 0
has answer: http://stackoverflow.com/a/48346193
answer count: 2
tagged with: django
has comment: http://stackoverflow.com/comment/83677331
has comment: http://stackoverflow.com/comment/83678143
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83677508
has comment: http://stackoverflow.com/comment/83677929
tagged with: python
has body: I am trying to upload multiple files but I get this error: __str__ returned non-string (type int) The thing is related to my __str__ function. If I leave it like return self.file, then it will just show an object, not the real filename. I have also, tried using os.basename but it wasn't successful either. class FileUpload(models.Model): file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.file.name class AnotherClas(models.Model): file_upload = models.ForeignKey('FileUpload', on_delete=models.CASCADE, blank=True)
has comment: http://stackoverflow.com/comment/83677571

http://stackoverflow.com/a/48450206
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48437179
downvote count: 0
has body: I was able to find a solution based on previous solutions for C++: # Resize border_v = 0 border_h = 0 if (IMG_COL/IMG_ROW) &gt;= (img.shape[0]/img.shape[1]): border_v = int((((IMG_COL/IMG_ROW)*img.shape[1])-img.shape[0])/2) else: border_h = int((((IMG_ROW/IMG_COL)*img.shape[0])-img.shape[1])/2) img = cv2.copyMakeBorder(img, border_v, border_v, border_h, border_h, cv2.BORDER_CONSTANT, 0) img = cv2.resize(img, (IMG_ROW, IMG_COL)) Here is what is going on: Compare the aspect ratio of the input image to the target image to determine whether borders should be added on the vertical (v) or horizontal (h) axis using the if statement. (taking for example the vertical case), I compute the height of an image with the same aspect ratio as the target image, but with width equal to the input image using the formula (IMG_COL/IMG_ROW)*img.shape[1]. I then subtract the actual height of the image to determine how large the borders need to be. Finally, divide by two (as border is added top/bottom or left/right) and call cv2.copyMakeBorder, this creates an image with the target aspect ratio with black bars "filling in" the difference between the aspect ratios. Example (Input -> Output)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48437179
type: Answer

http://stackoverflow.com/q/48482983
has body: I want to delete the text Página consultada el: but I don't know how because it's outside any tag. I've tried with this but nothing changes: for b in soup.find('br'): if( b.nextSibling == 'Página consultada el:'): b.nextSibling.replaceWith('') if(b.previousSibling == 'Página consultada el:'): b.previousSibling.replaceWith('') This is the html of the part I want to remove: Página consultada el: 27/01/2018 21:42:14 Whole html: Turno: Matutino Grupo: 401 Profesor tutor: MONICA OSORNIO PEREZ. Hora: Lunes Martes Miércoles Jueves Viernes 7:00 a 7:50 ORI.EDU.IV(A): A204 MATEMAT. IV B108 LENG. ESP. B108 MATEMAT. IV B108 MATEMAT. IV B108 7:50 a 8:40 INGLES IV(B): C303 INGLES IV(A): C304 MATEMAT. IV B108 INGLES IV(B): C303 INGLES IV(A): C304 MATEMAT. IV B108 INGLES IV(B): C303 INGLES IV(A): C304 8:40 a 9:30 LENG. ESP. B108 INFORMATICA CC2 HISTORIA III B116 ORI.EDU.IV(B): A205 DIBUJO II(A): B-8 DIBUJO II(B): C101 9:30 a 10:20 LENG. ESP. B108 GEOGRAFIA A102 FISICA III A303 GEOGRAFIA A102 DIBUJO II(A): B-8 DIBUJO II(B): C101 10:20 a 11:10 HISTORIA III B108 INFORMATICA B108 FISICA III A303 FISICA III LACE 11:10 a 12:00 LOGICA B108 LENG. ESP. B108 GEOGRAFIA A103 FISICA III LACE LOGICA B108 12:00 a 12:50 LENG. ESP. B108 LOGICA B108 HISTORIA III B108 12:50 a 13:40 13:40 a 14:30 ED FISICA IV GIM 14:30 a 15:20 Asignatura: Nombre del Profesor: Asignatura: Nombre del Profesor: ORI.EDU.IV(A): BECERRA ALCANTARA IVONNE INGLES IV(B): CARRILLO SANCHEZ JACOBO LENG. ESP. ESTRADA GASCA SCARLETT FISICA III FLORES FLORES ANA HISTORIA III GONZALEZ GARCIA ANGELICA ARACELI DIBUJO II(A): JIMENEZ GENCHI ERIKA PAOLA LOGICA NAVARRO LOZANO JULIANA V. MATEMAT. IV OLVERA PE¥A ALEJANDRO GEOGRAFIA OSORNIO PEREZ MONICA ORI.EDU.IV(B): PINEDA VALLEJO MARIA GABRIELA INGLES IV(A): REYES CRUZ KIMBERLY ED FISICA IV SANCHEZ LUGO EDGARDO JAIME INFORMATICA SOTOMAYOR GUERRA JUAN CARLOS DIBUJO II(B): VILLANUEVA VILCHIS MONICA EDITH Página consultada el: 27/01/2018 21:42:14
has answer: http://stackoverflow.com/a/48483078
tagged with: python
has comment: http://stackoverflow.com/comment/83958971
has title: Remove text outside of tags with bs4
type: AnsweredQuestion
downvote count: 0
tagged with: beautifulsoup
upvote count: 1
accepted answer: http://stackoverflow.com/a/48483078
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83958945
has comment: http://stackoverflow.com/comment/83959192
favorite count: 0
has comment: http://stackoverflow.com/comment/83958956
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/83883319
type: QuestionComment
comment on: http://stackoverflow.com/q/48445691
score: 1
type: Comment
has text: (I do use HDF5 but with h5py/numpy). Do you have some small example of code? In principle I don't think the HDF5 format support making the file read-only, but you can choose to open in it read-only mode. See e.g. the [documentation](https://support.hdfgroup.org/HDF5/doc/UG/FmSource/08_TheFile_favicon_test.html). But really, we could learn more from your code.

http://stackoverflow.com/comment/83815524
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48401162
has text: It did indeed. I committed the fix to my repo (see above). It's working on both desktop and mobile so far, with some issue still to be fixed for the touch. I'll post the updated code part as answer when I'll be not from mobile. Thanks!
score: 0

http://stackoverflow.com/q/48408062
has body: I was following along with a sentdex tutorial on writing a constitutional neural network and I got to wondering if I could figure out my own pooling layer. The problem is that as part of this pooling layer I have to perform a tensorflow function using a session. def customPool(x): patches = tf.extract_image_patches(x, [1, 2, 2, 1], [1,2,2,1], [1,1,1,1], 'SAME') tempSess = tf.Session() bool1 = tempSess.run( tf.greater( tf.reduce_max(patches) , tf.contrib.distributions.percentile(patches, q=75.) ) ) tempSess.close() if bool1: return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') else: return tf.nn.avg_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') but the problem is, at least I think, that since I start everything out with a place holder x = tf.placeholder('float', [None, 784]) Basically my question is: How do I compute something using a tensorflow session inside of the neural network model if it is being passed placeholder variables? Help is much appreciated! full code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) n_classes = 10 batch_size = 128 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') keep_rate = 0.8 keep_prob = tf.placeholder(tf.float32) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME') def maxpool2d(x): # size of window movement of window return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') def customPool(x): patches = tf.extract_image_patches(x, [1, 2, 2, 1], [1,2,2,1], [1,1,1,1], 'SAME') tempSess = tf.Session() bool1 = tempSess.run( tf.greater( tf.reduce_max(patches) , tf.contrib.distributions.percentile(patches, q=75.) ) ) tempSess.close() if bool1: return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') else: return tf.nn.avg_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') def convolutional_neural_network(x): wei…
has answer: http://stackoverflow.com/a/48408216
downvote count: 0
has comment: http://stackoverflow.com/comment/83805298
upvote count: 1
tagged with: python
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83805287
tagged with: conv-neural-network
type: Question
tagged with: if-statement
type: AnsweredQuestion
tagged with: max-pooling
tagged with: tensorflow
has title: How to use a tensorflow session inside a nerual network model
favorite count: 0
accepted answer: http://stackoverflow.com/a/48408216

http://stackoverflow.com/q/48412184
tagged with: pandas
answer count: 1
has title: How to get minimum value by week using Pandas and Python
score: 1
accepted answer: http://stackoverflow.com/a/48412299
type: Question
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48412299
has body: I have a data that looks like this that I get from an API (of course in JSON form): 0,1500843600,8872 1,1500807600,18890 2,1500811200,2902 . . . where the second column is the date/time in ticks, and the third column is some value. I basically have the data for every hour of the day, for every day for a couple of months. Now, what I want to achieve is that I want to get the minimum value for the third column for every week. I have a code segment that looks like this: from bs4 import BeautifulSoup import datetime import json import pandas # Partially removed for brevity. # dic holds now the data that I get from the API. dic = json.loads(soup.prettify()) df = pandas.DataFrame(columns=['Timestamp', 'Value']) for i in range(len(dic)): df.loc[i] = [datetime.datetime.fromtimestamp(int(dic[i][1])).strftime('%d-%m-%Y %H:%M:%S'), dic[i][2]] df.sort_values(by=['Timestamp']) df['Timestamp'] = pandas.to_datetime(df['Timestamp']) df.set_index(df['Timestamp'], inplace=True) print(df['Value'].resample('W').min()) Though, this does not quite give me correct results, also some of the results are NaN. Additionally, I also want to get the timestamp along with the minimum value, so I know at which date/time during the week the minimum occurred. Any ideas how to achieve what I want?

http://stackoverflow.com/a/48401139
score: 4
answers question: http://stackoverflow.com/q/48401102
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48401102
has body: You assign an integer to x in the loop: x = mult so the next iteration of your while loop now passes that integer to the len() function and you get your exception. Convert the value to a string instead: x = str(mult) I'd set mult to 1 inside the loop to simplify it, and test for more than 1 digit: def digit_multiply_steps(n): """Reduce n to one digit, multiplying the digits each step Returns the number of steps required to do so. """ x = str(n) counter = 0 while len(x) &gt; 1: mult = 1 for i in x: mult *= int(i) x = str(mult) counter += 1 return counter print(digit_multiply_steps(39)) The loop can also be done using the functools.reduce() function, together with operator.mul() function for speed. The map() function can be used to turn the characters of x back to integers to multiply with. We can use itertools.count() to produce the counter: from functools import reduce from itertools import count from operator import mul def digit_multiply_steps(n): """Reduce n to one digit, multiplying the digits each step Returns the number of steps required to do so. """ x = str(n) for counter in count(): if len(x) == 1: return counter x = str(reduce(mul, map(int, x), 1))
upvote count: 4
type: Answer

http://stackoverflow.com/q/48459172
tagged with: python
answer count: 0
tagged with: pandas
has body: Lets say i have the following code which create random numbers just for the example. Getting the group by is ok as long as it does only one action per each column. So df is grouped by C and gets column A max value and column B gets it's min. I am asking how I can get for column A both max and min (I assume this will have to create new columns? Your help is appreciated! import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0,5,size=(20, 3)), columns=list('ABC')) print(df) print(df.groupby('C').agg({'A': max, 'B':min})) #or can use this #print(df.agg({'A': np.max,'B': np.min,}).head(10))
score: 0
has comment: http://stackoverflow.com/comment/83911135
linked to: http://stackoverflow.com/q/14529838
type: Question
tagged with: numpy
has title: How to group by in python but doing multiply calculations for same column
has comment: http://stackoverflow.com/comment/83915416
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/14529838
has comment: http://stackoverflow.com/comment/83911141

http://stackoverflow.com/q/48336473
has answer: http://stackoverflow.com/a/48337228
tagged with: python
score: -1
has title: _tkinter.TclError: invalid command name error
has comment: http://stackoverflow.com/comment/83691244
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83691463
upvote count: 0
has comment: http://stackoverflow.com/comment/83691225
has body: So i'm following a tutorial to the t on tkinter, using the python shell. All the imports work, but trying a few methods and properties on a ttk.Button object gives the above error, even though it's exactly like in the tutorial. Namely: The button has the variable 'button'. Checking the button's 'text' property throws the error using button['text'] And setting the button's text property viabutton.config(text = 'text') throws the error as well, as does checking config() on the root window. The initial code with imports, ending with the first error yielding line, is: &gt;&gt;&gt; from tkinter import * &gt;&gt;&gt; from tkinter import ttk &gt;&gt;&gt; root = Tk() &gt;&gt;&gt; button = ttk.Button(root, text = 'Button') &gt;&gt;&gt; button.pack() &gt;&gt;&gt; button['text'] Basically setting or getting the text property of the button or other ttk object throws an error. Here's the line with error: Traceback (most recent call last): File "&lt;pyshell#11&gt;", line 1, in &lt;module&gt; button['text'] File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1483, in cget return self.tk.call(self._w, 'cget', '-' + key) _tkinter.TclError: invalid command name ".!button" Well, actually, according to the tutorial that uses python 3 a Button does have an attribute text. Edit. I swapped the error message with the relevant one,
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83691402
type: UnansweredQuestion
tagged with: ttk

http://stackoverflow.com/a/48448077
has comment: http://stackoverflow.com/comment/83888776
has comment: http://stackoverflow.com/comment/83888538
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48447841
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48447841
has body: You don't actually need to write code for the normalization yourself - it comes ready with sklearn.preprocessing.scale. Here is an example from the docs: &gt;&gt;&gt; from sklearn import preprocessing &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; X_train = np.array([[ 1., -1., 2.], ... [ 2., 0., 0.], ... [ 0., 1., -1.]]) &gt;&gt;&gt; X_scaled = preprocessing.scale(X_train) &gt;&gt;&gt; X_scaled array([[ 0. ..., -1.22..., 1.33...], [ 1.22..., 0. ..., -0.26...], [-1.22..., 1.22..., -1.06...]]) When used with the default setting axis=0, the mormalization happens column-wise (i.e. for each column j, as in your equestion). As a result, it is easy to confirm that scaled data has zero mean and unit variance: &gt;&gt;&gt; X_scaled.mean(axis=0) array([ 0., 0., 0.]) &gt;&gt;&gt; X_scaled.std(axis=0) array([ 1., 1., 1.])
has comment: http://stackoverflow.com/comment/83888654
has comment: http://stackoverflow.com/comment/83888684
type: Answer

http://stackoverflow.com/q/48463050
score: 0
has title: How to convert a set of row data in to a dataframe in pandas
has answer: http://stackoverflow.com/a/48463335
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have the input dataset in the following format input data format Input data was generated by the following code snippet. for i in range (0,10): my_list = df1.iloc[i].split(",") for x in my_list: if x in Waterbodies: print(i,"Waterbodies") if x in Beaches: print(i,"Beaches") And I want them to be added to a dataframe like in the below format. output data format I tried several examples and neither didn't work.What should I do?
accepted answer: http://stackoverflow.com/a/48463335
tagged with: dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83850467
type: Comment
comment on: http://stackoverflow.com/a/48429908
score: 0
has text: I can't have `'Loading Data... '` as part of the the update message
type: AnswerComment

datetime
tags question: http://stackoverflow.com/q/48484805
tags question: http://stackoverflow.com/q/48449355
tags question: http://stackoverflow.com/q/48416511
tags question: http://stackoverflow.com/q/48351274
tags question: http://stackoverflow.com/q/48473602
tags question: http://stackoverflow.com/q/48419506
tags question: http://stackoverflow.com/q/48431868
tags question: http://stackoverflow.com/q/48408946
tags question: http://stackoverflow.com/q/48444373
tag name: datetime
tags question: http://stackoverflow.com/q/48476595
tags question: http://stackoverflow.com/q/48449196
tags question: http://stackoverflow.com/q/48392243
tags question: http://stackoverflow.com/q/48472546
tags question: http://stackoverflow.com/q/48387224
tags question: http://stackoverflow.com/q/48473794
tags question: http://stackoverflow.com/q/48461168
tags question: http://stackoverflow.com/q/48423601
tags question: http://stackoverflow.com/q/48351977
type: Tag
tags question: http://stackoverflow.com/q/48353031
tags question: http://stackoverflow.com/q/48416481
tags question: http://stackoverflow.com/q/48478879
tags question: http://stackoverflow.com/q/48351811
tags question: http://stackoverflow.com/q/48401012
tags question: http://stackoverflow.com/q/48345087
tags question: http://stackoverflow.com/q/48343192
tags question: http://stackoverflow.com/q/48447123
tags question: http://stackoverflow.com/q/48351223
tags question: http://stackoverflow.com/q/48455189
tags question: http://stackoverflow.com/q/48445776
tags question: http://stackoverflow.com/q/48340410
tags question: http://stackoverflow.com/q/48397567
tags question: http://stackoverflow.com/q/48401423
tags question: http://stackoverflow.com/q/48430972
tags question: http://stackoverflow.com/q/48442514
tags question: http://stackoverflow.com/q/48466263
tags question: http://stackoverflow.com/q/48444603
tags question: http://stackoverflow.com/q/48454918
tags question: http://stackoverflow.com/q/48447287
tags question: http://stackoverflow.com/q/48394364
tags question: http://stackoverflow.com/q/48385083
tags question: http://stackoverflow.com/q/48485583
tags question: http://stackoverflow.com/q/48354195
tags question: http://stackoverflow.com/q/48375425
tags question: http://stackoverflow.com/q/48460466
tags question: http://stackoverflow.com/q/48448240
tags question: http://stackoverflow.com/q/48436665

http://stackoverflow.com/q/48483949
has body: I want to create an object car using inner classes, this object car have attributes like number of seats, color, year, engine. The last attribute engine capacity will have another attributes like number of valves, type of fuel, kms by lts. so I am creating a class car first and then engine class: class car: def __init__(self, color, year, engine): self.color = color self.year = year self.engine = engine class engine: def __init__(lts, kms_by_lts, fuel_type, valves ): self.lts = lts self.fuel = fuel self.valves = valves self.kms_by_lts = kms_by_lts &gt;&gt; my_car = car('blue','2010','v6') &gt;&gt;&gt; my_car.engine 'v6' I want to access a class inside another class like as follow: &gt;&gt;&gt; my_car.v6.lts = 4 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: car instance has no attribute 'v6' Could help me with this issue. Regards I recreate the object as follow: class car: def __init__(self, color, year, engine): self.color = color self.year = year self.engine = engine() class engine: def __init__(lts, kms_by_lts, fuel_type, valves ): self.lts = lts self.fuel = fuel self.valves = valves self.kms_by_lts = kms_by_lts Having the following error &gt;&gt;&gt; my_car = car('blue','2010','v6') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in __init__ TypeError: 'str' object is not callable
has title: Python inner classes
has comment: http://stackoverflow.com/comment/83960723
tagged with: python
has comment: http://stackoverflow.com/comment/83960789
has comment: http://stackoverflow.com/comment/83960863
has comment: http://stackoverflow.com/comment/83960643
score: 0
has comment: http://stackoverflow.com/comment/83960752
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83960944
has comment: http://stackoverflow.com/comment/83960861
downvote count: 1
linked to: http://stackoverflow.com/q/20668910
has comment: http://stackoverflow.com/comment/83960995
has comment: http://stackoverflow.com/comment/83960762
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48484155

http://stackoverflow.com/a/48359445
answers question: http://stackoverflow.com/q/48357634
has body: Unfortunately I haven't found a way to overwrite specific rows in a CSV using the csv module; you'll have to write a new file (or overwrite the existing file, as I have below) with your new data. In the following code, I read the CSV into a list of the rows (lines), then you can modify each element as you see fit, then delete the CSV and write a new one with the same name and modified data in lines. I'm using the with() operators, because close() is done automatically. import os import csv filepathIn = 'PATH TO YOUR CSV' # First read the contents of your current file with open(filepathIn,'r') as f: lines = f.readlines() ## lines is now a list of each row in the CSV. Modify as needed # Remove the file and write a new one of the same name os.remove(filepathIn) with open(filepathIn,'w',newline='') as output: write = csv.writer(output) write.writerows(lines)
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48357634
score: 0

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/48351129
tags question: http://stackoverflow.com/q/48428337
tags question: http://stackoverflow.com/q/48442834
tags question: http://stackoverflow.com/q/48415382
type: Tag

http://stackoverflow.com/comment/84049061
type: Comment
has text: @Basj I added a database partition implementation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48473953

http://stackoverflow.com/a/48375058
accepted answer of: http://stackoverflow.com/q/48374825
score: 0
has body: Here is one way to collect the items. I have left the writing to a file as an exercise: Code: with open('test.csv') as f: reader = csv.reader(f) columns = next(reader) results = [] record = {} current_type = 0 items = [] for id_, type, value in reader: if current_type != type: if current_type: record['id_{}'.format(current_type)] = items items = [] current_type = type if id_ != record.get('id'): if record: results.append(record) record = dict(id=id_) items.append(value) if record: record['id_{}'.format(current_type)] = items results.append(record) print(results) Results: [ {'id': '4678367', 'id_1': ['1001'], 'id_2': ['1007', '1008']}, {'id': '5678945', 'id_1': ['9000'], 'id_2': ['8000']} ]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48374825
type: Answer

http://stackoverflow.com/q/48473110
upvote count: 2
answer count: 2
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48476924
has comment: http://stackoverflow.com/comment/83939923
has title: while using responce.css in scrapy it shows error invalid syntax
tagged with: scrapy
downvote count: 1
has body: Here is my code import scrapy class spider1(scrapy.Spider): name= 'Wikiipedia' start_urls = ['https://en.wikipedia.org/wiki/Battery_(electricity)'] def parsed(self, response): print response.css("h1#firstHeading::text").extract() When executed in command prompt it shows the following error print response.css("h1#firstHeading::text").extract() ^ SyntaxError: invalid syntax I don't know what i did wrong. Can anyone help me with this one?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50776934
tagged with: spyder
tagged with: python
tagged with: css
tagged with: web-crawler

http://stackoverflow.com/q/48427501
accepted answer: http://stackoverflow.com/a/48430121
has body: I have the code below which is based on this question here: Expandable and contracting frame in Tkinter from tkinter import * from tkinter import ttk class Example: def __init__(self, root): list_1 = ['item_1', 'item_2'] list_2 = ['a', 'b', 'c'] for item in list_1 : frame = Frame(root, width=500, height=22) frame.pack(side=TOP, anchor=W) frame.propagate(0) Label(frame, text=item).pack(side=LEFT, anchor=W) entry = Entry(frame, width=11) entry.pack(side=RIGHT, pady=2, anchor=E) var = IntVar() var.set(0) sub_frame = Frame(root, relief="sunken", width=400, height=22, borderwidth=1) toggle_btn = ttk.Checkbutton(frame, width=2, text='+', command=lambda: self.toggle(var, toggle_btn, sub_frame), variable=var, style='Toolbutton') toggle_btn.pack(side=LEFT, anchor=E) for item in list_2: Label(sub_frame, text=item).pack(side=TOP) def toggle(self, show, toggle_button, sub_frame): if bool(show.get()): sub_frame.pack(fill="x", expand=1) sub_frame.propagate(1) toggle_button.configure(text='-') else: sub_frame.forget() toggle_button.configure(text='+') def main(): root = Tk() open = Example(root) root.mainloop() if __name__ == '__main__': main() I want here to create two expandable frames from list_1 and fill each with labels from list_2. The two frames should then be expandable and collapsible to show and hide the items from list_2. The second frame functions correctly, but the first doesn't because it was overwritten by the second frame. So the code initially gives you this: If you click the '+' next to item_1, nothing happens. If you click the '+' next to item_2, this happens. By clicking on the '+' next to item_1, I want the sub_frame to be shown underneath item_1(between item_1 and item_2), just like clicking on the '+' next to item_2 shows the sub_frame underneath it. Any help on how to get both frames to work correctly? I've read about storing the frames created in a list, however I couldn't get this to work for me. Many thanks
tagged with: python
has comment: http://stackoverflow.com/comment/83847338
has answer: http://stackoverflow.com/a/48428037
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83845723
linked to: http://stackoverflow.com/q/10865116
linked to: http://stackoverflow.com/q/2295290
linked to: http://stackoverflow.com/q/13355233
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/83845655
favorite count: 0
linked to: http://stackoverflow.com/q/13141259
type: Question
has title: Tkinter Dynamic Frames that are Expandable and Collapsible
upvote count: 0
linked to: http://stackoverflow.com/q/3431676
answer count: 2
tagged with: tkinter
duplicate of: http://stackoverflow.com/q/3431676
possible better answer: http://stackoverflow.com/a/48428037
has answer: http://stackoverflow.com/a/48430121

http://stackoverflow.com/comment/83807856
type: AnswerComment
comment on: http://stackoverflow.com/a/48406107
has text: I've added `engine='python'` in `read_csv', check if it will work for you.
type: Comment
score: 0

http://stackoverflow.com/q/48391695
has comment: http://stackoverflow.com/comment/83771896
answer count: 0
has comment: http://stackoverflow.com/comment/83790324
has comment: http://stackoverflow.com/comment/83771939
tagged with: python-requests
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83771866
type: UnansweredQuestion
has body: Okay so I'm testing pythons request module with beautifulsoup4 &amp; wanted to create an if statement &amp; an else statement, my current code is - from bs4 import BeautifulSoup import requests import re for page_no in range(1,2365): source = requests.get('http://example.com/page={}'.format(page_no)).text soup = BeautifulSoup(source, 'lxml') profile = soup.find('div', {'class': 'title'}) for content in profile.find_all('a'): print(content.text.encode("utf-8")) this will currently go through the given amount of pages and scraped all a tag contents within a div class title, but I want to create some failsafes.. so if "Example text" in source: proceed with script example - //profile = soup.find('div', {'class': 'title'}) //for content in profile.find_all('a'): // print(content.text.encode("utf-8")) else: print "response does not contain Example text" now I understand this is clearly not how you produce such results but I'm just giving you a example of how i would like things to be.
tagged with: python
has comment: http://stackoverflow.com/comment/83771686
has title: Python requests if response contains string
has comment: http://stackoverflow.com/comment/83772023
score: 0

http://stackoverflow.com/a/48458907
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48442322
downvote count: 0
type: Answer
score: 2
has body: I had a problem like this when I didn't need the page header in other pages and I didn't want the margin between the top page and the first line in the second page. What I did is avoid using the external layout provided by Odoo and create a new paper format with no header nor footer: 150 0 0 And I wrote my report after the tag of <page>, defining my own header in order to be rendered once per record in the whole PDF. <page> I hope you get the idea, it requires some skills with xpath in order to remove the external layout, or, you can define a new report with this technique. Note that the only way to remove the space in the header and bottom is the margins of the page.
has comment: http://stackoverflow.com/comment/83911471
has comment: http://stackoverflow.com/comment/83923260
answers question: http://stackoverflow.com/q/48442322

http://stackoverflow.com/q/48485115
score: 0
has title: what is the difference expect and mean in the scipy.stats?
has body: according the definition of the expected value, it also refers to mean. But in scipy.stats.binom, they get different values. like this, import scipy.stats as st st.binom.mean(10, 0.3) ----&gt; 3.0 st.binom.expect(args=(10, 0.3)) ----&gt;3.0000000000000013 so that makes me confusing!! why?
has comment: http://stackoverflow.com/comment/83964919
tagged with: python
accepted answer: http://stackoverflow.com/a/48488777
linked to: http://stackoverflow.com/q/588004
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48488777
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/48485435
tagged with: statistics
possible better answer: http://stackoverflow.com/a/48485435

http://stackoverflow.com/a/48455659
has comment: http://stackoverflow.com/comment/83904310
score: 0
answers question: http://stackoverflow.com/q/48455469
has comment: http://stackoverflow.com/comment/83904267
has comment: http://stackoverflow.com/comment/83904778
has body: On this website it says to add this url pattern to your project: urlpatterns += patterns(”, (r’^static/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.STATIC_ROOT}),) I haven't used heroku before but IF I understand correctly, it needs a path to send all the collected static files to. Usually that's in the server's settings. But the website above mentions that heroku uses an app which doesn't support static files deployment, and that's why you need a url pattern to make it get the static files from their respective places. Also, read the entire tutorial first. They might mention your problem somewhere near the end of the tutorial in like a Notes section. Read the comments also if they exist.
has comment: http://stackoverflow.com/comment/83904525
type: Answer

http://stackoverflow.com/q/48402652
has answer: http://stackoverflow.com/a/48403144
type: UnansweredQuestion
tagged with: plot
score: 0
has body: I am creating a barplot using ax = lasso_output_df2.plot(kind='bar', title ="Spain Coefficient Variables [alpha_10]", figsize=(15, 10), legend=False, fontsize=12) ax.set_xticklabels(lasso_output_df2.Features) ax.set_axis_bgcolor('white') The df is created using pandas. How do I add a frame or outline to the actual chart itself ? I have tried the below: edgecolor = 'black' frameon=False ax.spines['top'].set_visible(True) ax.spine_color('black') Current plot. Desired Plot.
answer count: 1
tagged with: python
tagged with: frame
tagged with: outline
has title: Add a frame/outline to a plot using Python
type: Question

http://stackoverflow.com/comment/83944782
has text: Dhaval also it's not working in section because I have set the {%for%} in footer. html
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48475718
type: AnswerComment

http://stackoverflow.com/a/48393057
has comment: http://stackoverflow.com/comment/83774052
answers question: http://stackoverflow.com/q/48392998
score: 1
upvote count: 1
type: Answer
has body: You need to remove quotes between your cookies "_twitter_sess=BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCKnkoiBhAToMY3NyZl9p%250AZCIlYjBmNmQ0NmY5NTVmMmVkNTgwYjM2NTU0YzQ2NDY4NzA6B2lkIiUwYTg3%250ANzU1MmU3ZmY3ZWE3NjAyYzIwZmU5ZjkxZWQ5OQ%253D%253D--43822fe18903b3578a1f5deaeb232a8186b75e7d; personalization_id=v1_jQItTVsewWTebwVuukbh6g==; guest_id=v1%3A151667100176659384; external_referer=padhuUp37zjgzgv1mFWxJzx4vPNPpMnZ52M34anUtp0%3D|0|8e8t2xd8A2w%3D; ct0=6d7781aae304f30bb5d6d0d64fc34ffe; _ga=GA1.2.1441535218.1516671002; _gid=GA1.2.1585412472.1516671002;_gat=1"
downvote count: 0
has comment: http://stackoverflow.com/comment/83776082

http://stackoverflow.com/a/48375404
answers question: http://stackoverflow.com/q/48374558
has body: Below's a rough example that does what you describe using onkeypress() and onkeyrelease() in combination. Once you press 'Up' it will start counting whole seconds until you release that key. Then it will write to the screen the number of whole seconds the key was held: from turtle import Turtle, Screen FONT = ('Arial', 36, 'normal') def add_start(): global seconds print('pressed') if seconds &lt; 0: turtle.undo() # remove previous time seconds = 0 screen.ontimer(add, 1000) def add(): global seconds if seconds &gt;= 0: seconds += 1 screen.ontimer(add, 1000) def add_stop(): global seconds print('released') turtle.write(seconds, align='center', font=FONT) seconds = -1 screen = Screen() turtle = Turtle(visible=False) turtle.write(0, align='center', font=FONT) seconds = -1 screen.onkeypress(add_start, 'Up') screen.onkeyrelease(add_stop, 'Up') screen.listen() screen.mainloop() Here's the catch: you need to turn off key repeat at the operating system level on your system. For example, On my Mac, in System Preferences / Keyboard, I'd do: Otherwise the system will generate press and release events as part of standard key repeat.
type: Answer
score: 0

http://stackoverflow.com/comment/83947887
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48465795
has text: I will post a picture on Monday. But I should see slanted red lines in the centre figure.. Sort of like this ///

http://stackoverflow.com/q/48466263
accepted answer: http://stackoverflow.com/a/48466480
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48466480
score: 0
answer count: 1
type: Question
has title: Python Converting minute number to datetime
has body: df['minutes'] = [0, 360, 1000, 1439] I have a pandas df with a column called minutes that I would like to convert to datetime. The desired result would look like the following (or a similar datetime format): df['new_min'] = ["00:00","06:00","16:40","23:59"] This didn't seem to work quite the way I wanted it to. df['new_min']=pd.TimedeltaIndex(df['minutes'], unit='m')
tagged with: time
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/83926108

http://stackoverflow.com/comment/83931708
type: AnswerComment
comment on: http://stackoverflow.com/a/48468919
type: Comment
has text: This took me to a python prompt.
score: 0

http://stackoverflow.com/a/48414552
upvote count: 2
has comment: http://stackoverflow.com/comment/83819007
has comment: http://stackoverflow.com/comment/83818990
downvote count: 0
type: Answer
score: 2
has body: How about this: from bs4 import BeautifulSoup html= """ Details about item name goes here """ soup = BeautifulSoup(html, "lxml") text = soup.find('h1', attrs={"id":"itemTitle"}).text span = soup.find('span', attrs={"class":"g-hdn"}).text final_text = text[len(span):] print(final_text) This results in: item name goes here
answers question: http://stackoverflow.com/q/48414407

http://stackoverflow.com/comment/83672011
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48342955
has text: thank you, it helps but in this question it is always "name" which is the key, followed by several vals. Like [{key1: val1, val2, val3}, {key1: val4, val5, val6} But I have different keys so I cant run it by accessing 'name' (key1)... This is just a first comment, maybe after some thinking I can build something on it... as I am new, everything takes ages to understand and adopt :)
type: Comment

http://stackoverflow.com/a/48429736
has comment: http://stackoverflow.com/comment/83850894
has comment: http://stackoverflow.com/comment/83851100
has comment: http://stackoverflow.com/comment/83850806
has comment: http://stackoverflow.com/comment/83851077
has body: Make sure to close the files when finished with them. The writing may stay in the buffer until you do. on.close() off.close() To write immediately without closing, you can flush the buffers: on.flush() off.flush()
answers question: http://stackoverflow.com/q/48429518
type: Answer
has comment: http://stackoverflow.com/comment/83850945
score: 0
has comment: http://stackoverflow.com/comment/83850929

http://stackoverflow.com/a/48453311
answers question: http://stackoverflow.com/q/48452103
type: Answer
has body: I am very sorry, I solved this by myself. I overlooked the following: There is a typo: Instead of p_1.hbar_stack(status, y='categories', height=0.9, color='red', source=self.exports_source.data, legend=['Legende']) it needs to read: p_1.hbar_stack(status, y='categories', height=0.9, color='red', source=self.exports_source, legend=['Legende']) I.e. instead of referencing the ColumnDataSource Object self.exports_source I had been referencing the dictionary self.exports_source.data. Changing this showed the desired result and the graph was updating.
score: 0

pandas
tags question: http://stackoverflow.com/q/48466743
tags question: http://stackoverflow.com/q/48454818
tags question: http://stackoverflow.com/q/48484475
tags question: http://stackoverflow.com/q/48434330
tags question: http://stackoverflow.com/q/48390128
tags question: http://stackoverflow.com/q/48373226
tags question: http://stackoverflow.com/q/48376000
tags question: http://stackoverflow.com/q/48403658
tags question: http://stackoverflow.com/q/48373088
tags question: http://stackoverflow.com/q/48454189
tags question: http://stackoverflow.com/q/48470053
tags question: http://stackoverflow.com/q/48447841
tags question: http://stackoverflow.com/q/48373687
tags question: http://stackoverflow.com/q/48442561
tags question: http://stackoverflow.com/q/48479558
tags question: http://stackoverflow.com/q/48372735
tags question: http://stackoverflow.com/q/48365443
tags question: http://stackoverflow.com/q/48369613
tags question: http://stackoverflow.com/q/48461969
tags question: http://stackoverflow.com/q/48363338
tags question: http://stackoverflow.com/q/48334347
tags question: http://stackoverflow.com/q/48339263
tags question: http://stackoverflow.com/q/48449087
tags question: http://stackoverflow.com/q/48468146
tags question: http://stackoverflow.com/q/48430972
tags question: http://stackoverflow.com/q/48334572
tags question: http://stackoverflow.com/q/48433275
tags question: http://stackoverflow.com/q/48463174
tags question: http://stackoverflow.com/q/48463868
tags question: http://stackoverflow.com/q/48428100
tags question: http://stackoverflow.com/q/48404120
tags question: http://stackoverflow.com/q/48462951
tags question: http://stackoverflow.com/q/48411751
tags question: http://stackoverflow.com/q/48336175
tags question: http://stackoverflow.com/q/48411570
tags question: http://stackoverflow.com/q/48442514
tags question: http://stackoverflow.com/q/48448647
tags question: http://stackoverflow.com/q/48445505
tags question: http://stackoverflow.com/q/48382219
tags question: http://stackoverflow.com/q/48387318
tags question: http://stackoverflow.com/q/48483560
tags question: http://stackoverflow.com/q/48386883
tags question: http://stackoverflow.com/q/48382757
tags question: http://stackoverflow.com/q/48430711
tags question: http://stackoverflow.com/q/48468660
tags question: http://stackoverflow.com/q/48452274
tags question: http://stackoverflow.com/q/48405608
tags question: http://stackoverflow.com/q/48448011
tags question: http://stackoverflow.com/q/48344566
tags question: http://stackoverflow.com/q/48347727
tags question: http://stackoverflow.com/q/48370638
tags question: http://stackoverflow.com/q/48400491
tags question: http://stackoverflow.com/q/48395966
tags question: http://stackoverflow.com/q/48454720
tags question: http://stackoverflow.com/q/48447812
tags question: http://stackoverflow.com/q/48472156
tags question: http://stackoverflow.com/q/48435538
tags question: http://stackoverflow.com/q/48362692
tags question: http://stackoverflow.com/q/48461829
tags question: http://stackoverflow.com/q/48378524
tags question: http://stackoverflow.com/q/48385244
tags question: http://stackoverflow.com/q/48444603
tags question: http://stackoverflow.com/q/48467410
tags question: http://stackoverflow.com/q/48454918
tags question: http://stackoverflow.com/q/48454604
tags question: http://stackoverflow.com/q/48428173
tags question: http://stackoverflow.com/q/48352482
tags question: http://stackoverflow.com/q/48454484
tags question: http://stackoverflow.com/q/48456959
tags question: http://stackoverflow.com/q/48404294
tags question: http://stackoverflow.com/q/48474087
tags question: http://stackoverflow.com/q/48475687
tags question: http://stackoverflow.com/q/48422269
tags question: http://stackoverflow.com/q/48397171
tags question: http://stackoverflow.com/q/48409682
tags question: http://stackoverflow.com/q/48394364
tags question: http://stackoverflow.com/q/48425964
tags question: http://stackoverflow.com/q/48364407
tags question: http://stackoverflow.com/q/48359692
tags question: http://stackoverflow.com/q/48360915

http://stackoverflow.com/comment/83687668
score: 0
comment on: http://stackoverflow.com/q/48348803
has text: Could you show how `a` and `h` look like and what is the expected output?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83767672
has text: The `csrftoken` cookie appears is missing. Are you using JavaScript to log in or a regular form submit? Are you making a GET request to the same `LoginView` before you make the POST request?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48389548
score: 0

http://stackoverflow.com/a/48389446
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48389384
has body: Have you tried self.some_prop()? Because it works. But also self.__class__.some_prop.__get__(self, self.__class__) if you just want to do it differently. Besides that, you are aware that __getattr__ won't be called for a reference for instance.some_prop, right? Since the descriptor exists, __getattr__ is not called. (Also, that is why it works). If you need to intercept the references for instance.some_prop itself, you will need to implement __getattribute__ instead - that is unconditionally called for all your attribute references. In that case, I'd recommend simply call super().__getattribute__ unconditionally, and just check afterwards if the attribute was some_prop. If not, just return the original value.
answers question: http://stackoverflow.com/q/48389384
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48411495
type: UnansweredQuestion
tagged with: python
has body: I am trying to make a simple program that closes a specific folder every time it gets opened to deny access to said folder. I've tried using VBScript , and the codes I was given worked at first, but they failed after some circumstances (like trying to open the specific folder a lot of times in quick succession, or sometimes even after closing an unrelated folder). The folder I'm trying to close is C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
has comment: http://stackoverflow.com/comment/83813164
has comment: http://stackoverflow.com/comment/83812834
has comment: http://stackoverflow.com/comment/83812955
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83812812
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83812931
has title: How to close a specific folder with Python

http://stackoverflow.com/q/48437673
upvote count: 0
has body: I have a dictionary where each key has a list as value, i.e. my_dict={"k":[], "kr":[]} for i in range (10): my_dict['k'].append(rand.uniform(12,60)) my_dict['kr'].append(rand.uniform(0.1,.3)) How can I access the first value of the lists corresponding to 'k' and 'kr'?
tagged with: list
has answer: http://stackoverflow.com/a/48437777
possible better answer: http://stackoverflow.com/a/48437777
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48437800
has comment: http://stackoverflow.com/comment/83866594
answer count: 2
has comment: http://stackoverflow.com/comment/83866379
tagged with: python
score: -1
has title: How do I access the first values of lists contained in a dictionary?
tagged with: dictionary
has answer: http://stackoverflow.com/a/48437800
type: AnsweredQuestion

http://stackoverflow.com/q/48457948
answer count: 2
tagged with: frame-rate
score: 1
has answer: http://stackoverflow.com/a/48459143
downvote count: 0
has comment: http://stackoverflow.com/comment/83911099
has comment: http://stackoverflow.com/comment/83928097
has comment: http://stackoverflow.com/comment/83910630
has comment: http://stackoverflow.com/comment/83910414
has comment: http://stackoverflow.com/comment/83909070
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83909610
has comment: http://stackoverflow.com/comment/83963023
has comment: http://stackoverflow.com/comment/83937289
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83910769
has comment: http://stackoverflow.com/comment/83910634
has answer: http://stackoverflow.com/a/67667486
upvote count: 1
tagged with: python
has title: Getting very high fps for video stream captured and stored using opencv
has body: I've written a small python code, which captures video stream from the webcam, and writes it into an output file. I've put a sleep of 50 ms, and specified a fps of 20.0 in the VideoWriter as following: #!/usr/bin/python import cv2 from PIL import Image import threading from http.server import BaseHTTPRequestHandler,HTTPServer from socketserver import ThreadingMixIn from io import StringIO,BytesIO import time import datetime capture=None out=None class CamHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path.endswith('.mjpg'): self.send_response(200) self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') self.end_headers() while True: try: rc,img = capture.read() if not rc: continue #Get the timestamp on the frame timestamp = datetime.datetime.now() ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p") cv2.putText(img, ts, (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) #Store the frame into the output file out.write(img) #Some processing before sending the frame to webserver imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) jpg = Image.fromarray(imgRGB) tmpFile = BytesIO() jpg.save(tmpFile,'JPEG') self.wfile.write("--jpgboundary".encode()) self.send_header('Content-type','image/jpeg') self.send_header('Content-length',str(tmpFile.getbuffer().nbytes)) self.end_headers() jpg.save(self.wfile,'JPEG') time.sleep(0.05) except KeyboardInterrupt: break return if self.path.endswith('.html'): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write('&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;'.encode()) self.wfile.write('&lt;img src="http://127.0.0.1:8080/cam.mjpg"/&gt;'.encode()) self.wfile.write('&lt;/body&gt;&lt;/html&gt;'.encode()) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def main(): global capture global out capture = cv2.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv2.Vid…
has comment: http://stackoverflow.com/comment/83909119
tagged with: opencv
tagged with: video
has comment: http://stackoverflow.com/comment/83910356

http://stackoverflow.com/comment/83719703
score: 0
has text: You'd probably have to write that yourself.The reason is that ISO codes have nothing to do with the `$` symbol.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48366469

http://stackoverflow.com/comment/84052389
score: 0
type: AnswerComment
has text: @Elazar: I think you are confusing likely readers more than helping by attempting to draw the similarity between a binding in Python and any static declaration in any other language. The code being evaluated is either in a function/method definition (which is a local scope, possibly nested) or it's in global scope. The namespaces searched are either Local (and possibly Enclosing) or just Global. It's really that simple.
comment on: http://stackoverflow.com/a/48453709
type: Comment

http://stackoverflow.com/q/48446236
tagged with: python
tagged with: gnuradio
tagged with: software-defined-radio
has answer: http://stackoverflow.com/a/48478185
tagged with: pyqt
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83926222
tagged with: gnuradio-companion
upvote count: 1
has title: GNU Radio: Some custom code in he middle of two blocks in GRC flowgraphs
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83890604
has comment: http://stackoverflow.com/comment/83923134
type: UnansweredQuestion
score: 1
has body: I need to apply a math formula (e.g. take a square root) to every sample (of 64 element vector) in the data stream coming out from a GRC signal source block (e.g.Complex to Mag Phase block in the attached GRC flowgraph) using Python code, just before that stream gets passed on to some other block down the stream (e.g. QT GUI Time Sink in the attached GRC flowgraph) I will be applying phase unwrapping to the 64 sample phase vector before it is displayed to time sink.

http://stackoverflow.com/comment/83718814
type: Comment
has text: I think the error is raised by Ruby's regex engine. And Python probably uses a different engine. I don't know Python but it certainly can check whether a string is valid UTF-8.
score: 0
comment on: http://stackoverflow.com/q/48365144
type: QuestionComment

http://stackoverflow.com/a/48338875
downvote count: 1
has comment: http://stackoverflow.com/comment/83663249
has body: Here it is, In [38]: a = {'a':1,'b':2,'c':3} In [39]: {j:i for i,j in a.items()} Out[39]: {1: 'a', 2: 'b', 3: 'c'} Or In [40]: dict(zip(a.values(),a.keys())) Out[40]: {1: 'a', 2: 'b', 3: 'c'}
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48338816
upvote count: 1

http://stackoverflow.com/a/48383366
accepted answer of: http://stackoverflow.com/q/48381351
type: AcceptedAnswer
downvote count: 0
has body: To perform this task you can use QTextDocument, to set the format we use QTextCharFormat() where you must set a font. doc = QTextDocument() cursor = QTextCursor(doc) fm = QTextCharFormat() font = painter.font() font.setBold(True) font.setUnderline(True) fm.setFont(font) # set QFont cursor.insertText(text1, fm) # insert text with new format. # establish new format for example: # font.setItalic(True) # font.setBold(True) cursor.insertText(text1, fm) painter.translate(80, 290) doc.drawContents(painter) Example: if __name__ == '__main__': app = QApplication(sys.argv) img = QImage(640, 480, QImage.Format_RGB32); img.fill(Qt.white); text1, text2 ="Stack Overflow".split() painter = QPainter(img); doc = QTextDocument() cursor = QTextCursor(doc) fm = QTextCharFormat() font = painter.font() font.setItalic(True) font.setUnderline(True) fm.setFont(font) cursor.insertText(text1, fm) font.setItalic(True) font.setBold(True) font.setUnderline(False) fm.setFont(font) cursor.insertText(text2, fm) painter.translate(80, 290) doc.drawContents(painter) painter.end(); img.save("text.png") Output: You can also use html in QTextDocument: if __name__ == '__main__': app = QApplication(sys.argv) img = QImage(640, 480, QImage.Format_RGB32); img.fill(Qt.white); text1, text2 ="Stack Overflow".split() painter = QPainter(img); doc = QTextDocument() cursor = QTextCursor(doc) cursor.insertHtml("&lt;i&gt;&lt;u&gt;{first}&lt;/u&gt;&lt;/i&gt;&lt;b&gt;&lt;i&gt;{second}&lt;b&gt;&lt;/i&gt;".format(first=text1, second=text2)) painter.translate(80, 290) doc.drawContents(painter) painter.end(); img.save("text.png")
upvote count: 1
answers question: http://stackoverflow.com/q/48381351
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83835299

http://stackoverflow.com/q/48408230
tagged with: rest
has body: In my application, I use a modified User model with 3 more field that I need. from django.contrib.auth.models import AbstractUser from django.db import models import ldapdb.models class User(AbstractUser): cotisant = models.BooleanField(default=False) nbSessions = models.IntegerField(default=0) tel = models.CharField(max_length=20, default="") I want people to be able to change their accounts settings, (like their password, email, tel,...). To do so I have a serializer like this : from rest_framework import serializers from django.contrib.auth.hashers import make_password from coreapp.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'cotisant', 'tel') extra_kwargs = { # Allow to set pwd, but disallow getting the hash from database 'password': {'write_only': True} } def validate_password(self, value: str): return make_password(value) And a view like this : class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScopeOrCreate,) lookup_field = 'username' def get_queryset(self): current_user = self.request.user if current_user.is_staff: user_set = User.objects.all() else: user_set = User.objects.filter(username=current_user.username) query = self.request.query_params.get('q', None) if not query: return user_set return user_set.filter( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) (This allow access to a user only to himself, unless he is staff) The problem is, to update nbSessions parameter, the user have to pay something on one of my apps. How can I allow the app to set the parameter, but disallow user to update it directly ? NOTE : I have other apps who use Password Credential Flow and are client side, so someone can get an app token through it.
tagged with: python
has answer: http://stackoverflow.com/a/48490750
type: Question
upvote count: 4
answer count: 2
tagged with: oauth
possible better answer: http://stackoverflow.com/a/48565686
downvote count: 0
has answer: http://stackoverflow.com/a/48565686
tagged with: django
has comment: http://stackoverflow.com/comment/83937712
accepted answer: http://stackoverflow.com/a/48490750
tagged with: django-rest-framework
has title: DRF - How to Authentify an application with Oauth Toolkit?
score: 4
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/48369222
upvote count: 4
type: AnsweredQuestion
has body: I need to convert int list into a byte string but I don't know how. I can't use bytes() because the values are too large. bytes([152710136, 76354857, 38177353, 2252736081, 1126368238]) I get this error: ValueError: bytes must be in range(0, 256) The expected value is: b'\xc4\xb7\x86\x17\xcd'
answer count: 2
has comment: http://stackoverflow.com/comment/83725099
has comment: http://stackoverflow.com/comment/83725221
score: 1
downvote count: 3
possible better answer: http://stackoverflow.com/a/65544173
has comment: http://stackoverflow.com/comment/83725106
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48369478
has answer: http://stackoverflow.com/a/65544173
tagged with: byte
has answer: http://stackoverflow.com/a/48369478
has title: converting large int list to byte string python
tagged with: python
tagged with: int

http://stackoverflow.com/q/48481606
possible better answer: http://stackoverflow.com/a/48481674
score: -1
tagged with: dictionary
has answer: http://stackoverflow.com/a/48481677
has comment: http://stackoverflow.com/comment/83956192
has title: Extract value from list add to dictionary
accepted answer: http://stackoverflow.com/a/48481658
answer count: 4
type: AnsweredQuestion
tagged with: list
has body: I have a list of lists such as pa_l = [[ABU, XXXXX, 0],[AZE, CCCCC,0]]. This pa_l contains 243 lists. iso_pa is a list with only country codes, such as: ABU and AZE (plus others) I need to create a dictionary all_countries = {} where each country code has its name. For this I have created the following code: for i in iso_pa: if i not in all_countries.keys(): all_countries[i] = pa_l[i][1] But this is not working. I would be pleased if someone could help me.
has comment: http://stackoverflow.com/comment/83956212
has answer: http://stackoverflow.com/a/48481687
downvote count: 1
has answer: http://stackoverflow.com/a/48481658
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83956221
tagged with: python-3.x
upvote count: 0
has comment: http://stackoverflow.com/comment/83956211
has comment: http://stackoverflow.com/comment/83956515
has answer: http://stackoverflow.com/a/48481674
tagged with: python

http://stackoverflow.com/q/48393236
type: Question
has body: I'm trying to create a program that asks if there was school that day and if so, subtracts that from the total, (86 days left as of 1-22-18). It works, but the program ends after one subtraction, so my question is, is there any way for it to continue running and update itself, or maybe ask the user again in 24 hours (no clue how)? Python 3.4.4 Windows 10 import time localtime = time.asctime(time.localtime(time.time())) day = localtime[0:3] check = 0 daysLeft = 87 #As of 1-22-18 daysOfTheWeek = ["Mon", "Tue", "Wed", "Thu", "Fri"] yesPossibilities = ["yes", "y", "yeah"] print ("Did you have school today?") schoolToday = input().lower() if schoolToday in yesPossibilities: if day in daysOfTheWeek: daysLeft -= 1 print ("There are", daysLeft, "days of school left!")
tagged with: python
has comment: http://stackoverflow.com/comment/83774438
score: -1
type: AnsweredQuestion
has title: Using python to track and constantly update days left of school
upvote count: 0
possible better answer: http://stackoverflow.com/a/48393304
answer count: 2
accepted answer: http://stackoverflow.com/a/48393356
tagged with: countdown
has answer: http://stackoverflow.com/a/48393304
has answer: http://stackoverflow.com/a/48393356
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83903145
comment on: http://stackoverflow.com/q/48438000
score: 0
has text: @JeffC Trid but I can’t log in StackOverFlow on PC.So I input my code and get a screenshot to show the error
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84071945
score: 0
type: AnswerComment
has text: @Basj SQLite engine could [handle this well by itself](https://www.sqlite.org/wal.html).
comment on: http://stackoverflow.com/a/48473953
type: Comment

avro
type: Tag
tags question: http://stackoverflow.com/q/48442534
tag name: avro

http://stackoverflow.com/comment/83753435
score: 0
comment on: http://stackoverflow.com/q/48383082
type: Comment
type: QuestionComment
has text: Which of the two words is confusing? Provide an explanation as to the reason. Furnish a justification for the requirement. What are you writing that cares which methods are decorated?

http://stackoverflow.com/comment/83940430
comment on: http://stackoverflow.com/q/48473357
type: Comment
type: QuestionComment
has text: thanks for the quick reply @jezrael
score: 0

http://stackoverflow.com/q/48487346
type: Question
linked to: http://stackoverflow.com/q/46768028
linked to: http://stackoverflow.com/q/24897681
has body: I'm having a 2D grid of points where each of the points have a corresponding label, which is in the range [0.0, 5.0]. Now I want to do the following: Plot all points in the grid and color them according to their label. However, I don't want to do this using a scatter plot. I've tried to do it with a contourf and pcolormesh plot: import matplotlib.pyplot as plt np.random.seed(1234) x = np.linspace(-1.0, 1.0, num=5) xx, yy = np.meshgrid(x, x) z = np.random.randint(low=0, high=6, size=xx.shape) levels = np.arange(0, 6) fig, axes = plt.subplots(nrows=2, ncols=2) axes[0, 0].contourf(xx, yy, z) axes[0, 1].contour(xx, yy, z, colors='k') axes[1, 0].scatter(xx, yy, marker='.', c=z) axes[1, 1].pcolormesh(xx, yy, z) plt.show() How should I specify the levels of the contourf plot such that I get contour lines separating the labels. (Similar to the pcolormesh plot) Additionally, how can I fix the color for every label, i.e label 4 should always have color red? EDIT: This is an example of a contourf plot which produces too many coloured areas: Actually, there are only two labels in the grid. However, at the border between the two areas, several additional contour lines are drawn. For the example above, there should be a single contour line separating the two areas (cyan and blue) I appreciate any help.
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83967652
tagged with: python
accepted answer: http://stackoverflow.com/a/48487992
tagged with: numpy
has comment: http://stackoverflow.com/comment/83967771
has answer: http://stackoverflow.com/a/48487886
has title: Filled contour using class labels
has answer: http://stackoverflow.com/a/48487992
tagged with: contour
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/12487060
possible better answer: http://stackoverflow.com/a/48487886
favorite count: 0

http://stackoverflow.com/a/48345001
has body: The error is coming from the serializer validation, which is called before the create method is called. Therefore, the changes to the create method are not making a difference. You can fix this by calling out that the user field is not required in the serializer. This will look like: from rest_framework import serializers class WaitercallCreateSerializer(serializers.ModelSerializer): user = serializers.JSONField(required=False) class Meta: model = Waitercall fields = ('order', 'user', 'done', 'type_of_call') read_only_fields = ('user', 'done')
score: 4
has comment: http://stackoverflow.com/comment/83676843
downvote count: 0
answers question: http://stackoverflow.com/q/48343941
type: Answer
upvote count: 4

http://stackoverflow.com/q/48354341
has answer: http://stackoverflow.com/a/48354384
accepted answer: http://stackoverflow.com/a/48354384
tagged with: python
type: AnsweredQuestion
has body: I'm using ChainMap method for dictionary data and I tried to save(dumps) as a JSON file but it didn't work, and the message is that "TypeError: Object of type 'ChainMap' is not JSON serializable" Example: t = [ChainMap({'a': 'ITT002', 'b': {'c': '2', 'd': '2', 'e': '2'}, 'f': '2'}, {'g': {'h1': {'i': '22', 'j': '2', 'k': '2', 'l': '2', 'n': '2'}}})] if I have a data t, is there any ways to save in a JSON file? Have a nice day Stack brothers!
downvote count: 0
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has title: How do I remove ChainMap method to save as JSON file?
favorite count: 0
type: Question

http://stackoverflow.com/a/48432878
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48431366
has body: You don't need separate heads and tail counters. Just use a variable to hold the previous element of the list, and compare the current element to it. If it's the same, increment the counter. If it's different, append the counter to the result list and reset the counter. After the loop, append the final counter. Also, if True: ... elif False: is nonsense. The True branch will always be taken. I guess you meant if i == True:. Or maybe if i == heads: (you never actually use the heads and tails variables). import numpy as np def run_lengths(n,p): tosses= np.random.choice(([True, False ]),p=[p,1-p], size=n) last_toss = tosses[0] counter = 1 runlist = [] for toss in tosses[1:]: if toss == last_toss: counter += 1 else: runlist.append(counter) counter = 1 last_toss = toss runlist.append(counter) print(runlist) print(tosses) run_lengths(15, .5) DEMO

http://stackoverflow.com/comment/83725949
score: 0
type: Comment
type: QuestionComment
has text: The data given to me is in string format. I did consider whether the format was causing an issue with the search.
comment on: http://stackoverflow.com/q/48369561

http://stackoverflow.com/comment/83714993
score: 0
has text: With many rows and few columns a `csc` `intptr` is smaller. Conversely for `csr`.
comment on: http://stackoverflow.com/q/48363953
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83711933
has text: This does work. Do you mind explaining your code to me as I am very new to regex.
comment on: http://stackoverflow.com/a/48362474
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83881762
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48445050
has text: Welcome, It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].

http://stackoverflow.com/q/48401560
linked to: http://stackoverflow.com/q/2953834
has comment: http://stackoverflow.com/comment/83791303
has comment: http://stackoverflow.com/comment/83792578
downvote count: 1
has comment: http://stackoverflow.com/comment/83797581
duplicate of: http://stackoverflow.com/q/12201928
favorite count: 0
has body: I cannot open a file on Jupyter Notebook on Windows. I tried all the advices in several posts on StackOverFlow (including this very complete one: Windows path in python) My code is this one: today_date = date.today() path2file = 'D:/Users/XXX123/My_folder/Project/Sub_folder/Relevés/audit/Forms_'+'{:%Y%m%d}'.format(today_date)+'.csv' print(path2file) pd.read_csv(os.path.normpath(path2file)) and I got this error message: --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) &lt;ipython-input-14-01089ab15706&gt; in &lt;module&gt;() 4 print(path2file) 5 ----&gt; 6 pd.read_csv(os.path.normpath(path2file)) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 653 skip_blank_lines=skip_blank_lines) 654 --&gt; 655 return _read(filepath_or_buffer, kwds) 656 657 parser_f.__name__ = name ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 403 404 # Create the parser. --&gt; 405 parser = TextFileReader(filepath_or_buffer, **kwds) 406 407 if chunksize or iterator: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 762 self.options['has_index_names'] = kwds['has_index_names'] 763 --&gt; 764 self._make_engi…
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/3409381
has title: File path with Python and Windows on Jupyter Notebook
type: UnansweredQuestion
tagged with: windows
linked to: http://stackoverflow.com/q/12201928
has answer: http://stackoverflow.com/a/51265238
tagged with: python
has comment: http://stackoverflow.com/comment/83792644
tagged with: jupyter-notebook
answer count: 2
has comment: http://stackoverflow.com/comment/83791318
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/48412891

http://stackoverflow.com/q/48414190
has answer: http://stackoverflow.com/a/48420761
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83818282
has body: I have 2 lists list_a = [1, 1, 2, 2, 4, 5] list_b = ['good', 'bad', 'worst', 'cheap', 'waste', 'waste1'] I am trying to write a python script and my mapping element in list_a with element in list_b and if someone inputs value 1 all the related values should populate. Eg if I enter 1 as input parameter the output should be good bad if I enter 2 as input parameter output should be worst cheap I tried python dictionaries but dictionary is not allowing duplicate keys. Is there is a way to achieve this in Python?
has comment: http://stackoverflow.com/comment/83818278
tagged with: list
has title: Python Dictionary duplicates
answer count: 2
has comment: http://stackoverflow.com/comment/83818320
has answer: http://stackoverflow.com/a/48414234
has comment: http://stackoverflow.com/comment/83818350
favorite count: 0
score: -1
type: Question

http://stackoverflow.com/q/48457134
accepted answer: http://stackoverflow.com/a/48457504
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48457504
tagged with: django-models
favorite count: 0
type: Question
has body: I have a database in mysql and I am setting up a django project. I have some entities with many-to-many relations, which are handled through association tables. With django, I have understood that I can use ManyToMany entity to achieve many-to-many relations BUT how do I do when the association table holds more information besides just the many-to-many relation? See the example below. CREATE TABLE `products` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` char(150) DEFAULT NULL ...) CREATE TABLE `pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `filename` char(100) NOT NULL ... ) CREATE TABLE `products_pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `fk_products_id` int(11) unsigned NOT NULL, `fk_pictures_id` int(11) unsigned NOT NULL, `priority` tinyint(4) unsigned DEFAULT NULL, `relation` varchar(25) DEFAULT 'same product family' ... )
answer count: 1
downvote count: 0
tagged with: django
has title: Django and ManyToMany fields
upvote count: 1
tagged with: python
score: 1

http://stackoverflow.com/comment/83797254
has text: actually, I still did decide the code I will write which is why I am asking how to do it.However, I think it might be something like this code :
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48402107

http://stackoverflow.com/q/48415920
has comment: http://stackoverflow.com/comment/83821464
has comment: http://stackoverflow.com/comment/83821552
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48416063
tagged with: python
has body: We are having some issue here. There are two python files parent and child in same folder. I want to reuse the function("sum") of parent in child, instead of copying the same function("sum") into child. Please refer the image below. child.py def add(a,b): sum(a,b) parent.py import child def sum(a,b): print(a+b) def main(): child.add(1,2) # Prints 3
downvote count: 1
has answer: http://stackoverflow.com/a/48415953
has title: How to reuse functions in python
tagged with: oop
answer count: 3
has comment: http://stackoverflow.com/comment/83821460
score: 1
has answer: http://stackoverflow.com/a/48415964

http://stackoverflow.com/q/48453769
has comment: http://stackoverflow.com/comment/83900947
downvote count: 1
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
has answer: http://stackoverflow.com/a/48454102
has comment: http://stackoverflow.com/comment/83901714
type: Question
tagged with: if-statement
answer count: 5
has comment: http://stackoverflow.com/comment/83900908
accepted answer: http://stackoverflow.com/a/48453911
duplicate of: http://stackoverflow.com/q/15112125
possible better answer: http://stackoverflow.com/a/48453790
tagged with: python
has comment: http://stackoverflow.com/comment/83900894
has answer: http://stackoverflow.com/a/48453811
has answer: http://stackoverflow.com/a/48453911
has answer: http://stackoverflow.com/a/48453790
has comment: http://stackoverflow.com/comment/83901229
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83900557
has title: How do I use or in Python 3.6
has answer: http://stackoverflow.com/a/48453835
has comment: http://stackoverflow.com/comment/83900993
upvote count: 1
has body: So I'm making a calculator in python 3.6, but there is an error message and my code is not working. if(op == "+"): print(add(num1, num2)) if(op == "-"): print(sub(num1, num2)) if(op == "*"): print(mul(num1, num2)) if(op == "/"): print(dev(num1, num2)) if(op == "stop"): rng = "f" elif(op != "+", or "-", or "*", or "/", or "stop"): print("Please enter a valid operation!") When I run the code, it gives me an error saying invalid syntax and highlights the "or" part in the string. Error Picture. How do I fix this?

http://stackoverflow.com/a/48373867
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: When Django processes a template, it treats the html file as a string, and interpolates the values of variables in it prior to returning a result. This means that the values stay as they were in the time the template was rendered. There are many approaches to the thing you want to achieve, the simplest one is to take an AJAX approach and continuously poll for new values.
has comment: http://stackoverflow.com/comment/83735990
answers question: http://stackoverflow.com/q/48373841
type: Answer
accepted answer of: http://stackoverflow.com/q/48373841
score: 1

http://stackoverflow.com/comment/83858345
comment on: http://stackoverflow.com/a/48427689
score: 0
has text: Also could you do me a favor and accept my solution to your problem? Thanks!
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48458322
downvote count: 0
accepted answer: http://stackoverflow.com/a/48458411
answer count: 1
tagged with: flask
has body: What I want is to share a variable between 2 flask requests! The variable is a large pandas dataframe. I have read in this answer that i need to use g from flask global ! basically, I have 2 views function like this : from flask import g @home.route('/save', methods=['GET']) def save_ressource(): an_object = {'key': 'value'} setattr(g, 'an_object', an_object) return 'sucees' @home.route('/read', methods=['GET']) def read_ressource(): an_object = getattr(g, 'an_object', None) if an_object: return 'sucess' else: return 'failure' but this always return failure ie : None and when i read in the documentation here it's said that : Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request. My question is how to solve this problem? As said in the docs how can I bound application context? Should I use sessions instead? Any helps will be appreciate
linked to: http://stackoverflow.com/q/30514749
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83909822
duplicate of: http://stackoverflow.com/q/30514749
has title: Unable to share variables between 2 flasks requests in a view function
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/46021694
tagged with: global
type: Question
duplicate of: http://stackoverflow.com/q/32815451
has answer: http://stackoverflow.com/a/48458411

http://stackoverflow.com/a/59197411
upvote count: 9
has body: If you have a pandas series with object datatype, you can first convert it into a DateTime series using pd.to_datetime() df[col] = pd.to_datetime(your_series, format = '%Y-%m-%d %H:%M:%S', errors ='coerce') Check if it is timezone aware or not by using series.dt.tz df[col].dt.tz If it's not timezone aware, we should make it timezone aware by using series.dt.tz_localize(). Also, do read about the ambiguous and nonexistent parameters of this function df[col] = your_series[col].dt.tz_localize('UTC') Now convert this series into the required timezone by series.dt.tz_convert() df[col] = your_series[col].dt.tz_convert('US/Eastern') The above method will take care of daylight savings time. If you want to check more timezones you can pip install pytz and import pytz pytz.common_timezones
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48416511
score: 9

http://stackoverflow.com/comment/83813993
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48411539
score: 0
has text: @juanpa.arrivillaga Yes! How does the function know that if I type str(100) to return "100". How does it figure it out?

http://stackoverflow.com/q/48454263
tagged with: python
tagged with: image
has title: get and display one image in a stack of 3 channel images, in a numpy array
answer count: 2
type: UnansweredQuestion
score: 1
has body: I have a stack of images. The first one on the stack looks like this: import dicom as dc dcm = dc.read_file('full_stack.dcm') dcm = dcm.pixel_array print type(dcm) print dcm.shape This gives me &lt;type 'numpy.ndarray'&gt; (3, 180, 480, 640) So it looks like there are: 3 channels 180 images width is 480 height is 640 Great. My goal is to extract an image in the stack. Then, I want to display that image. Sounds simple enough. This is my strategy. I would love any ideas/feedback on this: 1) Get one image. Use basic slicing to get the 10th image on the stack dcm1 = dcm[0:, 10:11] dcm1.shape (3, 1, 480, 640) 2) To use plt.imshow to actually plot this in pyplot, we need this shape: (r, c, channels). So I guess beat the image up by brute force. dcm2 = np.squeeze(dcm1, axis=1) # throw away the '1'...this makes me nervous print 'threw away the "1": ', dcm2.shape dcm3 = np.swapaxes(dcm2, 0,2) print 'swapped the first and last dim: ', dcm3.shape dcm4 = np.swapaxes(dcm3, 0,1) print 'swapped the first and second dim:', dcm4.shape Now, I've mangled this poor image as such: threw away the "1": (3, 480, 640) swapped the first and last dim: (640, 480, 3) swapped the first and second dim: (480, 640, 3) Time for plotting! What could possibly go wrnog? imgplot = plt.imshow(dcm4) Here's what I get: Somehow my image now has all kinds of color and looks terrible. Here's where my question starts -- does anyone know what happened? Clearly my methodology was unsophisticated and unsatisfying. But I'm not sure exactly where to go. extra stuff, probably not really relevant At this point, I tried to hack the channels down to one, then duplicate back up to three so that imshow could read it, and I'll save you the details but it gave me this:
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83902347
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48454470
has comment: http://stackoverflow.com/comment/83902310
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48454666
has comment: http://stackoverflow.com/comment/83902160
tagged with: imshow

http://stackoverflow.com/comment/83677437
type: Comment
has text: thank u! I solved that with your help
type: QuestionComment
comment on: http://stackoverflow.com/q/48344566
score: 0

http://stackoverflow.com/q/48348598
has title: Shoving Scrapy Objects into array when parsing; what am I doing wrong?
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83683751
has answer: http://stackoverflow.com/a/48390880
accepted answer: http://stackoverflow.com/a/48390880
tagged with: scrapy
has body: I've basically created a spider that follows a set of links acquired from an API, and then extracts text from the HTML body. I'm trying to append returned items to appropriate lists, which are then added to a dictionary. When I run the code, the resultant JSON file only successfully writes the first line. I am running Python 3.6 in a virtual environment on a Windows 10 64-bit machine, and I run pip-upgrade daily. from nltk.corpus import stopwords import smtplib from time import sleep # To prevent overwhelming the server between connections from bs4 import BeautifulSoup as soup import scrapy import mysql.connector as mariadb import sys from collections import Counter from pprint import pprint import json import re conn = mariadb.connect(user=dbuser, password=dbpassword, database=dbdatabase) c = conn.cursor() e = sys.exc_info()[0] c.execute("Select URL FROM [TABLE]") JobURLs = c.fetchall() for object in JobURLs: urls = [] url_string = str(object) rx = re.compile('\W\W\W$') res = rx.sub('', url_string) rx = re.compile('^\W\W') url = rx.sub('', res) urls.append(url) c.execute("Select JvId FROM [TABLE]") JobIDs = c.fetchall() for object in JobIDs: item = {} item['JvId'] = [] JobID_string = str(object) rx = re.compile('\W\W\W$') res = rx.sub('', JobID_string) rx = re.compile('^\W\W') JobID = rx.sub('', res) item['JvId'].append(JobID) class JobListing(scrapy.Spider): name = 'JobListingCrawler' start_urls = urls def parse(self, response): # pass item['urlText'] = response.url page_html = response.body page_soup = soup(page_html, 'lxml') for script in page_soup(['script', 'style']): script.extract() item['jobDescText'] = page_soup.get_text('''\n''', strip=True) ## TextCleaner Function for Word Counter text = item['jobDescText'].replace('\n', ' ') lines = [line.strip() for line in text.splitlines()] chunks = [phrase.strip() for line in lines for phrase in line.split(' ')] def chunk_space(chunk): chunk_out = chunk + ' ' return chunk_out text = ''.join(chunk_space(chunk) for ch…
has answer: http://stackoverflow.com/a/48374901
type: Question
possible better answer: http://stackoverflow.com/a/48374901
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83759087

http://stackoverflow.com/a/48444535
has comment: http://stackoverflow.com/comment/83885379
has body: In your code block you have used ’ instead of ' driver = webdriver.Ie(’C:\Program Files\Internet Explorer\IEDriverServer.exe’) This error can come from coping text from other source and paste into scripts. Replace ’ with ' and add the r switch and argument type executable_path as follows: driver = webdriver.Ie(executable_path=r'C:\path\to\IEDriverServer.exe') Additionally, to maintain compatibility between the binaries, if you are using the Selenium client of version 3.x.y try to use IEDriverServer.exe of version 3.x.y.z only. So as you are using Selenium 3.3.1 use the IEDriverServer.exe v3.3.x only. Ensure that you are using the correct binaries of effective architecture. IEDriverServer_Win32_3.8.0 can be used in place of IEDriverServer_x64_3.8.0 but not the vice-versa.
has comment: http://stackoverflow.com/comment/83884867
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48438000
has comment: http://stackoverflow.com/comment/83903876
has comment: http://stackoverflow.com/comment/83907982
has comment: http://stackoverflow.com/comment/83896800
has comment: http://stackoverflow.com/comment/83885160
has comment: http://stackoverflow.com/comment/83918986
type: Answer
upvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/83903196
answers question: http://stackoverflow.com/q/48438000
has comment: http://stackoverflow.com/comment/83919077
has comment: http://stackoverflow.com/comment/83886098
type: AcceptedAnswer

http://stackoverflow.com/a/48361098
answers question: http://stackoverflow.com/q/48360682
downvote count: 0
type: Answer
has body: This will get you started. Change self.canvasRoot.bind("&lt;&lt;foo&gt;&gt;", self.flashRow) to self.canvasRoot.after(10, self.flashRow). This will cause flashRow to run once. At the bottom of the flashRow method, if you want to repeatedly have flashRow run, schedule it to run itself again using after. def flashRow(self): '''Flashes the row specified as attribute''' global spellerFrame for col_index in range(self.n_col): spellerFrame.itemconfig(handle_comm[1][col_index], fill=color_text_hl) # Put conditions or change the delay to something else, # but this will reschedule flashRow in 100ms repeatedly. self.canvasRoot.after(100, self.flashRow)
score: 2
upvote count: 2

http://stackoverflow.com/q/48402981
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has title: Simplification of Dirac delta in xδ(x)
tagged with: sympy
tagged with: symbolic-math
answer count: 1
downvote count: 0
tagged with: simplification
favorite count: 0
type: Question
has body: I cannot get sympy to simplify xδ(x) to 0, where δ is DiracDelta. In : simplify(x*DiracDelta(x)) Out: x⋅δ(x) Is there another simplification routine that would evaluate the terms in factor of Dirac function at the zeros of its argument and check whether they vanish? This would be useful when constructing piecewise functions, such as f(x)= x H(x) (where H is Heaviside function), whose derivative should be H(x), but is x⋅δ(x) + Heaviside(x) in sympy. Mathematica does simplify xδ(x) to 0.
accepted answer: http://stackoverflow.com/a/48404115
has answer: http://stackoverflow.com/a/48404115

http://stackoverflow.com/q/48434999
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83861468
has answer: http://stackoverflow.com/a/48435034
has answer: http://stackoverflow.com/a/48435016
score: 0
has title: Why does my program never run what is contained in the "else" statement?
type: Question
has body: The entire program runs as I expect it to. I'm trying to make hangman and the one else statement never runs when the if thing doesn't work. def playGame(): letterGuess = input("What is your guess: ") if letterGuess in letters: print("The word included", letterGuess) while letterGuess in letters: if letterGuess in letters: storage = letters.index(letterGuess) spaces.pop(storage) spaces.insert(storage, letterGuess) letters.pop(storage) letters.insert(storage, "-") else: usedLetters.insert(0, str(letterGuess)) Board = Board + 1 print(t) print("Wrong Letters", usedLetters) print(spaces)
answer count: 2

http://stackoverflow.com/comment/83969651
comment on: http://stackoverflow.com/a/48477578
type: Comment
has text: For AWS cli... Check the git repository they have documented the examples as well. But you will have to execute your commands on shell through python where as boto3 will provide you python functions.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83836480
score: 4
has text: you would need some threading for that. and use a member data instead of a global!
type: QuestionComment
comment on: http://stackoverflow.com/q/48423488
type: Comment

http://stackoverflow.com/a/48460628
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48460589
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48460589
has body: A little trick with slicing, initialise a new DataFrame. pd.DataFrame(df.values.T[1:], columns=df.A.tolist()) Or, pd.DataFrame(df.values[:, 1:].T, columns=df.A.tolist()) a1 b1 c1 0 2 5 8 1 3 6 9
upvote count: 2

http://stackoverflow.com/q/48422544
tagged with: pairwise
downvote count: 0
tagged with: python
tagged with: distance
has body: I have a dataframe, and I would like to apply my own distance pairwise. The problem it that myDistance takes 2 dataframes, and using skelarn pairwise_distance or scipy pdist converts is to ndarray. Example: df = pd.DataFrame([[1,2,3,3],[2,3,3,4],[4,1,3,2]],columns=['A','B','C','D']) This returns: A B C D 0 1 2 3 3 1 2 3 3 4 2 4 1 3 2 Then: def myDistance(f1,f2): return f1['A']-f2['A'] myDistance(df.loc[0],df.loc[1]) This works and returns -1. But this doesn't, because pdist treat the df row as ndarray from scipy.spatial.distance import pdist dist = pdist(df,myDistance) IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
score: 1
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48423457
has title: apply pairwise function on a pandas dataframe python
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/83685444
has text: @buhtz My main is not more complex, I just added the `print_it` example to show you how it is done with regular functions. Your code missed it and, as it is the **prime** use for this kind of decorators, I figured I would add one. Other additional lines are comments.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48339861

http://stackoverflow.com/comment/83896992
has text: @PaulPanzer: This is just an observation. Thank you.
score: 0
comment on: http://stackoverflow.com/q/48450781
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48480917
has title: Issue with PyCharm
accepted answer: http://stackoverflow.com/a/48480926
tagged with: pycharm
answer count: 1
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48480926
has body: I've got problems running this code in PyCharm import string print string.ascii_lowercase The code runs normally in Python IDLE (version 3.6), whereas in PyCharm it throws an error "No module named 'string'" Any ideas why it is going such way? I'd appreciate any suggestion. P.S. I've also tried to reinstall PyCharm, but the problem still remains
tagged with: python
type: Question

http://stackoverflow.com/comment/83681885
type: Comment
type: QuestionComment
score: 2
has text: First part: `y3 + y1 = (y2+dx) + (x) = ((y1+dx)+dx) + x = (((x)+dx)+dx) + x = 2x + 2dx` Second part: `y3 + y1 - 2*y2 = (2x + 2dx) - 2*(y1 + dx) = 2x + 2dx - 2*(x + dx) = 2x + 2dx - 2x - 2dx = 0` Guess you either didn't do it by hand, or you done messed up
comment on: http://stackoverflow.com/q/48347827

http://stackoverflow.com/a/48420113
answers question: http://stackoverflow.com/q/48419462
has body: If you want to join and align an arbitrary number of dictionaries (maybe, not only Fantasy and Real), with multiple object types (maybe, not only city and town), you may find pandas useful: Fantasy = {'Gotham':['city', 2000], 'Smallville':['town', 30]} Real = {'London':['city', 1000], 'Whitby':['town', 40]} # You have to code 'Fantasy' and 'Real' as strings, for Python to interpret and print them dicts = {'Fantasy': Fantasy, 'Real': Real} import pandas as pd frames = [] for key, value in dicts.items(): # Create a small table from each dict frame = pd.DataFrame(value, index=['type', 'size']).T.reset_index().set_index('type') # Add an extra column name (e.g. 'Fantasy') frame.columns = pd.MultiIndex.from_arrays([[key]*2, frame.columns]) frames.append(frame) print(pd.concat(frames, axis=1)) This code prints a little bit more than you wanted, but I think this extra info is useful, and must be shown explicitly: Fantasy Real index size index size type city Gotham 2000 London 1000 town Smallville 30 Whitby 40
score: 2
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/48454826
type: Question
has comment: http://stackoverflow.com/comment/83902917
has comment: http://stackoverflow.com/comment/83902770
has title: Pythonic way to solve a text normalization task
has comment: http://stackoverflow.com/comment/83902763
has body: Basically, I have a Hive script file, from which I need to extract the names for all the tables created. For example, from the contents ... create table Sales ... ... create external table Persons ... ... Sales and Persons should be extracted. To accomplish this, my basic idea is like: Search for key phrases create table and create external table, Extract the next token which should be the table name. However, the input may not be canonical. For example, Tab/newline may be used along with space as token delimiter There may be multiple consecutive delimiters between tokens Mixed use of upper and lower case letters like create TABLE Therefore, I'm thinking about first normalizing the input to a canonical form before applying the basic algorithm. Then with some effort, I come up with the following ' '.join(input.split()).lower() As a Python newcomer, I'm wondering whether this is the Pythonic way to solve the problem, or it may be flawed in the very first place? Is there a simple way to do this in a streaming fashion, i.e., avoiding loading the whole input into memory at once?
answer count: 1
downvote count: 0
upvote count: 1
tagged with: text-processing
has comment: http://stackoverflow.com/comment/83902969
type: AnsweredQuestion
tagged with: algorithm
score: 1
accepted answer: http://stackoverflow.com/a/48455482
tagged with: python
has answer: http://stackoverflow.com/a/48455482
favorite count: 0

http://stackoverflow.com/q/48362944
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83713591
score: 5
has comment: http://stackoverflow.com/comment/129421155
has comment: http://stackoverflow.com/comment/83713349
has comment: http://stackoverflow.com/comment/83896222
type: UnansweredQuestion
downvote count: 0
tagged with: ios
has comment: http://stackoverflow.com/comment/88122847
tagged with: python
has body: Context: I have Been using an iOS python IDE app (Pythonista) to write some simple scripts that periodically executes post/get requests, interprets &amp; analyses these requests and then finally notifies me using builtin iOS notifications. I have been running these scripts on my phone as I take it everywhere and getting a push notification for this information is highly useful to me. Problem statement: When I execute a long-running script in Pythonista, and shift the app to the background i.e. my switching to another app or by locking the phone, code execution suspends after a few minutes, effectively making the script redundant for my purposes (code execution and therefore notifications are suspended). This is intended by apple in it's design to allow the system to manage resources and load to prolong battery life (ref: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html) I'm looking for options to bypass (or manage) this restriction in iOS and can range from perhaps another python IDE that has increased permissions in its implementation to jail breaking the phone (but ideally i would like to avoid this). Thanks guys, just shoot if anyone requires more clarification. Note: There are other questions on SO that are similiar, but the majority are referring to writing an iOS app from scratch (xcode) so have increased access to permissions handling and background refresh/fetch features, something I don't as I am writing python natively in an iOS IDE.
has comment: http://stackoverflow.com/comment/87370354
has comment: http://stackoverflow.com/comment/83858477
answer count: 0
has comment: http://stackoverflow.com/comment/87431591
has title: Options to execute long-running scripts in iOS background without them being suspended
upvote count: 5
has comment: http://stackoverflow.com/comment/83713178
tagged with: pythonista
has comment: http://stackoverflow.com/comment/89509601

http://stackoverflow.com/q/48463842
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/121758512
has comment: http://stackoverflow.com/comment/83937936
has comment: http://stackoverflow.com/comment/83920931
has body: I am currently developing an app which is primarily based in .NET but need to integrate some math based code which is in Python3 and contains many references to the numpy, scipy and pandas packages. I have read that IronPython will not support these packages and that pythonnet cannot be embedded into a C# application to use from .net..... The python functions need to receive arguements of type dictionary, list and user defined class from the c# application and then return dictionaries that can be interpreted by the c# code. Is there a way to integrate the two code bases in their current format or to maintain the functionality does the python code need to be re-scripted into another language?
has comment: http://stackoverflow.com/comment/83988791
score: 3
upvote count: 3
tagged with: pythonnet
downvote count: 0
has comment: http://stackoverflow.com/comment/83924722
tagged with: ironpython
has comment: http://stackoverflow.com/comment/121635546
favorite count: 0
tagged with: numpy
tagged with: c#
has title: Integration of Python code into a C# application when python code contains numpy
type: Question
answer count: 0

http://stackoverflow.com/q/48395540
type: Question
has comment: http://stackoverflow.com/comment/83827830
upvote count: 0
type: UnansweredQuestion
answer count: 1
score: -3
has body: I need to extract Subject, Verb and the Object from a sentence given by user using python. Please advice me.
has title: SVO extraction from a sentence using Python
downvote count: 3
has answer: http://stackoverflow.com/a/48419042
tagged with: python
tagged with: nlp
favorite count: 0
has comment: http://stackoverflow.com/comment/83778679

http://stackoverflow.com/comment/83944276
type: AnswerComment
comment on: http://stackoverflow.com/a/48471792
score: 0
type: Comment
has text: I'm puzzled... if this is the right way what's the point of using GridSearchCV at all instead of using of a manual cross_validation + parameter search...?

http://stackoverflow.com/q/48395097
tagged with: vba
has comment: http://stackoverflow.com/comment/95634059
has title: How to import xlwings functions in Excel?
has comment: http://stackoverflow.com/comment/98742713
tagged with: excel
score: 7
answer count: 1
tagged with: python
upvote count: 7
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64592803
tagged with: python-3.x
tagged with: xlwings
type: UnansweredQuestion
has body: I installed the xlwings Python package using pip and subsequently installed the Excel add-in, using the steps documented here. When I try to open an .xlsm file and then import the Python functions from an identically titled .py file, I get the following error message in Excel: I tried reinstalling xlwings. I found no help specific to this error message online other than this unanswered post. This github page code suggests this error message is thrown when a command is [not] specified in the config I do not know what this means or how one would go about fixing it. Python version: 3.6.1 |Anaconda custom (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)] xlwings version: 0.11.5-py36_0
downvote count: 0

http://stackoverflow.com/comment/83727840
has text: Change `save_place=` to `path, _=`
type: QuestionComment
comment on: http://stackoverflow.com/q/48370347
type: Comment
score: 0

excel
tags question: http://stackoverflow.com/q/48471466
tags question: http://stackoverflow.com/q/48395097
tags question: http://stackoverflow.com/q/48427118
tags question: http://stackoverflow.com/q/48384928
tags question: http://stackoverflow.com/q/48355847
tags question: http://stackoverflow.com/q/48356899
tags question: http://stackoverflow.com/q/48469796
tag name: excel
tags question: http://stackoverflow.com/q/48461969
tags question: http://stackoverflow.com/q/48354113
tags question: http://stackoverflow.com/q/48410032
tags question: http://stackoverflow.com/q/48471702
type: Tag
tags question: http://stackoverflow.com/q/48372584
tags question: http://stackoverflow.com/q/48354279
tags question: http://stackoverflow.com/q/48470434
tags question: http://stackoverflow.com/q/48400953
tags question: http://stackoverflow.com/q/48339961
tags question: http://stackoverflow.com/q/48463500
tags question: http://stackoverflow.com/q/48414370
tags question: http://stackoverflow.com/q/48424045
tags question: http://stackoverflow.com/q/48444961
tags question: http://stackoverflow.com/q/48444444
tags question: http://stackoverflow.com/q/48357587
tags question: http://stackoverflow.com/q/48482187
tags question: http://stackoverflow.com/q/48351727
tags question: http://stackoverflow.com/q/48452882
tags question: http://stackoverflow.com/q/48488047
tags question: http://stackoverflow.com/q/48343337
tags question: http://stackoverflow.com/q/48459628
tags question: http://stackoverflow.com/q/48420111
tags question: http://stackoverflow.com/q/48435107
tags question: http://stackoverflow.com/q/48332632

http://stackoverflow.com/comment/83794189
score: 0
type: QuestionComment
has text: yes from Error Code to --- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux ---
comment on: http://stackoverflow.com/q/48400514
type: Comment

http://stackoverflow.com/a/48481567
type: Answer
has body: My band-aid solution was to notice that when I tried a sudo pip install pandas, I got a notice: Requirement already satisfied: pandas in /usr/lib/python2.7/dist-packages I stuck a sys.path.insert(1, '/usr/lib/python2.7/dist-packages') near the top of my script and it's now working okay. Thanks tremendously to @Joe!! My next steps are a complete do-over of my python install, hopefully without the sudos... (thank you @xgord)
score: 0
answers question: http://stackoverflow.com/q/48479910

http://stackoverflow.com/comment/83799041
has text: Done the changes (and removed success)... still no avail. I have added the data for totals to my question, not sure if that will help!
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48404678

http://stackoverflow.com/q/48375618
answer count: 2
has comment: http://stackoverflow.com/comment/83738538
upvote count: 1
has comment: http://stackoverflow.com/comment/83738293
has comment: http://stackoverflow.com/comment/83738530
accepted answer: http://stackoverflow.com/a/48375645
linked to: http://stackoverflow.com/q/9773121
has body: How to exclude the key 'u' from below, {u'{"auth":{"user_id":"2"},"data":{"collection":"master-services"}}': [u'']} I need to get my dictionary like below, {"auth":{"user_id":"2"},"data":{"collection":"master-services"}}
downvote count: 1
favorite count: 0
has title: Remove u key from dictionary python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/105483466
has answer: http://stackoverflow.com/a/48375706
possible better answer: http://stackoverflow.com/a/48375706
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48375645
type: Question
linked to: http://stackoverflow.com/q/13940272
has comment: http://stackoverflow.com/comment/83738235

global
type: Tag
tags question: http://stackoverflow.com/q/48446368
tags question: http://stackoverflow.com/q/48458322
tags question: http://stackoverflow.com/q/48388511
tags question: http://stackoverflow.com/q/48367157
tag name: global

http://stackoverflow.com/comment/83758008
score: 0
has text: @TedKleinBergman Thanks for reply, how do I get the hitbox to move with the Vehicle?
type: Comment
comment on: http://stackoverflow.com/q/48382937
type: QuestionComment

http://stackoverflow.com/q/48459104
tagged with: web-scraping
has body: How do I make a list from twitter content that I have scraped? I have scraped the content from tweets, now I want to make a list in order to manipulate it. How do I this? I am using python 3.6 here is my code: here is what prints:
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83912143
score: 0
has answer: http://stackoverflow.com/a/48459271
has title: Scraping Twitter content using BeautifulSoup
tagged with: python
tagged with: twitter
type: Question
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/48428901
accepted answer: http://stackoverflow.com/a/48429342
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48429342
has comment: http://stackoverflow.com/comment/83849136
upvote count: 0
has answer: http://stackoverflow.com/a/48431786
has body: I have a 3D matrix ‘DATA’ whose dimension is 100(L)X200(B)X50(H). The values are random for each grid point. I want to the find the number of points where the values are between 10 and 20 in each vertical column. The output will be a 2D matrix. For this I used the following code: out = [] for i in range(np.shape(DATA)[0]): for j in range(np.shape(DATA)[1]): a = DATA[i,j,:] b = a[(a&gt;25) &amp; (a&lt;30)] c = len(b) out.append(c) but I am not getting the 2D matrix. Instead I am getting an array Please Help
downvote count: 1
has comment: http://stackoverflow.com/comment/83849255
favorite count: 0
has comment: http://stackoverflow.com/comment/83848716
type: Question
has comment: http://stackoverflow.com/comment/83849181
possible better answer: http://stackoverflow.com/a/48431786
has comment: http://stackoverflow.com/comment/83848848
tagged with: python
score: -1
has title: store two for loop output in a 2D matrix

http://stackoverflow.com/comment/83919998
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48463500
has text: It'd be lovely if you posted your thought process and or attempt first so we could help you figure out what's wrong!

http://stackoverflow.com/q/48487788
tagged with: dynamic
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has body: I have the following json: post = { "file_name" : file_name, "function" : [{ "func_name" : func_name, "start_line" : start_line, "end_line" : end_line }] } I am trying to populate the functions array for each file using python... but am not able ... Can someone help tell how to add more functions to that array assuming the we already have one entry with file name and the first function in that file ?
has title: Array within json object - How to populate it using python
favorite count: 0
type: Question
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/83968927
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/48488819
accepted answer: http://stackoverflow.com/a/48488819
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83974386
downvote count: 2

http://stackoverflow.com/q/48375753
tagged with: python
possible better answer: http://stackoverflow.com/a/73382650
score: 17
has comment: http://stackoverflow.com/comment/83738667
tagged with: comparison
has comment: http://stackoverflow.com/comment/83738733
has comment: http://stackoverflow.com/comment/83738621
has answer: http://stackoverflow.com/a/73382650
type: Question
answer count: 2
tagged with: python-internals
has comment: http://stackoverflow.com/comment/83739233
has comment: http://stackoverflow.com/comment/83739310
has answer: http://stackoverflow.com/a/48375935
downvote count: 0
has comment: http://stackoverflow.com/comment/83738762
has comment: http://stackoverflow.com/comment/83739157
favorite count: 0
has body: In python, it is possible to chain operators in this manner: a op b op c Which is evaluated to a op b and b op c With the only difference being that b is evaluated only once (so, something more like t = eval(b); a op t and t op c). This is advantageous from the view point that it is very readable and more concise than the equivalent version with explicit conjunction (using and). However... I've noticed that there is a minor performance difference between chained expressions and the equivalent, be it for 3 operands or 20. This becomes apparent when you time these operations. import timeit timeit.timeit("a &lt;= b &lt;= c", setup="a,b,c=1,2,3") 0.1086414959972899 timeit.timeit("a &lt;= b and b &lt;= c", setup="a,b,c=1,2,3") 0.09434155100097996 And, timeit.timeit("a &lt;= b &lt;= c &lt;= d &lt;= e &lt;= f", setup="a,b,c,d,e,f=1,2,3,4,5,6") 0.2151330839988077 timeit.timeit("a &lt;= b and b &lt;= c and c &lt;= d and d &lt;= e and e &lt;= f", setup="a,b,c,d,e,f=1,2,3,4,5,6") 0.19196406500122976 Note: All tests were done with Python-3.4. Examining the byte code for both expressions, I noticed that one performs significantly more (actually, 4 more) operations than the other. import dis dis.dis("a &lt;= b &lt;= c") 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 1 (&lt;=) 11 JUMP_IF_FALSE_OR_POP 21 14 LOAD_NAME 2 (c) 17 COMPARE_OP 1 (&lt;=) 20 RETURN_VALUE &gt;&gt; 21 ROT_TWO 22 POP_TOP 23 RETURN_VALUE Contrast this with, dis.dis("a &lt;= b and b &lt;= c") 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 COMPARE_OP 1 (&lt;=) 9 JUMP_IF_FALSE_OR_POP 21 12 LOAD_NAME 1 (b) 15 LOAD_NAME 2 (c) 18 COMPARE_OP 1 (&lt;=) &gt;&gt; 21 RETURN_VALUE I am not experienced with reading byte code, but the first code snippet definitely performs more operations at the byte code level than the second. Here's how I've interpreted this. In the first case, variables are pushed onto some sort of stack, and popped successively for comparison. All variables are popped only once. In the…
upvote count: 17
has comment: http://stackoverflow.com/comment/83738680
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83738577
accepted answer: http://stackoverflow.com/a/48375935
has comment: http://stackoverflow.com/comment/83738603
has title: Why are chained operator expressions slower than their expanded equivalent?

http://stackoverflow.com/a/76414336
has comment: http://stackoverflow.com/comment/134775354
has comment: http://stackoverflow.com/comment/134818142
type: Answer
answers question: http://stackoverflow.com/q/48399871
has comment: http://stackoverflow.com/comment/134817194
has body: This works for me. import os import pandas as pd import boto3 from io import StringIO from dotenv import load_dotenv load_dotenv("/path/to/.env", override=True) def df_to_s3(df, bucket, key): # Create a session session = boto3.session.Session(profile_name=os.environ.get("AWS_SECRETS_PROFILE_NAME")) aws_s3_client = session.client( service_name="s3", region_name=os.environ.get("AWS_SECRETS_REGION_NAME"), ) # Create a CSV string from the DataFrame csv_buffer = StringIO() df.to_csv(csv_buffer, index=False) # Put the CSV string to S3 aws_s3_client.put_object( Body=csv_buffer.getvalue(), Bucket=bucket, Key=key ) print(f'Successfully put DataFrame to {bucket}/{key}') df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) df_to_s3(df, 'bucketName/folder/', 'test3.csv')
score: 0

http://stackoverflow.com/a/48432649
score: 0
has comment: http://stackoverflow.com/comment/83875565
answers question: http://stackoverflow.com/q/48432564
type: Answer
has comment: http://stackoverflow.com/comment/83856686
has body: for i in range(len(val)): val[i] = val[i] - wavg[i]

http://stackoverflow.com/q/48417159
has body: I am new to python and learning the language from Udacity. I wanted to write a python program that takes 2 dates and outputs the day difference between these 2 dates, assuming the second date is latter. It throws an error saying that: File /Users/gonewiththewind/Documents/days old.py", line 20, in daysBetweenDates currentDaysOfMonths = daysOfMonths[isLeap(year)][month - 1] TypeError: list indices must be integers, not NoneType" when I tried to call the function by "daysBetweenDates(1995,7,28,2018,1,26) Here is the code: daysOfMonths = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]] def isLeap(year): if year % 400 == 0: return True else: if year % 100 == 0: return False else: if year % 4 == 0: return True def daysBetweenDates(year1, month1, day1, year2, month2, day2): counter = 0 month = month1 year = year1 day = day1 while(year != year2 or month != month2 or day != day2): currentDaysOfMonths = daysOfMonths[isLeap(year)][month - 1] if(day &lt; currentDaysOfMonths): day = day + 1 counter = counter + 1 print 'counter = '+ counter else: day = 1 if(month1 &lt; 12): month = month + 1 else: month = 1 year = year + 1 counter = counter + 1 print 'counter = '+ counter return counter
has comment: http://stackoverflow.com/comment/83824064
type: Question
has title: python error “list indices must be integers not Nonetype”
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48417206

http://stackoverflow.com/q/48345415
upvote count: 1
has body: I have a adult dataset that has a country column that has 41 different countries. To calculate accuracy, I have to convert categorical values into one hot encoder format which increases dimensionality. Here, in pandas, I want to group some countries to reduce dimensionality. For example, for {Columbia Ecuador Peru} I want to represent it as a new group named as {South-America}. Is there any pandas function to provide it?
downvote count: 1
has answer: http://stackoverflow.com/a/48345771
favorite count: 0
has answer: http://stackoverflow.com/a/48345583
type: Question
has title: how to group categorical values as a group in pandas
tagged with: group-by
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83676605
tagged with: categorical-data
answer count: 2
tagged with: pandas
score: 0
accepted answer: http://stackoverflow.com/a/48345771
possible better answer: http://stackoverflow.com/a/48345583

pygraphviz
tags question: http://stackoverflow.com/q/48380550
tag name: pygraphviz
type: Tag

http://stackoverflow.com/q/48368186
score: 1
tagged with: python
tagged with: kivy
has body: I need to set up dynamically list in Drop-Down. For setting I want to use constructor of class DiscDropDown, which is decendant of class DropDown. (It means, that want to set up value for variable li_disc in class DiscDropDown). Instance of this class is not part of python code, because I use Builder. How do I realize it in next code? Builder.load_string(''' &lt;Save_As&gt;: drop_down: drop_down orientation:'vertical' DiscDropDown: id: drop_down size_hint: None,None height: 50 Button: id: bt_delete_file disabled: False size_hint: 1,None height: 250 text: 'Fictive' ''') class DiscDropDown(DropDown): def __init__(self, **kwarg): super(DiscDropDown, self).__init__(**kwarg) self.dropdown = DropDown() # I wanted to set up value Button.text during creation Buttons for name in li_disc: btn = Button(text = name, size_hint_y=None, height=44) btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) self.dropdown.add_widget(btn) mainbutton = Button(text='Disc', size_hint=(None, None),size = (50,50)) mainbutton.bind(on_release = self.dropdown.open) self.dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x)) self.add_widget(mainbutton) class Save_As(BoxLayout): # drop_down = ObjectProperty() def __init__(self, **kwargs): super(Save_As, self).__init__( **kwargs) return class ExplorerApp(App): def build(self): self.save_as = Save_As() return self.save_as if __name__ == '__main__': ExplorerApp().run() For solving my problem I used next process for setting value variable Button.text: class Save_As(BoxLayout): drop_down = ObjectProperty() def __init__(self, **kwargs): li_disc = ['aa','bb','cc'] super(Save_As, self).__init__( **kwargs) # I set up Button.text here for i in range(0,3): self.children[1].dropdown.children[0].children[i].text = li_disc[i] return I think that my solution isn't ideal, cann you recommend me better process?
type: Question
tagged with: kivy-language
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83723213
upvote count: 1
has title: Kivy: How set up item Drop-Down
has comment: http://stackoverflow.com/comment/83768791
favorite count: 0

http://stackoverflow.com/comment/83762298
has text: I'd naturally expect an array of shape `(3, 4, 5)` as output; the solution with the right-hand side `b(:, i, j)` is `sol(:, i, j)`, much like in the other cases.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48387261

http://stackoverflow.com/comment/83729317
has text: python lists are **mutable**. you are changing the contents of your list `pizza`. this has nothing to do with the scope of variables.
type: Comment
comment on: http://stackoverflow.com/q/48371259
type: QuestionComment
score: 5

http://stackoverflow.com/q/48390703
has answer: http://stackoverflow.com/a/48406791
downvote count: 0
tagged with: openai-gym
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I have been studying some of the OpenAI gym envs and came across this line: self.model = mujoco_py.MjModel(fullpath) (https://github.com/openai/gym/blob/master/gym/envs/mujoco/mujoco_env.py#L28) Can anyone tell me where mujoco_py.MjModel() is defined? I assume this is somehow pulled from native MuJoCo / Cython... EDIT Also when I search the install folder of mujoco_py (&lt;Python-installation-directory&gt;/Lib/site-packages/mujoco_py/), there is literally no MjModel found (Sublime fulltext search). (The search might exclude some files.) What I do find a lot are 'mjModel' and 'PyMjModel' though. I am confused because the instantiation through mujoco_py.MjModel() also seems to create a different kind of model than using functions like mujoco_py.load_model_from_path(). The former have a .data attribute while the latter apparently don't.
has title: Where is mujoco_py.MjModel(<filepath>) defined?
type: Question
score: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/c
favorite count: 0
tagged with: c++

http://stackoverflow.com/q/48448472
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/74190369
has answer: http://stackoverflow.com/a/48599414
has answer: http://stackoverflow.com/a/69045724
has answer: http://stackoverflow.com/a/48599443
has comment: http://stackoverflow.com/comment/83890382
type: Question
has comment: http://stackoverflow.com/comment/86014419
has comment: http://stackoverflow.com/comment/130306837
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: ipython
answer count: 4
has body: In the working space I have bunch of csv 'summer_xxx1.csv' 'summer_xxx2.csv' 'summer_xxx3.csv' that is accesssable from the remote ipython command shell , I want to download them to local machine and try to make sense out of them. I have try following code import base64 from IPython.display import HTML def create_download_link(df, title = "Download CSV file", filename = "data.csv"): csv = df.to_csv() b64 = base64.b64encode(csv.encode()) payload = b64.decode() html = '&lt;a download="{filename}" href="data:text/csv;base64, {payload}" target="_blank"&gt;{title}&lt;/a&gt;' html = html.format(payload=payload,title=title,filename=filename) return HTML(html) Here create_download_link(medals_df) would return &lt;IPython.core.display.HTML object&gt; Is there way to make medals_df to csv and downloadable from the ipython command shell
has title: Try to download all the csv from the ipython console from datacamp

coding-style
type: Tag
tags question: http://stackoverflow.com/q/48465311
tag name: coding-style
tags question: http://stackoverflow.com/q/48433683
tags question: http://stackoverflow.com/q/48433755
tags question: http://stackoverflow.com/q/48459235

http://stackoverflow.com/a/48398010
has body: On your Ras-pi side, you are reading from newsockfd but you are neither declaring it nor, initializing it. Also, you are just listen-ing to the socket, but never accept-ing a connection. You need to add this - socklen_t length = 0; int newsockfd = accept(socket, NULL, &amp;length); before your call to read. Also, as mentioned by @sjsam in the comments, you need to close the socket after you are done reading using - close(newsockfd); close(socket); It would also be good to refactor the code and move the connection handling to a separate function (or a thread), so that your server can accept more connection. But if this is just a MCVE, that is alright.
accepted answer of: http://stackoverflow.com/q/48397845
has comment: http://stackoverflow.com/comment/83784166
type: Answer
answers question: http://stackoverflow.com/q/48397845
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/comment/83725348
type: Comment
comment on: http://stackoverflow.com/q/48369279
type: QuestionComment
has text: Hint: You're always calling the `bar` from 1 to n, for 1 to n in `foo` function.
score: 0

http://stackoverflow.com/comment/83811204
has text: It looks like, in my particular scnerio, the solution was to use a different python module. I found one called zbar-py that works correctly, without any additional headache.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48408128

python-import
tags question: http://stackoverflow.com/q/48469667
tags question: http://stackoverflow.com/q/48438806
tags question: http://stackoverflow.com/q/48444218
tags question: http://stackoverflow.com/q/48474688
tag name: python-import
tags question: http://stackoverflow.com/q/48357265
type: Tag
tags question: http://stackoverflow.com/q/48456028
tags question: http://stackoverflow.com/q/48384420
tags question: http://stackoverflow.com/q/48362432
tags question: http://stackoverflow.com/q/48471252
tags question: http://stackoverflow.com/q/48481700
tags question: http://stackoverflow.com/q/48354359
tags question: http://stackoverflow.com/q/48459455
tags question: http://stackoverflow.com/q/48356906
tags question: http://stackoverflow.com/q/48430236
tags question: http://stackoverflow.com/q/48365000
tags question: http://stackoverflow.com/q/48455129
tags question: http://stackoverflow.com/q/48411672

http://stackoverflow.com/a/48449387
has comment: http://stackoverflow.com/comment/83895026
has comment: http://stackoverflow.com/comment/83908155
has comment: http://stackoverflow.com/comment/83973282
has body: A few key issues here. You're trying to define a 1-layer neural network, which sounds good for this problem. But your hidden layer is much larger than it should be. Experiment with smaller weight sizes. Try 128, 256, 512, numbers like this (powers of two are not required). Also, your input dimensionality is quite high. I know someone working on a very similar gene expression problem for cancer with something like 60,000 gene expressions and 10,000 samples. She has used PCA to reduce the dimensionality of the data while maintaining ~90% of the variance (she experimented with different values and found this about optimal). That improved the results. Neural networks can overfit, the PCA dimensionality reductions was beneficial. The 1-layer fully connected network also out performed Logstic Regression and XGA boost in her experiments. A couple of other things that she's working on with this problem, which may also apply to you: Multi-task learning proved to improve the results. She originally had 4 different neural networks (4 outputs given the same data) when she combined them into 1 neural network with 4 loss functions it improved the results of all 4. Instead of PCA you can use auto-encoders as an alternative dimensionality reduction technique. It's entirely possible to connect an auto-encoder to this network and train it in conjunction with a loss function. I haven't actually experimented with this (yet) though, so I can only say that I expect it to improve the results in theory. The PCA approach will be quicker to test so I'd start there.
answers question: http://stackoverflow.com/q/48446306
type: Answer
has comment: http://stackoverflow.com/comment/83892698
has comment: http://stackoverflow.com/comment/83895720
has comment: http://stackoverflow.com/comment/83942595
has comment: http://stackoverflow.com/comment/83947830
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/83867450
type: AnswerComment
comment on: http://stackoverflow.com/a/48437860
has text: import psycopg2 conn = psycopg2.connect(user='postgres', host='localhost', password='123456') conn.autocommit = True cur = conn.cursor() cur.execute('CREATE DATABASE example;') conn = psycopg2.connect(database = 'example', user='postgres', host='localhost', password='123456') conn.autocommit = True cur = conn.cursor()
type: Comment
score: 0

http://stackoverflow.com/a/48371587
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/83730364
type: Answer
answers question: http://stackoverflow.com/q/48370708
downvote count: 0
has body: Consider the following sample DF: In [307]: df Out[307]: sex age name 0 M 40 Max 1 F 35 Anna 2 M 29 Joe 3 F 18 Maria 4 F 23 Natalie There are quite a few good reasons to prefer .query() method. it might be much shorter and cleaner compared to boolean indexing: In [308]: df.query("20 &lt;= age &lt;= 30 and sex=='F'") Out[308]: sex age name 4 F 23 Natalie In [309]: df[(df['age']&gt;=20) &amp; (df['age']&lt;=30) &amp; (df['sex']=='F')] Out[309]: sex age name 4 F 23 Natalie you can prepare conditions (queries) programmatically: In [315]: conditions = {'name':'Joe', 'sex':'M'} In [316]: q = ' and '.join(['{}=="{}"'.format(k,v) for k,v in conditions.items()]) In [317]: q Out[317]: 'name=="Joe" and sex=="M"' In [318]: df.query(q) Out[318]: sex age name 2 M 29 Joe PS there are also some disadvantages: we can't use .query() method for columns containing spaces or columns that consist only from digits not all functions can be applied or in some cases we have to use engine='python' instead of default engine='numexpr' (which is faster) NOTE: Jeff (one of the main Pandas contributors and a member of Pandas core team) once said: Note that in reality .query is just a nice-to-have interface, in fact it has very specific guarantees, meaning its meant to parse like a query language, and not a fully general interface.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83730344
accepted answer of: http://stackoverflow.com/q/48370708

pyserial
tags question: http://stackoverflow.com/q/48333690
tags question: http://stackoverflow.com/q/48359729
tag name: pyserial
tags question: http://stackoverflow.com/q/48356223
tags question: http://stackoverflow.com/q/48373982
tags question: http://stackoverflow.com/q/48405799
tags question: http://stackoverflow.com/q/48361774
tags question: http://stackoverflow.com/q/48418140
tags question: http://stackoverflow.com/q/48350066
tags question: http://stackoverflow.com/q/48446989
tags question: http://stackoverflow.com/q/48437856
type: Tag
tags question: http://stackoverflow.com/q/48400862

http://stackoverflow.com/q/48350117
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/48351911
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48351911
has title: Feed Iterator to Tensorflow Graph
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-datasets
has body: I have a tf.data.Iterator created with make_one_shot_iterator() and want to use it to train my (existing) model. Currently my training looks like this input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels)) net = models.ResNet50UpProj({'data': input_node}, batch_size, keep_prob=True,is_training=True) labels = tf.placeholder(tf.float32, shape=(None, width, height, 1)) huberloss = tf.losses.huber_loss(predictions=net.get_output(),labels=labels) And then calling sess.run(train_op, feed_dict={labels:output_img, input_node:input_img}) After training I can get a prediction like that: pred = sess.run(net.get_output(), feed_dict={input_node: img}) Now with an iterator I tried something like this next_element = iterator.get_next() Passing the input data like this: net = models.ResNet50UpProj({'data': next_element[0]}, batch_size, keep_prob=True,is_training=True) Defining the loss function like this: huberloss = tf.losses.huber_loss(predictions=net.get_output(),labels=next_element[1]) And executing the training as simple as while iterating over the iterator automatically with every call of this: sess.run(train_op) My problem is: After training I can't make any prediction. Or rather I don't know the proper way of using the iterator in my case.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83791925
comment on: http://stackoverflow.com/q/48368292
score: 0
type: Comment
type: QuestionComment
has text: @qspitzer Managed to find the solution. Basically what was happening was even though I was checking for the name of the ticket in the category and telling it to not create a new ticket with a certain name if it found one with that name, it was still creating a text channel with the name I didn't want it to. I managed to fix it by changing `elif discord.utils.get(channel.channels, name="{}-ticket".format(ctx.message.author.name))` to `elif discord.utils.get(channel.channels, name="{}-ticket".format(ctx.message.author.name.lower()))`

http://stackoverflow.com/comment/83900626
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48453660
type: Comment
has text: @DibyenduDey You can _always_ provide more info because you should reduce your problem down to a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) which will abstract away all confidential info.

http://stackoverflow.com/a/48363675
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48363627
upvote count: 1
has body: c = 5 cmds.pointPosition(geo[0]+".cv[0][" + str(c) + "2]", w=True) In Python, you can't concatenate str and int.
downvote count: 0

http://stackoverflow.com/comment/83718978
type: QuestionComment
has text: Here are [the docs](https://stackoverflow.com/help/how-to-ask) on how to ask good questions!
comment on: http://stackoverflow.com/q/48366187
score: 1
type: Comment

http://stackoverflow.com/q/48451459
possible better answer: http://stackoverflow.com/a/48458375
type: Question
has answer: http://stackoverflow.com/a/48453891
has answer: http://stackoverflow.com/a/48460932
accepted answer: http://stackoverflow.com/a/48460932
has answer: http://stackoverflow.com/a/48458375
has body: I'm a bit new in scripting and french so exuse me if my explanations are not perfectly clear. I'm trying to make a script in Maya to manage easily the keys value for animation. So I created a window reproducing Maya's ChannelBox with another organisation. And now I'm trying to set and upadate automaticaly the attribute values of selected object inside the different textField (transX, transY..). I found some informations about a command called scriptJob that could help me, but didn't find any context looking like mine or recent informations about how to place it inside my code. Here is what I have for now : transX_value = cmds.textField( w=100 , h=22 , tx= cmds.getAttr("%s.translateX" %selected[0]) ) So now I'd need some help about connecting an update function inside my textField, so when it change and press Enter, the attribute would change too so I think that I need to insert a scriptJob inside my function but I don't know how. def updateValues () : for sel in selection : sel_attr = cmds.getAttr("%s+.name" %selected[0]) cmds.setAttr( "%s+.name" , textField) The end of the code is not right of course. Thanks for your help.
has comment: http://stackoverflow.com/comment/83917176
has answer: http://stackoverflow.com/a/48453159
tagged with: python
has title: Update textField value connected to a setAttr
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83915010
tagged with: maya
linked to: http://stackoverflow.com/q/37041184

http://stackoverflow.com/q/48472085
type: Question
tagged with: python
has body: I am scraping two columns out of a table and looping the script over the HTML (there are 19 pages of tables). However, when I enter in the range for what is supposed to be the webpage loop, it sets it as the range of rows to gain. What am I doing wrong with my loop so that it is setting the range for the rows of data gathered INSTEAD of setting the range for the HTML pages I want to scrape over? import requests from bs4 import BeautifulSoup import pandas as pd import csv empty_list = [] for i in range (1,19): url = requests.get("https://www.foxsports.com/nhl/stats?season=2017&amp;category=SCORING&amp;group=1&amp;sort=3&amp;time=0&amp;pos=0&amp;team=0&amp;qual=1&amp;sortOrder=0&amp;page={}".format(i)) if not url.ok: continue data = url.text soup = BeautifulSoup(data, 'lxml') table = soup.find('table', {'class' : 'wisbb_standardTable'}) player = table.find('a', {'class':'wisbb_fullPlayer'}).find('span').text team = table.find('span',{'class':'wisbb_tableAbbrevLink'}).find('a').text empty_list.append((player, team)) df = pd.DataFrame(empty_list, columns=["player", "team"]) df
tagged with: pandas
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48472172
answer count: 1
has answer: http://stackoverflow.com/a/48472172
has title: Python scrape over Webpage Loop

http://stackoverflow.com/comment/83837378
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48423777
has text: @Jean-FrançoisFabre Thank you! But I'm facing another problem. I just want to encapsulate all in the class, in order to just need to call start() and stop() without creating Threads outside it. I tried to do it using your code, but I could not figure it. I have updated the comment, can you revise it?

http://stackoverflow.com/q/48355388
has comment: http://stackoverflow.com/comment/83699391
tagged with: python
tagged with: macos
type: Question
has comment: http://stackoverflow.com/comment/83699314
answer count: 0
has title: checking if safari in macos process list
type: UnansweredQuestion
tagged with: process
has comment: http://stackoverflow.com/comment/83698716
tagged with: python-os
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/83699476
has body: I'm wrote this code to check if 'bad_process' is running: bad_process_list=['iTerm'] c = os.popen('ps ea') #'ps aux' for complicated cases for smth in c: #make a timer to run fulltime for s in bad_process_list: if s in smth: print('close ', s,' right now!') break so, this code can detect if iTerm running, but no luck with safari: result with iTerm result with safari so, i can detect safari using ps ea | grep safari, but no luck with my code. should i use os.popen('ps ea | grep '+s) instead? is dynamic changing of PID of safari process alltime is associated with my case?

http://stackoverflow.com/q/48418250
has comment: http://stackoverflow.com/comment/83826140
type: Question
accepted answer: http://stackoverflow.com/a/48418356
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48418356
possible better answer: http://stackoverflow.com/a/48418529
has comment: http://stackoverflow.com/comment/83826682
tagged with: python
has comment: http://stackoverflow.com/comment/83826222
answer count: 3
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/48418529
has comment: http://stackoverflow.com/comment/83826224
has answer: http://stackoverflow.com/a/48420165
has body: I have a variable that can sometimes have a value of -0.0, and I want to change its value to 0.0 whenever this is the case. The problem is, I can't find a nice way to check if it has a value of -0.0! I can't use something like: if a == -0.0: a = 0.0 because a can have other values like False (and False == -0.0). I thought if I used is, then that would work, but -0.0 is -0.0 is false! Another idea I had was to try: if str(a) == '-0.0': a = 0.0 Unfortunately, this is also problematic because a can have a value of '-0.0', which I want to keep as a string. So, right now I can only think of doing: if not isinstance(a, str) and str(a) == '-0.0': a = 0.0 which is pretty crazy considering what I want to do... Does anyone know of any better ways to do this? Thanks so much for the help! :)
has title: python - how can I check if a variable has a value of -0.0?
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/48350125
has body: I have a column in a dataframe that I need to convert from object to boolean. However, the value changes from False to True when using astype. Any ideas on how to prevent this? df['isgood'] returns: 0 True 1 False 2 False df['isgood'].astype(bool) returns: 0 True 1 True 2 True
has title: Pandas conversion from object to boolean always returns True using astype
score: 5
upvote count: 5
tagged with: python
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48350163
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48350163

http://stackoverflow.com/comment/83910560
type: QuestionComment
has text: Thanks @Clifford! The latter is what I am looking for: how do I inspect the last log message to initialise the counter? Is this something I do from the logger, or just by doing [something like this?](https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python)
comment on: http://stackoverflow.com/q/48449126
type: Comment
score: 0

http://stackoverflow.com/q/48450785
tagged with: python
upvote count: 6
type: Question
linked to: http://stackoverflow.com/q/50412495
has body: I've run into an issue trying to use Tensorflow's feature_column mappings inside of a function passed in to the Dataset map method. This happens when trying to one hot encode categorical string features of a Dataset as part of the input pipeline using Dataset.map. The error message I'm getting is that: tensorflow.python.framework.errors_impl.FailedPreconditionError: Table already initialized. The following code is a basic example that recreates the problem: import numpy as np import tensorflow as tf from tensorflow.contrib.lookup import index_table_from_tensor # generate tfrecords with two string categorical features and write to file vlists = dict(season=['Spring', 'Summer', 'Fall', 'Winter'], day=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']) writer = tf.python_io.TFRecordWriter('test.tfr') for s,d in zip(np.random.choice(vlists['season'],50), np.random.choice(vlists['day'],50)): example = tf.train.Example( features = tf.train.Features( feature={ 'season':tf.train.Feature( bytes_list=tf.train.BytesList(value=[s.encode()])), 'day':tf.train.Feature( bytes_list=tf.train.BytesList(value=[d.encode()])) } ) ) serialized = example.SerializeToString() writer.write(serialized) writer.close() Now there's a tfrecord file in the cwd called test.tfr with 50 records, and each record consists of two string features, 'season' and 'day', The following will then create a Dataset that will parse the tfrecords and create batches of size 4 def parse_record(element): feats = { 'season': tf.FixedLenFeature((), tf.string), 'day': tf.FixedLenFeature((), tf.string) } return tf.parse_example(element, feats) fname = tf.placeholder(tf.string, []) ds = tf.data.TFRecordDataset(fname) ds = ds.batch(4).map(parse_record) At this point if you create an iterator and call get_next on it several times, it works as expected and you would see output like this each run: iterator = ds.make_initializable_iterator() nxt = iterator.get_next() sess.run(tf.tables_initializer()) sess.run(iterator.initialize…
has answer: http://stackoverflow.com/a/50432666
has title: Tensorflow feature columns in Dataset map Table already initialized issue
type: UnansweredQuestion
answer count: 1
score: 6
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
downvote count: 0
tagged with: deep-learning

http://stackoverflow.com/comment/83933979
type: Comment
comment on: http://stackoverflow.com/q/48469916
type: QuestionComment
has text: That's what I meant, yes. Seriously -- use paramiko. Trying to drive an interactive program through an interface that wasn't intended for programmatic use is inherently fragile.
score: 0

http://stackoverflow.com/q/48346563
tagged with: python
has body: Getting error: "invalid element state" when using Chrome driver for selenium. What I'm trying to do: Pass in some data to http://www.dhl.de/onlinefrankierung My first issue is that when I try to use the .click() method on the checkbox named "Nachnahme" nothing happens, no check is made. When you make a check manually, the page refreshes and additional fields open up, which is what I'm trying to access. The second issue, which throws the invalid element state, happens when trying to pass in data using the .send_keys() method. Here is my code so far: from selenium import webdriver driver = webdriver.Chrome('C:\\Users\\Owner\\AppData\\Local\\Programs\\Python\\Python36-32\\Lib\\site-packages\\chromedriver.exe') driver.get('http://www.dhl.de/onlinefrankierung') product_element = driver.find_element(by='id', value='bpc_PAK02') product_element.click() services_element = driver.find_element(by='id', value='sc_NNAHME') services_element.click() address_element_name = driver.find_element(by='name', value='formModel.sender.name') address_element_name.send_keys("JackBlack") ERROR: C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\python.exe "C:/Users/Owner/Desktop/UpWork/Marvin Sessner/script.py" Traceback (most recent call last): File "C:/Users/Owner/Desktop/UpWork/Marvin Sessner/script.py", line 23, in address_element_name.send_keys("tester") File "C:\Users\Owner\AppData\Roaming\Python\Python36\site-packages\selenium\webdriver\remote\webelement.py", line 352, in send_keys 'value': keys_to_typing(value)}) File "C:\Users\Owner\AppData\Roaming\Python\Python36\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute return self._parent.execute(command, params) File "C:\Users\Owner\AppData\Roaming\Python\Python36\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute self.error_handler.check_response(response) File "C:\Users\Owner\AppData\Roaming\Python\Python36\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in c…
favorite count: 0
has answer: http://stackoverflow.com/a/48349007
type: Question
answer count: 2
downvote count: 0
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/48349096
type: UnansweredQuestion
score: 1
has title: selenium python issue - invalid element state
has comment: http://stackoverflow.com/comment/83680727
has comment: http://stackoverflow.com/comment/83679085

http://stackoverflow.com/a/48374367
upvote count: 3
answers question: http://stackoverflow.com/q/48372508
has body: Try this for row in soup.select('tbody tr'): row_text = [x.text for x in row.find_all('td')] print(', '.join(row_text)) # You can save or print this string however you want. Output: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa, 62e907b15cbf27d5425399ebf6f0fb50ebb88f18, 66.67711246 BTC, 66.67711246 BTC, 1089 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX, 119b098e2e980a229e139a9ed01a469e518e6f26, 50.05723154 BTC, 50.05723154 BTC, 55
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48372508
score: 3

http://stackoverflow.com/a/48453709
type: Answer
has body: Your assumption was wrong. There is no such thing as a uninitialized variable in Python. Any reference to a "variable" in Python either finds an entry in the namespace of some scope (Local, Enclosing, Global, or Builtin) or it's name lookup error. It is better to think of Python statements of the form x=y as binding statements rather than assignments. A binding associates a name with an object. The object exists independently of its bindings (instantiated by a literal expression, for example). By contrast, most of the programming languages people are more familiar with have variables ... which have an associated type and location. Python "variables" are entries in a dictionary and the id() returns the the location of the object to which a name is bound. (The fact that this is a memory location is an implementation detail; but the principle is that Python "variable names" are not like the "variables" of more conventional languages). Here's a bit more on that: https://softwareengineering.stackexchange.com/a/200123/11737 The best way to do accomplish this is simply refrain from using names before binding values thereto. Poking around in locals() or globals() for such things is just poor, ugly, coding practice.
has comment: http://stackoverflow.com/comment/84052389
score: 0
has comment: http://stackoverflow.com/comment/83900572
has comment: http://stackoverflow.com/comment/84015197
answers question: http://stackoverflow.com/q/48453558
has comment: http://stackoverflow.com/comment/83973301
has comment: http://stackoverflow.com/comment/83967846
has comment: http://stackoverflow.com/comment/84032447
has comment: http://stackoverflow.com/comment/84017417
has comment: http://stackoverflow.com/comment/83974842
has comment: http://stackoverflow.com/comment/83973211
has comment: http://stackoverflow.com/comment/132989105

http://stackoverflow.com/comment/83893943
has text: Thanks for mentioning which program you use to open the file. CSV is not a single, universal standard; each program implements it indifferent ways. The default dialect of the `csv` module is "excel", but you are changing some of the parameters from their defaults. What happens when you try just `csv_writer = csv.writer(f)` with no other parameters?
score: 0
comment on: http://stackoverflow.com/q/48449480
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83655314
type: QuestionComment
comment on: http://stackoverflow.com/q/48335063
type: Comment
has text: Yes, that's what I thought to do but it did not help. 384 raise ValueError("No JSON object could be decoded") ValueError: Expecting ',' delimiter: line 1 column 5 (char 4)
score: 0

http://stackoverflow.com/q/48382662
linked to: http://stackoverflow.com/q/35287786
answer count: 1
has body: I am trying to implement some distributed MDO architectures following the tips that I found here and here When I try to implement the CO for the Sellar problem it simply does not converge, it ends up violating the constraints, according to the answer below: Minimum target found at (5.000000, 1.964134, 0.821694) Coupling vars target: 3.514927, 1.876374 ('Minimum objective: ', 6.3073869839326475) ('constraints: ', 1.4712589277025103, 5.8788877332794067) I think it's not an optimizer problem, since it's a simple math challenge. But I can not identify the error. Depending on the initial values the answer is NAN when using 'FD' instead of 'CS' for gradient calculations. My code is ( OpenMDAO 1.7): class SellarDis1(Component): """Component containing Discipline 1.""" def __init__(self): super(SellarDis1, self).__init__() # Global Design Variable self.add_param('z', val=np.zeros(2)) # Local Design Variable self.add_param('x', val=0.) # Coupling parameter self.add_param('y2', val=0.) # Coupling output self.add_output('y1', val=1.0) def solve_nonlinear(self, params, unknowns, resids): """Evaluates the equation y1 = z1**2 + z2 + x1 - 0.2*y2""" z1 = params['z'][0] z2 = params['z'][1] x1 = params['x'] y2 = params['y2'] unknowns['y1'] = z1**2 + z2 + x1 - 0.2*y2 def linearize(self, params, unknowns, resids): """ Jacobian for Sellar discipline 1.""" J = {} J['y1','y2'] = -0.2 J['y1','z'] = np.array([[2*params['z'][0], 1.0]]) J['y1','x'] = 1.0 return J class SellarDis2(Component): """Component containing Discipline 2.""" def __init__(self): super(SellarDis2, self).__init__() # Global Design Variable self.add_param('z', val=np.zeros(2)) # Coupling parameter self.add_param('y1', val=0.) # Coupling output self.add_output('y2', val=1.0) def solve_nonlinear(self, params, unknowns, resids): """Evaluates the equation y2 = y1**(.5) + z1 + z2""" z1 = params['z'][0] z2 = params['z'][1] y1 = params['y1'] # Note: this may cause some issues. However, y1 is constrained to be # above 3.16, so let…
has title: Distributed Architectures
accepted answer: http://stackoverflow.com/a/48393288
type: Question
tagged with: openmdao
has answer: http://stackoverflow.com/a/48393288
linked to: http://stackoverflow.com/q/42611927
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83698749
type: AnswerComment
has text: I'd also add a clock to show the questioner how to cap the frame rate, and replace [`quit()` by `sys.exit()`](https://stackoverflow.com/a/19747562/6220679) or just a flag to leave the while loop. The `time` import can be removed as well.
comment on: http://stackoverflow.com/a/48355258
type: Comment
score: 1

http://stackoverflow.com/q/48347269
has comment: http://stackoverflow.com/comment/83684179
has title: Using Boto3 to upload a file to Amazon WorkDocs
has comment: http://stackoverflow.com/comment/96841109
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/83681280
downvote count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83690210
has body: According to the Amazon WorkDocs SDK page, you can use Boto3 to migrate your content to Amazon WorkDocs. I found the entry for the WorkSpaces Client in the Boto3 documentation, but every call seems to require a "AuthenticationToken" parameter. The only information I can find on AuthenticationToken is that is it supposed to be a "Amazon WorkDocs authentication token". Does anyone know what this token is? How do I get one? Is there any code examples of using the WorkDocs Client in Boto3? I am trying to create a simple Python script that will upload a single document into WorkDocs, but there seems to be little to no information on how to do this. I was easily able to write a script that can upload/download files from S3, but this seems like something else entirely.
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
type: Question
score: 2

http://stackoverflow.com/q/48374469
score: 0
accepted answer: http://stackoverflow.com/a/48380429
has title: python findall and regex while searching in the entire row
tagged with: find
linked to: http://stackoverflow.com/q/48346183
has answer: http://stackoverflow.com/a/48380429
answer count: 1
type: Question
has body: I have below code that searches for a given words in the entire row. The code is from my earlier question. Currently, python search for occurrence of given words within the row. But I want to find complete words only. when python searches for 'jo', it shouldn't return any results as there is no word 'jo', but when searching for 'jones' python should return 5 in the first row 1) How should I modify my search? I understand that I have to use regex. But I am not sure how to implement it. I tried findall((?i)\bsearch_string\b), but got an error 2) Below code gives errors if any column has datatype float. To overcome the problem, I am splitting my original dataframe in non-numeric and numeric columns, running below code and then joining numeric columns back. Is there an elegant way to do the same sales = [{'account': 'jones', 'Jan': '150 jones', 'Feb': '200 jones', 'Mar': '140 jones jones'}, {'account': '1', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'}, {'account': '1', 'Jan': '50', 'Feb': '90', 'Mar': '95' }] df = pd.DataFrame(sales) df df_list = [] search_string='jones' for search_string in ['jo', 'jones']: #use above method but rename the series instead of setting to # a columns. The append to a list. df_list.append(df.apply(lambda x: x.str.lower().str.findall(search_string).str.len()).sum(axis=1).astype(int).rename(search_string)) #concatenate the list of series into a DataFrame with the original df df = pd.concat([df] + df_list, axis=1) df # Updated code that uses answer given below sales = [{'account': 'jones.', 'Jan': '150 jones', 'Feb': '200 .jones', 'Mar': '140 jones jones'}, {'account': '1', 'Jan': 'Jones', 'Feb': '210', 'Mar': '215'}, {'account': '1', 'Jan': '50', 'Feb': '90', 'Mar': '95' }] df = pd.DataFrame(sales) df df_list = [] search_string='jones' for search_string in ['jones.', 'jone','jones']: #use above method but rename the series instead of setting to # a columns. The append to a list. df_list.append(df.apply(lambda x: x.str.lower().str.findall(r'\b{…
tagged with: python
tagged with: regex
tagged with: search
type: AnsweredQuestion

http://stackoverflow.com/comment/83760503
score: 0
type: Comment
type: QuestionComment
has text: @anandsun im actually still confused to read regex pattern like this r'/&q=([^&]*)', so what i am doing was straight re.search the 'category' string one by one
comment on: http://stackoverflow.com/q/48386339

http://stackoverflow.com/comment/83941573
type: AnswerComment
comment on: http://stackoverflow.com/a/48466886
score: 0
has text: Cool thanks. Do you think I could bother you here in the comment section if I have any other things that are unclear ?
type: Comment

http://stackoverflow.com/comment/83961316
comment on: http://stackoverflow.com/a/48484217
has text: Thank You. I tried it out separately too. But didn't work. Would be great if you could tell me the exact usage! However, I was able to make it work when i used the full path of ffmpeg in os.system(). In order to retrieve the full path of ffmpeg, I used "which ffmpeg" in the terminal.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48355173
tagged with: python
has title: Flask session value not persisting on shared hosting
tagged with: flask
has comment: http://stackoverflow.com/comment/83906443
has answer: http://stackoverflow.com/a/48505148
type: AnsweredQuestion
tagged with: cs50
score: 1
has comment: http://stackoverflow.com/comment/83907998
answer count: 1
tagged with: cgi
accepted answer: http://stackoverflow.com/a/48505148
favorite count: 0
type: Question
tagged with: shared-hosting
has comment: http://stackoverflow.com/comment/83719173
has body: I developed a Flask application on localhost (running Python 3). It works, but when transferred to my shared hosting account (running Python 2), it doesn't. I fixed all the issues related to Python versions. But the session is not working. Its value does not persists between requests. I tried to recreate the problem with simpler code (test.py), the commented out part is how session is configured in my application: import sys sys.path.insert(0, '/home/user_name/public_html') from flask import Flask, request, session from flask.ext.session import Session from tempfile import mkdtemp from cs50 import SQL from constants import * app = Flask(__name__) #app.config["SESSION_TYPE"] = "filesystem" #app.config["SESSION_PERMANENT"] = False #app.config["SESSION_FILE_DIR"] = mkdtemp() Session(app) @app.route('/set/') def set(): session['key'] = 'value' return 'ok' @app.route('/get/') def get(): return "{}".format(session.get('key')) If you go to /set/, you will see ok. But on /get/ you will see None. And here's my CGI file (which I need only for shared hosting, not for localhost): #!/home/user_name/public_html/cgi-bin/flask/bin/python import sys sys.path.insert(0, '/home/user_name/public_html') # Enable CGI error reporting import cgitb cgitb.enable() import os from wsgiref.handlers import CGIHandler app = None try: import test app = test.app except Exception, e: print "Content-type: text/html" print cgitb.handler() exit() #os.environ['SERVER_PORT'] = '80' #os.environ['REQUEST_METHOD'] = 'POST' class ScriptNameStripper(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = '' return self.app(environ, start_response) app = ScriptNameStripper(app) try: CGIHandler().run(app) except Exception, e: print "Content-type: text/html" print cgitb.handler() exit() In case .htaccess file is needed: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /cgi-bin/mas.cgi/$1 [L] Googling didn't help, and other simil…
downvote count: 0
has comment: http://stackoverflow.com/comment/83840569
upvote count: 1

http://stackoverflow.com/a/48473564
score: 3
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48473543
has body: &gt;&gt;&gt; lst = [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] &gt;&gt;&gt; [str(x) + str(y) for x, y in lst] ['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
downvote count: 1

http://stackoverflow.com/a/48373464
type: Answer
answers question: http://stackoverflow.com/q/48373303
score: 0
has body: You're looking for the argparse module. You can use that to parse command line arguments. There are a lot of good examples in the docs.

http://stackoverflow.com/q/48371782
duplicate of: http://stackoverflow.com/q/45621722
has title: IndentationError: unexpected indent / python
favorite count: 0
type: Question
downvote count: 4
has body: def createnewwallet(request): data = {} mykey = RSA.generate(1024) public_key = mykey.publickey().exportKey('PEM') private_key = mykey.exportKey('PEM') wallet_id = hashlib.sha256(public_key).hexdigest() data["public_key"] = public_key data["private_key"] = private_key data["wallet_id"] = wallet_id return HttpResponse(json.dumps(data), content_type="application/json") when ı got go this code i got this alert ; File "/opt/venv/cloudbank/cloudbank/views.py", line 41 return HttpResponse(json.dumps(data), content_type="application/json") ^ IndentationError: unexpected indent anyone can help me thanks
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
has comment: http://stackoverflow.com/comment/83730573
score: -4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48371796
has answer: http://stackoverflow.com/a/48371796
answer count: 1
tagged with: python

http://stackoverflow.com/comment/83800682
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48405646
has text: I have tested it in PyQt5 5.9.2 in Arch Linux and I do not see that problem, it is probably a bug, report it to ubuntu.
score: 0

http://stackoverflow.com/q/48440753
has comment: http://stackoverflow.com/comment/83872666
has comment: http://stackoverflow.com/comment/83873846
has comment: http://stackoverflow.com/comment/83872764
has title: ImportError: No module named 'project.app'
has comment: http://stackoverflow.com/comment/83872875
has comment: http://stackoverflow.com/comment/83873212
has body: Getting this error whenever I use python manage.py test. It fails to import all of my apps. Here's an example: ImportError: No module named 'project.profiles' My project tree is: /project /project /profiles ... /bin /lib /include Any idea what the problem is? EDIT: Here's the traceback (it's the same traceback for each of the 9 apps, I removed 7 of the errors from below to reduce bloat): Creating test database for alias 'default'... System check identified no issues (0 silenced). EEEEEEEEE ====================================================================== ERROR: draft1.advertise (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: draft1.advertise Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'draft1.advertise' ====================================================================== ERROR: draft1.careers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: draft1.careers Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'draft1.careers' ====================================================================== ---------------------------------------------------------------------- Ran 9 tests in 0.002s FAILED (errors=9) Destroying test database for alias 'def…
has comment: http://stackoverflow.com/comment/83874863
has comment: http://stackoverflow.com/comment/83874446
type: Question
has comment: http://stackoverflow.com/comment/83875718
score: 0
has comment: http://stackoverflow.com/comment/83899761
answer count: 0
has comment: http://stackoverflow.com/comment/83874759
has comment: http://stackoverflow.com/comment/83872947
has comment: http://stackoverflow.com/comment/83873123
has comment: http://stackoverflow.com/comment/83872661
tagged with: django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83873975
has comment: http://stackoverflow.com/comment/83874162

http://stackoverflow.com/a/48371908
score: 2
has body: Stdin, by definition is a stream of bytes representing control codes and characters. It is not a stream of key events. To get keys, you need to use an OS specific function. On Linux, the curses window objects have a getch methods. (There is something for Windows in another module.) Tk, and Python's tkinter wrapper thereof, uses OS-specific methods to let one bind to both key press and release events, which include the modifiers you mention, in code that is mostly not OS specific.
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48371780

http://stackoverflow.com/q/48431125
tagged with: time
has title: Comparing times in a list and to give the time between instances
has comment: http://stackoverflow.com/comment/83853254
tagged with: compare
has comment: http://stackoverflow.com/comment/83853474
tagged with: python
accepted answer: http://stackoverflow.com/a/48431491
has comment: http://stackoverflow.com/comment/83853218
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/83853507
has body: I have a log that outputs the time stamps for time of boot. I want to compare the time between each boot in to mins and seconds. Here is the format of the list below. 16:18:17.10 16:20:31.48 = 2 mins 14.38 seconds &lt;-- This what i want the output to show. 16:27:52.06 = 3 mins 20.18 seconds &lt;-- This what i want the output to show. 16:33:33.06 16:35:50.94 Any help would be greatly appreciated. Edit: Thanks @smallwat3r the finished code is def split_format(var1, var2): hour = int(var1.split(':')[0]) - int(var2.split(':')[0]) minute = int(var1.split(':')[1]) - int(var2.split(':')[1]) seconds = float(var1.split (':')[2]) - float(var2.split(':')[2]) time = '{} hours {} minutes {} seconds'.format( hour, minute, round(seconds, 2) ) return time def getFile(): prose = str(input('Please enter the file path for your text file: ')) dictionary = {} infile = open(prose, 'r') line_num = 1 line_num2 = 2 for line in infile: dictionary[line_num]=line line_num += 1 line_num2 += 1 base = 1 base2 = 2 for x in dictionary: print(dictionary[base2],(split_format(dictionary[base2],dictionary[base]))) base += 1 base2 += 1 infile.close() getFile()
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48431491
type: Question

http://stackoverflow.com/q/48459628
tagged with: python
tagged with: excel
has body: I have simple code from https://automatetheboringstuff.com/chapter12/ Which should make a chart, but I have no idea why Reference module doesn't work for me in this example. import openpyxl from openpyxl import Workbook from openpyxl.charts import BarChart, Series, Reference wb = Workbook() ws = wb.active for i in range(10): ws.append([i]) values = Reference(ws, min_col = 1, min_row=1, max_col=1, max_row=10) chart = BarChart() chart.add_data(values) ws.add_chart(chart, "E15") wb.save("SampleChart.xlsx") It gives me a TypeError: Traceback (most recent call last): File "charts_excel.py", line 9, in &lt;module&gt; refObj = openpyxl.charts.Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) TypeError: __init__() got an unexpected keyword argument 'min_col' Does anyone have an idea why this code doesn't work? I didn't find the answer anywhere. I found couple examples where Reference is used but it also doesn't work for me, for example: values = openpyxl.charts.Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10)
score: 2
tagged with: charts
type: AnsweredQuestion
has title: Reference in openpyxl.charts doesn't work (min_col) Python 3
accepted answer: http://stackoverflow.com/a/48460257
possible better answer: http://stackoverflow.com/a/64732960
has answer: http://stackoverflow.com/a/48460257
favorite count: 0
has answer: http://stackoverflow.com/a/64732960
type: Question
answer count: 2
upvote count: 2
tagged with: openpyxl
downvote count: 0

http://stackoverflow.com/comment/83759343
has text: @KlausD. that was it, thank You very much
score: 0
comment on: http://stackoverflow.com/q/48385748
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83857341
type: Comment
type: AnswerComment
has text: Sure; the same way you could use a machine with 11 cores to calculate groups of 9 starting digits in parallel for eg. I don't think that's particularly insightful though? In any case it still sounds like a duplicate of [this](https://stackoverflow.com/questions/10262138/how-do-i-multi-process-the-itertools-product-module)
score: 0
comment on: http://stackoverflow.com/a/48432907

http://stackoverflow.com/q/48393806
downvote count: 0
has body: What is the difference between setting the logging level from the logger and from the handler? The following code: myLogging = logging.getLogger('myOp') myLogging.setLevel(10) hdlr = logging.FileHandler(myLogFile) myLogging.addHandler(hdlr) myLogging.debug("Message here") will log to myLogFile, but this other one won't: myLogging = logging.getLogger('myOp') hdlr = logging.FileHandler(myLogFile) hdlr.setLevel(10) myLogging.addHandler(hdlr) myLogging.debug("Message here") Why is it that the FileHandler.setLevel() won't write to myLogFile?
favorite count: 0
tagged with: logging
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/71776092
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48393882
possible better answer: http://stackoverflow.com/a/71776092
type: Question
has title: logging level vs handler level
answer count: 2
score: 5
tagged with: handler
accepted answer: http://stackoverflow.com/a/48393882

http://stackoverflow.com/comment/83655694
type: Comment
type: QuestionComment
has text: (The last sentence isn't strictly true in the technical sense, but I'm thinking it would help shape your thinking here. If several things are optional, you have to add some guidance as to what to skip if *something* is there and needs to be matched.)
score: 0
comment on: http://stackoverflow.com/q/48335102

http://stackoverflow.com/comment/83797877
type: Comment
type: QuestionComment
has text: `df.groupby(['Year', 'Month']).User.nunique()` would do it, I think.
score: 0
comment on: http://stackoverflow.com/q/48404694

http://stackoverflow.com/comment/83951005
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48478705
type: AnswerComment
has text: thanks. I see. you are right. let me try to make it specific.

http://stackoverflow.com/comment/83751404
type: Comment
type: QuestionComment
score: 0
has text: You'd need to declare `two_paths` as global for that to work. DFS is not exponential time. It's proportional to the number of nodes. You have to DFS to find the paths to the two (which you did) in `O(n)` and then you have to traverse up to `log(n)` of the two paths (not technically correct I guess, because it isn't a balanced binary tree, could be as worse as n I guess, but that doesn't effect the overall). So overall this is `O(n)`.
comment on: http://stackoverflow.com/q/48382047

http://stackoverflow.com/q/48343260
has comment: http://stackoverflow.com/comment/83672076
answer count: 0
has title: Tensorflow: can I define a weighted mean squared error loss function?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/132637007
downvote count: 0
tagged with: python
tagged with: keras
has body: I've got a data set with the following shape: x1 x2 x3 w y 1 2 5 3 4 4 6 6 1 2 5 2 7 3 1 1 6 8 1 8 ... I would like to predict y from x1, x2 and x3, with the following loss function (example in Pyhton): loss = numpy.dot(w, (y-y_pred)**2) Is it possible to train a model with this loss function in Tensorflow (or Keras)? The model must use only x1, x2 and x3 to predict y, while w is unknown during inference.
score: 3
has comment: http://stackoverflow.com/comment/132636999
upvote count: 3
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/132652198
has comment: http://stackoverflow.com/comment/83672023
type: Question

http://stackoverflow.com/a/48432602
has comment: http://stackoverflow.com/comment/83860089
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48432316
upvote count: 4
answers question: http://stackoverflow.com/q/48432316
has comment: http://stackoverflow.com/comment/83859856
has comment: http://stackoverflow.com/comment/83859899
has body: The class attributes was set outside of the class? why? timedelta doesn't exist when the body of the timedelta class is being executed. You have to execute all of the code in the class timedelta: block before the class object is created and can be used on its own. I wonder where does this AttributeError coming from? I can not find in anywhere in the source code that this error message will be raised? The datetime module is written in pure Python but tries to use a faster module written in C if it can. The pure Python code works as you'd expect: &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.modules['_datetime'] = None # prevent the C module from loading &gt;&gt;&gt; from datetime import timedelta &gt;&gt;&gt; timedelta.min = 5 &gt;&gt;&gt; timedelta.min 5 The timedelta class has tp_flags set to Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE. You can only set the attributes of objects which include the Py_TPFLAGS_HEAPTYPE flag.
type: Answer
score: 4

http://stackoverflow.com/comment/83673444
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48343268
type: QuestionComment
has text: This would only apply to infix operators for which there is a small (fixed) set. All these operators can be accessed as functions with the [`operator`](https://docs.python.org/3/library/operator.html) library. What you have done is simply to re-create the functionality of `apply` (which was deemed unnecessary and depreciated)

http://stackoverflow.com/a/48354384
has comment: http://stackoverflow.com/comment/83696648
type: Answer
has body: A Chainmap groups multiple dicts and returns a view.To dump it, you have to convert it to dict. Here is a minimal example: import collections import json a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print(json.dumps(dict(m))) &gt;&gt;{"b": "B", "a": "A", "c": "C"} This is your specific example: You have to access the index of your list to access the ChainMap object: t = [collections.ChainMap({'a': 'ITT002', 'b': {'c': '2', 'd': '2', 'e': '2'}, 'f': '2'}, {'g': {'h1': {'i': '22', 'j': '2', 'k': '2', 'l': '2', 'n': '2'}}})] print(json.dumps(dict(t[0]))) &gt;&gt;{"f": "2", "g": {"h1": {"i": "22", "j": "2", "k": "2", "l": "2", "n": "2"}}, "b": {"c": "2", "d": "2", "e": "2"}, "a": "ITT002"}
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48354341
answers question: http://stackoverflow.com/q/48354341

decode
tags question: http://stackoverflow.com/q/48359250
tag name: decode
tags question: http://stackoverflow.com/q/48430174
type: Tag

http://stackoverflow.com/a/48385223
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48384322
accepted answer of: http://stackoverflow.com/q/48384322
downvote count: 0
type: Answer
has body: Ideally it would be this: x = IndexedBase("x") i, j, N = symbols("i j N") expr = Sum(Product(exp(-x[j]**2), (j, 1, N)).diff(x[i]), (i, 1, N)) So far this is unevaluated, expr is Sum(Derivative(Product(exp(-x[j]**2), (j, 1, N)), x[i]), (i, 1, N)) The method doit can be used to evaluate it. Unfortunately the differentiation of a product doesn't quite work yet: expr.doit() returns N*Derivative(Product(exp(-x[j]**2), (j, 1, N)), x[i]) Rewriting the product as the sum prior to differentiation helps: expr = Sum(Product(exp(-x[j]**2), (j, 1, N)).rewrite(Sum).diff(x[i]), (i, 1, N)) expr.doit() returns Sum(Piecewise((-2*exp(Sum(log(exp(-x[j]**2)), (j, 1, N)))*x[i], (1 &lt;= i) &amp; (i &lt;= N)), (0, True)), (i, 1, N)) which is the correct result of differentiation. Sadly we have that extraneous condition in Piecewise, and also log(exp(...)) that should have been simplified. SymPy doesn't infer that (1 &lt;= i) &amp; (i &lt;= N) is True from the context of the outer sum, and it also hesitates to simplify log(exp thinking x[j] might be complex. So I resort to surgical procedure with Piecewise, replacing it by the first piece, and to forcefully expanding logs: e = expr.doit() p = next(iter(e.atoms(Piecewise))) e = expand_log(e.xreplace({p: p.args[0][0]}), force=True) Now e is Sum(-2*exp(Sum(-x[j]**2, (j, 1, N)))*x[i], (i, 1, N)) Couldn't get exp(Sum(..)) to become a Product again, unfortunately.
score: 3
has comment: http://stackoverflow.com/comment/83758515
upvote count: 3

http://stackoverflow.com/q/48403108
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83796753
tagged with: python
has body: I am attempting to read a .docx file into Python. The file is organized into two tables (it's messy), one with Chinese characters and the other with English. However, it seems that when I am reading the text from these tables, the parentheses do not show up. I read the text from the .docx file as follows import numpy as np from docx import Document doc = Document('2003 PPC for corpus.docx') chinese_text = doc.tables[0].rows[0].cells[0].text print(chinese_text) english_text = doc.tables[0].rows[0].cells[1].text.encode('utf-8') print(english_text) These print statements then show ［］女士们，先生们， and b"Good morning ladies and gentlemen, we are very honor My question is why am I not reading the characters inside the square brackets in the Chinese text. And why am I not reading the "(3)" at the start of the English text?
has comment: http://stackoverflow.com/comment/83794848
tagged with: text
score: 2
tagged with: .doc
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83795232
has title: Reading text that has parentheses
tagged with: unicode

http://stackoverflow.com/q/48361249
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83709309
tagged with: python
has body: train.py y = cnn_model.CNN(x) ... print("Optimization Finished!") tf.reset_default_graph() saver.restore(sess, MODEL_DIRECTORY) # Calculate accuracy for all mnist test images test_size = test_labels.shape[0] batch_size = 50 total_batch = int(test_size / batch_size) acc_buffer = [] # Loop over all batches for i in range(total_batch): # Compute the offset of the current minibatch in the data. offset = (i * batch_size) % (test_size) batch_xs = test_data[offset:(offset + batch_size), :] batch_ys = test_labels[offset:(offset + batch_size), :] y_final = sess.run(y, feed_dict={x: batch_xs, y_: batch_ys, is_training: False}) correct_prediction = numpy.equal(numpy.argmax(y_final, 1), numpy.argmax(batch_ys, 1)) acc_buffer.append(numpy.sum(correct_prediction) / batch_size) print("******Test Results **********") print("test accuracy for the current model: %g" % numpy.mean(acc_buffer)) test accuracy for the current model:0.9756 sess.close() tf.reset_default_graph() test.test_org(MODEL_DIRECTORY, batch_size) test.py def test_org(model_directory, batch_size): train_total_data, train_size, validation_data, validation_labels, test_data, test_labels = mnist_data.prepare_MNIST_data( False) is_training = tf.placeholder(tf.bool, name='MODE') # tf Graph input x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 10]) # answer y = cnn_model.CNN(x, is_training=is_training) # Add ops to save and restore all the variables sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer(), feed_dict={is_training: True}) # Restore variables from disk saver = tf.train.Saver() # Calculate accuracy for all mnist test images test_size = test_labels.shape[0] print(test_size) total_batch = int(test_size / batch_size) saver.restore(sess, model_directory) acc_buffer = [] # Loop over all batches for i in range(total_batch): # Compute the offset of the current minibatch in the data. offset = (i * batch_size) % (test_size) batch_xs = test_data[offset:(offset + batch_si…
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83713699
has title: I get a significant difference in my accuracy when testing a saved model in my current module or an external module
tagged with: tensorflow

http://stackoverflow.com/comment/83792451
comment on: http://stackoverflow.com/q/48401628
type: QuestionComment
has text: Thanks for reply! Looks like there is a hidden file in my folder but I can't see it even with 'ls' command
type: Comment
score: 0

http://stackoverflow.com/q/48458865
has body: Some previous information I have the following method which loads two data sets from disk then combines them and returns the combined data set. def _get_data(self, data_set_name): training_data = DataSet.from_file('path_to_data_file','path_to_label_file') test_data = DataSet.from_file('path_to_data_file','path_to_label_file') return training_data.concat(test_data) # doubles the memory consumption The DataSetlooks like this: class DataSet: def __init__(self, data, labels): self.x = data # float64 array of shape (x,y) self.y = labels # int array of shape (x,) def concat(self, other_data_set): new_x = numpy.vstack((self.x, other_data_set.x)) new_y = numpy.concatenate((self.y, other_data_set.y)) return DataSet(new_x, new_y) My Problem When calling DataSet.concat the memory gets doubled. That's expected behavior in first place, since numpy creates two new arrays containing the combined data. BUT after leaving the _get_data method, the variables training_data and test_data should no longer reference the smaller data sets. So I expected that the memory consumption should reduce again. This doesn't happen. Because I was wondering, I tried to call garbage collection manually without any success. data_set = _get_data('someName') gc.collect(0) gc.collect(1) gc.collect(2) # Still same memory consumption Can anyone explain to me what happens here? Am I doing something wrong? Update I measure the memory by the following code: pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0] / 2. ** 30 # memory use in GB print('memory use:', memoryUse)
has comment: http://stackoverflow.com/comment/83912147
score: 1
has answer: http://stackoverflow.com/a/48459808
tagged with: python
tagged with: numpy
tagged with: memory-management
has title: concatenate or vstack numpy arrays doubling memory
has comment: http://stackoverflow.com/comment/83912072
has comment: http://stackoverflow.com/comment/83911889
tagged with: arrays
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83911567
has comment: http://stackoverflow.com/comment/83911417
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83911503
accepted answer: http://stackoverflow.com/a/48459808
has comment: http://stackoverflow.com/comment/83911062

http://stackoverflow.com/comment/83649906
score: 0
type: AnswerComment
has text: @Valachio `chain` returns an iterable, which doesn't support `len`. To use it in the way you describe, make it a list first: `a = list(itertools.chain(a[1:2], a[4:7], a[9:10])); range(len(a))`. However, if that's your use-case, you're better off using list concatenation (see Scott Hunter's answer).
comment on: http://stackoverflow.com/a/48331947
type: Comment

http://stackoverflow.com/q/48425276
has body: I have this url that the content of its response, contains some JSON data. https://www.tripadvisor.com/TypeAheadJson?action=API&amp;types=geo%2Cnbrhd%2Chotel%2Ctheme_park&amp;legacy_format=true&amp;urlList=true&amp;strictParent=true&amp;query=sadaf%20dubai%20hotel&amp;max=6&amp;name_depth=3&amp;interleaved=true&amp;scoreThreshold=0.5&amp;strictAnd=false&amp;typeahead1_5=true&amp;disableMaxGroupSize=true&amp;geoBoostFix=true&amp;neighborhood_geos=true&amp;details=true&amp;link_type=hotel%2Cvr%2Ceat%2Cattr&amp;rescue=true&amp;uiOrigin=trip_search_Hotels&amp;source=trip_search_Hotels&amp;startTime=1516800919604&amp;searchSessionId=BA939B3D93510DABB510328CBF3353131516800881576ssid&amp;nearPages=true Everytime i paste this url in the browser with different queries, i get a nice JSON result. But in the scrapy or scrapy shell, i don't get any result. This is my scrapy spider class : link = "https://www.tripadvisor.com/TypeAheadJson?action=API&amp;types=geo%2Cnbrhd%2Chotel%2Ctheme_park&amp;legacy_format=true&amp;urlList=true&amp;strictParent=true&amp;query={}%20dubai%20hotel&amp;max=6&amp;name_depth=3&amp;interleaved=true&amp;scoreThreshold=0.5&amp;strictAnd=false&amp;typeahead1_5=true&amp;disableMaxGroupSize=true&amp;geoBoostFix=true&amp;neighborhood_geos=true&amp;details=true&amp;link_type=hotel%2Cvr%2Ceat%2Cattr&amp;rescue=true&amp;uiOrigin=trip_search_Hotels&amp;source=trip_search_Hotels&amp;startTime=1516800919604&amp;searchSessionId=BA939B3D93510DABB510328CBF3353131516800881576ssid&amp;nearPages=true" def start_requests(self): files = [f for f in listdir('results/') if isfile(join('results/', f))] for file in files: with open('results/' + file, 'r', encoding="utf8") as tour_info: tour = json.load(tour_info) for hotel in tour["hotels"]: yield scrapy.Request(self.link.format(hotel)) name = 'tripadvisor' allowed_domains = ['tripadvisor.com'] def parse(self, response): print(response.body) For this code, in scrapy shell, i get this result: b'{"normalized":{"query":""},"qu…
tagged with: scrapy
downvote count: 1
has comment: http://stackoverflow.com/comment/83843398
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48445165
tagged with: python
has title: scrape an api result page with scrapy
has comment: http://stackoverflow.com/comment/83841258
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1

http://stackoverflow.com/comment/83701574
has text: Since you are using android can't you use GRPC?. https://grpc.io/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48357439
score: 1

http://stackoverflow.com/a/48430919
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48430606
type: Answer
has body: Here my solution, I hope someone has a better one: g = sns.FacetGrid(df, col=col_quantity) def p(x, passed, **kwargs): bins = kwargs.get('bins', None) plt.hist(x, bins=bins, normed=False) plt.hist(x[passed == 1], bins=bins, normed=False) g = g.map(p, hist_quantity, "isPassed", bins=np.linspace(-5, 5, 50))
score: 1

http://stackoverflow.com/comment/83899104
has text: with this dataframe how I can set the Time as my only index and keep the smae structure ?
type: Comment
comment on: http://stackoverflow.com/a/48449277
score: 0
type: AnswerComment

http://stackoverflow.com/q/48336242
upvote count: 2
type: UnansweredQuestion
tagged with: sqlite
answer count: 1
downvote count: 0
has body: import sqlite3 location = 'data' table_name = 'table_name' try: conn = sqlite3.connect(location) c = conn.cursor() sql = 'insert into ' + table_name + ' (id) values (%d)' % (1) c.execute(sql) # Some exception occurs here conn.commit() # This line is not reached, so database is locked. except Exception as e: pass: So if we run the above code and an exception occurs, the database is locked. So what should we do ? EDIT: I am aware that this is vulnerable to sql injection. I've posted this example simply so that I can quickly ask the question.
has comment: http://stackoverflow.com/comment/83657780
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48336463
has title: What to do with sqlite connection if an exception occurs before you can close the connection and datasbe is locked?
tagged with: python
has comment: http://stackoverflow.com/comment/83657525
tagged with: python-3.x
score: 2

http://stackoverflow.com/comment/83718422
score: 0
comment on: http://stackoverflow.com/q/48362679
type: Comment
type: QuestionComment
has text: I use Webfaction, Google Cloud and Azure. Their cheapest stuff is good enough for proof-of-concept web apps and even for production.

http://stackoverflow.com/q/48436380
has comment: http://stackoverflow.com/comment/83864947
has comment: http://stackoverflow.com/comment/83864181
has comment: http://stackoverflow.com/comment/83864087
tagged with: python
upvote count: 6
has title: why blas is slower than numpy
has comment: http://stackoverflow.com/comment/83910050
tagged with: c++
tagged with: numpy
has comment: http://stackoverflow.com/comment/83907932
has comment: http://stackoverflow.com/comment/83980840
has comment: http://stackoverflow.com/comment/83864125
has comment: http://stackoverflow.com/comment/83866667
has comment: http://stackoverflow.com/comment/83877004
has comment: http://stackoverflow.com/comment/83865996
has comment: http://stackoverflow.com/comment/83864105
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83880190
has comment: http://stackoverflow.com/comment/83907781
has comment: http://stackoverflow.com/comment/83864142
score: 4
has comment: http://stackoverflow.com/comment/83865124
has body: Thanks for Mats Petersson's help. The running time of his C++ does look properly finally! But I have new two questions. Why Mats Petersson's code is twice times faster than my code ? Mats Petersson's C++ code is: #include &lt;iostream&gt; #include &lt;openblas/cblas.h&gt; #include &lt;array&gt; #include &lt;iterator&gt; #include &lt;random&gt; #include &lt;ctime&gt; using namespace std; const blasint m = 100, k = 100, n = 100; // Mats Petersson's declaration array&lt;array&lt;double, k&gt;, m&gt; AA[500]; array&lt;array&lt;double, n&gt;, k&gt; BB[500]; array&lt;array&lt;double, n&gt;, m&gt; CC[500]; // My declaration array&lt;array&lt;double, k&gt;, m&gt; AA1; array&lt;array&lt;double, n&gt;, k&gt; BB1; array&lt;array&lt;double, n&gt;, m&gt; CC1; int main(void) { CBLAS_ORDER Order = CblasRowMajor; CBLAS_TRANSPOSE TransA = CblasNoTrans, TransB = CblasNoTrans; const float alpha = 1; const float beta = 0; const int lda = k; const int ldb = n; const int ldc = n; default_random_engine r_engine(time(0)); uniform_real_distribution&lt;double&gt; uniform(0, 1); double dur = 0; clock_t start,end; double total = 0; // Mats Petersson's initialization and computation for(int i = 0; i &lt; 500; i++) { for (array&lt;array&lt;double, k&gt;, m&gt;::iterator iter = AA[i].begin(); iter != AA[i].end(); ++iter) { for (double &amp;number : (*iter)) number = uniform(r_engine); } for (array&lt;array&lt;double, n&gt;, k&gt;::iterator iter = BB[i].begin(); iter != BB[i].end(); ++iter) { for (double &amp;number : (*iter)) number = uniform(r_engine); } } start = clock(); for(int i = 0; i &lt; 500; ++i){ cblas_dgemm(Order, TransA, TransB, m, n, k, alpha, &amp;AA[i][0][0], lda, &amp;BB[i][0][0], ldb, beta, &amp;CC[i][0][0], ldc); } end = clock(); dur += (double)(end - start); cout&lt;&lt;endl&lt;&lt;"Mats Petersson spends "&lt;&lt;(dur/CLOCKS_PER_SEC)&lt;&lt;" seconds to compute it"&lt;&lt;endl&lt;&lt;endl; // It turns me! dur = 0; for(int i = 0; i &lt; 500; i++){ for(array&lt;array&lt;double, k…
accepted answer: http://stackoverflow.com/a/48438678
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48438678
has comment: http://stackoverflow.com/comment/83874379

http://stackoverflow.com/a/48366525
downvote count: 0
score: 89
type: Answer
answers question: http://stackoverflow.com/q/48366506
upvote count: 89
has body: Use .mean. By specifying the axis you can take the average across the row or the column. df['average'] = df.mean(axis=1) df returns salary_1 salary_2 salary_3 average 0 230 235 210 225.000000 1 345 375 385 368.333333 2 222 292 260 258.000000 If you only want the mean of a few you can select only those columns. E.g. df['average_1_3'] = df'salary_1', 'salary_3'.mean(axis=1) df returns salary_1 salary_2 salary_3 average_1_3 0 230 235 210 220.0 1 345 375 385 365.0 2 222 292 260 241.0

http://stackoverflow.com/comment/83711951
comment on: http://stackoverflow.com/a/48362464
score: 0
type: Comment
has text: I modified this and succeeded 90% , there is still one space left between the digits : http://i66.tinypic.com/1fcl05.png
type: AnswerComment

http://stackoverflow.com/comment/83964484
has text: Thank you! This helped me a lot!
score: 0
comment on: http://stackoverflow.com/a/48485606
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83663340
has text: I just want to identify them, most likely will then keep first (need to analyse my dataset first)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48338971
score: 0

http://stackoverflow.com/q/48367943
type: AnsweredQuestion
tagged with: django-views
answer count: 2
has answer: http://stackoverflow.com/a/48368011
score: 0
has body: These are the relevant classes of my app. I want basically understand if the a certain user (form AuthUser) is linked to a business (from BusinessInformation) by looking at UserBusinessInformation. Thanks class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class BusinessInformation(models.Model): business_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lat = models.CharField(max_length=255) lng = models.CharField(max_length=255) formatted_address = models.CharField(max_length=255, blank=True, null=True) locality = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_5 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_4 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_3 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_2 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_1 = models.CharField(max_length=255, blank=True, null=True) postal_code = models.CharField(max_length=45, blank=True, null=True) route = models.CharField(max_length=255, blank=True, null=True) street_number = models.CharField(max_length=45, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) phone2 = models.CharField(max_length=255, blank=True, null=True) phone3 = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255,…
type: Question
possible better answer: http://stackoverflow.com/a/48368081
has answer: http://stackoverflow.com/a/48368081
has title: How can I access objects in a django model composed of two foreign keys?
tagged with: django
tagged with: django-models
tagged with: python
accepted answer: http://stackoverflow.com/a/48368011

http://stackoverflow.com/q/48392096
has comment: http://stackoverflow.com/comment/83772207
answer count: 3
has title: Passing global var values between Processes
has comment: http://stackoverflow.com/comment/83772212
tagged with: multithreading
type: Question
tagged with: scope
has comment: http://stackoverflow.com/comment/83772464
has answer: http://stackoverflow.com/a/48392563
has answer: http://stackoverflow.com/a/48392282
has comment: http://stackoverflow.com/comment/85436561
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83772301
linked to: http://stackoverflow.com/q/17377426
has comment: http://stackoverflow.com/comment/84039714
tagged with: python
has comment: http://stackoverflow.com/comment/83772283
has body: So, the one missing piece to a complex (for me at least) program I made in python is that I have two variables outside of two functions (both of which funcs I run as processes, and the processes execute concurrently as expected), and the issue I have is both Process functions are altering the exterior (global) variables, yet when I try to get one from the other, it does not get the proper value (in fact, the first function does not receive any change when the other function prints it. I made a really simplified version of this issue to help explain: from multiprocessing import Process import time global n def func1(): n = False while True: print(n) time.sleep(1) def func2(): n = False while True: n = True time.sleep(1) Process(target=func1).start() Process(target=func2).start() So, as you see, n is not getting changed (at least not in the func1). Even if it were to get changed I believe that as they run concurrently it would reset back, as the process would call and reset the value, and I'm really not sure how to get around this situation. I do understand scope but everything I had read indicated this was the proper way to declare this, I was confused as well, but did so. What am I missing/what syntax am I incorrectly handling? I'm sure this is a simple question, and apologies for it, but could not find on this site or elsewhere and it's driving me nuts.
has comment: http://stackoverflow.com/comment/83772370
has answer: http://stackoverflow.com/a/48392338
score: 0

http://stackoverflow.com/a/48348060
score: 38
type: Answer
has body: df['Cumulative'] = df.Profit.cumsum().round(2) df['HighValue'] = df['Cumulative'].cummax() df['Drawdown'] = df['Cumulative'] - df['HighValue'] That is the simplest solution I found.
answers question: http://stackoverflow.com/q/48344727
upvote count: 38
downvote count: 0

http://stackoverflow.com/comment/83862752
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48414717
type: QuestionComment
has text: [This](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.max.html)

http://stackoverflow.com/a/48360747
downvote count: 0
has comment: http://stackoverflow.com/comment/83708608
has comment: http://stackoverflow.com/comment/83708632
has comment: http://stackoverflow.com/comment/83708457
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/83709104
answers question: http://stackoverflow.com/q/48360678
has body: Yes! You have a few options. One quick and dirty thing that I employ frequently is dropping to a console. Add this to the end of your script (right after the training finishes): model = train_for_hours_and_hours() import code code.interact(local=locals()) This works exactly like just the REPL you get from running python3, except all of the variables (including your trained model) are available: $ python3 script.py [ ... THREE HOURS LATER ... ] &gt; print(model) &lt;NLTK.Model ...&gt; A more permanent solution would be to serialize your model and save it to a file right after training finishes. To do this you can use pickle: import pickle MODEL_FILE = 'model.pickle' try: # Try to load the model from disk with open(MODEL_FILE, 'rb') as f: model = pickle.load(f) except FileNotFoundError: # Train the model if it doesn't exist yet model = train_for_hours_and_hours() with open(MODEL_FILE, 'wb') as f: pickle.dump(f, model) # now use `model` here
score: 5

http://stackoverflow.com/q/48410192
answer count: 2
tagged with: code-coverage
possible better answer: http://stackoverflow.com/a/48447512
downvote count: 0
accepted answer: http://stackoverflow.com/a/48418446
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/48418446
has answer: http://stackoverflow.com/a/48447512
favorite count: 0
type: AnsweredQuestion
has body: When I try to send a python project with sonar-scanner, it throws an exception: Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1.". Before trying to introduce the cover, the project was run normally, the project is python code and the report is created with django-nose. More information: sonar version: 6.7.1 sonar scanner command: sonar-scanner -Dsonar.projectKey=nanas -Dsonar.host.url=http://192.168.0.1:9001 -Dsonar.login=F00B4Z sonar doesn't run through a proxy I'm attaching the sonar project configuration file and coverage xml file generated by django-nose. Exception: 12:53:31.919 ERROR: Error during SonarQube Scanner execution Error during parsing of the generic coverage report '/home/bamboo-home/xml-data/build-dir/NAN-CI6-JOB1/xmlrunner/coverage.xml'. Look at SonarQube documentation to know the expected XML format. Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1. at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parseRootNode(GenericCoverageReportParser.java:72) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.lambda$parse$0(GenericCoverageReportParser.java:64) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:115) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:95) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:65) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:54) at org.sonar.scanner.genericcoverage.GenericCoverageSensor.execute(GenericCoverageSensor.java:109) at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53) at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:88) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:82) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:68) at org.sonar.scan…
score: 1
has title: Why doesn't Sonar read the format of django-nose coverage results?
tagged with: python
tagged with: sonarqube
type: Question

http://stackoverflow.com/q/48424813
tagged with: dask
tagged with: performance
has comment: http://stackoverflow.com/comment/83843909
has body: Hi I have a python script that uses dask library to handle a very large data frame, larger than the physical memory. I notice that the job get killed in the middle of a run if the memory usage stays at 100% of the computer for some time. Is it expected? I would thought the data would be spilled to disk and there are plenty of disk space left. Is there a way to limit its total memory usage? Thanks EDIT: I also tried: dask.set_options(available_memory=12e9) It did not work. It did not seemed to limit its memory usage. Again, when memory usage reach 100%, the job gets killed.
accepted answer: http://stackoverflow.com/a/48426917
tagged with: python
score: 4
has title: dask job killed because memory usage?
has answer: http://stackoverflow.com/a/48426917
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48425028
answer count: 2
has comment: http://stackoverflow.com/comment/83839278
has answer: http://stackoverflow.com/a/48425028
downvote count: 0
has comment: http://stackoverflow.com/comment/83840007
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83839429

http://stackoverflow.com/q/48431579
has body: I'm creating a bot with python &amp; selenium to subscribe to a list of channels. The problem I'm having is that sometimes its already subscribed and errors. I'm therefore trying to make a function to check if its already subscribed with is_displayed() but it what i've tried isn't working. The error message I receive is :Message: no such element: unable to locate element ( https://prnt.sc/i54an3 ) And my code is: if driver.find_element_by_xpath('//paper-button[@subscribed=""]').is_displayed() &amp; driver.find_element_by_xpath('//paper-button[@aria-label="Se désabonner de cette chaîne"]').is_displayed(): do what i want else: do what i want
score: 0
has comment: http://stackoverflow.com/comment/83855101
tagged with: selenium
has title: subscribe button youtube with selenium python
has comment: http://stackoverflow.com/comment/83854449
type: Question
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48432179
tagged with: python
has comment: http://stackoverflow.com/comment/83860741
has comment: http://stackoverflow.com/comment/83854519

http://stackoverflow.com/comment/83956860
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48481927
type: QuestionComment
has text: And I took the paths from my user (c:users)

http://stackoverflow.com/q/48487623
accepted answer: http://stackoverflow.com/a/48487732
tagged with: multithreading
downvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/67019453
possible better answer: http://stackoverflow.com/a/67019453
has title: Running time.sleep() on another thread freezes Tkinter program
has answer: http://stackoverflow.com/a/48487732
type: Question
tagged with: timer
answer count: 2
has body: So I am trying to run time.sleep() on another thread, but the my entire program still freezes upon calling the function. I call it using a button. This is to create an error, and then wait a couple seconds to remove the error. Not sure what else to do here. import threading, time class Block(): def createError(self, text): background.itemconfig(errorText, text=text, state=NORMAL, font="Neoteric 11 bold") background.itemconfig(errorBG, state=NORMAL) # Mainly this part to worry about t = threading.Thread(target=self.removeError()) t.start() print("Function called") # Only prints AFTER 5 seconds, even though removeError() should be running on another thread def removeError(self): time.sleep(5) background.itemconfig(errorText, text="", state=HIDDEN) background.itemconfig(errorBG, state=HIDDEN) # Tkinter stuff here to create button and run createError() Any ideas would be awesome!
tagged with: python-multithreading
upvote count: 1

http://stackoverflow.com/a/66413913
has body: you can just enter colon(:) between format= like this below df['Date/Time']=pd.to_datetime(df['Date/Time'],format='%m/%d/%Y %H:%M:%S')
downvote count: 0
upvote count: 8
answers question: http://stackoverflow.com/q/48444373
type: Answer
score: 8

http://stackoverflow.com/comment/83922481
type: Comment
has text: I dont understand your shell script. You set as condition "run the python script" with a empty loop body?
type: AnswerComment
comment on: http://stackoverflow.com/a/48463730
score: 0

http://stackoverflow.com/q/48468702
type: Question
has body: I'm trying to setup a static webpage on the Google Cloud Platform (GCP) with a contact-form. I originally used php but it doesn't work with GCP. In my research,LINK, I tried using the provided code and got the following error: Leave a message INFO 2018-01-26 11:17:08,904 module.py:833] default: "POST / HTTP/1.1" 500 2317 File "F:\Programs\google-cloud-sdk\platform\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "F:\Documents\Programming\html\perrykowebdesigns2\contact.py", line 48, in post message.send() File "F:\Programs\google-cloud-sdk\platform\google_appengine\google\appengine\api\mail.py", line 1129, in send message = self.ToProto() File "F:\Programs\google-cloud-sdk\platform\google_appengine\google\appengine\api\mail.py", line 1385, in ToProto message = super(EmailMessage, self).ToProto() File "F:\Programs\google-cloud-sdk\platform\google_appengine\google\appengine\api\mail.py", line 1067, in ToProto self.check_initialized() File "F:\Programs\google-cloud-sdk\platform\google_appengine\google\appengine\api\mail.py", line 1370, in check_initialized raise MissingRecipientsError() MissingRecipientsError I'm relatively new, so I don't understand the error and how to fix it. If you understand how to fix it, please provide the solution. Thanks! import webapp2 import jinja2 import os from google.appengine.api import mail template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) class Handler(webapp2.RequestHandler): def write(self, * a, * * kw): self.response.out.write( * a, * * kw) def render_str(self, template, * * params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, * * kw):`enter code here` self.write(self.render_str(template, * * kw)) class contact(Handler): def get(self): self.render("contact.html") # template = jinja_env.get_template('contact.html')# def …
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48483853
answer count: 1
has comment: http://stackoverflow.com/comment/83957688
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83932402
favorite count: 0
tagged with: google-app-engine
score: 1
has title: Google App Engine Error - in check_initialized raise MissingRecipientsError()
tagged with: python
tagged with: contact-form

http://stackoverflow.com/q/48410063
has body: Error Generated: UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) Data Example: 2014-08-06 7:00,4.06E+04,42878.05892 2014-08-06 8:00,4.40E+04,42857.00667 I followed this accepted answer but haven't had any luck making it work: timestamps passed to matplotlib.date2num: 'str' object has no attribute 'toordinal' Code: timeformat = '%Y-%m-%d %H:%M' columns = ["Datetime","Prediction","Actual"] dtypes = ["object","float","float"] myResults1 = np.genfromtxt("/Users/project/results_1.csv", delimiter=",", names=columns, dtype=dtypes) time = [datetime.strptime(i,timeformat) for i in myResults1['Datetime']] predictions = myResults1['Prediction'] actual = myResults1['Actual'] fig = pyplot.figure() ax1 = fig.add_subplot(3,2,1,axisbg='grey') ax1.plot_date(time,predictions) ax1.set_xlabel('Time') ax1.set_ylabel('Prediction') pyplot.setp(ax1.xaxis.get_majorticklabels(),rotation=25) Thanks anyone who can help!!
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83864455
has title: How to Solve UnicodeDecodeError when plotting Time Series in Python?
has comment: http://stackoverflow.com/comment/83810599
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33001373
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25391617
tagged with: matplotlib
tagged with: python
duplicate of: http://stackoverflow.com/q/33001373
has comment: http://stackoverflow.com/comment/83810969
answer count: 0

http://stackoverflow.com/comment/83819077
score: 0
comment on: http://stackoverflow.com/q/48414513
type: Comment
has text: Why not place a `print(unit)` in your for loop and observe, what `unit` and `unit[0]` really is instead of guessing? Or try your code on [Pythontutor](http://pythontutor.com/visualize.html#mode=edit)
type: QuestionComment

http://stackoverflow.com/comment/83823493
type: Comment
has text: That is explained [here](https://docs.python.org/3/reference/expressions.html#evaluation-order). When `=` is used, the expression becomes L.H.S and R.H.S. Here LHS is a tuple and RHS is a tuple. The values are assigned with one to one correspondence.
comment on: http://stackoverflow.com/a/48416477
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83890245
type: QuestionComment
comment on: http://stackoverflow.com/q/48448830
has text: Check out `hashlib`, pythons builtin hashing library.
score: 1
type: Comment

ethereum
type: Tag
tags question: http://stackoverflow.com/q/48432880
tags question: http://stackoverflow.com/q/48413900
tags question: http://stackoverflow.com/q/48334659
tag name: ethereum

http://stackoverflow.com/q/48432029
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52971142
tagged with: python
answer count: 4
upvote count: 19
has answer: http://stackoverflow.com/a/48432979
has answer: http://stackoverflow.com/a/71518298
has title: Mocking requests.post and requests.json decoder python
has body: I'm creating a test suite for my module that uses the requests library quite a bit. However, I'm trying to mock several different return values for a specific request, and I'm having trouble doing so. Here is my code snippet that doesn't work: class MyTests(unittest.TestCase): @patch('mypackage.mymodule.requests.post') def test_change_nested_dict_function(self, mock_post): mock_post.return_value.status_code = 200 mock_post.return_value.json = nested_dictionary modified_dict = mymodule.change_nested_dict() self.assertEqual(modified_dict['key1']['key2'][0]['key3'], 'replaced_value') The function I am attempting to mock: import requests def change_nested_dict(): uri = 'http://this_is_the_endpoint/I/am/hitting' payload = {'param1': 'foo', 'param2': 'bar'} r = requests.post(uri, params=payload) # This function checks to make sure the response is giving the # correct status code, hence why I need to mock the status code above raise_error_if_bad_status_code(r) dict_to_be_changed = r.json() def _internal_fxn_to_change_nested_value(dict): ''' This goes through the dict and finds the correct key to change the value. This is the actual function I am trying to test above''' return changed_dict modified_dict = _internal_fxn_to_change_nested_value(dict_to_be_changed) return modified_dict I know a simple way of doing this would be to not have a nested function, but I am only showing you part of the entire function's code. Trust me, the nested function is necessary and I really do not want to change that part of it. My issue is, I don't understand how to mock requests.post and then set the return value for both the status code and the internal json decoder. I also can't seem to find a way around this issue since I can't seem to patch the internal function either, which also would solve this problem. Does anyone have any suggestions/ideas? Thanks a bunch.
has answer: http://stackoverflow.com/a/52971142
downvote count: 0
has answer: http://stackoverflow.com/a/48439628
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83859901
score: 19
accepted answer: http://stackoverflow.com/a/48432979
favorite count: 0
tagged with: unit-testing
type: Question

http://stackoverflow.com/a/48410871
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48410616
has body: Without a regex, you could achieve a O(n) solution: &gt;&gt;&gt; s = "About 181,000 results" &gt;&gt;&gt; int(''.join(i for i in s if i.isdigit())) 181000
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48410616

http://stackoverflow.com/a/48339216
has comment: http://stackoverflow.com/comment/83663921
type: Answer
has comment: http://stackoverflow.com/comment/83667985
has comment: http://stackoverflow.com/comment/83666258
has comment: http://stackoverflow.com/comment/83667781
score: 0
has body: The error says it all : OUT: ElementNotVisibleException: element not visible: Element is nocurrently visible and may not be manipulated(Session info: crome=63.0.3239.132) The error clearly indicates that the element with which you are trying to interact is not visible as they are dynamic. So we have to induce Explicit Wait for the element_to_be_visible as follows : from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://www.costacrociere.it/B2C/I/Pages/Default.aspx') driver.maximize_window() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='selectric-wrapper selectric-ddlMacroArea']"))).click() WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='selectric-items']//ul//li[text()='Caraibi']"))).click() print("Option Caraibi clicked") Console Output : Option Caraibi clicked
answers question: http://stackoverflow.com/q/48337788
has comment: http://stackoverflow.com/comment/83664259

http://stackoverflow.com/q/48435894
answer count: 1
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48438870
type: UnansweredQuestion
tagged with: python
has title: Slicing from date from csv file rows
score: 2
downvote count: 0
tagged with: pandas
has body: date LEV1 LEV2 LEV3 L2 L3 L4 2013-01-01 1:00 266.591 266.591 266.591 1000 1200 1400 2013-01-01 2:00 266.479 266.479 266.479 1000 1200 1400 2013-01-01 3:00 266.373 266.373 266.373 1000 1200 1400 2013-01-01 4:00 266.273 266.273 266.273 1000 1200 1400 2013-01-01 5:00 266.178 266.178 266.178 1000 1200 1400 2013-01-01 6:00 265.05 265.05 265.05 1000 1200 1400 2013-01-01 7:00 266.065 266.065 266.065 1000 1200 1400 I want to select and plot the data (from pandas dataframe) as X and Y for each hour on multiple figures for the selected range (say 2013-01-01 20:00 to 2013-01-02 15:00). I want to select rows based on selected range for values from column 2~4 as X-axis with 3 records in each row [273.548 273.322 272.8313] and for the same date range another set of rows as Y-axis e.g. [1000 1200 1400] for values from columns 39~41. I tried with import pandas as pd dft = pd.read_table("3year.csv", sep=" ",delimiter =",") J = dft'LEV1','LEV2', 'LEV3'.as_matrix() G = dft'L2','L3','L4'.as_matrix() print J [ 270. 270. 270.] [ 270. 270. 270.] [ 270. 270. 270.] ..., [ 273.548 273.322 272.831] [ 273.575 273.289 272.634] [ 273.598 273.254 272.43]] but I can not select based on dates as it selects out all the data for the relevant columns
tagged with: matplotlib

http://stackoverflow.com/a/48411808
has comment: http://stackoverflow.com/comment/83826964
type: Answer
downvote count: 0
has body: I'm not sure you need to specify the package kwarg, import_module says this about the package kwarg: The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. I usually just use importlib.import_module in this way (I guess specifying it as an absolute import): import importlib m = importlib.import_module('package.models.ModelClass') Sometimes I might set a variable in django settings like MY_CLASS='package.models.ModelClass' and use import_module to switch between what class is being used.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48411672
has comment: http://stackoverflow.com/comment/83827303
has comment: http://stackoverflow.com/comment/83825586

http://stackoverflow.com/q/48351673
upvote count: 0
has body: I have following two lists to combine. I'm trying to use zip() but header_list runs out for obvious reason. header_list = ['1 mo', '3 mo', '6 mo', '1 yr', '2 yr', '3 yr', '5 yr', '7 yr', '10 yr', '20 yr', '30 yr'] data_list = [1.29, 1.44, 1.61, 1.83, 1.92, 2.01, 2.25, 2.38, 2.46, 2.64, 2.81, 1.29, 1.41, 1.59, 1.81, 1.94, 2.02, 2.25, 2.37, 2.44, 2.62, 2.78, 1.28, 1.41, 1.6, 1.82, 1.96, 2.05, 2.27, 2.38, 2.46, 2.62, 2.79] The result should be a tuple in the following format: ('1 mo', 1.29) ('3 mo', 1.44) ('6 mo', 1.61) ('1 yr', 1.83) ('2 yr', 1.92) ('3 yr', 2.01) ('5 yr', 2.25) ('7 yr', 2.38) ('10 yr', 2.46) ('20 yr', 2.64) ('30 yr', 2.81) ('1 mo', 1.29) ('3 mo', 1.41) ('6 mo', 1.59) ('1 yr', 1.81) ('2 yr', 1.94) ('3 yr', 2.02) ('5 yr', 2.25) ('7 yr', 2.37) ('10 yr', 2.44) ('20 yr', 2.62) ('30 yr', 2.78) ...
duplicate of: http://stackoverflow.com/q/19686533
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48351719
answer count: 3
possible better answer: http://stackoverflow.com/a/48351701
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48351701
has title: Combining two lists which do not have same numbers of entries
type: Question
accepted answer: http://stackoverflow.com/a/48351707
linked to: http://stackoverflow.com/q/19686533
has answer: http://stackoverflow.com/a/48351707

http://stackoverflow.com/a/48444949
accepted answer of: http://stackoverflow.com/q/48444246
type: Answer
answers question: http://stackoverflow.com/q/48444246
has comment: http://stackoverflow.com/comment/83881471
score: 1
has body: If you want to run specific methods for options, simply check the sent string and select the method based on the string using if / elif statements: from tkinter import * def xyz17(): print('xyz17') def abc27(): print('abc27') def qwe90(): print('qwe90') def uio19(): print('uio19') def jkl09(): print('jkl09') def zxc28(): print('zxc28') class Menu(OptionMenu): def __init__(self, master, status, *options): self.var = StringVar(master) self.var.set(status) OptionMenu.__init__(self, master, self.var, *options, command=self.option_handle) def option_handle(self, selected): # above specific case is simply print(selected) but if selected == "xyz17": xyz17() elif selected == "abc27": abc27() elif selected == "qwe90": qwe90() elif selected == "uio19": uio19() elif selected == "jkl09": jkl09() elif selected == "zxc28": zxc28() # if you specifically want to call methods that has exactly # the same name as options # eval(selected + "()") def main(): TopFrame = Frame(root) TopFrame.pack() Menu1 = Menu(TopFrame, 'xyz', 'xyz17','abc27','qwe90') Menu2 = Menu(TopFrame, 'uio', 'uio19','jkl09','zxc28') Menu1.pack() Menu2.pack() root = Tk() main() root.mainloop()
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48415412
has body: I am trying to parse this to download the xblr document. The document I am interested in is Annual securities report - 113th period. Inside the zip folder, there is an HTML document. C:\Users\smathew\Downloads\Xbrl_Search_20180124_142609.zip\S100AKEX\XBRL\PublicDoc\0104010 Once you open the link it shows a Japanese webpage. What I want is to capture data in table no 5. The problem seems that all characters are in Japanese and I am unable to identify table no 5 to get the data. I tried with python and beautiful soup. Can someone please advise me? Thanks, Subin
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83824183
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83820703
has title: python beautiful soup japanese website
tagged with: python
tagged with: python-2.7
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83821872

http://stackoverflow.com/comment/83920834
comment on: http://stackoverflow.com/q/48463883
type: QuestionComment
score: 0
has text: From the looks of it, you don't have TensorFlow dependencies
type: Comment

http://stackoverflow.com/q/48398923
has comment: http://stackoverflow.com/comment/83806477
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83809813
downvote count: 4
has comment: http://stackoverflow.com/comment/83787350
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83808501
has title: How does plt.show() know what to show?
has answer: http://stackoverflow.com/a/48410495
has comment: http://stackoverflow.com/comment/83808631
has body: My question is not about matplotlib in detail, but a general programming and question, and i'm looking for an answer on the mechanisms making this possible in python or matplotlib core. Let's say I have a scatter plot using the code: import matplotlib.pyplot as plt plt.scatter(a,b) plt.show() I'm wondering how is this statement handled? How does python (or matplotlib?) know what to plot and where to get the data? How are these statement handled by interpreter?
has comment: http://stackoverflow.com/comment/83790373
has comment: http://stackoverflow.com/comment/83809273
answer count: 1
has comment: http://stackoverflow.com/comment/83786852
favorite count: 0
has comment: http://stackoverflow.com/comment/83808763
tagged with: python-3.x
linked to: http://stackoverflow.com/q/42593933
linked to: http://stackoverflow.com/q/46450731
type: Question
accepted answer: http://stackoverflow.com/a/48410495
has comment: http://stackoverflow.com/comment/83809927
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83809764
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/83820853

http://stackoverflow.com/comment/83952543
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48479766
score: 0
has text: thanks for the suggestion, I am editing the varaibles now

http://stackoverflow.com/q/48466957
tagged with: character-encoding
answer count: 1
has comment: http://stackoverflow.com/comment/83927523
tagged with: raspberry-pi
type: Question
has body: I am trying to send an email including an attachment via Python from my Raspberry Pi. The following code (email.py) works when I'm using sudo python3 email.py but does not via sudo python email.py. ######WRITE EMAIL AND SEND from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import locale locale.setlocale(locale.LC_TIME, "de_DE") attachment = 0 fromaddr = 'MAIL@gmail.com' toaddr = ['MAIL@gmail.com'] msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = ", ".join(toaddr) msg['Subject'] = 'ÄÖÜäöü' body = 'Ääüäöü' msg.attach(MIMEText(body, 'plain',_charset='latin-1')) filename = 'Picture' for file in os.listdir('/path/to/Pictures/'): if file.__contains__('.png'): a_file=file attachment = open('/path/to/pi/Pictures/'+a_file, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename= %s' % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, 'Password') text = msg.as_string() print ('# Sending mail') server.sendmail(fromaddr, toaddr, text) server.quit() print('# Mail Sent') The Error I am getting when using the python method is: SyntaxError: Non ASCII character \xc3 in file email.py on line XX but no encoding declared; see htttp://python.org/dev/peps/pep-0263/ for details. The Umlaute ÄÖÜ... are causing the problem. I know that different python versions use different encodings as default and I python3 uses utf-8. Somehow with python email.pyanother encoding is used and I don't know how to change it. I would like to know where I'd have to add specific encoding instructions into the code so that the code works on both python versions.
linked to: http://stackoverflow.com/q/23370025
tagged with: python
accepted answer: http://stackoverflow.com/a/48467156
has answer: http://stackoverflow.com/a/48467156
type: AnsweredQuestion
score: 0
has title: Encoding Differences (Umlaute) between Python Versions

http://stackoverflow.com/comment/115638142
has text: Unlike with pandas `.to_csv` method which can take a relative path, it seems that open needs a full path from root `/`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48358692

http://stackoverflow.com/q/48335590
has title: python - Is it possible to convert a string and put it into a list [] containing tuple ()?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48336323
answer count: 3
has answer: http://stackoverflow.com/a/48335701
has body: For example, these two are the strings and they are separated by tabs. 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex Is it possible to convert string to list [] containing tuple () : [("2012-01-01", "09:00", "San Jose", "Men's Clothing", "214.05", "Amex")] If so, how can I do it? Thank you in advance! edit: Changed title
has comment: http://stackoverflow.com/comment/83656256
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48335804
accepted answer: http://stackoverflow.com/a/48335701
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/48336323

http://stackoverflow.com/a/48405220
has body: Finding the right chunk cache size At first I want to discuss some general things. It is very important to know that each individual chunk could only be read or written as a whole. The standard chunk-cache size of h5py which can avoid excessive disk I/Os is only one MB per default and should in many cases be increased, which will be discussed later on. As an example: We have a dset with shape (639038, 10000), float32 (25,5 GB uncompressed) we want to write our data column wise dset[:,i]=arr and read it row wise arr=dset[i,:] we choose a completely wrong chunk-shape for this type of work ie (1,10000) In this case reading speed won't be to bad (although the chunk size is a little small) because we read only the data we are using. But what happens when we write on that dataset? If we access a column one floating point number of each chunk is written. This means we are actually writing the whole dataset (25,5 GB) with every iteration and read the whole dataset every other time. This is because if you modify a chunk, you have to read it first if it is not cached (I assume a chunk-cache-size below 25,5 GB here). So what can we improve here? In such a case we have to make a compromise between write/read speed and the memory which is used by the chunk-cache. An assumption which will give both decent/read and write speed: We choose a chunk-size of (100, 1000) If we want to iterate over the first Dimension we need at least (1000*639038*4 ->2,55 GB) cache to avoid additional IO-overhead as described above and (100*10000*4 -> 0,4 MB). So we should provide at least 2,6 GB chunk-data-cache in this example. Conclusion There is no generally right chunk size or shape, it depends heavily on the task which one to use. Never choose your chunk size or shape without making some minds about the chunk-cache. RAM is orders of magnite faster than the fastest SSD in regards of random read/write. Regarding your problem I would simply read the random rows, the improper chunk-cache-size is your …
type: Answer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/48385256
has comment: http://stackoverflow.com/comment/83799589
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/108385310
accepted answer of: http://stackoverflow.com/q/48385256

http://stackoverflow.com/comment/83851925
score: 0
has text: I like it better your way as it is a little bit more readable, but it is essentially the same solution, right? It is still too complex and it does not improve performance. Isn't there a simpler way?
type: Comment
comment on: http://stackoverflow.com/a/48430523
type: AnswerComment

http://stackoverflow.com/comment/83692038
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48352616
has text: Subclass the `dict` type and overwrite `__getitem__`.
type: QuestionComment

http://stackoverflow.com/q/48348791
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83683914
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83684433
has comment: http://stackoverflow.com/comment/83684601
has comment: http://stackoverflow.com/comment/83684465
answer count: 1
has answer: http://stackoverflow.com/a/48349149
has comment: http://stackoverflow.com/comment/83684603
type: Question
has title: Tkinter label has wrong output
has body: I have written python code with the aim to output MD5 hashes in the tkinter.Label widget but my output within the label is the following: {filename: } llos.docx{ MD5:}312b1face983fe7ad82bd9909888680 Whereas, I would like the output to be the following which is displayed in my console: Directory: C:\Users\User\Documents\Test Filename: cpck2.py MD5: 1d05f6e9c551280098987dd32b64a2d Filename: llos.docx MD5: 312b1face97877ad82bd87e4fa78680
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/48349149
tagged with: python
has comment: http://stackoverflow.com/comment/83684564
has comment: http://stackoverflow.com/comment/83684347

http://stackoverflow.com/comment/83967873
has text: @IharobAlAsimi You are quite right that the issue is simply Debian-specific, Fedora handles this as expected.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48462792
score: 0

http://stackoverflow.com/q/48397745
upvote count: 1
has body: I have been taught to improve the code is the following manner, but the bubble_sort_1 function is still not returning a sorted list, I cannot see which part of my code am I assigning the variables wrongly, because it is now simply returning the same original list The indentation seems to be messed up while I copy it over, I hope you can understand what I am writing here students= [ ('tiffany','A',15), ('jane','B',10), ('ben','C',8), ('simon','A',15), ('john','A',21), ('jimmy','F',1), ('charles','C',9), ('freddy','D',4), ('dave','B',12)] def bubble_sort_1(list): def swap(item1,item2): temp=item1 list[list.index(item1)]=item2 list[list.index(item2)]=temp for i in range(len(list)-1): if list[i][2]&gt;list[i+1][2]: swap(list[i],list[i+1]) def bubble_sort_2(list): def swap(index1,index2): temp=list[index1] list[index1]=list[index2] list[index2]=temp for i in range(len(list)-1): if list[i][2]&gt;list[i+1][2]: swap(i,(i+1)) def bubble_sort_2_improved(list): def swap(index1,index2): temp=list[index1] list[index1]=list[index2] list[index2]=temp still_need_sorting=True while still_need_sorting==True: still_need_sorting=False for i in range(len(list)-1): if list[i][2]&gt;list[i+1][2]: swap(i,(i+1)) still_need_sorting=True bubble_sort_2_improved(students) for i in students: print(i)
score: 1
has comment: http://stackoverflow.com/comment/83783672
has comment: http://stackoverflow.com/comment/83783266
tagged with: python
has answer: http://stackoverflow.com/a/48398205
answer count: 4
has comment: http://stackoverflow.com/comment/83783638
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83783395
has comment: http://stackoverflow.com/comment/83783501
has answer: http://stackoverflow.com/a/48398248
possible better answer: http://stackoverflow.com/a/48398248
has answer: http://stackoverflow.com/a/48398398
accepted answer: http://stackoverflow.com/a/48398398
has comment: http://stackoverflow.com/comment/83783622
tagged with: sorting
has comment: http://stackoverflow.com/comment/83784070
has title: I write myself a little bubble sorting code while self-learning python, but couldnt figure out why it doesnt work
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83783697
has comment: http://stackoverflow.com/comment/83783965
downvote count: 0
has answer: http://stackoverflow.com/a/48398489

http://stackoverflow.com/q/48431331
has body: I would like to use two databases in my application: local database external database in the first one I want to save all django tables , e.g auth_group To do this I tried to use router class, but unsuccessfully - it doesn't work. Below you can find my code Django 1.11 setings file: DATABASE_ROUTERS = ['mainApp.models.DefaultDBRouter','subfolder.newApp.models.testDBRouter',] models.py - main app - I want to use default DB for this model from __future__ import unicode_literals from django.db import models class list_a( models.Model ): region = models.CharField(max_length=50, verbose_name="Region") country = models.CharField(max_length=50, verbose_name="Country") def __unicode__(self): return str( self.country ) class DefaultDBRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Reads go to a default. """ return "default" def db_for_write(self, model, **hints): """ Writes always go to default. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the default. """ db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model=None, **hints): """ All non-micro-management models end up in this pool. """ return True models.py - test app - I want to use second db for this model class testTable( models.Model ): date = models.DateField(verbose_name="Date") number_name = models.CharField(max_length=50, verbose_name="Number name") def __unicode__(self): return str( self.number_name ) ELIGIBLE_APPS = [ 'subfolder.newApp', ] class testDBRouter(object): def db_for_read(self, model, **hints): print model._meta.app_label if model._meta.app_label in ELIGIBLE_APPS: return 'secondDB' return None def db_for_write(self, model, **hints): if model._meta.app_label in ELIGIBLE_APPS: return 'secondDB' return None def allow_relation(self…
score: 0
answer count: 1
tagged with: django-models
has title: Django multiple databases - correct router class
has answer: http://stackoverflow.com/a/48432276
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/48480999
tagged with: nltk
tagged with: python
has answer: http://stackoverflow.com/a/48481641
score: 0
type: UnansweredQuestion
answer count: 1
has title: python NLTK script for removing duplicate sentences
has body: The purpose of my script is to go to a directory, walk through the files in the directory, remove duplicate sentences from each file and save the results for each file to a new named file. This is the file that I used to test the script: This is a sentence with the word capital in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. This is a sentence with the word truck in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. This is a sentence with the word environment in it. and this is the output file: This is a sentence with the word capital in it.This is a sentence with the word environment in it.This is a sentence with the word truck in it.This is a sentence with the word environment in it. The problem appears to be with the tokenized form of the input file. Printing the tokenized file to the screen shows the following: [‘This is a sentence with the word capital in it.’,’This is a sentence with the word environment in it.’,’This is a sentence with the word environment in it.’,’This is a sentence with the word environment in it.’This is a sentence with the word truck in it.’,’ This is a sentence with the word environment in it.’,’This is a sentence with the word environment in it.’,’This is a sentence with the word environment in it.’,’This is a sentence with the word environment in it.\n’] It appears that sent_tokenizer added a \n new line symbol at the end of the last line of input. The sentence that has \n at the end is not recognized as a duplicate and is not removed. Any insights into what is happening and what I can do to correct the problem is appreciated. import os, os.path,re, pprint,sys, nltk from nltk.tokenize import sent_tokenize, word_tokenize for dirPath, subdirNames, fileList in os.wal…
type: Question

http://stackoverflow.com/comment/84016983
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48501417
has text: Changing the memory SQLite dB with a file DB works fine, as expected, but using a memory DB is what keeps failing, as if the connections were referring to different memory DBS...

http://stackoverflow.com/q/48428193
has answer: http://stackoverflow.com/a/48428194
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48428194
has title: shifting pandas series for only some entries
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48428498
score: 0
accepted answer: http://stackoverflow.com/a/48428498
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I've got a dataframe that has a Time Series (made up of strings) with some missing information: # Generate a toy dataframe: import pandas as pd data = {'Time': ['0'+str(i)+':15:45' for i in range(10)]} data['Time'][4] = 'unknown' data['Time'][8] = 'unknown' df = pd.DataFrame(data) # df Time 0 00:15:45 1 01:15:45 2 02:15:45 3 03:15:45 4 unknown 5 05:15:45 6 06:15:45 7 07:15:45 8 unknown 9 09:15:45 I would like the unknown entries to match the entry above, resulting in this dataframe: # desired_df Time 0 00:15:45 1 01:15:45 2 02:15:45 3 03:15:45 4 03:15:45 5 05:15:45 6 06:15:45 7 07:15:45 8 07:15:45 9 09:15:45 What is the best way to achieve this?

http://stackoverflow.com/comment/83764772
has text: Where did you see that error message? It's not there now. Maybe they already updated to fix that.
comment on: http://stackoverflow.com/q/48388554
score: 0
type: Comment
type: QuestionComment

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

http://stackoverflow.com/comment/83915014
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/a/7165877 this shows how to use `scipy.optimize` and also includes setting initial parameter guesses
score: 0
comment on: http://stackoverflow.com/q/48349556

http://stackoverflow.com/q/48408608
accepted answer: http://stackoverflow.com/a/48409315
has comment: http://stackoverflow.com/comment/83806422
has answer: http://stackoverflow.com/a/48409555
tagged with: python
has body: I am trying to do the following with a sed script but it's taking too much time. Looks like something I'm doing wrongly. Scenario: I've student records (> 1 million) in students.txt. In This file (each line) 1st 10 characters are student ID and next 10 characters are contact number and so on students.txt 10000000019234567890XXX... 10000000029325788532YYY... . . . 10010000008766443367ZZZZ... I have another file (encrypted_contact_numbers.txt) which has all the phone but numbers and corresponding encrypted phone numbers as below encrypted_contact_numbers.txt Phone_Number, Encrypted_Phone_Number 9234567890, 1122334455 9325788532, 4466742178 . . . 8766443367, 2964267747 I wanted to replace all the contact numbers (11th&ndash;20th position) in students.txt with the corresponding encrypted phone number from encrypted_contact_numbers.txt. Expected Output: 10000000011122334455XXX... 10000000024466742178YYY... . . . 10010000002964267747ZZZZ... I am using the below sed script to do this operation. It is working fine but too slowly. Approach 1: while read -r pattern replacement; do sed -i "s/$pattern/$replacement/" students.txt done &lt; encrypted_contact_numbers.txt Approach 2: sed 's| *\([^ ]*\) *\([^ ]*\).*|s/\1/\2/g|' &lt;encrypted_contact_numbers.txt | sed -f- students.txt &gt; outfile.txt Is there any way to process this huge file quickly? Update: 9-Feb-2018 Solutions given in AWK and Perl is working fine if the phone number is in specified position (column 10-20), If I try to do global replacement it took too much time to process. Is there any best way to achieve this? students.txt : Updated version 10000000019234567890XXX...9234567890 10000000029325788532YYY... . . . 10010000008766443367ZZZZ9234567890...
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83806463
has title: SED or AWK script to replace multiple text
answer count: 3
downvote count: 0
tagged with: awk
has comment: http://stackoverflow.com/comment/83806696
tagged with: unix
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48409024
linked to: http://stackoverflow.com/q/48719330
score: 5
upvote count: 5
tagged with: sed
has answer: http://stackoverflow.com/a/48409024
tagged with: perl
has answer: http://stackoverflow.com/a/48409315

http://stackoverflow.com/q/48369117
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83728024
type: UnansweredQuestion
downvote count: 0
has body: How to merge df1 and df2 into df? df1 = pd.DataFrame(list(zip(['4.txt', '5.txt', '6.txt'], [1,0,0], [1,1,1])), columns = ['file', 'is_about_heroes', 'is_about_pony']) df2 = pd.DataFrame(list(zip(['5.txt', '6.txt'], [1,0], [1,0])), columns = ['file', 'is_about_pony', 'is_about_wolf']) df1 file is_about_heroes is_about_pony 0 4.txt 1 1 1 5.txt 0 1 2 6.txt 0 1 df2 file is_about_pony is_about_wolf 0 5.txt 1 1 1 6.txt 0 0 And I want to get df which is the boolean union of two previous dfs. df = pd.DataFrame(list(zip(['4.txt', '5.txt', '6.txt'], [1,0,0], [1,1,1], [0,1,0])), columns = ['file', 'is_about_heroes', 'is_about_pony', 'is_about_wolf']) file is_about_heroes is_about_pony is_about_wolf 0 4.txt 1 1 0 1 5.txt 0 1 1 2 6.txt 0 1 0 Is it possible without several manual cycles?
tagged with: dataframe
tagged with: python
has title: how to merge 2 boolean dataframes with different columns?
has comment: http://stackoverflow.com/comment/83724922
has answer: http://stackoverflow.com/a/48369155
tagged with: boolean
tagged with: pandas

http://stackoverflow.com/comment/83668677
type: QuestionComment
comment on: http://stackoverflow.com/q/48341413
type: Comment
score: 0
has text: You may need to increase the timeout of gunicorn, the default is 30 seconds. http://docs.gunicorn.org/en/stable/settings.html#timeout

http://stackoverflow.com/q/48478163
has comment: http://stackoverflow.com/comment/83949543
tagged with: opencv
tagged with: python-2.7
score: 0
has title: Resizing video resolution in OpenCV python
has body: I want to reduce the resolution of video that I am getting from my webcam to half(i.e from 640x480 to 320x240) but I am getting error. import numpy as np import cv2 cap = cv2.VideoCapture(0) cap.set(3,320) cap.set(4,240) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() The error that I am getting is Traceback (most recent call last): File "C:\Users\Nemi\Desktop\bbb.py", line 17, in cv2.imshow('frame',frame) error: ......\opencv-2.4.13.2\modules\highgui\src\window.cpp:269: error: (-215) size.width>0 &amp;&amp; size.height>0 in function cv::imshow I am new to this and could not find the solution. Could someone please tell me what am I doing wrong?
has comment: http://stackoverflow.com/comment/83949997
tagged with: python
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83950000
linked to: http://stackoverflow.com/q/11420748

http://stackoverflow.com/q/48480396
tagged with: google-cloud-platform
has title: Using Python with Dialogflow and Facebook Messenger
has comment: http://stackoverflow.com/comment/83953842
has body: I'm trying to take user input from a facebook messenger interaction with a dialogflow bot and use it in python. This dialogflow bot is a project in google cloud platform. How do I connect these?
type: Question
tagged with: dialogflow-es
tagged with: python
has comment: http://stackoverflow.com/comment/83954894
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83963926

http://stackoverflow.com/comment/83795985
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48403888
has text: the link is broken, can you please double check @pratik

http://stackoverflow.com/q/48414407
favorite count: 0
has answer: http://stackoverflow.com/a/48414582
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has body: Here is output of my code Details about item name goes here I want to get item name only, without "details about" part. My Python code the selects the certain div id is for content in soup.select('#itemTitle'): print(content.text)
tagged with: python
linked to: http://stackoverflow.com/q/30159020
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48414574
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/48414574
downvote count: 0
has answer: http://stackoverflow.com/a/48414552
has title: How to skip with beautiful soup
has answer: http://stackoverflow.com/a/48414527
answer count: 4
possible better answer: http://stackoverflow.com/a/48414527

http://stackoverflow.com/comment/83810992
type: QuestionComment
has text: @Nae Dunno, I guess I just didn't feel a solution that trivial was worth an answer. SO answers are supposed to be well thought out essays with citations and graphics, right?
comment on: http://stackoverflow.com/q/48409575
score: 0
type: Comment

http://stackoverflow.com/comment/83679232
score: 0
has text: Did you read the [docs](https://docs.python.org/3/library/functions.html#super), or [google](https://www.google.com/search?q=python+super+init)?
type: QuestionComment
comment on: http://stackoverflow.com/q/48346675
type: Comment

http://stackoverflow.com/a/48497302
has comment: http://stackoverflow.com/comment/84000832
type: Answer
has comment: http://stackoverflow.com/comment/84000209
has comment: http://stackoverflow.com/comment/84001226
accepted answer of: http://stackoverflow.com/q/48480766
has comment: http://stackoverflow.com/comment/84001085
has body: I believe loop is not necessary, use pivot + fillna + to_dict: d = df.pivot('HS2','HS1','EffNotional_UnMG').fillna(0).to_dict() Alternative solution with set_index + unstack + to_dict: d = df.set_index(['HS2','HS1'])['EffNotional_UnMG'].unstack(fill_value=0).to_dict() print (d) {'EUR': {'2': 0.0, '3': -10082.91381}, 'USD': {'2': -36253.84938, '3': 78693.86806000001}}
score: 0
answers question: http://stackoverflow.com/q/48480766
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83999732

http://stackoverflow.com/comment/83725212
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48367352
has text: @costrouc I mean maximize the max value of the curve

http://stackoverflow.com/q/48373982
possible better answer: http://stackoverflow.com/a/48383710
tagged with: python
has comment: http://stackoverflow.com/comment/83735202
score: 2
type: AnsweredQuestion
has body: I have a question about sending and receiving multiple data using the pySerial Python library. According to what I understand, serial port communication works with byte variables. How do I send four different variables with method write and then with method read receive two different variables? As an example: import serial import time sendSerial = serial.Serial ("COM4", 9600) readoutSerial = serial.Serial ("COM4", 9600) time.sleep (2) sendSerial.write ("data1" + "data2" + "data3" + "data4") while True: readoutSerial.read ("data5" + "data6") What should I do to send the four variables with write differentiated by some character and then separate them for the respective use of each variable? (applying the same for the two variables received with read) Also, what can I do to send the variables asfloat and not generate conflict with the reading in byte?
answer count: 3
upvote count: 2
tagged with: pyserial
has answer: http://stackoverflow.com/a/62662348
has answer: http://stackoverflow.com/a/48382635
accepted answer: http://stackoverflow.com/a/48382635
tagged with: arduino
downvote count: 0
tagged with: arduino-uno
favorite count: 0
type: Question
has title: pySerial sending and receiving multiple data
has comment: http://stackoverflow.com/comment/83735532
has answer: http://stackoverflow.com/a/48383710
has comment: http://stackoverflow.com/comment/83754010

http://stackoverflow.com/comment/83789118
has text: Why aren't the 3 cells of "2" in the top-right corner considered a zone with sum over 5?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48400602
score: 0

http://stackoverflow.com/q/48440502
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83872213
tagged with: nginx
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: My problem is: I need to generate a csv file from the data I have in the database and then download it. Seems easy, but I cannot find a solution that will allow me to do it in the background so the user won't be redirected anywhere. What I need is user clicking a button and the download starting immediately with the user staying on the same page. Something like a simple html download attribute, but with actually generating a file first. I cannot generate file in advance as the data changes all the time and I need to output the most recent version of it, also, user may specify some filters for the data, so I need to take it into account. I use Django with Nginx as a production server. Django should always return a response, so I'm not sure I would be able to do what I want at all. Is there any different way to do it then? I've searched for a long time, but unable to find anything similar to my request. Thanks everyone!
has comment: http://stackoverflow.com/comment/83902409
score: 0
linked to: http://stackoverflow.com/q/1156246
has title: Generate and download file with Django and Nginx

http://stackoverflow.com/q/48352058
score: 2
has comment: http://stackoverflow.com/comment/83690971
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
linked to: http://stackoverflow.com/q/47334885
upvote count: 2
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83691558
downvote count: 0
has answer: http://stackoverflow.com/a/48352197
tagged with: python
has body: import os import tkinter import tkinter.font as tkFont from tkinter import * coord1 = "0,0" coord2 = "0,0" EQ = "y = mx + b" def tkinter_window(): global coord1Entry global coord2Entry global coord1 global coord tk = Tk() tk.title("Math Graph") #create font1 = tkFont.Font(family="Source Code Pro", size=16) font2 = tkFont.Font(family="Source Code Pro", size=10) coord1Label = Label(tk, text='X coordinate 1:\n( "x,y", no parentheses )', font=font1) coord2Label = Label(tk, text='Y coordinate 2:\n( "x,y", no parentheses )', font=font1) This is the part where i define the two entries that seem to use the same numbers: coord1Entry = Entry(tk, textvariable=coord1) coord2Entry = Entry(tk, textvariable=coord2) So the problem is, when i run the program they show nothing, as usual. But as soon as i enter one character in one of the entries, they both show the character(s). I don't understand why, they use different variables? Can someone help me? coordButton = Button(tk, text="Done! (use coordinates)", font=font1) equationLabel = Label(tk, text="Equation: y =", font=font1) equationEntry = Entry(tk, textvariable=EQ, font=font1) equationButton = Button(tk, text="Done! (use equation)", font=font1) iwantanswersCheckbox = Checkbutton(tk, text="I want m, x, b, intercept and x-intercept", font=font1) iwantgraphCheckbox = Checkbutton(tk, text="I want a graph", font=font1) info1Label = Label(tk, text="***Both boxes may be checked***", font=font2) #pack coord1Label.grid(row=0, column=0, padx=15, pady=15) coord2Label.grid(row=1, column=0, padx=15, pady=15) coord1Entry.grid(row=0, column=1, padx=5, pady=5) coord2Entry.grid(row=1, column=1, padx=5, pady=5) coordButton.grid(row=2, columnspan=2, padx=5, pady=15) equationLabel.grid(row=3, column=0, sticky=E, padx=5, pady=5) equationEntry.grid(row=3, column=1, padx=5, pady=5) equationButton.grid(row=4, columnspan=2, padx=5, pady=15) iwantanswersCheckbox.grid(row=5, columnspan=2, padx=5, pady=5) iwantgraphCheckbox.grid(row=6, columnspan=2) info1…
has title: Why are the two tkinter entries using the same number?

http://stackoverflow.com/comment/83716749
score: 0
type: Comment
has text: I have the time costing data, while you don't.
type: QuestionComment
comment on: http://stackoverflow.com/q/48364168

http://stackoverflow.com/comment/83725584
comment on: http://stackoverflow.com/q/48365080
score: 0
has text: maybe, but is this a python-caldav or a vobject issue or just me not understanding the API?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48378752
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48377506
has body: To access the separate arrays above, one could do the following: &gt;&gt;&gt; mesh[0][0][0][0][0] # dim array([[ 6., 6.]]) &gt;&gt;&gt; mesh[0][0][0][0][1] # x array([[-131.659809], [-131.659809], [-131.659809], [ 52.022239], [ 52.022239], [ 52.022239]]) &gt;&gt;&gt; mesh[0][0][0][0][2] # y array([[ 189.358345], [ 187.271049], [ 185.183753], [ -29.807736], [ -31.895032], [ -33.982328]]) And to set a value, one could for example do: &gt;&gt;&gt; mesh[0][0][0][0][0][0][0]=1 &gt;&gt;&gt; mesh array([[[[ (array([[ 1., 6.]]), array([[-131.659809], [-131.659809], [-131.659809], [ 52.022239], [ 52.022239], [ 52.022239]]), array([[ 189.358345], [ 187.271049], [ 185.183753], [ -29.807736], [ -31.895032], [ -33.982328]]))]]]], dtype=object) Disclaimer This answer is a hack, not a solution. It is not meant to be interpreted as a general answer, but rather is specific to the exact example above. It does not deal with numpy, just with being able to access the specific arrays.
answers question: http://stackoverflow.com/q/48377506

http://stackoverflow.com/comment/83954887
comment on: http://stackoverflow.com/q/48480766
score: 0
has text: Ignore AssetClass in the output.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53537085
has body: You can also use pandas.DataFrame.assign function: e,g import numpy as np import pandas as pd df = pd.DataFrame([["Australia", 1, 3, 5], ["Bambua", 12, 33, 56], ["Tambua", 14, 34, 58] ], columns=["Country", "Val1", "Val2", "Val10"] ) df = df.assign(Val10_minus_Val1 = df['Val10'] - df['Val1']) The best part of assign is you can add as many assignments as you wish. e.g. getting both the difference and then the log of it df = df.assign(Val10_minus_Val1 = df['Val10'] - df['Val1'], log_result = lambda x: np.log(x.Val10_minus_Val1) ) Results:
downvote count: 0
answers question: http://stackoverflow.com/q/48350850
type: Answer
upvote count: 8
score: 8

http://stackoverflow.com/q/48373044
tagged with: python
tagged with: boto3
has answer: http://stackoverflow.com/a/55056470
tagged with: amazon-web-services
has body: I am trying to run a simple python script that goes through all of my AWS buckets and print outs the buckets name. I am trying to figure out where to put my AWS credentials for authorization. In the documentation it says to put them in a specific aws config file Alternatively, you can create the credential file yourself. By default, its location is at ~/.aws/credentials: When running a standalone python script, lets call it s3_test.py, where do I put the credentials ? On my local machine, do I create a file called credentials at ~/.aws/ , or can I just put my credentials in the script itself ? import boto3 s3 = boto3.resource('s3') bucket_name = 'bucketnamehere' for bucket in s3.buckets.all(): print(bucket.name)
accepted answer: http://stackoverflow.com/a/48373068
type: AnsweredQuestion
answer count: 3
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/48373068
score: 1
upvote count: 1
has title: Where to put AWS credentials for Boto3 S3 instance
possible better answer: http://stackoverflow.com/a/48373079
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48373079
downvote count: 0

http://stackoverflow.com/q/48472135
has comment: http://stackoverflow.com/comment/83943813
tagged with: python
tagged with: mysql
has body: I'm attempting to read a BLOB object from a MySQL database in Python. The BLOB object is a NumPy array. To convert the array to a buffer type for insertion into the database I use the following function: numpy.getbuffer(arr) Upon reading back I am able to recreate the buffer object via: bytes(memoryview(arr)) Everything is working correctly at this point. My issue arises when using the below function on the buffer object in an attempt to convert it back to a NumPy array: numpy.frombuffer(arr, dtype=numpy.float64) The error is as follows: ValueError: buffer size must be a multiple of element size Please note that the dtype is set correctly, my Python version is 2.7.13 and NumPy is 1.13.3. EDIT: So upon doing some further digging, here is some extra information and a peculiarity on which I have stumbled: The length of the numpy.getbuffer(arr) object is 7392. If I print the length of the returned value as is from the MySQL DB (returned using cursor.fetchall() or fetchone() for example, the length is 7668. So I printed the first 30 characters of each object, and while they are clearly the same thing, the object returned from the DB has a number of additional characters: Before DB: ?=G????B?i?j??w??LG???ࢩ?a After DB: '?=G????B?i?\0j??w??LG???ࢩ? I assume that the issue stems from the way the data is stored in the DB. My reasoning is that the following code produces no errors: numpy.frombuffer(numpy.getbuffer(arr), dtype=numpy.float64) Thanks, Adam
tagged with: numpy
upvote count: 3
downvote count: 0
answer count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83938550
has comment: http://stackoverflow.com/comment/83938508
has title: Converting Python buffer to NumPy array - ValueError: buffer size must be a multiple of element size
has comment: http://stackoverflow.com/comment/83938862

http://stackoverflow.com/q/48482933
tagged with: css
has comment: http://stackoverflow.com/comment/83960496
score: 0
has body: I am trying to scrape a website using scrapy, and the structure that i am trying to get data from is as below: 16HAYA 42 21HAYA I want to extract the text within second div span. For example, in this case, I want to extract 21. My code is as below: def parse(self, response): sel = Selector(response) sel.css('div.coin-summary-item-detail').extract() My question is , how do I select the second AA class using css ? and after that, how do I specify that I want only the text inside second span ? Any help will be greatly appreciated, thank you !!!
tagged with: web-scraping
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/48487353
answer count: 2
type: UnansweredQuestion
has title: multiple divs with scrapy
has answer: http://stackoverflow.com/a/48483850
tagged with: python

http://stackoverflow.com/q/48407153
duplicate of: http://stackoverflow.com/q/1207406
tagged with: python
has body: I have the following list in Python: x = [[1,2],[3,4],[5,'inf'],[6,7],['nan',10]] I also have the following index list: idx = [2,4] I'm trying to remove the elements from the list x corresponding to the index values in idx. For that, I did the following: for i in idx: del x[i] I however got the following error: IndexError: list assignment index out of range How can I solve this issue?
tagged with: delete-operator
tagged with: list
linked to: http://stackoverflow.com/q/11303225
score: 1
has title: list assignment index out of range when trying to remove an element by index
answer count: 1
has comment: http://stackoverflow.com/comment/83803223
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/1207406
has answer: http://stackoverflow.com/a/48407181
favorite count: 0
type: Question
tagged with: indexing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83803191
tagged with: del

http://stackoverflow.com/a/51944026
downvote count: 0
answers question: http://stackoverflow.com/q/48477909
upvote count: 1
has body: Please download the proper drivers as latest version of cuda v8.0 toolkit needs tensorflow 1.4.x needs. As, by default pip3 install --upgrade tensorflow-gpu install latest version of tensorflow which needs cuda v9.0 (latest) not cuda v8.0 toolkit You'll need to install the version 1.4.1 for CUDA-8 as pip install tensorflow-gpu==1.4.1 The latest (version 1.5) is for CUDA-9 You'll need to install the version 1.5 for CUDA-9 as pip install tensorflow-gpu==1.5 Download cuddn for your appropriate cuda version toolkit from here and follow this. Download appropriate cuda toolkit from here
score: 1
type: Answer

http://stackoverflow.com/a/48426579
has body: I just figure it out. Just change it to list type and then delete it. And I can use those elements in the list like queryset.And I don't know why. Can anyone explain? Thanks anyway.
score: -1
accepted answer of: http://stackoverflow.com/q/48426463
upvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48426463
downvote count: 1
type: Answer

http://stackoverflow.com/q/48443624
accepted answer: http://stackoverflow.com/a/48443949
has title: Custom sentence boundary detection in SpaCy
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/48443949
tagged with: python
tagged with: nlp
favorite count: 0
type: Question
has body: I'm trying to write a custom sentence segmenter in spaCy that returns the whole document as a single sentence. I wrote a custom pipeline component that does it using the code from here. I can't get it to work though, because instead of changing the sentence boundaries to take the whole document as a single sentence it throws two different errors. If I create a blank language instance and only add my custom component to the pipeline I get this error: ValueError: Sentence boundary detection requires the dependency parse, which requires a statistical model to be installed and loaded. If I add the parser component to the pipeline nlp = spacy.blank('es') parser = nlp.create_pipe('parser') nlp.add_pipe(parser, last=True) def custom_sbd(doc): print("EXECUTING SBD!!!!!!!!!!!!!!!!!!!!") doc[0].sent_start = True for i in range(1, len(doc)): doc[i].sent_start = False return doc nlp.begin_training() nlp.add_pipe(custom_sbd, first=True) I get the same error. If I change the order for it to parse first and then change the sentence boundaries, the error changes to Refusing to write to token.sent_start if its document is parsed, because this may cause inconsistent state. So if it throws an error requiring the dependency parse if it's not present or it executes after the custom sentence boundary detection, and a different error when the dependency parse is executed first, what's the appropriate way to do it? Thank you!
tagged with: spacy
answer count: 1
downvote count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/48428247
answer count: 2
has comment: http://stackoverflow.com/comment/83847016
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/48429073
tagged with: django
has title: How to get pk of an instance of a django model before saving the instance
downvote count: 1
has body: I am trying to upload an image using models.ImageField(upload_to=upload_location) def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s" %(instance.id,filename) but its giving "GET /media/None/image_qacfEsv.jpg HTTP/1.1" I have tried using slug field it worked fine but neither id nor pk is working I want to use the obj ID to name the folder for image but its giving none in id attribute here are my files def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) class Post(models.Model): draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False,auto_now_add=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) slug = models.SlugField(unique=True) title = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_location, null=True,blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83847111
tagged with: foreign-keys
has comment: http://stackoverflow.com/comment/83847173
tagged with: database
accepted answer: http://stackoverflow.com/a/48428923
tagged with: python
has answer: http://stackoverflow.com/a/48428923
has answer: http://stackoverflow.com/a/48429073
type: AnsweredQuestion

http://stackoverflow.com/comment/84294074
score: 0
type: Comment
has text: Sorry for late reply, this worked out for me when i re-visited the problem. Thanks for the sample.
type: AnswerComment
comment on: http://stackoverflow.com/a/48410905

combinations
tags question: http://stackoverflow.com/q/48333927
type: Tag
tag name: combinations
tags question: http://stackoverflow.com/q/48375270
tags question: http://stackoverflow.com/q/48352591
tags question: http://stackoverflow.com/q/48387205

http://stackoverflow.com/q/48459090
has answer: http://stackoverflow.com/a/48462129
has body: I'm working with Tkinter in Python, and I created multiple TextWidgets. I put these Objects in a list called output. Each text widget has the property text, which can be changed with the methods .delete(index1,index2) and insert(index, chars). Now, I'd like to apply the insert function. From another fuction kg_to_pounds_ounces_grams I get a list of values for the Text Widgets: def kg_to_pounds_ounces_grams(kilogram): pound = kilogram * 2.20462 oounce = kilogram * 35.274 gram = kilogram * 1000 return [pound, oounce, gram] How can I apply insert to Output so that pound goes into TextWidget1, ounce into TextWidget2 and gram into TextWidget3, and call the function kg_to_pounds_ounces_grams only one time in a one line expression? Same goes for delte - also applied to all in one line? Edit: I managed to do both in three lines: for textWidget,weight in zip(output, kg_to_pounds_ounces_grams(kg) ): textWidget.delete(1.0, END) textWidget.insert(END,weight) But it still bothers me - is there no elegant two-line solution? For better understanding, I put the full code here: from tkinter import * window = Tk() def kg_to_pounds_ounces_grams(kilogram): pound = kilogram * 2.20462 ounce = kilogram * 35.274 gram = kilogram * 1000 return [pound, ounce, gram] def convert_button_pressed(): try: kg = float(e1_text.get()) except: kg = float("NaN") map(lambda x: x.delete(1.0, END), output) # Missing Code goes here! l1 = Label(window, text="Kg") l1.grid(row=0, column=0) e1_text = StringVar() e1 = Entry(window, textvariable=e1_text) e1.grid(row=0, column=1) b1 = Button(window, text="Convert", command=convert_button_pressed) b1.grid(row=0, column=2) t1 = Text(window, height=1, width=20) t1.grid(row=1, column=0) t2 = Text(window, height=1, width=20) t2.grid(row=1, column=1) t3 = Text(window, height=1, width=20) t3.grid(row=1, column=2) output = [t1, t2, t3] window.mainloop()
has comment: http://stackoverflow.com/comment/83930979
tagged with: python
tagged with: dictionary
tagged with: lambda
has comment: http://stackoverflow.com/comment/83931033
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48462129
tagged with: tkinter
tagged with: functional-programming
has title: Call method from list of multiple objects with list of multiple arguments
has comment: http://stackoverflow.com/comment/83910950
answer count: 1
type: Question

http://stackoverflow.com/q/48461784
tagged with: xlsxwriter
answer count: 1
has comment: http://stackoverflow.com/comment/83916719
has comment: http://stackoverflow.com/comment/83916839
has answer: http://stackoverflow.com/a/48476502
has comment: http://stackoverflow.com/comment/83925471
has comment: http://stackoverflow.com/comment/83916413
type: Question
upvote count: 2
downvote count: 0
tagged with: error-handling
tagged with: python
has body: I'm using Pandas and Xlsxwriter to analyze some data, and then periodically create a Excel simple report for another users. The report should always get overwritten by the last one I export. Also, once I export it, it gets automatically opened to review it quickly. The only issue I have is that I get an [Errno 13] if someone has left that file opened (or even if I'm using it, which I must admit happens). IOError: [Errno 13] Permission denied: '2320PLFY2018.xlsx' So i just wanted to add some Error handling to that IOError at the end of the XLSXWRITER part, to let me know about it, and give me a chance to close the file. Started with a simple attempt just to give me an error message. Tried several times but cant make it work. This is one attempt: try: writer.save() os.startfile(company_code_choice + 'PLFY2018.xlsx') except IOError as e: print(e.errno) Also tried without specifying the Error type: while True: try: writer.save() os.startfile(company_code_choice + 'PLFY2018.xlsx') break except: print "Close the file!" I'm new to creating code so I apologize if this is an obvious question... I've been googling for this all morning and read several other questions but couldn't make it work on my code. Thanks in advance-
favorite count: 0
has title: Python [Errno 13] - Exception handling when saving a file that is opened by user
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83925491
has comment: http://stackoverflow.com/comment/83916968
accepted answer: http://stackoverflow.com/a/48476502
tagged with: pandas
tagged with: errno
has comment: http://stackoverflow.com/comment/83916466

http://stackoverflow.com/comment/83923835
has text: Is re-encoding STDOUT (from within Python) an option?
type: QuestionComment
comment on: http://stackoverflow.com/q/48464972
score: 1
type: Comment

http://stackoverflow.com/comment/83689017
type: Comment
type: QuestionComment
score: 0
has text: "but it's still preferable to parsing the yaml file every time config is referenced" why would you have to parse the yaml file every time `config` is referenced?
comment on: http://stackoverflow.com/q/48351139

http://stackoverflow.com/comment/83707501
type: QuestionComment
has text: Related threads: https://stackoverflow.com/questions/46965098/how-does-one-move-data-to-multiple-gpu-towers-using-tensorflows-dataset-api https://github.com/tensorflow/tensorflow/issues/13610
comment on: http://stackoverflow.com/q/48351883
score: 2
type: Comment

http://stackoverflow.com/comment/83996081
type: Comment
has text: Don't worry , i already did that but found another way to solve it. Thanks for all your help !!
comment on: http://stackoverflow.com/a/48433052
type: AnswerComment
score: 0

iot
tags question: http://stackoverflow.com/q/48427361
type: Tag
tag name: iot

http://stackoverflow.com/comment/83951812
type: AnswerComment
has text: One workaround is to use BSRCH() - please review the help on this function. Another workaround is to use BOND_CHAIN field, however, it will be deprecated according to FLDS<GO>, moreover, the returned bonds may not match =BChain().
comment on: http://stackoverflow.com/a/48456124
score: 1
type: Comment

http://stackoverflow.com/comment/83916860
comment on: http://stackoverflow.com/a/48461810
score: 0
type: Comment
has text: I don't have much time now, but will add some more explanation later on. I recommend to open an iPython notebook and go through it step by step. But as I said, I will write more explantion later on...
type: AnswerComment

http://stackoverflow.com/comment/83764839
type: Comment
type: QuestionComment
has text: @Nae I do not have a local tkinter.py in the same directory, I have never used python 3, and as the screenshot shows above it will import tkinter in a 2.7 shell
comment on: http://stackoverflow.com/q/48388368
score: 1

http://stackoverflow.com/comment/83872835
comment on: http://stackoverflow.com/q/48436707
score: 0
type: Comment
type: QuestionComment
has text: The example doesn't make sense to me. Can you please explain how the diff is calculated and where is 4 in the A column and why col B is not sorted?

http://stackoverflow.com/a/69772020
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48353551
downvote count: 0
has body: I think you could try with glob.glob, what should help import numpy as np import glob import cv2 import csv Libraries ⬆️; You know what⬇️ image_list = [] for filename in glob.glob(r'C:\your path to\file*.png'): # '*' will count files each by one #Read img = cv2.imread(filename) flattened = img.flatten() print(flattened) # recommend to avoid duplicates, see files and so on. #Save with open('output2.csv', 'ab') as f: #ab is set np.savetxt(f, flattened, delimiter=&quot;,&quot;) Cheers

http://stackoverflow.com/q/48349409
has answer: http://stackoverflow.com/a/50450088
favorite count: 0
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Can the map function supplied to `tf.data.Dataset.from_generator(...)` resolve a tensor object?
accepted answer: http://stackoverflow.com/a/50450088
has answer: http://stackoverflow.com/a/49040044
possible better answer: http://stackoverflow.com/a/49040044
tagged with: tensorflow
type: Question
has body: I'd like to create a tf.data.Dataset.from_generator(...) dataset. I need to pass in a Python generator. I would like to pass in a property of a previous dataset to the generator like so: dataset = dataset.interleave( map_func=lambda x: tf.data.Dataset.from_generator(generator=lambda: gen(x), output_types=tf.int64), cycle_length=2 ) Where I define gen(...) to take a value (which is a pointer to some data such as a filename which gen knows how to access). This fails because gen receives a tensor object, not a python/numpy value. Is there a way to resolve the tensor object to a value inside of gen(...)? The reason for interleaving the generators is so I can manipulate the list of data-pointers/filenames with other dataset operations such as .shuffle() and .repeat() without the need to bake those into the gen(...) function, which would be necessary if I started with the generator directly from the list of data-pointers/filenames. I want to use the generator because a large number of data values will be generated per data-pointer/filename.
answer count: 2
has comment: http://stackoverflow.com/comment/83707435
upvote count: 1
tagged with: dataset
tagged with: python

http://stackoverflow.com/a/48361259
score: 1
has comment: http://stackoverflow.com/comment/83709455
type: Answer
answers question: http://stackoverflow.com/q/48361170
has body: Have a look at the matplotlib contourplot and colormap demos. From the contour plot demo's last example, you can specify a colour map for the contour plot as follows plt.figure() # plots a bunch of colours im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3, 3, -2, 2)) # plot the contour lines levels = np.arange(-1.2, 1.6, 0.2) CS = plt.contour(Z, levels, origin='lower', linewidths=2, extent=(-3, 3, -2, 2)) you'll need to define your own color map if you want to leave some regions white/unfilled. The colormap is just a dict that maps numeric values to colours https://matplotlib.org/examples/pylab_examples/contour_demo.html https://matplotlib.org/examples/pylab_examples/custom_cmap.html
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48365331
has body: You can try glob solution For example,these are files in folder ~/Test-folder$ ls *.txt -1 AB_DEFG17Sitanything.n.txt AB_DEFG17SOManything.copy(2).txt AB_DEFG17SOManything.nis.txt AB_DEFG17SOManything.n.txt AB_DEFG18SOManything.n.txt AB_DEFG28SOManything.n.txt AB_PIZG17SOManything.piz.txt AB_PIZG28SOManything.n.txt AB_PIZG76SOManything.n.txt My code import glob r = [f for f in glob.glob("*.txt") if "AB_DEFG" in f or "17" in f] for f in r: print (f) You will get AB_DEFG17SOManything.n.txt AB_DEFG17SOManything.nis.txt AB_PIZG17SOManything.piz.txt AB_DEFG17Sitanything.n.txt AB_DEFG28SOManything.n.txt AB_DEFG17SOManything.copy(2).txt AB_DEFG18SOManything.n.txt I forgot to add remove solution import glob,os r = [f for f in glob.glob("*.txt") if "AB_DEFG" in f or "17" in f] for f in r: os.remove(f) Only two files will stay AB_PIZG28SOManything.n.txt AB_PIZG76SOManything.n.txt
answers question: http://stackoverflow.com/q/48365055
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/83771688
type: AnswerComment
score: 1
has text: Thanks, this is great, I'll try this now but this is pretty much what I wanted so I count this solved. Somewhere in here, a good lesson for me about not treating everything like nails when you have a hammer.
type: Comment
comment on: http://stackoverflow.com/a/48391743

http://stackoverflow.com/comment/83820120
comment on: http://stackoverflow.com/a/48414842
type: Comment
score: 0
type: AnswerComment
has text: Sorry, it may be silly question, code is working with no error, however i was trying to print compared values, but it's stating "i" is not defined.

http://stackoverflow.com/comment/83737372
score: 0
comment on: http://stackoverflow.com/q/48375167
has text: What errors do you get? And which line causes them?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84107202
type: Comment
comment on: http://stackoverflow.com/a/48514792
has text: and when I chenge to pprint data, I get `<Response [500]>)`
score: 0
type: AnswerComment

http://stackoverflow.com/a/48427561
type: Answer
answers question: http://stackoverflow.com/q/48425201
has comment: http://stackoverflow.com/comment/83865544
upvote count: 2
has comment: http://stackoverflow.com/comment/102802541
downvote count: 0
has comment: http://stackoverflow.com/comment/83876872
score: 2
has body: Here is a solution for that problem : from collections import Counter import numpy as np import matplotlib.pyplot as plt def balanced_sample_maker(X, y, sample_size, random_seed=42): uniq_levels = np.unique(y) uniq_counts = {level: sum(y == level) for level in uniq_levels} if not random_seed is None: np.random.seed(random_seed) # find observation index of each class levels groupby_levels = {} for ii, level in enumerate(uniq_levels): obs_idx = [idx for idx, val in enumerate(y) if val == level] groupby_levels[level] = obs_idx # oversampling on observations of each label balanced_copy_idx = [] for gb_level, gb_idx in groupby_levels.items(): over_sample_idx = np.random.choice(gb_idx, size=sample_size, replace=True).tolist() balanced_copy_idx+=over_sample_idx np.random.shuffle(balanced_copy_idx) data_train=X[balanced_copy_idx] labels_train=y[balanced_copy_idx] if ((len(data_train)) == (sample_size*len(uniq_levels))): print('number of sampled example ', sample_size*len(uniq_levels), 'number of sample per class ', sample_size, ' #classes: ', len(list(set(uniq_levels)))) else: print('number of samples is wrong ') labels, values = zip(*Counter(labels_train).items()) print('number of classes ', len(list(set(labels_train)))) check = all(x == values[0] for x in values) print(check) if check == True: print('Good all classes have the same number of examples') else: print('Repeat again your sampling your classes are not balanced') indexes = np.arange(len(labels)) width = 0.5 plt.bar(indexes, values, width) plt.xticks(indexes + width * 0.5, labels) plt.show() return data_train,labels_train X_train,y_train=balanced_sample_maker(X,y,10) inspired by Scikit-learn balanced subsampling
has comment: http://stackoverflow.com/comment/83876836

http://stackoverflow.com/a/48430400
downvote count: 0
type: Answer
has body: If you want different functions on each click, try the following: from turtle import * def f(x, y): goto(x, -y) onscreenclick(g) # what happens next time def g(x, y): goto(-x, y) onscreenclick(f) # what happens next time def main(): onscreenclick(f) main() mainloop() You should be able to repeatedly click and see the behavior alternating between the two functions. Your understanding of the third argument to onscreenclick() was correct, you can either replace existing event handling or you can augment it, but it's not set up to alternate it.
answers question: http://stackoverflow.com/q/48428157
score: 3
upvote count: 3

http://stackoverflow.com/a/48442541
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48442481
has body: I was able to achieve this using sklearn as follows (continue the code above): def build_matrix(x): """ Converts a signal into a matrix of delayed signals. I.e. `row_j` is each time `t`, `column_i` is the signal at `t - i`, It assumes that no past signal =&gt; no signal: each row is left-padded with zeros. For example, for 3 times, the matrix would be: ``` [0, 0 , 0 ] (-&gt; y[0]) [0, 0 , x[0]] (-&gt; y[1]) [0, x[0], x[1]] (-&gt; y[2]) ``` I.e. The parameter fitted to column 2, a2, is the influence of `x[t - 1]` on `y[t]`. The parameter fitted to column 1, a1, is the influence of `x[t - 2]` on `y[t]`. It assumes that we only measure x[t] when we measure y[t], the reason why that column does not appear """ data_x = [] for i in range(len(x)): data_x.append(np.append(np.zeros(len(x) - i), x[:i])) return np.array(data_x) class VARClassifier: """ A Classifier based on any sklearn linear classifier that contain a method to return the fitted response function """ def __init__(self, classifier): self.classifier = classifier self.number_of_signals_ = None self.time_len_ = None def _transform_x(self, x): for x_i in x: assert len(x_i) == self.time_len_ assert len(x_i.shape) == 1, 'Each of the elements must be a time-series (1D)' return np.concatenate(tuple(build_matrix(x_i) for x_i in x), axis=1) def fit(self, x, y): self.number_of_signals_ = len(x) self.time_len_ = len(x[0]) return self.classifier.fit(self._transform_x(x), y) def predict(self, x): return self.classifier.predict(self._transform_x(x)) @property def response_functions(self): # ::-1 because the coefficients are reversed, see `build_matrix ` return [self.classifier.coef_[i*self.time_len_:(i+1)*self.time_len_][::-1] for i in range(self.number_of_signals_)] def __getattr__(self, item): return self.classifier.__getattr__(item) classifier = VARClassifier(Lasso(alpha=0.1)) classifier.fit((x1, x2), y) plt.subplot(514) plt.xlabel('delay') plt.ylabel('fitted response\nfunction 1') r1, r2 = classifier.response_functions pl…
score: 1

http://stackoverflow.com/a/48368561
type: Answer
has comment: http://stackoverflow.com/comment/83850883
has body: Replace: canvas.itemconfig(canvas_id, text="MD5 File Hashes") with: canvas.itemconfig(canvas_id, text=output) if you want to display rootDir as well you can instead replace with: canvas.itemconfig(canvas_id, text="Directory: {}\n{}".format(rootDir, output)) The output you have is a string: &gt;&gt;&gt;type(output) &lt;class 'str'&gt; So you can easily put it on as any place that accepts strings, such as print(output) and canvas.itemconfig(canvas_id, text=output).
has comment: http://stackoverflow.com/comment/83850219
has comment: http://stackoverflow.com/comment/83850488
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83850356
answers question: http://stackoverflow.com/q/48368509
has comment: http://stackoverflow.com/comment/83850940
has comment: http://stackoverflow.com/comment/83850289
accepted answer of: http://stackoverflow.com/q/48368509

http://stackoverflow.com/q/48459235
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83911345
downvote count: 0
has comment: http://stackoverflow.com/comment/83911748
tagged with: python
has body: Coming from a Java background I'm currently learning Python and I found this example in a Python beginner book. It's proposing the use of the ValueError exception in a function for a spreadsheet-like calculation to return 0 for empty cells like this: def cell_value(string): try: return float(string) except ValueError: if string == "": return 0 else: return None Now, to my understanding, in the Java world, such a use of exceptions would be frowned upon, because having an empty cell in a spreadsheet and interpreting it as 0 is clearly not an exceptional condition but rather normal program flow and in Java "exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow." (Joshua Bloch: Effective Java) I already read another similar question and answer suggesting that this rule might not be adhered to as strictly in the Python world, but I'm still not sure about the given example. Would the use of ValueError as illustrated in the function above be considered bad practice in Python or not?
linked to: http://stackoverflow.com/q/7274310
favorite count: 0
has comment: http://stackoverflow.com/comment/83911295
score: 2
tagged with: coding-style
tagged with: exception
has comment: http://stackoverflow.com/comment/83911504
has title: Is it acceptable in terms of good Python style to use ValueError for returning a default value?
has comment: http://stackoverflow.com/comment/83911796
type: Question
has comment: http://stackoverflow.com/comment/83911661
answer count: 0

http://stackoverflow.com/a/48487946
has comment: http://stackoverflow.com/comment/83968841
has comment: http://stackoverflow.com/comment/83968944
accepted answer of: http://stackoverflow.com/q/48487880
has comment: http://stackoverflow.com/comment/83968972
type: Answer
score: 4
has body: You should print 16 characters at a time: i = 0 #for word in SIGNS: for i in range(0, len(SIGNS), 16): print(SIGNS[i:i+16]) Don't use for word in SIGNS: as it iterates through the string in SIGNS character-by-character, which is what messed you up.
has comment: http://stackoverflow.com/comment/83968937
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83968860
answers question: http://stackoverflow.com/q/48487880
upvote count: 4

http://stackoverflow.com/a/68616083
type: Answer
answers question: http://stackoverflow.com/q/48377214
upvote count: 14
downvote count: 0
has body: The problem is that you are passing in bad arguments to torch.nn.CrossEntropyLoss in your classification problem. Specifically, in this line ---&gt; 18 loss = criterion(outputs, labels) the argument labels is not what CrossEntropyLoss is expecting. labels should be a 1-D array. The length of this array should be the batch size that matches outputs in your code. The value of each element should be the 0-based target class ID. Here's an example. Suppose you have batch size B=2, and each data instance is given one of K=3 classes. Further, suppose that the final layer of your neural network is outputting the following raw logits (the values before softmax) for each of the two instances in your batch. Those logits and the true label for each data instance are shown below. Logits (before softmax) Class 0 Class 1 Class 2 True class ------- ------- ------- ---------- Instance 0: 0.5 1.5 0.1 1 Instance 1: 2.2 1.3 1.7 2 Then in order to call CrossEntropyLoss correctly, you need two variables: input of shape (B, K) containing the logit values target of shape B containing the index of the true class Here's how to correctly use CrossEntropyLoss with the values above. I am using torch.__version__ 1.9.0. import torch yhat = torch.Tensor([[0.5, 1.5, 0.1], [2.2, 1.3, 1.7]]) print(yhat) # tensor([[0.5000, 1.5000, 0.1000], # [2.2000, 1.3000, 1.7000]]) y = torch.Tensor([1, 2]).to(torch.long) print(y) # tensor([1, 2]) loss = torch.nn.CrossEntropyLoss() cel = loss(input=yhat, target=y) print(cel) # tensor(0.8393) I'm guessing that the error you received originally RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) probably occurred because you are trying to compute cross entropy loss for one data instance, where the target is encoded as one-hot. You probably had your data like this: Logits (before softmax) Class 0 Class 1 Class 2 True class 0 True class 1 True class 2 ------- ------- ------- ------------ ------------ ------------ Instance 0: 0.5 1.5 0.1 …
score: 14
has comment: http://stackoverflow.com/comment/124757861

http://stackoverflow.com/a/48461509
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48461297
has comment: http://stackoverflow.com/comment/83916188
has comment: http://stackoverflow.com/comment/83916150
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48461297
score: 1
has body: The StandardScaler() function in sklearn expects the input(X) to be in the following format: X : numpy array of shape [n_samples, n_features] So, reshape X to (-1,1) if you have only one feature column. sc_X.fit_transform(X.reshape[-1,1]) This should work!

http://stackoverflow.com/q/48331994
tagged with: plotnine
accepted answer: http://stackoverflow.com/a/52028199
type: Question
upvote count: 20
score: 20
has answer: http://stackoverflow.com/a/52028199
has comment: http://stackoverflow.com/comment/83733816
has body: I'm trying to use plotnine to save a high-resolution png image. With a test dataset, this looks like: from plotnine import * import pandas as pd import numpy as np df = pd.DataFrame() df['x'] = np.arange(0,10,0.01) df['y'] = np.sin(df['x']) p = ggplot(df, aes(x='x',y='y')) + labs(x='x', y='y') + geom_point(size=0.1) p.save(filename = 'test3.png', height=5, width=5, units = 'in', dpi=1000) This produces a low-resolution .png file containing my plot, which is not improved when I increase the specified dpi. I've also tried saving with: ggsave(plot=p, filename='test.png', dpi=1000) and replacing dpi=1000 with res=1000. This produces identical low-resolution png files. How can I save my plot at the resolution I want? Edit: This bug is resolved in plotnine version 0.3.0. and the above code works correctly.
answer count: 2
has comment: http://stackoverflow.com/comment/83735556
tagged with: python
has answer: http://stackoverflow.com/a/70817254
has comment: http://stackoverflow.com/comment/83726416
tagged with: ggplot2
has comment: http://stackoverflow.com/comment/84350130
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/70817254
has title: Saving high-resolution images with plotnine
favorite count: 0
has comment: http://stackoverflow.com/comment/83733461

http://stackoverflow.com/a/48366860
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/101151621
has comment: http://stackoverflow.com/comment/97952133
has comment: http://stackoverflow.com/comment/97913406
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48357343
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48357343
has body: You only need to capture EVENT_JOB_ERROR. Also, sentry.captureException() requires an exc_info tuple as its argument, not the exception object. The following will work on Python 3: def listen_to_exceptions(event): exc_info = type(event.exception), event.exception, event.exception.__traceback__ sentry.captureException(exc_info) scheduler.add_listener(listen_to_exceptions, EVENT_JOB_ERROR)
has comment: http://stackoverflow.com/comment/83811954

http://stackoverflow.com/q/48389320
has comment: http://stackoverflow.com/comment/83766440
favorite count: 0
has comment: http://stackoverflow.com/comment/83766642
has answer: http://stackoverflow.com/a/48389421
has comment: http://stackoverflow.com/comment/83766732
score: 1
has title: Sort only the first two elements in each sub-array of 3 elements
has answer: http://stackoverflow.com/a/48389871
tagged with: python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83766904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83766396
tagged with: arrays
downvote count: 0
upvote count: 1
has body: I have an array: list=[[1, 2, 3], [31, 10, 2], [7, 2, 4]] And I want to sort the only the first two elements in each sub-array (in increasing order). The list should look like this: list=[[1, 2, 3], [10, 31, 2], [2, 7, 4]] The code that I used to do was: list=[[1, 2, 3], [10, 31, 2], [2, 7, 4]] for i in list: if list[0]&gt;list[1]: list[0],list[1]=list[1],list[0] else: print('Do Nothing') Is there any faster way to do it?
tagged with: sorting

http://stackoverflow.com/q/48481492
accepted answer: http://stackoverflow.com/a/48481830
answer count: 4
has answer: http://stackoverflow.com/a/48481833
has comment: http://stackoverflow.com/comment/83956584
has comment: http://stackoverflow.com/comment/83956611
tagged with: class
tagged with: python
has title: Creating classes and variable assignment
has answer: http://stackoverflow.com/a/48482152
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83956026
has comment: http://stackoverflow.com/comment/83956416
has comment: http://stackoverflow.com/comment/83956011
downvote count: 0
has answer: http://stackoverflow.com/a/48481830
favorite count: 0
has answer: http://stackoverflow.com/a/48481907
possible better answer: http://stackoverflow.com/a/48481907
type: Question
has comment: http://stackoverflow.com/comment/83956565
has comment: http://stackoverflow.com/comment/83956947
has body: I'm trying to understand how classes work a bit better "under the hood" of python. If I create a class Foo like so class Foo: bar = True Foo is then directly accessible, such as print(Foo) or print(Foo.bar) However, if I dynamically create create a class and don't set it to a variable like so type('Foo',(),{'bar':True}) If done in the interpreter it shows &lt;class '__main__.Foo'&gt;. However, when I try to print Foo it's undefined...NameError: name 'Foo' is not defined Does this mean that when a class is created the "traditional" way (the first Foo class above), that python automatically sets a variable for the class of the same name? Sort of like this # I realize this is not valid, just to convey the idea Foo = class Foo: bar = True If so, then why doesn't python also create a variable named Foo set to class Foo when using type() to create it?

http://stackoverflow.com/a/59305416
has comment: http://stackoverflow.com/comment/104881193
has body: One solution for this question by using Pool and Queue is from time import sleep from multiprocessing import Pool,Queue id_list = [1,2,3,4,5,6,7,8,9,10] def mp_worker(q): try: print(q.get()) sleep(.1) except: pass print ("worker closed") if __name__ == "__main__": q = Queue() p = Pool(processes = 2) #number of processes for x in id_list: q.put(x) p.map(mp_worker, id_list) #devides id_list between 2 processes, defined above you must add vaules to Quene by put in main section of your code and in the function read the value from Queue by get
has comment: http://stackoverflow.com/comment/104835249
answers question: http://stackoverflow.com/q/48363237
score: 1
downvote count: 1
upvote count: 2
type: Answer

http://stackoverflow.com/a/48404611
has comment: http://stackoverflow.com/comment/83803971
type: Answer
answers question: http://stackoverflow.com/q/48391579
score: 0
has body: Initialize an empty dict outside the for loop, and then update that with the values of each of your input dictioanries. from collections import OrderedDict l=[OrderedDict([('UF' , 'New York'), ('Total', 44.13), ('DEF', 9.5)]), OrderedDict([('UF' , 'LA'), ('Total', 54.13), ('DEF', 1.0)]), OrderedDict([('UF' , 'New York'), ('Total', 12.01), ('DEF', 0.4)])] d = {} for od in l: city = od['UF'] if city not in d: d[city] = od else: d[city]['DEF'] += od['DEF'] d[city]['Total'] += od['Total'] print(d) # {'New York': OrderedDict([('UF', 'New York'), ('Total', 68.15), ('DEF', 10.3)]), # 'LA': OrderedDict([('UF', 'LA'), ('Total', 54.13), ('DEF', 1.0)])}

http://stackoverflow.com/comment/83759523
comment on: http://stackoverflow.com/a/48385894
type: AnswerComment
score: 1
has text: It's not object references but rather the variables that the object references are stored in. Also, both of these examples are showing the same thing, referring to variables. Just one is in OOP and one is not.
type: Comment

http://stackoverflow.com/comment/83713905
type: QuestionComment
comment on: http://stackoverflow.com/q/48363552
score: 3
has text: `[cls.somefunc(**i) for i in [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]`?
type: Comment

keras
tags question: http://stackoverflow.com/q/48389545
tags question: http://stackoverflow.com/q/48373685
tags question: http://stackoverflow.com/q/48447149
tags question: http://stackoverflow.com/q/48407856
tags question: http://stackoverflow.com/q/48335212
tags question: http://stackoverflow.com/q/48467000
tags question: http://stackoverflow.com/q/48452570
tags question: http://stackoverflow.com/q/48434459
tags question: http://stackoverflow.com/q/48377289
tags question: http://stackoverflow.com/q/48471040
tags question: http://stackoverflow.com/q/48466901
tags question: http://stackoverflow.com/q/48418907
tags question: http://stackoverflow.com/q/48391265
tags question: http://stackoverflow.com/q/48387602
tags question: http://stackoverflow.com/q/48385830
tags question: http://stackoverflow.com/q/48458635
tags question: http://stackoverflow.com/q/48370819
tags question: http://stackoverflow.com/q/48420005
tags question: http://stackoverflow.com/q/48389563
tags question: http://stackoverflow.com/q/48373845
tags question: http://stackoverflow.com/q/48364108
tags question: http://stackoverflow.com/q/48344228
tags question: http://stackoverflow.com/q/48460460
tags question: http://stackoverflow.com/q/48333633
tags question: http://stackoverflow.com/q/48343260
tags question: http://stackoverflow.com/q/48447371
tags question: http://stackoverflow.com/q/48423769
tags question: http://stackoverflow.com/q/48377332
tags question: http://stackoverflow.com/q/48382859
tags question: http://stackoverflow.com/q/48470409
tags question: http://stackoverflow.com/q/48372575
tags question: http://stackoverflow.com/q/48415447
tags question: http://stackoverflow.com/q/48456483
tags question: http://stackoverflow.com/q/48418468
tags question: http://stackoverflow.com/q/48429743
tags question: http://stackoverflow.com/q/48470539
tags question: http://stackoverflow.com/q/48415957
tags question: http://stackoverflow.com/q/48407730
tags question: http://stackoverflow.com/q/48353617
tags question: http://stackoverflow.com/q/48480751
tags question: http://stackoverflow.com/q/48482483
tags question: http://stackoverflow.com/q/48416982
tags question: http://stackoverflow.com/q/48432300
tags question: http://stackoverflow.com/q/48356683
tags question: http://stackoverflow.com/q/48339129
tag name: keras
tags question: http://stackoverflow.com/q/48389764
tags question: http://stackoverflow.com/q/48431282
tags question: http://stackoverflow.com/q/48345755
tags question: http://stackoverflow.com/q/48452999
tags question: http://stackoverflow.com/q/48455338
tags question: http://stackoverflow.com/q/48352234
tags question: http://stackoverflow.com/q/48482766
tags question: http://stackoverflow.com/q/48392457
tags question: http://stackoverflow.com/q/48362612
tags question: http://stackoverflow.com/q/48407377
tags question: http://stackoverflow.com/q/48457124
tags question: http://stackoverflow.com/q/48375634
tags question: http://stackoverflow.com/q/48470591
tags question: http://stackoverflow.com/q/48388641
type: Tag
tags question: http://stackoverflow.com/q/48485937
tags question: http://stackoverflow.com/q/48342068
tags question: http://stackoverflow.com/q/48453143
tags question: http://stackoverflow.com/q/48422892
tags question: http://stackoverflow.com/q/48345711
tags question: http://stackoverflow.com/q/48355700
tags question: http://stackoverflow.com/q/48365990
tags question: http://stackoverflow.com/q/48412424
tags question: http://stackoverflow.com/q/48447250
tags question: http://stackoverflow.com/q/48486598
tags question: http://stackoverflow.com/q/48454195

http://stackoverflow.com/comment/83955334
has text: The error is exactly saying what is missing, an Email field. 1) Does the Student Model have an Email field? 2) Did you add the email in the fields in the Meta Class of StudentEditForm?
type: AnswerComment
comment on: http://stackoverflow.com/a/48478002
type: Comment
score: 0

http://stackoverflow.com/comment/83951263
has text: But it does support JSON indexing.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48478947

http://stackoverflow.com/a/48470791
has comment: http://stackoverflow.com/comment/83935972
has comment: http://stackoverflow.com/comment/83935846
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83936359
downvote count: 0
has comment: http://stackoverflow.com/comment/83936352
has comment: http://stackoverflow.com/comment/83936055
accepted answer of: http://stackoverflow.com/q/48470734
has comment: http://stackoverflow.com/comment/83944589
has comment: http://stackoverflow.com/comment/83944798
answers question: http://stackoverflow.com/q/48470734
has comment: http://stackoverflow.com/comment/83936414
type: Answer
score: 2
has body: If your language is JavaScript so use the following code else you can use same function for other language just else changing the syntax: Javascript: var angle_converter = function(value,valueType){ if (valueType=="degree"){ return (value*Math.PI)/180; }else if (valueType=="radian"){ return value*180/Math.PI; } else{ return "Not a valid type!" } } console.log(angle_converter(2.5,"degree")) console.log(angle_converter(2.5,"radian")) console.log(angle_converter(2.5,"float")) Python: import math def angle_converter(value,valueType): if valueType=="degree": return (value*math.pi)/180; else: if valueType=="radian": return value*180/math.pi; else: return "Not a valid type!" #------------ USE: ------------ print(angle_converter(2.5,'degree')) # &gt;&gt; 0.0436332312999 print(angle_converter(2.5,"radian")) # &gt;&gt; 143.239448783 print(angle_converter(2.5,"float")) # &gt;&gt; Not a valid type! Live Demo Or this one: import math def angle_converter(value,valueType): if valueType=="degree": return degree_to_radian(value); else: if valueType=="radian": return radian_to_degree(value); else: return "Not a valid type!" def degree_to_radian(in_degree): return((in_degree*math.pi)/180) def radian_to_degree(in_radian): return(in_radian*180/math.pi) print(degree_to_radian(2.5)) # &gt;&gt; 0.0436332312999 print(radian_to_degree(2.5)) # &gt;&gt; 143.239448783 print(angle_converter(2.5,'degree')) # &gt;&gt; 0.0436332312999 print(angle_converter(2.5,"radian")) # &gt;&gt; 143.239448783 print(angle_converter(2.5,"float")) # &gt;&gt; Not a valid type!
has comment: http://stackoverflow.com/comment/83945577
upvote count: 2

http://stackoverflow.com/comment/83968876
type: QuestionComment
comment on: http://stackoverflow.com/q/48487802
score: 0
type: Comment
has text: There's no output in your loop except a single integer - success or fail - as far as the `.split()` is concerned. It's not reading stdout.

http://stackoverflow.com/q/48375250
has comment: http://stackoverflow.com/comment/83737863
has comment: http://stackoverflow.com/comment/83737537
has comment: http://stackoverflow.com/comment/83737582
tagged with: python
has body: I defined a class that holds a list collection of objects, and defined the __iter__ and __next__ methods to make it for loopable. The collection here, is a Deck class that holds a list of Card objects. Code: import random class Card: @staticmethod def get_ranks(): return ("A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2") # A is highest, 2 is lowest @staticmethod def get_suites(): return ("H", "D", "S", "C") def __init__(self, suite, rank): if suite not in Card.get_suites(): raise Exception("Invalid suite") if rank not in Card.get_ranks(): raise Exception("Invalid rank") self.suite = suite self.rank = rank def __lt__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank > card2_rank def __le__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank >= card2_rank def __gt__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank < card2_rank def __ge__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank <= card2_rank def __eq__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank == card2_rank def __ne__(self, card2): self_rank = Card.get_ranks().index(self.rank) card2_rank = Card.get_ranks().index(card2.rank) return self_rank != card2_rank def __str__(self): return(self.rank + self.suite) def __repr__(self): return str(self) class Deck: def __init__(self): self.contents = [Card(suite, rank) for suite in Card.get_suites() for rank in Card.get_ranks()] random.shuffle(self.contents) self.index = 0 def __len__(self): return len(self.contents) def __iter__(self): return self def __next__(self): if self.index == len(self.contents): raise StopIteration item = self.contents[self.index] self.index += 1 return ite…
answer count: 4
type: AnsweredQuestion
score: 0
tagged with: iterator
has comment: http://stackoverflow.com/comment/83737891
has answer: http://stackoverflow.com/a/48375456
has comment: http://stackoverflow.com/comment/83737702
has answer: http://stackoverflow.com/a/48376037
has title: Python Iterator class index overflows on second of for loop run
type: Question
has comment: http://stackoverflow.com/comment/83737548
has answer: http://stackoverflow.com/a/48375303
has answer: http://stackoverflow.com/a/48375280
possible better answer: http://stackoverflow.com/a/48375280
accepted answer: http://stackoverflow.com/a/48375456

http://stackoverflow.com/a/48463809
has comment: http://stackoverflow.com/comment/83999628
upvote count: 2
downvote count: 0
has body: You can use builtin map function to assign 10 at start of each sublist. &gt;&gt;&gt; l = [[0 for i in range(4)] for i in range(4)] &gt;&gt;&gt; list(map(lambda x, y: x+y[1:], [[10]]*len(l), l)) &gt;&gt;&gt; [[10, 0, 0, 0], [10, 0, 0, 0], [10, 0, 0, 0], [10, 0, 0, 0]]
answers question: http://stackoverflow.com/q/48463204
type: Answer
score: 2

http://stackoverflow.com/a/48459960
has comment: http://stackoverflow.com/comment/83912965
accepted answer of: http://stackoverflow.com/q/48459649
has comment: http://stackoverflow.com/comment/83913182
has comment: http://stackoverflow.com/comment/83913170
score: 1
answers question: http://stackoverflow.com/q/48459649
has comment: http://stackoverflow.com/comment/83913222
has comment: http://stackoverflow.com/comment/83913220
has body: You can annotate your queryset with the number of answers: from django.db.models import Count results = Question.objects.annotate(num_answers=Count('answer')) Then you can access question.num_answers as you loop through the queryset: {% for question in questions %} {{ question.title }} {{ question.num_answers }} {% endfor %}
has comment: http://stackoverflow.com/comment/83913078
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83855772
type: QuestionComment
comment on: http://stackoverflow.com/q/48432090
has text: @DanielRoseman I disagree, I think python *never* passes by reference. But I admit, my understanding of these things may be incorrect. To my understanding, passing a reference isn't the same thing as passing by reference, which is generally characterized by having assignments to the variable being seen by the caller. I.E. `def special(&x): x = 4` then `y = 3; special(y); print(y)` would print `4`
score: 0
type: Comment

http://stackoverflow.com/a/48392495
type: AcceptedAnswer
downvote count: 0
has body: A little contrived, but this is probably the easiest way of doing it. Note that addition on lists is very expensive. df'B', 'C' = df'B', 'C'.values.reshape(-1, 2, 1).tolist() df'B', 'C'.cumsum() B C 0 [1] [2] 1 [1, 2] [2, 3] 2 [1, 2, 1] [2, 3, 1] 3 [1, 2, 1, 2] [2, 3, 1, 6] The trick is to augment the dimensionality of your array, so each element becomes a list with a single element. Once you assign back, you can call df.cumsum which operates row-wise and adds the lists together, cumulatively.
answers question: http://stackoverflow.com/q/48392386
has comment: http://stackoverflow.com/comment/83774741
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48392386
score: 2

http://stackoverflow.com/a/48589530
score: 4
downvote count: 0
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48471648
has body: There is a lot of questions to be answered here. Let's start by understanding what a 'category' is... Definition of Categorical dtype Quoting from pandas docs for "Categorical Data": Categoricals are a pandas data type, which correspond to categorical variables in statistics: a variable, which can take on only a limited, and usually fixed, number of possible values (categories; levels in R). Examples are gender, social class, blood types, country affiliations, observation time or ratings via Likert scales. There are two points I want to focus on here: The definition of categoricals as a statistical variable: basically, this means we have to look at them from a statistical point of view, not the "regular" programming one. i.e. they are not 'enumerates'. Statistical categorical variables has specific operations and usecases, you can read more about them in wikipedia. I'll talk more about this after the second point. Categories are levels in R: We can understand more about categoricals if we read about R levels and factors. I don't know much about R, but I found this source simple and sufficient. Quoting an interesting example from it: When a factor is first created, all of its levels are stored along with the factor, and if subsets of the factor are extracted, they will retain all of the original levels. This can create problems when constructing model matrices and may or may not be useful when displaying the data using, say, the table function. As an example, consider a random sample from the letters vector, which is part of the base R distribution. &gt; lets = sample(letters,size=100,replace=TRUE) &gt; lets = factor(lets) &gt; table(lets[1:5]) 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 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 Even though only five of the levels were actually represented, the table function shows the frequencies for all of the levels of the original factors. To change this, we can simply use another call to factor &gt; table(facto…

http://stackoverflow.com/q/48344898
has title: Python filter function usage
downvote count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/25336726
answer count: 0
score: 1
has body: I'm trying to understand how filter() function works in Python. Namely, Python 3. I know about list comprehensions, and they work as they should in my example, I just want to understand how filter() function works. Suppose I have a list of integers I'd like to filter once, and then filter one more time: myList = [1, 2, 3, 4, 5] myList = filter(lambda i: i &lt;= 3, myList) myList2 = filter(lambda i: i == 1, myList) print(list(myList)) print(list(myList2)) The output is: [1, 2, 3] [] Why myList2 is empty? I know that filter() function returns a filter object, but isn't it iterable and allowed for use in subsequent filter() call? If I change the code to myList = [1, 2, 3, 4, 5] myList = filter(lambda i: i &lt;= 3, myList) myList2 = filter(lambda i: i == 1, list(myList)) print(list(myList)) print(list(myList2)) the output is: [] [1] Why myList became empty after converting it to list explicitly in the 2nd filter call?
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44420135
type: UnansweredQuestion

http://stackoverflow.com/comment/83706291
comment on: http://stackoverflow.com/q/48359744
type: QuestionComment
has text: what about if you run the code once ? And there is something left ?. Note you are renaming your files, so they 'dissappear'...
score: 1
type: Comment

http://stackoverflow.com/a/48485734
type: Answer
score: 0
has body: Ethernet packets consist of destination MAC address source MAC address type payload Padding MAC addresses are 48 bits or 6 bytes long. Type is a 1 byte field. If I'm in doubt about those headers, I use Wireshark and look at its interpretation. They also have a wiki that explains the structure. In your string, ! tells to use standard size and network endianness (big endian) when unpacking, 6s takes 6 characters to build a string for the destination address, 6s takes the source address and H takes an unsigned short for the type. You find the format characters in 7.3.2.2 of the Python documentation and 7.3.2.1
answers question: http://stackoverflow.com/q/48485672
has comment: http://stackoverflow.com/comment/83965204

http://stackoverflow.com/q/48474056
type: AnsweredQuestion
score: 0
has title: BadOptionError when import volatility.conf
type: Question
has comment: http://stackoverflow.com/comment/83941686
tagged with: exception
has answer: http://stackoverflow.com/a/48474357
has body: I write below code and it gives me error in first line! whats wrong is with this code: import volatility.conf as conf import volatility.registry as reg import volatility.commands as commands import volatility.addrspace as addrspace import volatility.plugins.taskmods as taskmode # configure volatility reg.PluginImporter() config=conf.ConfObject() reg.register_global_options(conf,commands.Command) reg.register_global_options(conf,addrspace.BaseAddressSpace) config.parse_options() config.PROFILE="Linuxfedora32x64" config.LOCATION="./dumps/mem.lime" p=taskmode.PSList(config) for process in p.calculate: print(process) the error code:i think there is some code insode conf.py witch in not support in python 3.6 .but volatility is copatible with python 3.6. so i don't know what to do : Traceback (most recent call last): File "../PycharmProjects/volpractive/test.py", line 6, in &lt;module&gt; import volatility.conf as conf File "/anaconda3/lib/python3.6/site-packages/volatility-2.6-py3.6.egg/volatility/conf.py", line 84 except (optparse.BadOptionError, optparse.OptionValueError), err:
accepted answer: http://stackoverflow.com/a/48474357
answer count: 1
tagged with: volatility
tagged with: python
has comment: http://stackoverflow.com/comment/83941729

http://stackoverflow.com/q/48336692
type: AnsweredQuestion
tagged with: if-statement
tagged with: python
has answer: http://stackoverflow.com/a/48336736
favorite count: 0
type: Question
upvote count: 0
downvote count: 2
duplicate of: http://stackoverflow.com/q/15112125
has title: else and elif statements result in if statement
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/83658498
accepted answer: http://stackoverflow.com/a/48336736
linked to: http://stackoverflow.com/q/15112125
has body: hello I am new to python coding and am wondering why whatever is inputted it results in the if statement. def opnbx(): opn = input("in frount of you is a box do you open it? ") if opn == "yes" or "Y" or "y" or "Yes": print("you open the box") elif opn == "no" or "No" or "N" or "n": print("you ignore the box and move on") else: print("please repeat...") opnbx() opnbx()

http://stackoverflow.com/comment/83982715
score: 0
type: Comment
has text: Get rid of 301 redirect to https. You can not redirect to https until after you have properly configured SSL.
type: AnswerComment
comment on: http://stackoverflow.com/a/48478243

http://stackoverflow.com/comment/83893892
has text: Dimensions of `target_sequence` are 100x80. Moreover, the length of y_sequence cannot be an issue since I am interested in accessing the index corresponding to the ASCII code of the jth character in the y_sequence variable and setting `target_sequence[j][y_sequence_ix[j]` = 1
comment on: http://stackoverflow.com/q/48450268
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83916650
comment on: http://stackoverflow.com/q/48461739
score: 0
has text: No, unfortunately I only have the header file (which I cannot distribute, but the function prototypes correspond to the ones stated). Python version is 3.6.3, 64bit
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48412744
has body: Processing the items in a list to make a new list calls for a list comprehension. Combine it with the x if y else z conditional expression to modify the items as you want. old_list = ['the dog ran', 'tomorrow is Wednesday', 'hello sir'] new_list = [('\n' + item) if "Wednesday" in item else item for item in old_list]
score: 5
accepted answer of: http://stackoverflow.com/q/48412711
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48412711

http://stackoverflow.com/comment/83785579
score: 0
has text: even if we do it line by line:
comment on: http://stackoverflow.com/q/48398376
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83861440
type: Comment
comment on: http://stackoverflow.com/a/48434845
score: 0
type: AnswerComment
has text: thank you @Angel F so much for your time. I added a default value and it is working as expected.

http://stackoverflow.com/comment/83859022
type: QuestionComment
has text: Do you mean the question isn't clear? I have tried to run an if statement and a where function. I can do it in excel but need to run this over a large dataset
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48433694

list
tags question: http://stackoverflow.com/q/48380512
tags question: http://stackoverflow.com/q/48437673
tags question: http://stackoverflow.com/q/48472710
tags question: http://stackoverflow.com/q/48408529
type: Tag
tags question: http://stackoverflow.com/q/48412699
tags question: http://stackoverflow.com/q/48415006
tags question: http://stackoverflow.com/q/48352791
tags question: http://stackoverflow.com/q/48414645
tags question: http://stackoverflow.com/q/48356973
tags question: http://stackoverflow.com/q/48395838
tags question: http://stackoverflow.com/q/48414190
tags question: http://stackoverflow.com/q/48372510
tags question: http://stackoverflow.com/q/48357213
tags question: http://stackoverflow.com/q/48465368
tags question: http://stackoverflow.com/q/48484709
tags question: http://stackoverflow.com/q/48360661
tags question: http://stackoverflow.com/q/48393644
tags question: http://stackoverflow.com/q/48463204
tags question: http://stackoverflow.com/q/48458104
tags question: http://stackoverflow.com/q/48331164
tags question: http://stackoverflow.com/q/48472029
tags question: http://stackoverflow.com/q/48457570
tags question: http://stackoverflow.com/q/48385793
tags question: http://stackoverflow.com/q/48454827
tags question: http://stackoverflow.com/q/48353766
tags question: http://stackoverflow.com/q/48411344
tags question: http://stackoverflow.com/q/48350061
tags question: http://stackoverflow.com/q/48362903
tags question: http://stackoverflow.com/q/48406300
tags question: http://stackoverflow.com/q/48359366
tags question: http://stackoverflow.com/q/48354276
tags question: http://stackoverflow.com/q/48475312
tags question: http://stackoverflow.com/q/48362768
tags question: http://stackoverflow.com/q/48413991
tags question: http://stackoverflow.com/q/48464607
tags question: http://stackoverflow.com/q/48366442
tags question: http://stackoverflow.com/q/48470778
tags question: http://stackoverflow.com/q/48473646
tags question: http://stackoverflow.com/q/48349197
tags question: http://stackoverflow.com/q/48374568
tags question: http://stackoverflow.com/q/48351558
tags question: http://stackoverflow.com/q/48332050
tags question: http://stackoverflow.com/q/48354756
tags question: http://stackoverflow.com/q/48468510
tags question: http://stackoverflow.com/q/48451909
tags question: http://stackoverflow.com/q/48358320
tags question: http://stackoverflow.com/q/48371760
tags question: http://stackoverflow.com/q/48485289
tags question: http://stackoverflow.com/q/48395623
tags question: http://stackoverflow.com/q/48424003
tags question: http://stackoverflow.com/q/48478357
tags question: http://stackoverflow.com/q/48434453
tags question: http://stackoverflow.com/q/48431125
tags question: http://stackoverflow.com/q/48363552
tags question: http://stackoverflow.com/q/48457934
tags question: http://stackoverflow.com/q/48443151
tags question: http://stackoverflow.com/q/48475989
tags question: http://stackoverflow.com/q/48452996
tags question: http://stackoverflow.com/q/48366939
tags question: http://stackoverflow.com/q/48417972
tags question: http://stackoverflow.com/q/48385082
tags question: http://stackoverflow.com/q/48372680
tags question: http://stackoverflow.com/q/48469454
tags question: http://stackoverflow.com/q/48390647
tags question: http://stackoverflow.com/q/48341537
tags question: http://stackoverflow.com/q/48414404
tags question: http://stackoverflow.com/q/48375270
tags question: http://stackoverflow.com/q/48434989
tags question: http://stackoverflow.com/q/48486784
tags question: http://stackoverflow.com/q/48360390
tags question: http://stackoverflow.com/q/48480786
tags question: http://stackoverflow.com/q/48430360
tags question: http://stackoverflow.com/q/48466298
tags question: http://stackoverflow.com/q/48355942
tags question: http://stackoverflow.com/q/48362151
tags question: http://stackoverflow.com/q/48349548
tags question: http://stackoverflow.com/q/48369505
tags question: http://stackoverflow.com/q/48332152
tags question: http://stackoverflow.com/q/48351334

http://stackoverflow.com/comment/83800542
comment on: http://stackoverflow.com/a/48405457
score: 0
type: AnswerComment
has text: @Techflu It should be work :-) Base on your sample data , unless you have multiple key in code
type: Comment

http://stackoverflow.com/a/48362338
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48362085
type: Answer
has body: You could also create a file object by directly inputting a filename into the open() parameters file = open(input("Enter Filename: "),'w')

http://stackoverflow.com/comment/83896958
has text: @wwii: I want to specify the number of sub-lists and then populate entries in each sub-list. Given my input, I do not know how many entries each sub-list would contain, but I do know the number of sub-lists.
score: 0
comment on: http://stackoverflow.com/q/48450781
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48468011
has comment: http://stackoverflow.com/comment/83929885
has body: collections.defaultdict is your friend. from collections import defaultdict lst = [('verb1', 'caption', 'video_id'), ('verb2', 'caption', 'video_id'), ('verb3', 'caption', 'video_id')] aggregator = defaultdict(list) # first create a dictionary mapping (caption, video_id) -&gt; verb for i, j, k in lst: aggregator[(j, k)].append(i) # then reverse dictionary result = [tuple(('|'.join(v), k[0], k[1])) for k, v in aggregator.items()] # [('verb1|verb2|verb3', 'caption', 'video_id')]
has comment: http://stackoverflow.com/comment/83930144
has comment: http://stackoverflow.com/comment/83929847
has comment: http://stackoverflow.com/comment/83932122
has comment: http://stackoverflow.com/comment/83930893
type: Answer
has comment: http://stackoverflow.com/comment/83932175
accepted answer of: http://stackoverflow.com/q/48467833
answers question: http://stackoverflow.com/q/48467833
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48481668
has title: Simple proxy server "Connection reset by peer" error
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: proxy-server
tagged with: sockets
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: proxy
has body: I am trying to write my own very basic proxy server, I just want my code to send the request and receive a response and sends it back to the browser. My code (which I got from this tutorial) is: import socket, sys from thread import * try: listeningPort = int(raw_input("[*] : inter port to listen to ")) print "your port is " + str(listeningPort) except KeyboardInterrupt : print "\n[*] : User Requested Interrupt ! " print "[*] : Bye :D ! " sys.exit(); maxConnections = 5 bufferSize = 4096 def start(): try: s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) # init socket s.bind(('' , listeningPort)) # binf with listening port s.listen(maxConnections) print("[*] : Initializing sockets .. Done") print("[*] : listening on port [%d] \n" , listeningPort) except Exception , e: print("[*] : Unable to initialize socket" + str(e)) sys.exit(2) while 1: try : print "accepting connection" conn , addr = s.accept() # accpet connection from browser data = conn.recv(bufferSize) # get client data start_new_thread(conn_string , (conn , data ,addr)) # start a new thread except KeyboardInterrupt: s.close() print "\nWer'e shutting Down ! " print "Bye ! " sys.exit(1) s.close() def conn_string(conn , data , addr): # accepts data from the browser print "herererer" try: firstLine = data.split('\n')[0] url = firstLine.split(' ')[1] print "first line " + str(firstLine) print "url iss : " + str(url) httpPos = url.find("://") if httpPos == -1: temp = url else: temp = url[(httpPos + 3):] portPoss = temp.find(":") # position of the port webServerPos = temp.find("/") # end of the web server if webServerPos == -1: webServerPos = len(temp) webServer = "" port = -1 if (portPoss == -1 or webServerPos &lt; portPoss): port = 80 webServer = temp[:webServerPos] else: #sepecific port port = int((temp[(portPoss + 1):])[:webServerPos - portPoss - 1]) webServer = temp[:portPoss] proxy_server(webServer , port , conn , addr , data) except Exception , e : print "expectionnn " + str(e) def proxy_server(webServer…
tagged with: python
score: 1

http://stackoverflow.com/q/48389842
has comment: http://stackoverflow.com/comment/83767921
has body: I am new with this, I was trying to connect to the couchbase bucket using python, just tried whatever given in the documentation. from couchbase.cluster import Cluster from couchbase.cluster import PasswordAuthenticator cluster = Cluster('couchbase://localhost') authenticator = PasswordAuthenticator('username', 'password') cluster.authenticate(authenticator) bucket = cluster.open_bucket('bucket-name') Replaced the IP, username, password, bucket name. But I am getting this error everytime I am trying to run this, File "get_data_couche.py", line 6, in &lt;module&gt; bucket = cluster.open_bucket('jizo') File "/usr/lib64/python2.7/site-packages/couchbase/cluster.py", line 100, in open_bucket rv = self.bucket_class(str(connstr), **kwargs) File "/usr/lib64/python2.7/site-packages/couchbase/bucket.py", line 252, in __init__ self._do_ctor_connect() File "/usr/lib64/python2.7/site-packages/couchbase/bucket.py", line 261, in _do_ctor_connect self._connect() couchbase.exceptions._AuthError_0x2 (generated, catch AuthError): &lt;RC=0x2[Authentication failed. You may have provided an invalid username/password combination], There was a problem while trying to send/receive your request over the network. This may be a result of a bad network or a misconfigured client or server, C Source=(src/bucket.c,793)&gt; Please help me with this, not able to find so much on internet. Thanks in advance.
type: UnansweredQuestion
tagged with: database
tagged with: couchbase
tagged with: python
score: 2
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/83998731
has comment: http://stackoverflow.com/comment/83822787
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/102429782
has title: Using Python sdk | Couchbase

http://stackoverflow.com/comment/83732800
type: AnswerComment
score: 0
type: Comment
has text: @JustinasMarozas yw:-)
comment on: http://stackoverflow.com/a/48372794

http://stackoverflow.com/comment/83728014
comment on: http://stackoverflow.com/q/48370347
has text: nothing happen ....
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83923196
has text: Thank you @Mike. It works well but l need that with ones not zeros. However if np.ones() will alter my 2048 values
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48464790
type: Comment

http://stackoverflow.com/a/48430302
has body: Why don't you use the requests module to connect to the metadata server and determine if it is running in AWS or not. import requests try: resp = requests.get('http://169.254.169.254', timeout=0.001) print 'In AWS' except: print 'Not in AWS'
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48419066
accepted answer of: http://stackoverflow.com/q/48419066

http://stackoverflow.com/q/48432622
tagged with: tensor
upvote count: 2
type: UnansweredQuestion
has title: How to use SessionRunHook to print tensor with tf.data.Dataset API?
downvote count: 0
has answer: http://stackoverflow.com/a/72555469
tagged with: python
tagged with: tensorflow-datasets
has body: I am using the tf.data.Dataset API and assigning names to operations within the closure that is passed to Dataset.map as in the below import tensorflow as tf def model_fn(features, mode): loss = tf.constant(1) train_op = tf.no_op() return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) def input_fn(): dataset = tf.data.Dataset \ .from_generator(lambda: (x*x for x in range(10)), tf.int32) \ .map(lambda x: tf.identity(x, name='tokens_inside')) ret = dataset.make_one_shot_iterator().get_next() tf.identity(ret, 'tokens_outside') return ret tf.logging.set_verbosity(tf.logging.INFO) hooks = [ tf.train.LoggingTensorHook(['tokens_outside'], every_n_iter=1), tf.train.LoggingTensorHook(['tokens_inside'], every_n_iter=1), ] est = tf.estimator.Estimator(model_fn=model_fn, model_dir='mout') est.train(input_fn=input_fn, hooks=hooks, max_steps=1) When using tf.train.LoggingTensorHook to dump some of the values the second hook throws an exception: I am getting errors like this: KeyError: "The name 'tokens_inside:0' refers to a Tensor which does not exist. The operation, 'tokens_inside', does not exist in the graph." I guess the Dataset operations create a new graph for each function? Is there a way to customize tf.train.LoggingTensorHook so it knows which graph to search for the named tensor?
score: 2
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/83964214
type: QuestionComment
comment on: http://stackoverflow.com/q/48465739
has text: I encoded the image and sent it back to the client as a json request. At the client side, decode this response using base64.b64decode(response) and lastly cv2.imdecode(np.frombuffer(image, np.uint8), 1) to get the image.
score: 0
type: Comment

http://stackoverflow.com/q/48482774
has comment: http://stackoverflow.com/comment/83985968
tagged with: python
type: AnsweredQuestion
score: 0
has title: 2D matrix for labelbinarizer
answer count: 1
has answer: http://stackoverflow.com/a/48482793
accepted answer: http://stackoverflow.com/a/48482793
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/83985920
type: Question
has body: There is one behavior of labelbinarizer import numpy as np from sklearn import preprocessing lb = preprocessing.LabelBinarizer() lb.fit(np.array([[0, 1, 1], [1, 0, 0]])) lb.classes_ The output is array([0, 1, 2]). Why there is a 2 there?

http://stackoverflow.com/comment/83919890
type: QuestionComment
score: 0
has text: How does the pdb.set_trace() work? Where do I have to put it in?
type: Comment
comment on: http://stackoverflow.com/q/48463349

http://stackoverflow.com/a/48354114
upvote count: 58
answers question: http://stackoverflow.com/q/48353738
score: 58
downvote count: 0
has body: Change all of your super.__init__(...) calls to super().__init__(...). The problem was the missing pair of parentheses (). From the official Python 3.3 reference here, super is actually a built-in function with the signature super([type[, object-or-type]]).
type: Answer

http://stackoverflow.com/q/48352771
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48353174
has body: I've only recently found out what a pre-commit hook is, and from what I understand it's a file (.git/hooks/pre-commit) that tracks my code for errors before the changes are committed to my server (DigitalOcean). So I want to make this file but I don't know what code to add to it. I've tried to find example files of pre-commit for Django projects but cannot find any. Advice appreciated.
has title: How to create a pre-commit hook that will track errors from my Django code before I push to my server
favorite count: 0
type: Question
tagged with: pre-commit-hook
has comment: http://stackoverflow.com/comment/83692522
has comment: http://stackoverflow.com/comment/83692677
tagged with: version-control
accepted answer: http://stackoverflow.com/a/48353174
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83694688
linked to: http://stackoverflow.com/q/7230820
tagged with: git

http://stackoverflow.com/q/48432558
tagged with: xgboost
favorite count: 0
has comment: http://stackoverflow.com/comment/83857209
tagged with: pipenv
score: 3
has body: I love xgboost. And I love pipenv. But they don't love each other :( pipenv install xgboost Error: An error occurred while installing xgboost! Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-9cab91je/xgboost/ I've installed a compiled version of xgboost with anaconda but I just can't get it to play nicely with pipenv... Any ideas? Thanks!
tagged with: anaconda
has title: xgboost + pipenv = </3
has comment: http://stackoverflow.com/comment/83889221
tagged with: python
has answer: http://stackoverflow.com/a/61508627
has comment: http://stackoverflow.com/comment/95256546
has comment: http://stackoverflow.com/comment/83885081
type: Question
upvote count: 3
has comment: http://stackoverflow.com/comment/98299845
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83703421
type: QuestionComment
has text: You need to specify what substring splits your string. Something like: `split("\t")`. It's explained [here](https://stackoverflow.com/a/743807/3103891)
comment on: http://stackoverflow.com/q/48358348
type: Comment
score: 1

http://stackoverflow.com/a/48406412
type: Answer
has body: You should create t inside the for loop. Now t will always reflect the last time it is changed. Look at t as a name for a certain piece of memory. Since you don't change the memory-location, you keep on adapting the same piece over and over again for element in a: t = [0]*2 if element == 0: #rest of your code Here the memory-location is changed, since you create t anew eachtime
answers question: http://stackoverflow.com/q/48406242
score: 0
has comment: http://stackoverflow.com/comment/83877680
has comment: http://stackoverflow.com/comment/83826812
has comment: http://stackoverflow.com/comment/83803433

http://stackoverflow.com/q/48437255
type: Question
tagged with: python-3.x
tagged with: for-loop
tagged with: python
has comment: http://stackoverflow.com/comment/83865801
has body: EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! @DYZ, @Rob I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3. The user inputs how many guesses they need, and the program should run the function that many times. But instead my code prints the same results that many times. Can you help me with this? I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/@AEE/PersonalLottoEn from random import randint def loto(limit): while len(guess) &lt;= 6: #will continue until 6 numbers are found num = randint(1, limit) #and all numbers must be unique in the list if num not in guess: guess.append(num) else: continue return guess guess = [] #Need to create an empty list 1st #User input to select which type of lotto (6/49 or 6/54) while True: choice = int(input("""Please enter your choice: For Lotto A enter "1" For Lotto B enter "2" ------&gt;""")) if choice == 1: lim = 49 #6/49 break elif choice == 2: lim = 54 #6/54 break else: print("\n1 or 2 please!\n") times = int(input("\nHow many guesses do you need?")) print("\nYour lucky numbers are:\n") for i in range(times): result = str(sorted(loto(lim))) print(result.strip("[]"))
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48437362
has comment: http://stackoverflow.com/comment/83868597
answer count: 1
has answer: http://stackoverflow.com/a/48437362
has title: How to run a function several times for different results in Python 3

http://stackoverflow.com/comment/83789868
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48400932
has text: Please [read the documentation](https://pip.pypa.io/en/stable/). Pip must be run in your shell, not in python itself.

networkx
tags question: http://stackoverflow.com/q/48380550
tags question: http://stackoverflow.com/q/48360952
tags question: http://stackoverflow.com/q/48382575
tag name: networkx
tags question: http://stackoverflow.com/q/48420223
tags question: http://stackoverflow.com/q/48416445
tags question: http://stackoverflow.com/q/48342214
tags question: http://stackoverflow.com/q/48389481
tags question: http://stackoverflow.com/q/48479512
tags question: http://stackoverflow.com/q/48435320
tags question: http://stackoverflow.com/q/48371266
type: Tag
tags question: http://stackoverflow.com/q/48474681

http://stackoverflow.com/a/48362664
has comment: http://stackoverflow.com/comment/83712422
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48362611
has comment: http://stackoverflow.com/comment/83712400
has comment: http://stackoverflow.com/comment/83712386
score: 3
type: Answer
has body: to write to a file you do this: file = open("file.txt","w") file.write("something") file.close() when you use file.write() it deletes all of the contents of the file, if you want to write to the end of the file do this: file = open("file.text","w+") file.write(file.read()+"something") file.close() There are other ways to do this but this one is the most intuitive (not the most efficient), also the other way tends to be buggy so there is no reason to post it because this is reliable.

http://stackoverflow.com/q/48393301
upvote count: 0
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48393547
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48393547
tagged with: list
tagged with: pandas
answer count: 1
has title: Using pandas.DataFrame.at() in a for loop
has comment: http://stackoverflow.com/comment/83774747
downvote count: 1
score: -1
favorite count: 0
has body: pandas DataFrame I'm starting with: pandas DataFrame I'm trying to build: I'm very new to computer science so I wasn't quite sure how to word my question without providing images. Basically, I want to build a pandas DataFrame with one row that has columns with column names -3 to 3 and the values below are the maximum absolute values of the second column from the first pandas DataFrame in relation to the first column from the first pandas DataFrame. I also have the same data in a list a shown here: Here is what I've tried but I keep getting an error:
type: Question
has comment: http://stackoverflow.com/comment/83774610
tagged with: for-loop

http://stackoverflow.com/comment/83954843
has text: @pault I was seeing "Customer orderedxvanillia cookie(s)..."
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48472121

http://stackoverflow.com/q/48356052
linked to: http://stackoverflow.com/q/28757389
has answer: http://stackoverflow.com/a/71980137
tagged with: python
linked to: http://stackoverflow.com/q/14940743
has body: Take the DataFrame in the answer of Loc vs. iloc vs. ix vs. at vs. iat? for example. df = pd.DataFrame( {'age':[30, 2, 12, 4, 32, 33, 69], 'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'], 'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'], 'height':[165, 70, 120, 80, 180, 172, 150], 'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2], 'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']}, index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'] ) Now I want all columns except 'food' and 'height'. I thought something like df.loc[:,['age':'color', 'score':'state']] would work, but Python returns SyntaxError: invalid syntax. I am aware of that there is one way to work around: df.drop(columns = ['food', 'height']). However, in my real life situation, I have hundreds of columns to be dropped. Typing out all column names is so inefficient. I am expecting something similar with dplyr::select(df, -(food:height)) or dplyr::select(df, age:color, score:state) in R language. Also have read Selecting/Excluding sets of columns in Pandas.
possible better answer: http://stackoverflow.com/a/48356211
has answer: http://stackoverflow.com/a/48356056
type: AnsweredQuestion
score: 3
answer count: 3
has comment: http://stackoverflow.com/comment/83699009
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/83698843
downvote count: 0
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48356056
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48356211
has title: Select two sets of columns by column names in Pandas

http://stackoverflow.com/q/48456028
has title: Trouble with importing pyplot from matplotlib
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83905314
has comment: http://stackoverflow.com/comment/83904848
has answer: http://stackoverflow.com/a/48456465
has comment: http://stackoverflow.com/comment/83925580
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83905531
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/83905147
has body: This program currently does not work #!/usr/bin/env python3 import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('trial.jpg',0) plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() I get an error Traceback (most recent call last): File "C:\Users\Karl\Desktop\Python\OpenCV\matplotlib.py", line 4, in &lt;module&gt; from matplotlib import pyplot as plt File "C:\Users\Karl\Desktop\Python\OpenCV\matplotlib.py", line 4, in &lt;module&gt; from matplotlib import pyplot as plt ImportError: cannot import name 'pyplot' But when I type in each line of that code in the I.E. (using IDLE)... it works? Why would this be. It seems to be when executing all of this code at once it fails, but for some reason not when I type it individually into the interactive environment.
accepted answer: http://stackoverflow.com/a/48456465
answer count: 1

http://stackoverflow.com/comment/83823928
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48399991
has text: So.. yes make yourself a d-drive of minimum 20-50 GB as back-up drive for all your important documents and files. (e.g. your windows download folder is somewhere (c:\user\..app...\download) is on c-drive... if its piled with pdfs, prog-installers...etc.. remember to back them up elsewhere. unless you want spending days gathering what you may have lost in the future.

http://stackoverflow.com/comment/83895113
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48442389
type: Comment
has text: I just downloaded the file, and I get 188 and 188 matches with both python 2.7.3 and grep. I can't test python 3 until tomorrow morning when I'm at work.

http://stackoverflow.com/q/48474742
has comment: http://stackoverflow.com/comment/83945865
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83945954
tagged with: python
has comment: http://stackoverflow.com/comment/83943096
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/84011498
tagged with: bash
linked to: http://stackoverflow.com/q/7353054
has title: converting command line syntax to os.system call or subprocess cal; in python
has body: I can run this command cat /home/norman/conf/second.txt | sort | uniq &gt; /home/norman/conf/third.txt but would like to use an os,system call or a subprocess call but whatever I have tried always causes an error. I have tried such things as command = "cat /home/norman/conf/second.txt | sort | uniq &gt; /home/norman/conf/third.txt".split() subprocess.call(command) but get cat: '|': No such file or directory cat: sort: No such file or directory cat: '|': No such file or directory cat: uniq: No such file or directory cat: '>': No such file or directory
duplicate of: http://stackoverflow.com/q/7353054
linked to: http://stackoverflow.com/q/21029154

http://stackoverflow.com/comment/83882876
score: 0
type: Comment
type: QuestionComment
has text: If `k` is a typo for `j` then it seems like you swap the order of iteration of `i` and `j` and then parallelize the outermost loop on `j`, giving each parallel job a chunk of columns to be processed in row order. As @schwobaseggl points out, you could also pre-compute simple_function and use it in all the workers, assuming no pesky side effects.
comment on: http://stackoverflow.com/q/48444590

http://stackoverflow.com/q/48369440
answer count: 2
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/48025283
has answer: http://stackoverflow.com/a/48369730
has answer: http://stackoverflow.com/a/48372805
tagged with: sprite
has body: I am currently making a top down racing game and need a way to detect when a vehicle has completed a full lap. I have chosen to do this by adding images around the circuit, acting as checkpoints, which match with the track surface. When driven over, they output true, all must have output true in order for a lap to count. However, I cannot find a way to detect a collision between my vehicles and an image. I have tried adding rects to the vehicles and checking if an output can be produced when the two vehicles collide but I just get this error: AttributeError: 'pygame.Surface' object has no attribute 'rect' Is there any way I can do this? My code can be seen below. import pygame from pygame.locals import * import math import time pygame.init() F1image = pygame.image.load("F1image.png") sportsimage = pygame.image.load("sportsimage.png") bikeimage = pygame.image.load("bikeimage.png") muscleimage = pygame.image.load("muscleimage.png") truckimage = pygame.image.load("truckimage.png") screen = pygame.display.set_mode((1280,720)) xpos = 280 xpos_2 = 280 ypos = 50 ypos_2 = 85 keys = [False, False, False, False] keys_2 = [False, False, False, False] direction = 0 direction_2 = 0 forward = 0 forward_2 = 0 class Background(pygame.sprite.Sprite): def __init__(self, image_file, location): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.left, self.rect.top = location BackGround = Background('track.png', [0,0]) class Vehicle: 'Base class for all vehicles (Cars and Motorbikes) in the game' vehicleCount = 0 def __init__(self, max_speed, acceleration, turning_radius, image): pygame.sprite.Sprite.__init__(self) self.max_speed = max_speed self.acceleration = acceleration self.turning_radius = turning_radius self.image = image self.rect = self.image.get_rect() Vehicle.vehicleCount = Vehicle.vehicleCount + 1 def displayAmount(): print ("Total number of Vehicle enteries: ", Vehicle.vehicleCount) def displayVehicle(s…
tagged with: rect
has comment: http://stackoverflow.com/comment/83728708
has title: How to make a variable output 'True' when two images collide in pygame
upvote count: 1
score: 1
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/83725905
tagged with: collision
favorite count: 0
type: Question

http://stackoverflow.com/comment/83765115
comment on: http://stackoverflow.com/q/48388675
score: 0
type: Comment
has text: `re.findall(r'(?<!\d)\d{10}(?!\d)',word)`?
type: QuestionComment

http://stackoverflow.com/comment/83653221
type: Comment
has text: oh, i can't add my code to my question because the code is so long
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48333823

http://stackoverflow.com/comment/96370218
type: AnswerComment
score: 0
has text: <thumbs-up.gif>
type: Comment
comment on: http://stackoverflow.com/a/54406742

http://stackoverflow.com/comment/83881235
score: 0
type: Comment
has text: `merged_data = data_REF.merge(data_PCU, on=['Timestamp'], l_suffix='', r_suffix='PCU')` This does a join on the Timestamp meaning the resulting DataFrame will only contain the rows of data where the timestamp of the two files were the same.
comment on: http://stackoverflow.com/a/48425430
type: AnswerComment

http://stackoverflow.com/comment/83883254
type: QuestionComment
comment on: http://stackoverflow.com/q/48445154
score: 0
has text: path('edit_sale/(?P<pk>\w+)/ is returning- - NoReverseMatch at /geo_gas/sale/
type: Comment

osx-elcapitan
tag name: osx-elcapitan
tags question: http://stackoverflow.com/q/48486281
type: Tag

http://stackoverflow.com/q/48455182
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/48504114
has body: Is there an algorithm that could help sort the left table (which is an abstraction for multidimensional array of scalars or objects) down below so the result would be as in the right one, given that there maybe a limited amount of available depth in the right table (e.g. max of 30 rows)? And slightly more complex version of the problem (first key in a cell is having precedence over another): EDIT: And another level of complexity (merge rows/levels if it's safe to do so to prevent redundancy):
possible better answer: http://stackoverflow.com/a/48494651
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/48504114
tagged with: php
has answer: http://stackoverflow.com/a/48494651
score: 2
type: AnsweredQuestion
tagged with: algorithm
has title: Table cells / 2d array sorting algorithm
has comment: http://stackoverflow.com/comment/84021807
favorite count: 0
tagged with: c++
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83904084

http://stackoverflow.com/comment/83935039
comment on: http://stackoverflow.com/a/48452901
has text: I am currently using Python 2.7. Can you give me a hint how to replace `yield from` such that the above code can work?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48372357
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83733222
has comment: http://stackoverflow.com/comment/83732308
has comment: http://stackoverflow.com/comment/83732093
has comment: http://stackoverflow.com/comment/83731785
has title: Testing `CharField(unique=True)` in django with py.test
tagged with: python
has comment: http://stackoverflow.com/comment/83732232
tagged with: pytest-django
has comment: http://stackoverflow.com/comment/83732109
answer count: 0
tagged with: pytest
score: 1
has comment: http://stackoverflow.com/comment/83732296
downvote count: 0
has comment: http://stackoverflow.com/comment/83732327
tagged with: django
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83732350
has comment: http://stackoverflow.com/comment/83731877
has body: I'm working to move all tests for a django application over to py.test. One case I have not been able to overcome is testing that uniqueness constraints on model fields are enforced. An example test: # requirements.txt pytest pytest-django ... # myapp/models.py from django.db import models class UniqueModel(models.Model): unique_field = models.CharField(max_length=100, unique=True) # myapp/tests/test_unique_model.py from django.db import IntegrityError import pytest from myapp.models import UniqueModel def test_unique(self, db): unique_1 = UnqiueModel(unique_field='not-unique') unique_1.save() unique_2 = UniqueModel(unique_field='not-unique') with pytest.raises(IntegrityError): unique_2.save() This test fails: ... with pytest.raises(IntegrityError): &gt; unique_2.save() E Failed: DID NOT RAISE &lt;class 'django.db.utils.IntegrityError'&gt; ... Any guidance? Thanks!

http://stackoverflow.com/q/48373577
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60047280
answer count: 3
downvote count: 0
upvote count: 26
favorite count: 0
has answer: http://stackoverflow.com/a/48373785
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/67549301
score: 26
has body: I have been editing a Jupyter Notebook for the past week, and tried saving it today. While attempting to save it, I got an error, so I refreshed the page and successfully saved it. However, to my dismay almost all of my command history was lost! I still have access to the variables (the kernel never died), but I don't have access to any of the code. Is there any way to recover the code? The kernel is still running, but I do not see any checkpoints in my notebook.
has title: Recovering command history in Jupyter Notebook?
tagged with: python
accepted answer: http://stackoverflow.com/a/48373785
tagged with: jupyter
tagged with: ipython
possible better answer: http://stackoverflow.com/a/60047280
tagged with: jupyter-notebook

http://stackoverflow.com/comment/83809971
type: QuestionComment
comment on: http://stackoverflow.com/q/48397589
score: 0
type: Comment
has text: That is the 'real' data. I've just replaced the 'real' words with 'data_type' and 'name'

http://stackoverflow.com/comment/83817017
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48391959
has text: when I remove that entire line, the same issue seems to be happening

http://stackoverflow.com/comment/83888033
score: 1
comment on: http://stackoverflow.com/a/48407506
has text: Can you test it out in your system and let me know? I can change the answer if it works.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48434713
has comment: http://stackoverflow.com/comment/83887138
has body: Here is an answer given in days, since you don't specify how you'd like to round your months. from dateutil.relativedelta import relativedelta for i in range(1,11): df["d{}".format(i)] = (df['Date1'].apply(lambda x: x + relativedelta(months=+i)) - df['Date2']) this gives you:
score: 1
has comment: http://stackoverflow.com/comment/83887060
downvote count: 1
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48434330

http://stackoverflow.com/q/48362010
linked to: http://stackoverflow.com/q/9264763
answer count: 2
has comment: http://stackoverflow.com/comment/83711934
tagged with: tkinter
tagged with: local
has answer: http://stackoverflow.com/a/48362073
has answer: http://stackoverflow.com/a/48362117
score: 0
tagged with: sqlite
upvote count: 1
tagged with: variables
downvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48362117
has body: I'm writing a Python 3.6 script that works with Tkinter and an SQLite 3 database, but I get this error: if "fImage" in globals() and not(fImage==None): UnboundLocalError: local variable 'fImage' referenced before assignment The interested code is this: from tkinter import * from ttk import * from tkinter import Toplevel, Tk import sqlite3 as sql def Salvataggio(mode,nome,cognome,sitoweb,email,idx): conn=sql.connect(os.path.join(path, fn_prof),isolation_level=None) c=conn.cursor() if mode=="add": if "fImage" in globals() and not(fImage==None): c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),fImage,sitoweb.get(),email.get())) else: c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),"",sitoweb.get(),email.get())) del fImage wa.destroy() elif mode=="edit": if "fImage" in globals() and not(fImage==None): c.execute("""UPDATE prof SET nome = '{}', cognome = '{}', imageURI='{}', web='{}', email='{}' WHERE ID={}; """.format(nome.get(),cognome.get(),fImage,sitoweb.get(),email.get(),idx)) else: c.execute("""UPDATE prof SET nome = '{}', cognome = '{}', web='{}', email='{}' WHERE ID={}; """.format(nome.get(),cognome.get(),sitoweb.get(),email.get(),idx)) del fImage def selImmagine(bi): if not("fImage" in globals()): global fImage fImage=askopenfilename(filetypes=[(_("File Immagini"),"*.jpg *.jpeg *.png *.bmp *.gif *.psd *.tif *.tiff *.xbm *.xpm *.pgm *.ppm")]) # other code... Do you know how to solve this? The error results with the if and the elif in the salvataggio() function. Thanks
tagged with: python
has title: Python - UnboundLocalError: local variable referenced before assignment`
possible better answer: http://stackoverflow.com/a/48362073
type: Question

http://stackoverflow.com/comment/83868600
has text: I added an answer just comment under it so others know it is not what you are looking for, also try to make it clear in your question, otherwise is difficult to answer ;-)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48438686

http://stackoverflow.com/comment/83688177
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48350693
type: QuestionComment
has text: Also, typing `numpy.int0` into the Python command line identifies the item.

http://stackoverflow.com/a/48443204
has body: We've done this with a custom callback. However this isn't fast enough to do live, doing layout and rendering the image with graphviz can be quite slow: https://gist.github.com/mrocklin/5b7bf78621496697fa3001462e1910ae
accepted answer of: http://stackoverflow.com/q/48436033
has comment: http://stackoverflow.com/comment/83947664
answers question: http://stackoverflow.com/q/48436033
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83937879

http://stackoverflow.com/comment/83919144
has text: i have already tried setting ROS_IP and ROS_MASTER_URI, however the problem seems to be that the computer and robot are in different subnets which i cannot fix currently. Connecting a monitor is going to be difficult since the error only occurs when the robot is entirely disconnected and moves away from his original position. I dont think i understand what you mean with "how movement commands are constructed"? they use two geometry_msgs.Vector3 variables if thats what you mean
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48458092

http://stackoverflow.com/comment/83805668
type: AnswerComment
score: 1
has text: @Jonas.S. There doesn't seem to be any need for `self.f` at all, since `self` itself is a frame. I recommend getting rid of `self.f` entirely.
type: Comment
comment on: http://stackoverflow.com/a/48407982

http://stackoverflow.com/q/48474034
has answer: http://stackoverflow.com/a/48474125
has title: I'm trying to make a simple script that says two different two phrase lines(Python)
linked to: http://stackoverflow.com/q/22741319
downvote count: 2
has body: So, I'm just starting to program Python and I wanted to make a very simple script that will say something like "Gabe- Hello, my name is Gabe (Just an example of a sentence" + "Jerry- Hello Gabe, I'm Jerry" OR "Gabe- Goodbye, Jerry" + "Jerry- Goodbye, Gabe". Here's pretty much what I wrote. answers1 = [ "James-Hello, my name is James!" ] answers2 = [ "Jerry-Hello James, my name is Jerry!" ] answers3 = [ "Gabe-Goodbye, Samuel." ] answers4 = [ "Samuel-Goodbye, Gabe" ] Jack1 = (answers1 + answers2) Jack2 = (answers3 + answers4) Jacks = ([Jack1,Jack2]) import random for x in range(2): a = random.randint(0,2) print (random.sample([Jacks, a])) I'm quite sure it's a very simple fix, but as I have just started Python (Like, literally 2-3 days ago) I don't quite know what the problem would be. Here's my error message Traceback (most recent call last): File "C:/Users/Owner/Documents/Test Python 3.py", line 19, in &lt;module&gt; print (random.sample([Jacks, a])) TypeError: sample() missing 1 required positional argument: 'k' If anyone could help me with this, I would very much appreciate it! Other than that, I shall be searching on ways that may be relevant to fixing this.
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/48474088
has comment: http://stackoverflow.com/comment/83941676
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48474094
has comment: http://stackoverflow.com/comment/83941673
has comment: http://stackoverflow.com/comment/83941637
tagged with: python
score: -1

http://stackoverflow.com/a/48347401
has body: will this work? final_result=[] def recursive_approach(aa,bb): if not bb: return 0 else: for i in zip(aa,bb): final_result.extend([i[0],i[1]]) return recursive_approach(aa,bb[len(aa):]) recursive_approach(a,b) print(final_result) output: ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']
score: 1
answers question: http://stackoverflow.com/q/48346169
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/48378524
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83743980
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48378591
score: 1
accepted answer: http://stackoverflow.com/a/48378591
answer count: 1
type: Question
tagged with: python-3.x
has body: Good day All I would kindly please like your assistance. So i would like to create a new column called df['Income_Status'], using the customers Income Proxy. Where 1 = High Avg Income, 2 = Med Avg Income, 3= Low Avg Income This is how my data set looks like: Customer_id Income_Proxy Average_Income_Proxy Standard_dev_Income_Proxy 123 7681559.15 44288.02 176568.76 456 15156.29 44288.02 176568.76 789 50497.69 44288.02 176568.76 096 44138.41 44288.02 176568.76 158 67866.45 44288.02 176568.76 The condition is: IF INCOME_PROXY &lt;= MEAN_INCOME_PROXY - (0.5)*&amp;STD_INCOME_PROXY then High Avg Income IF INCOME_PROXY &gt;= MEAN_INCOME_PROXY + (0.5)*STD_INCOME_PROXY then Low Avg Income else Low Avg Income How do i go about creating a column that will give me the Income status, by using the condition provided. And how will i write this condition in Pandas python format?
upvote count: 1
linked to: http://stackoverflow.com/q/48380425
tagged with: python
has title: Conditional Sum in pandas python

http://stackoverflow.com/a/48488106
type: Answer
answers question: http://stackoverflow.com/q/48487849
has comment: http://stackoverflow.com/comment/83969084
downvote count: 0
upvote count: 1
score: 1
has body: You should use setuptools to distribute your application, creating a setup.py file to configure its setup and installation. Binaries can be delivered using the console_scripts option, while data files can be delivered using either package_data.

http://stackoverflow.com/comment/83675339
score: 0
has text: Possible duplicate of [reading external sql script in python](https://stackoverflow.com/questions/19472922/reading-external-sql-script-in-python)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48344470

http://stackoverflow.com/a/67533782
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48459238
type: Answer
has body: The current command to run your celery worker will be: celery -A app worker --loglevel=info Provided your worker file is called app.py

http://stackoverflow.com/comment/83867180
score: 1
comment on: http://stackoverflow.com/q/48437429
type: QuestionComment
type: Comment
has text: I *suspect* that using a pipe forces data to be copied, while a read-only list of arguments can be shared between processes by the kernel, and so no copying needs to take place (until the other process starts modifying the arguments, which then triggers a copy-on-write). Which OS is this? Can you repeat the experiment on other platforms?

http://stackoverflow.com/q/48449020
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48870949
has title: slice assignment goes wrong in numpy array while in a "for" recurrent
type: UnansweredQuestion
tagged with: python
tagged with: slice
has comment: http://stackoverflow.com/comment/83890709
has comment: http://stackoverflow.com/comment/83890754
score: 1
answer count: 1
downvote count: 0
has body: I find something wrong with python numpy.I want to use slices assignment to get a new numpy array.Just as the pictures shows: enter image description here When I use slices assignment in "for" recurrent,such as: v = np.array([[0,1],[2,3],[3,4],[7, 8]) s = v[:2] for i in range(1): s[1] = v[2] The result show that the value of "v" changes in the assignment. The result is different from below(just discard the "for" recurrent): s[1] = v[2] I'm crazy about this problem and I even doubt something wrong with numpy!!! Wish help from someone!
upvote count: 1
has comment: http://stackoverflow.com/comment/83890691
favorite count: 0

http://stackoverflow.com/a/48344469
has comment: http://stackoverflow.com/comment/83674871
has comment: http://stackoverflow.com/comment/83674651
has comment: http://stackoverflow.com/comment/83674944
accepted answer of: http://stackoverflow.com/q/48344129
type: Answer
answers question: http://stackoverflow.com/q/48344129
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83676432
has body: As per PEP 289, we can rewrite your generator expression as follows: # b = (c for c in a if c in a) def __gen(expr): for c in expr: if c in a: yield c b = __gen(iter(a)) Here, a reference to [1, 2, 3] for use in the for loop is captured immediately (when you create b), but the if c in a check uses the new global a which is equal to [2, 3, 4]. On the other hand, when you write a generator function, a1 is passed to the function and stored for later use in both for and if x in y expressions. Assigning a1 = [2, 3, 4] has no effect. To make the function do the same thing as the generator expression, all you need to do is replace if c in expr with if c in a1.
has comment: http://stackoverflow.com/comment/83675062

http://stackoverflow.com/comment/83700614
type: Comment
has text: True, but since you can update the widgets without the `textvariable`, in tkinter it's fairly useless unless you're going to add a trace or unless you explicitly want to tie two or more widgets together.
comment on: http://stackoverflow.com/a/48352197
type: AnswerComment
score: 1

http://stackoverflow.com/q/48392998
has answer: http://stackoverflow.com/a/48393057
type: UnansweredQuestion
answer count: 1
has body: I have tried to scrape my twitter account using beautifulsoup instead of using twitter APIs. I am getting an error saying invalid syntax in the payload dictionary. My code is: import requests from bs4 import BeautifulSoup payload={ ":authority":"twitter.com", ":method":"POST", ":path":"/sessions", ":scheme":"https", "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding":"gzip, deflate, br", "accept-language":"en-US,en;q=0.9", "cache-control":"max-age=0", "content-length":"993", "content-type":"application/x-www-form-urlencoded", "cookie":"_twitter_sess=BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCKnkoiBhAToMY3NyZl9p%250AZCIlYjBmNmQ0NmY5NTVmMmVkNTgwYjM2NTU0YzQ2NDY4NzA6B2lkIiUwYTg3%250ANzU1MmU3ZmY3ZWE3NjAyYzIwZmU5ZjkxZWQ5OQ%253D%253D--43822fe18903b3578a1f5deaeb232a8186b75e7d;" "personalization_id"="v1_jQItTVsewWTebwVuukbh6g=="; "guest_id"="v1%3A151667100176659384"; "external_referer=padhuUp37zjgzgv1mFWxJzx4vPNPpMnZ52M34anUtp0%3D|0|8e8t2xd8A2w%3D"; "ct0"="6d7781aae304f30bb5d6d0d64fc34ffe"; "_ga"="GA1.2.1441535218.1516671002"; "_gid"="GA1.2.1585412472.1516671002"; "_gat"="1", "origin":"https://twitter.com", "referer":"https://twitter.com/login", "upgrade-insecure-requests":"1", "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "username":"aaaaaaa", "password":"ppppppp", "authenticity_token":"40a1cc3105efeb2f1a978cf97502bc4e8f97580b" } res = requests.get("https://twitter.com/login",data=payload) soup = BeautifulSoup(res.text,"lxml") print(soup.prettify()) for item in soup.find_all(class_="title"): print(item.text) I am getting error saying "invalid syntax" at "cookie" part in payload. What is the mistake there? Please help me. UPDATE: I have kept '' on cookie part like this. "cookie":'"_twitter_sess"="BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFza…
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83773893
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83799866
has comment: http://stackoverflow.com/comment/83776306
has comment: http://stackoverflow.com/comment/83773885
tagged with: session
has comment: http://stackoverflow.com/comment/83773877
has title: Getting error in requests.get()
tagged with: python
has comment: http://stackoverflow.com/comment/83799618
tagged with: twitter
has comment: http://stackoverflow.com/comment/83773907
has comment: http://stackoverflow.com/comment/83773923
score: 0
has comment: http://stackoverflow.com/comment/83794861
has comment: http://stackoverflow.com/comment/83774061

http://stackoverflow.com/a/77948584
type: Answer
has body: After running K-means, we can use sklearn.neighbors.NearestNeighbors to fit our dataset. We can then query the Nearest Neighbor model with our K-means centroids to retrieve the neighbors. Like this: # Copyright 2024 Google LLC. # SPDX-License-Identifier: Apache-2.0 from sklearn.cluster import KMeans from sklearn.neighbors import NearestNeighbors # random dense embeddings for 100 points with 10 dimensions. dataset = np.random.rand(100,10) # fit K-means with 3 clusters on our dataset. kme = KMeans(n_clusters=3) kme.fit(dataset) # we should have 3 vectors for 3 centroids. print(kme.cluster_centers_.shape) # (3, 10) # initialize NearestNeighbor with 5 neighbors and fit our dataset. knn = NearestNeighbors(n_neighbors=5, metric='cosine') knn.fit(dataset) # Use the model to query the centroids' neighbors. distances, indices = knn.kneighbors(kme.cluster_centers_) for centroid, distance_from_centroid, index in zip(kme.cluster_centers_, distances, indices): print(centroid, distance_from_centroid, index) The last loop will output 3 lines. Each one resembles the vector of a centroid along with 5 distances and indices of its closest neighbors.
answers question: http://stackoverflow.com/q/48413264
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48392761
has body: basically the problem is that the fetch all method is returning an empty list , and Ive checked outside of this method to see if the values i entered witch is ronaldb and 123456 currently reside inside of the login TABLE and they do , so i believe there is something wrong with the signin_check method that im not seeing. Ive seen other problems on the website with a similar problem , but none solves my problem. conn = sqlite3.connect('login.db') c = conn.cursor() def signin_check(): global obj username_information = obj.username.get() password_information = obj.password.get() c.execute("SELECT * FROM login WHERE password =:password and user = :user" , {'password' : str(username_information) , 'user' : str(password_information)}) if c.fetchall() == []: print (False) else: print(True) The code I used to check the contents c.execute("SELECT * FROM login WHERE user = :user" , {'password' : '123456' , 'user' : 'ronaldb'}) print(c.fetchall()) The results [('qeqwe', 'qweqwewq', 'ronaldb', '123456', 'multiple', 'Dr.', 'ee')] Here is the code i used to create the table c.execute("""CREATE TABLE login ( first text, last text, user text , password text, accounttype text, title text, buisness text )""")
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83773426
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83773462
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48392877
has comment: http://stackoverflow.com/comment/83773443
has comment: http://stackoverflow.com/comment/83773377
score: 1
tagged with: database
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/83773531
tagged with: python-3.6
has title: Why does .fetchall() method return empty list in this situation?
has comment: http://stackoverflow.com/comment/83773327
has comment: http://stackoverflow.com/comment/83773365
has comment: http://stackoverflow.com/comment/83773352
has comment: http://stackoverflow.com/comment/83773425
accepted answer: http://stackoverflow.com/a/48392877
downvote count: 0

http://stackoverflow.com/q/48472379
has comment: http://stackoverflow.com/comment/83938590
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83939192
type: AnsweredQuestion
has body: I am new to python. I am writing a script to pull some data from website and graph it. However, my code is erroring out, saying that the data types aren't correct. Specifically, I have both decimal values for 'value' and dates for 'year'. I tried to redefine them but I think I'm putting the definition in the wrong place. Any help would be appreciated, the code is below. import numpy as np import pandas as pd import json import matplotlib.pyplot as mp from IPython.display import HTML import getpass import requests def frame(url, height=400, width=100): display_string = '&lt;frame src={url} width={w} height={h}&gt; &lt;/iframe&gt;'.format(url=url, w=width, h=height) return HTML(display_string) frame('https://data.bls.gov/registrationEngine/') registration_key = getpass.getpass('Enter Registration Key: ') series = 'MPU4900012' frame('https://api.bls.gov/publicAPI/v1/timeseries/data/') def capture_series(series, start, end, key=registration_key): url = 'https://api.bls.gov/publicAPI/v2/timeseries/data/' url += '?registrationkey={key}'.format(key=key) data = json.dumps({ "seriesid": [series], "startyear": str(start), "endyear": str(end) }) headers = { "Content-type": "application/json" } result = requests.post(url, data=data, headers=headers) return json.loads(result.text) json_data = capture_series(series, 1987, 2016) json_data df_data = pd.DataFrame(json_data['Results']['series'][0]['data']) print(df_data) df_sub = df_data'value', 'year'.astype(float).astype(int) df_sub.set_index('year', inplace=True) df_sub.sort_index(inplace=True) df_sub x = df_sub.index y = df_sub['value'] mp.plot(x,y) mp.title('Major Sector Multifactor Productivity') mp.xlabel('years') mp.ylabel('values') mp.show When I run the code, I first get this table, which is the site data. footnotes period periodName value year 0 [{}] A01 Annual 86.244 1996 1 [{}] A01 Annual 84.713 1995 2 [{}] A01 Annual 85.141 1994 3 [{}] A01 Annual 84.688 1993 4 [{}] A01 Annual 85.037 1992 5 [{}] A01 Annual 82.280 199…
has title: Python error: invalid literal for int()
tagged with: python
has comment: http://stackoverflow.com/comment/83939053
has answer: http://stackoverflow.com/a/48472700
accepted answer: http://stackoverflow.com/a/48472700
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83938624
score: 2

http://stackoverflow.com/q/48434391
tagged with: python
has answer: http://stackoverflow.com/a/48434531
has body: Given a pandas DataFrame with columns for group, x, and y (multiple records per group value), I'd like to create a new DataFrame with one row per group and the associated t-statistic for x and y values in that group. I'd like to do this with groupby, not a loop. Example: import pandas as pd import numpy as np from scipy import stats N = 100 # Observations per group. tt_df = pd.DataFrame({'group': np.append(['A'] * N, ['B'] * N), 'x': np.random.randn(2 * N)}) tt_df['y'] = tt_df['x'] + np.random.randn(2 * N) stats.ttest_ind(tt_df['x'], tt_df['y'])[0] # -0.32 global t statistic.
score: 6
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: scikit-learn
upvote count: 7
has title: Calculate t-test statistic for each group in pandas DataFrame
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/48486199
has body: This might help(not exactly a one-liner): def polynonmial_equation(coefficients): degree = len(coefficients) - 1 temp = "".join(map(lambda x: "" if x[1] == 0 else [" - ", " + "][x[1]&gt; 0] + [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] + "x^" + str(degree -x[0]), enumerate(reversed(coefficients)))).strip() return temp if temp.startswith('-') else temp[1:] More re-presentable form of the function above: def polynonmial_equation(coefficients): degree = len(coefficients) - 1 temp = "".join(map(lambda x: "" if x[1] == 0 else [" - ", " + "][x[1] &gt; 0] + [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] + "x^" + str(degree - x[0]), enumerate(reversed(coefficients)))).strip() return temp if temp.startswith('-') else temp[1:] print(polynonmial_equation([0, 0, 0, 1, 1])) print(polynonmial_equation([0, 0, 0, 1, -1])) print(polynonmial_equation([0, 0, 0, -1, -1])) print(polynonmial_equation([0, 0, 0, -1, 1])) print() print(polynonmial_equation([0, 0, 0, 1, 3])) print(polynonmial_equation([0, 0, 0, 1, -3])) print(polynonmial_equation([0, 0, 0, -1, -3])) print(polynonmial_equation([0, 0, 0, -1, 3])) print() print(polynonmial_equation([1, 2, 3, 4, 5])) print(polynonmial_equation([-1, 2, -3, 4, -5])) print(polynonmial_equation([-1, 2, 0, 4, -5])) print(polynonmial_equation([0, 0, 6, -1, -3])) print(polynonmial_equation([0, -3, 4, -1, 0])) And the output: x^4 + x^3 - x^4 + x^3 - x^4 - x^3 x^4 - x^3 3*x^4 + x^3 - 3*x^4 + x^3 - 3*x^4 - x^3 3*x^4 - x^3 5*x^4 + 4*x^3 + 3*x^2 + 2*x^1 + x^0 - 5*x^4 + 4*x^3 - 3*x^2 + 2*x^1 - x^0 - 5*x^4 + 4*x^3 + 2*x^1 - x^0 - 3*x^4 - x^3 + 6*x^2 - x^3 + 4*x^2 - 3*x^1
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48485289
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83868093
has text: Let me modify my previous guess. You are explicitly copying things in both cases, but when you are using the pipe, the kernel probably ends up copying it behind the scenes multiple times. See also https://stackoverflow.com/a/11710888/874188
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48437429

http://stackoverflow.com/comment/83767068
type: Comment
comment on: http://stackoverflow.com/a/48372981
type: AnswerComment
has text: Thank you very much! I used your statements and modified my code.
score: 0

http://stackoverflow.com/comment/83650602
comment on: http://stackoverflow.com/q/48332272
has text: What was your best attempt and what was the problem with it? Also please specify: Can there be more than one 'YES' per column? What should happen in this case? How large is your dictionary? Are numpy or pandas solutions an option?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/84010205
comment on: http://stackoverflow.com/q/48486988
type: Comment
score: 0
type: QuestionComment
has text: @elliot-beach thanks. I tried a fresh repro based on my question and unit tests were recognized. I think maybe in my original project the `__pycache__` files became corrupted.

http://stackoverflow.com/q/48384175
has body: I've got Python script for merge .wav files, based on list with paths. It's based on this code import wave infiles = ["sound_1.wav", "sound_2.wav"] outfile = "sounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() from this topic How to join two wav files using python? But I realized, It takes too much time to generate file. In fact I don't need to store merged data as the file on physical disk. So question is, is there any way to read .wav files merge them and play it just from RAM memory? EDIT: I forgot to specify, that I need to play it using Raspberry pi 3. I tried to use PyAudio which on my laptop works fine, but when I tried it in RPI the sound is slowly and crackling (I used this example https://people.csail.mit.edu/hubert/pyaudio/docs/#example-blocking-mode-audio-i-o)
tagged with: raspberry-pi3
tagged with: wave
linked to: http://stackoverflow.com/q/2890703
type: Question
tagged with: audio
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83784260
tagged with: wav
has comment: http://stackoverflow.com/comment/83784433
has comment: http://stackoverflow.com/comment/83755405
has comment: http://stackoverflow.com/comment/83784337
has comment: http://stackoverflow.com/comment/83755398
score: 0
has title: Raspberry PI - Python - merge wav files and play
answer count: 0

http://stackoverflow.com/comment/83844732
has text: `for i in courselist and j in previouscourselist` that won't work of course! what do you want? 2 nested loops?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48427224

http://stackoverflow.com/comment/83821324
has text: What have you tried so far? If you haven't tried anything yet, you would be better off trying to find a tutorial.
score: 3
comment on: http://stackoverflow.com/q/48415862
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83708556
type: AnswerComment
comment on: http://stackoverflow.com/a/48360026
type: Comment
has text: did you reproduce this scenario in practice ?. I ran the code and files do not dissapear. In the case a new file (some_file) is created between runs, then you get a FileExistError because you can not create MR0001.dcm if it already exists.
score: 0

http://stackoverflow.com/comment/83959508
comment on: http://stackoverflow.com/q/48483210
type: Comment
type: QuestionComment
score: 0
has text: Thanks I wasn't having issues with the break, it just indented weird when I posted it here.

gtk3
tags question: http://stackoverflow.com/q/48459051
tags question: http://stackoverflow.com/q/48409067
type: Tag
tags question: http://stackoverflow.com/q/48382610
tags question: http://stackoverflow.com/q/48370743
tag name: gtk3
tags question: http://stackoverflow.com/q/48431689

http://stackoverflow.com/a/48374881
score: 1
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83736851
has body: You shouldn't throw an expection unless the behavior is actually exceptional. In your case, it seems like you want to check for a case, and have your behavior change based on that. So just check if self.website is not None: DoThisThing else: DoTheOtherThing The reason your try/except doesn't work like you expect is that try/except doesn't work like if/else. Instead try/except will first try to run the code in the try block. If the code runs fine, then it skips except and continues on. But if the code throws and Exception then it will run an except block that catches that particular exception. Your try block looks like this: try: self.website == None Now, if self.website is None, then the code in the try block resolves to True. This isn't an exception, so the except block won't be executed. If self.website isn't none, then this block will resolve to False, which is also not an exception, so the except block won't run. Now, if your try block looked like this: try: len(self.website) the code inside of try would throw TypeError: object of type 'NoneType' has no len() so if you followed that with except TypeError: print("This will run now") your except block would execute. You use try/except to deal with exceptions that your code throws (often when the runtime data is different that what was expected). Use if/else specify contingencies in normal operating cases.
answers question: http://stackoverflow.com/q/48374761

http://stackoverflow.com/comment/83652446
has text: Every chunk creates a new `Worker` in Memory and those are shared. So if you have chunksize `2` and `10` jobs, `5` objects will share the same worker.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48332391
score: 0

http://stackoverflow.com/a/48485302
score: 0
answers question: http://stackoverflow.com/q/48483229
type: Answer
has body: I believe that you are looking for a function like this : def sumOfNegativ(arrayOfValue): res = 0 for i in arrayOfValue: if i &lt; 0: res += i return res And to display the result : print(sumOfNegativ(myvals))

http://stackoverflow.com/comment/83960436
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48483832
score: 2
has text: [Okay](https://stackoverflow.com/help/how-to-ask).

http://stackoverflow.com/a/48358672
has body: Kivy's GridLayout, unlike many other GUI Frameworks, don't allow you to choose which specific row/column you want to put the children in. Instead it fills up a row before starting on the next row. You can however create your own custom GridLayout using IDs. For example class CustomRow(FloatLayout): pass class CustomGrid(FloatLayout): pass &lt;CustomRow&gt;: FloatLayout: id: 0 FloatLayout: id: 1 # etc, creating as many FloatLayouts as many number of columns you want. &lt;CustomGrid&gt;: CustomRow: id: 0 CustomRow: id: 1 Then in the py file of CustomGrid class CustomGrid(FloatLayout): def add_child_to_specific(self, row, col, widget): self.ids[row].ids[col].add_widget(widget)
answers question: http://stackoverflow.com/q/48357972
downvote count: 0
upvote count: 1
score: 1
type: Answer

numpy
tags question: http://stackoverflow.com/q/48419408
tags question: http://stackoverflow.com/q/48342726
tags question: http://stackoverflow.com/q/48333445
tags question: http://stackoverflow.com/q/48406578
tags question: http://stackoverflow.com/q/48379243
tags question: http://stackoverflow.com/q/48362180
tags question: http://stackoverflow.com/q/48458438
tags question: http://stackoverflow.com/q/48353359
tags question: http://stackoverflow.com/q/48451061
tags question: http://stackoverflow.com/q/48354125
tags question: http://stackoverflow.com/q/48354259
tags question: http://stackoverflow.com/q/48336165
tags question: http://stackoverflow.com/q/48409570
tags question: http://stackoverflow.com/q/48484454
tags question: http://stackoverflow.com/q/48400578
tags question: http://stackoverflow.com/q/48468448
tags question: http://stackoverflow.com/q/48355644
tags question: http://stackoverflow.com/q/48337371
tags question: http://stackoverflow.com/q/48362729
tags question: http://stackoverflow.com/q/48348275
tags question: http://stackoverflow.com/q/48447814
tags question: http://stackoverflow.com/q/48400602
tags question: http://stackoverflow.com/q/48424130
tags question: http://stackoverflow.com/q/48425010
tags question: http://stackoverflow.com/q/48444086
tags question: http://stackoverflow.com/q/48405980
tags question: http://stackoverflow.com/q/48350693
tags question: http://stackoverflow.com/q/48344706
tags question: http://stackoverflow.com/q/48464281
tags question: http://stackoverflow.com/q/48356593
tags question: http://stackoverflow.com/q/48365313
tags question: http://stackoverflow.com/q/48347221
tags question: http://stackoverflow.com/q/48474882
tags question: http://stackoverflow.com/q/48412510
tags question: http://stackoverflow.com/q/48386883
tags question: http://stackoverflow.com/q/48375484
tags question: http://stackoverflow.com/q/48377998
tags question: http://stackoverflow.com/q/48371188
tags question: http://stackoverflow.com/q/48442034
tags question: http://stackoverflow.com/q/48425814
tags question: http://stackoverflow.com/q/48427365
tags question: http://stackoverflow.com/q/48463629
tags question: http://stackoverflow.com/q/48486814
tags question: http://stackoverflow.com/q/48480053
tags question: http://stackoverflow.com/q/48420400
tags question: http://stackoverflow.com/q/48476206
tags question: http://stackoverflow.com/q/48364447
tags question: http://stackoverflow.com/q/48445577
tags question: http://stackoverflow.com/q/48365594
tags question: http://stackoverflow.com/q/48409226
tags question: http://stackoverflow.com/q/48429596
tags question: http://stackoverflow.com/q/48465407
tags question: http://stackoverflow.com/q/48482256
tags question: http://stackoverflow.com/q/48457087
tags question: http://stackoverflow.com/q/48352234
tags question: http://stackoverflow.com/q/48353551
tags question: http://stackoverflow.com/q/48405005
tags question: http://stackoverflow.com/q/48393640
tags question: http://stackoverflow.com/q/48469889
tags question: http://stackoverflow.com/q/48471852
tags question: http://stackoverflow.com/q/48482262
tags question: http://stackoverflow.com/q/48463842
tags question: http://stackoverflow.com/q/48471648
tags question: http://stackoverflow.com/q/48334185
tags question: http://stackoverflow.com/q/48393536
tags question: http://stackoverflow.com/q/48408264
tags question: http://stackoverflow.com/q/48464861
tags question: http://stackoverflow.com/q/48465683
tags question: http://stackoverflow.com/q/48339315
tags question: http://stackoverflow.com/q/48461551
tags question: http://stackoverflow.com/q/48373590
tags question: http://stackoverflow.com/q/48343583
tags question: http://stackoverflow.com/q/48419214
tags question: http://stackoverflow.com/q/48390268
tags question: http://stackoverflow.com/q/48348803
tags question: http://stackoverflow.com/q/48350320
tags question: http://stackoverflow.com/q/48406687
tags question: http://stackoverflow.com/q/48487928
tags question: http://stackoverflow.com/q/48409525
tags question: http://stackoverflow.com/q/48377146

http://stackoverflow.com/q/48466131
has comment: http://stackoverflow.com/comment/83926060
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83925862
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84169554
has body: I am trying to use argsort on an array of float arrays, but faced some problem. Here is what I try to do: import numpy as np z = np.array([np.array([30.9,29.0,5.87],dtype=float),np.array([20.3,1.3,8.8,4.4],dtype=float)]) # actually z is transferred from a tree using root2array whose corrseponding branches is a vector&lt;vector&lt;float&gt;&gt; Index_list = np.argsort(z) Then I received: ValueError: operands could not be broadcast together with shapes (4,) (3,) So what should I do to modify z or change the way of argsort to make it work?
has title: how to argsort with an array of arrays
tagged with: python
has comment: http://stackoverflow.com/comment/83925982

http://stackoverflow.com/q/48370121
has body: I am new to RL and the best I've done is CartPole in openAI gym. In cartPole, the API automatically provides the reward given the action taken. How am I supposed to decide the reward when all I have is pixel data and no "magic function" that could tell the reward for a certain action. Say, I want to make a self driving bot in GTA San Andreas. The input I have access to are raw pixels. How am I supposed to figure out the reward for a certain action it takes?
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48370179
type: Question
tagged with: reinforcement-learning
type: UnansweredQuestion
tagged with: python
tagged with: artificial-intelligence
has title: Reinforcement Learning - How to we decide the reward to the agent when the input to the game is only pixels?
tagged with: openai-gym
score: 0

http://stackoverflow.com/comment/83801234
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48405956
score: 0
has text: so you want to keep the existing column names and leave out the ones with no names as blank and open the file in pandas?

http://stackoverflow.com/a/48427123
has body: The first step is to work out how to do the data validation in Excel and then transfer it to XlsxWriter. This will probably require a "Custom" data validation like this: import xlsxwriter wb = xlsxwriter.Workbook('staff.xlsx') ws = wb.add_worksheet() ws.data_validation('A1:C3', {'validate': 'custom', 'value': '=ISTEXT(A1)', 'input_title': 'Enter a non numeric value', 'error_message': 'Enter a string not a number'}) wb.close() Output: However, this doesn't do exactly what you are looking for. It is still possible to add non character data or even strings like 123h as shown in the screenshot. So you will need to figure out a formula that works in Excel and then apply it to XlsxWriter. I googled for an example but didn't find anything that worked.
has comment: http://stackoverflow.com/comment/84771208
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84808301
has comment: http://stackoverflow.com/comment/83866087
answers question: http://stackoverflow.com/q/48422473
has comment: http://stackoverflow.com/comment/84779517
has comment: http://stackoverflow.com/comment/84776564
has comment: http://stackoverflow.com/comment/84779465
has comment: http://stackoverflow.com/comment/84775198
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83866343
has comment: http://stackoverflow.com/comment/84776418

http://stackoverflow.com/comment/83928707
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48467267
score: 0
has text: If you're connecting to the instance that's remote, from your local computer, then you need to put the public IP address/hostname from the AWS dashboard for your instance as the host. I suspect you have MySQL installed locally and you're connecting to that, but don't have the dbname database created there.

http://stackoverflow.com/comment/83973310
type: QuestionComment
has text: yes, the Twitter API returns 100 Retweeter IDs, and no more.
comment on: http://stackoverflow.com/q/48487340
score: 0
type: Comment

http://stackoverflow.com/a/48384788
upvote count: 1
has comment: http://stackoverflow.com/comment/86584191
score: 1
answers question: http://stackoverflow.com/q/48380663
type: Answer
has body: Ok, I solved this by doing: img = Image.open(img_path) img = img.resize((128, 128), Image.ANTIALIAS) \ .transform(device.size, Image.AFFINE, (1, 0, 0, 0, 1, 0), Image.BILINEAR) \ .convert(device.mode) So do image resize first, before running transform and convert.
downvote count: 0

http://stackoverflow.com/q/48452294
has body: I have a python script that accepts a -f flag, and appends multiple uses of the flag. For example, if I run python myscript -f file1.txt -f file2.txt, I would have a list of files, files=['file1.txt', 'files2.txt']. This works great, but am wondering how I can automatically use the results of a find command to append as many -f flags as there are files. I've tried: find ./ -iname '*.txt' -print0 | xargs python myscript.py -f But it only grabs the first file
score: 0
has title: How to add argparse flags based on shell find results
answer count: 2
tagged with: argparse
has comment: http://stackoverflow.com/comment/83897877
has comment: http://stackoverflow.com/comment/83898280
tagged with: shell
has answer: http://stackoverflow.com/a/48452606
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48452402

http://stackoverflow.com/q/48446119
tagged with: python
accepted answer: http://stackoverflow.com/a/48448500
has comment: http://stackoverflow.com/comment/83885513
has answer: http://stackoverflow.com/a/48448500
tagged with: import
has title: How to separate function call from this function
has comment: http://stackoverflow.com/comment/83888095
type: Question
score: 0
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/83886189
has comment: http://stackoverflow.com/comment/83886533
has body: I have an existing script that contains functions that I would like to call from another script. I would like to modify it such that the main function does not automatically call the primitives function. The full script reads: import time import datetime from luma.core.render import canvas def primitives1(device, draw): # First define some constants to allow easy resizing of shapes. padding = 2 shape_width = 20 top = padding bottom = device.height - padding - 1 # Move left to right keeping track of the current x position for drawing shapes. x = padding # Write two lines of text. size = draw.textsize('World!') x = device.width - padding - size[0] draw.rectangle((x, top + 4, x + size[0], top + size[1]), fill="black") draw.rectangle((x, top + 16, x + size[0], top + 16 + size[1]), fill="black") draw.text((device.width - padding - size[0], top + 4), 'Hello', fill="cyan") draw.text((device.width - padding - size[0], top + 16), 'World!', fill="purple") time.sleep(5) def primitives2(device, draw): # First define some constants to allow easy resizing of shapes. padding = 2 shape_width = 20 top = padding bottom = device.height - padding - 1 # Move left to right keeping track of the current x position for drawing shapes. x = padding # Write two lines of text. size = draw.textsize('World!') x = device.width - padding - size[0] draw.rectangle((x, top + 4, x + size[0], top + size[1]), fill="black") draw.rectangle((x, top + 16, x + size[0], top + 16 + size[1]), fill="black") draw.text((device.width - padding - size[0], top + 4), 'Bye', fill="cyan") draw.text((device.width - padding - size[0], top + 16), 'Bye!', fill="purple") time.sleep(5) def main(): from luma.core.interface.serial import spi from luma.core.render import canvas from luma.oled.device import ssd1351 serial = spi(device=0, port=0, gpio_DC=20) device = ssd1351(serial) device.width=128 device.height=128 print("Testing basic canvas graphics...") for _ in range(2): with canvas(device) as draw: primitives1(device, draw) …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83886290

http://stackoverflow.com/a/48389734
has comment: http://stackoverflow.com/comment/83767353
score: 1
downvote count: 0
upvote count: 1
has body: It seems like the error is with using the C engine to parse the csv. I'm not knowledgeable enough to know why that might be, but a possible workaround to to force the df.read_csv() bit to use the python engine by passing the engine = 'python' argument. As per the Pandas documentation, pd.read_csv() defaults to using the C engine for speed. Given that your error is hinting at a problem with the C engine, that might be a good place to start. so, try pd.read_csv('converted_timezone_tweets.csv', parse_dates=['Time'], engine = 'python') There was also something on GitHub hinting towards similar problems and fixes
type: Answer
answers question: http://stackoverflow.com/q/48389030

http://stackoverflow.com/q/48358297
tagged with: wtforms
answer count: 1
type: AnsweredQuestion
has body: Hey guys I am using Sanic with WTForms and Sanic-WTF. I have this code for my SignUpForm: class SignUpForm(SanicForm): email = EmailField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=25), EqualTo('confirm_password', message='Passwords must match.')]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired()]) I also have this as my validation for my validation in a Class Based View. async def post(self, request): form = SignUpForm(request) email = form.email.data print(email) email_exists = await unique_db(email) print(form.errors) print ('Form validated: {}, Email Exists: {}'.format(form.validate_on_submit(), email_exists)) if form.validate_on_submit() and email_exists == False: print('Validated') await app.db.user_details.update_one({'user':'details'},{'$set': data}, upsert=True) return json({'success':True}) return template('signup.html', form=form) I have no idea what is going on. I have also tried doing form.validate() My SignUp Form is {{ form.csrf_token }} Sign up {{ macros.render_field(form.email, label_visible=true, placeholder='Email', type='email') }} Your email must be in the form name@example.com {{ macros.render_field(form.password, label_visible=true, placeholder='Password', type='password') }} {{ macros.render_field(form.confirm_password, label_visible=true, placeholder='Confirm Password', type='password') }} Submit Already have an account? Log in
tagged with: sanic
tagged with: python
has title: Sanic Form Validation Failing Silently
accepted answer: http://stackoverflow.com/a/48446950
has answer: http://stackoverflow.com/a/48446950
type: Question
score: 0

http://stackoverflow.com/comment/83760718
score: 0
type: AnswerComment
has text: I was trying to do this [Question](https://www.hackerrank.com/challenges/permutation-equation/problem) in hackerank. I dont this your solution fits in.It causes index out of range error.
type: Comment
comment on: http://stackoverflow.com/a/48345763

http://stackoverflow.com/comment/83728144
comment on: http://stackoverflow.com/q/48370708
has text: Because some people can not easily construct the correct filtering and aggregates, but know how to write something like SQL?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83756665
comment on: http://stackoverflow.com/q/48372903
score: 0
has text: I fixed it, thanks for pointing that out!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83675123
has text: You can write your own class which only stores one triangular part (+ diag) in a flattened form (while storing the flattening-order Fortran vs. C (maybe not needed; can't wrap my head around currently); part of numpy-array). But if you are using compression (savez_compressed) during saving, i expect it to be nearly as efficient (guessing). At least for smaller arrays as compression is probably typical LZW-like using some window-size.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48344706

regex
tags question: http://stackoverflow.com/q/48472346
tags question: http://stackoverflow.com/q/48383199
tags question: http://stackoverflow.com/q/48359026
tags question: http://stackoverflow.com/q/48385960
tags question: http://stackoverflow.com/q/48484812
tags question: http://stackoverflow.com/q/48362436
tags question: http://stackoverflow.com/q/48455650
tags question: http://stackoverflow.com/q/48465262
tags question: http://stackoverflow.com/q/48338495
tags question: http://stackoverflow.com/q/48470964
tags question: http://stackoverflow.com/q/48345205
tags question: http://stackoverflow.com/q/48410616
tags question: http://stackoverflow.com/q/48428804
tags question: http://stackoverflow.com/q/48335102
tags question: http://stackoverflow.com/q/48413762
tags question: http://stackoverflow.com/q/48348095
tags question: http://stackoverflow.com/q/48428916
tags question: http://stackoverflow.com/q/48414878
tags question: http://stackoverflow.com/q/48392454
tags question: http://stackoverflow.com/q/48386339
tags question: http://stackoverflow.com/q/48411705
tags question: http://stackoverflow.com/q/48409527
tags question: http://stackoverflow.com/q/48371541
tags question: http://stackoverflow.com/q/48468660
tags question: http://stackoverflow.com/q/48352706
tags question: http://stackoverflow.com/q/48368879
tags question: http://stackoverflow.com/q/48475440
tag name: regex
tags question: http://stackoverflow.com/q/48411634
tags question: http://stackoverflow.com/q/48387448
tags question: http://stackoverflow.com/q/48357988
tags question: http://stackoverflow.com/q/48468009
tags question: http://stackoverflow.com/q/48452041
tags question: http://stackoverflow.com/q/48428732
tags question: http://stackoverflow.com/q/48411801
tags question: http://stackoverflow.com/q/48365055
tags question: http://stackoverflow.com/q/48388686
tags question: http://stackoverflow.com/q/48447614
tags question: http://stackoverflow.com/q/48337438
tags question: http://stackoverflow.com/q/48452959
tags question: http://stackoverflow.com/q/48348882
tags question: http://stackoverflow.com/q/48476521
tags question: http://stackoverflow.com/q/48453992
tags question: http://stackoverflow.com/q/48340058
tags question: http://stackoverflow.com/q/48385609
tags question: http://stackoverflow.com/q/48470114
tags question: http://stackoverflow.com/q/48469708
tags question: http://stackoverflow.com/q/48425063
tags question: http://stackoverflow.com/q/48383774
tags question: http://stackoverflow.com/q/48361755
tags question: http://stackoverflow.com/q/48349028
tags question: http://stackoverflow.com/q/48359255
tags question: http://stackoverflow.com/q/48412955
tags question: http://stackoverflow.com/q/48400133
tags question: http://stackoverflow.com/q/48404499
tags question: http://stackoverflow.com/q/48368148
tags question: http://stackoverflow.com/q/48357619
tags question: http://stackoverflow.com/q/48374469
tags question: http://stackoverflow.com/q/48400514
tags question: http://stackoverflow.com/q/48351197
tags question: http://stackoverflow.com/q/48363477
tags question: http://stackoverflow.com/q/48345250
tags question: http://stackoverflow.com/q/48361143
tags question: http://stackoverflow.com/q/48425228
tags question: http://stackoverflow.com/q/48464062
tags question: http://stackoverflow.com/q/48333419
tags question: http://stackoverflow.com/q/48392848
tags question: http://stackoverflow.com/q/48408057
tags question: http://stackoverflow.com/q/48360628
tags question: http://stackoverflow.com/q/48433605
tags question: http://stackoverflow.com/q/48392510
tags question: http://stackoverflow.com/q/48440226
tags question: http://stackoverflow.com/q/48466578
tags question: http://stackoverflow.com/q/48457321
tags question: http://stackoverflow.com/q/48426027
tags question: http://stackoverflow.com/q/48400336
tags question: http://stackoverflow.com/q/48375480
tags question: http://stackoverflow.com/q/48358555
tags question: http://stackoverflow.com/q/48388675
tags question: http://stackoverflow.com/q/48453412

http://stackoverflow.com/comment/133454234
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48597140
has text: Thanks for this, nice bit of detective work. Messing around with it I found that you can set the padding on the <StripLayout> directly to get rid of the border/padding. Having to set it to -2dp is *ridiculous* imo, poor design by Kivy here.

http://stackoverflow.com/comment/83847434
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48428115
has text: Thanks for editing my question. Sorry I did not intend to come across that way.

http://stackoverflow.com/a/48368724
accepted answer of: http://stackoverflow.com/q/48364814
has body: I know this code is complicated or bad. But it gets the job done. You can optimize it over time. from bs4 import BeautifulSoup,Comment import requests r = requests.get('https://www.baseball-reference.com/boxes/SLN/SLN201704020.shtml') soup = BeautifulSoup(r.text, 'lxml') comments = soup.find_all(string=lambda text:isinstance(text, Comment)) for comment in comments: comment.extract() #After getting rid of comments we need Soup again another_soup = BeautifulSoup(str(comment),'lxml') tables = another_soup.find_all('table' ,{"class": "sortable stats_table"}) for table in tables: #Since we can't get id from table we are going to use table header as stat type. stat_type = '' for data in table.find('thead').find_all('tr'): stat_type = data.th.text.strip() #You only need batting. if stat_type != 'Batting': break for data in table.find('tbody').find_all('tr'): player = data.th.text.strip() stats = data.find_all('td') stat_ab = stats[0].text stat_r = stats[1].text stat_h = stats[2].text stat_rbi = stats[3].text # Table goes on print(player,stat_ab,stat_r,stat_h,stat_rbi) print('-------------------------------------') The output is: Kyle Schwarber LF 3 0 2 0 Kris Bryant 3B 4 0 0 0 Anthony Rizzo 1B 4 0 1 0 Ben Zobrist RF 3 1 0 0 Addison Russell SS 4 0 1 0 Jason Heyward CF 4 1 1 0 Willson Contreras C 4 1 2 3 Jon Lester P 2 0 0 0 Carl Edwards P 0 0 0 0 Koji Uehara P 0 0 0 0 Tommy La Stella PH 1 0 0 0 Pedro Strop P 0 0 0 0 Jon Jay PH 1 0 0 0 Mike Montgomery P 0 0 0 0 Javier Baez 2B 4 0 1 0 ------------------------------------- Dexter Fowler CF 4 1 1 0 Aledmys Diaz SS 5 0 2 0 Matt Carpenter 1B 4 0 1 1 Jhonny Peralta 3B 4 0 1 0 Seung-hwan Oh P 0 0 0 0 Jose Martinez PH 1 1 1 0 Yadier Molina C 3 0 2 0 Stephen Piscotty RF 3 1 1 0 Jedd Gyorko 2B 2 0 0 0 Kolten Wong PH-2B 2 0 0 0 Randal Grichuk LF 4 1 2 3 Carlos Martinez P 3 0 0 0 Greg Garcia 3B 0 0 0 0 -------------------------------------
answers question: http://stackoverflow.com/q/48364814
has comment: http://stackoverflow.com/comment/83814868
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/83814990
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48457356
has comment: http://stackoverflow.com/comment/83907784
linked to: http://stackoverflow.com/q/396856
answer count: 1
has comment: http://stackoverflow.com/comment/83907570
has answer: http://stackoverflow.com/a/48457475
favorite count: 0
has comment: http://stackoverflow.com/comment/83907899
type: Question
has comment: http://stackoverflow.com/comment/83907345
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/83907357
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1301346
downvote count: 0
tagged with: python
tagged with: variables
has body: I try to make a Toy class here class Toy: def __init__(self,name,ID,price,age): self.__ToyName = name self.__ToyID = ID self.__Price = price self.__MinimumAge = int(age) ##some methods here And when i try to make a sub-class computer game, i need to make 7 arguments(with 5 from the Toy class)to instantiating the computer game class, and it shows "too many arguements (7/5)" class ComputerGame(Toy): def __init__(self,name,ID,price,age,catogory,console): Toy.__init__(self,name,ID,price,age) self.__Catogory = catogory self.__Console = console What should I do to with this situation?
tagged with: class
score: 2
has title: How to deal with the error "too many arguments" in python 3

http://stackoverflow.com/comment/101177448
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48373959
type: Comment
has text: I appears like it doesn't recognize the nested function (I use focal loss, but it doesn't matter), I get "Unknown loss function" (for the nested model).

http://stackoverflow.com/comment/83922795
type: QuestionComment
has text: @Wen I'm semi new to SO, still learning. Thanks for your patience.
type: Comment
comment on: http://stackoverflow.com/q/48464467
score: 0

http://stackoverflow.com/comment/83806273
has text: Do the `original` and the `changed` list have the same order?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48408529

http://stackoverflow.com/q/48438074
answer count: 2
downvote count: 0
has body: I am trying to make an aap for MCQ's. Here i want a function, if anyone even click on the label corresponding to a checkbox, that check box must also be checked.. Is it possible in Kivy? Because Kivy doesn't provide any text association with checkbox directly. Here is a portion of kv. &lt;MCQCheckBox@CheckBox&gt;: color:0,0,0,1 size_hint: 0.15, 1 group: 'opts' &lt;MCQLabel@Label&gt;: text_size: self.size valign: 'center' font_size: '13sp' color: 0,0,0,1 &lt;MCQsGUI&gt;: BoxLayout: orientation:'vertical' size_hint: 0.95, 0.7 spacing: 2 pos_hint: {'center_x': .5, 'center_y': .5} MCQBoxLayout: MCQCheckBox: MCQLabel: text:"option 1" MCQBoxLayout: MCQCheckBox: MCQLabel: text:"option 2" MCQBoxLayout: MCQCheckBox: MCQLabel: text:"option 3" MCQBoxLayout: MCQCheckBox: MCQLabel: text:"option 4"
favorite count: 0
has answer: http://stackoverflow.com/a/48450380
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48443383
tagged with: python
tagged with: kivy
tagged with: checkbox
has answer: http://stackoverflow.com/a/48443383
accepted answer: http://stackoverflow.com/a/48450380
has title: Kivy: Touch the label to check the checkbox
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83953219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48479964
has text: So why would one prefer this lengthy solution instead of `scipy.ndimage.rotate(img, angle)`, which is a single line of code?
type: AnswerComment

http://stackoverflow.com/q/48393941
has answer: http://stackoverflow.com/a/48394294
accepted answer: http://stackoverflow.com/a/48394294
has comment: http://stackoverflow.com/comment/83784911
tagged with: python
has comment: http://stackoverflow.com/comment/83778064
linked to: http://stackoverflow.com/q/47735375
type: Question
upvote count: 2
tagged with: selenium-chromedriver
has body: EDIT: I figured out the culprit. That extra 's' certainly didn't do me any favors but the real issue was that I needed to switch to a new frame before searching for my element. Works like a charm now. Thanks for all the help! I'm trying to pull the number of total results from various text searches in ServiceNow. I don't have access to the API so I'm having to brute force it a bit. Right now I have a python script that's using selenium to run the search. My problem is that for the life of me I can't scrape the results. Here's the snippet of my code that isn't working: elm_result = web_driver.find_elements_by_name("ts_count_8c58a5aa0a0a0b07008047e8ef0fe07d") print("Total results: ", elm_result.text) And here's the html and screenshot of the page it's pulling from: &lt;span name="ts_count_8c58a5aa0a0a0b07008047e8ef0fe07d" id="ts_count_8c58a5aa0a0a0b07008047e8ef0fe07d"&gt; &amp;nbsp;(162 matches)&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;em&gt; &lt;span class="search_no_results"&gt;No matches for &lt;a title="" class="noresultlink" href="ticket_list.do sysparm_query=123TEXTQUERY321%3DSAP%5Eactive%3Dtrue"&gt;Tickets&lt;/a&gt; &lt;span&gt; &lt;/span&gt; &lt;/span&gt; &lt;/em&gt; &lt;/span&gt; When I run the script it seems to hang on this last little before eventually throwing out the following error: Traceback (most recent call last): File "...", line 35, in &lt;module&gt; print("Total results: ", elm_result.text) AttributeError: 'list' object has no attribute 'text' I've tried attacking it from a bunch of different angles but nothing seems to work. My goal is to get the "162 results" text into a variable that I can then pass onto a csv.
has title: Trying to get text from span with Selenium and Python
answer count: 1
tagged with: selenium
tagged with: web-scraping
favorite count: 0
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83775896
downvote count: 0

http://stackoverflow.com/comment/83691591
comment on: http://stackoverflow.com/a/48352342
has text: Thanks, clear. Method with Example1.VARIABLE = VARIABLE does't work AttributeError: type object 'Example1' has no attribute when I try to print it
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83727327
type: Comment
score: 0
has text: Finding the stationary distribution is equivalent to finding that eigenvector of A which has eigenvalue one. One possible difficulty is if the structure of A is such that this eigenvector contains zeros. If you pick your 'idx' such that you hit one of those zeros, I expect that could be a source of problems. Alternatively, I'm wondering if you can just set A[idx, idx]=1, after zeroing the rest of that row, to improve numerical conditioning. The fact that scaling your "x" matrix changes the behaviour of spsolve() is indeed interesting.
comment on: http://stackoverflow.com/q/48370035
type: QuestionComment

http://stackoverflow.com/q/48349630
has body: I have just start coding with python since fall. So i am not a professional python coder. I have started to code a Sudoku program. And fortunately at last I could have come up with this code: def isValid(num, x, y): for i in range(9): if board[i][y] == num: return False if board[x][i] == num: return False row = x - x % 3 col = y - y % 3 for i in range(3): for j in range(3): if board[i + row][j + col] == num: return False return True def solve(remaining): if remaining == 0: return True for i in range(9): for j in range(9): if board[i][j] != 0: continue for num in range(1, 10): if isValid(num, i, j): board[i][j] = num if solve(remaining - 1): return True board[i][j] = 0 return False return False def pp(): for i in range(9): for j in range(9): print(board[i][j], end=" ") print() print() board = [] remaining = 0 for i in range(9): a=input() a=a.split() a = list(map(int, a)) for j in a: if j == 0: remaining += 1 board.append(a) solve(remaining) pp() For instance I give such an input to it: 0 0 0 0 0 0 0 1 0 0 0 2 0 0 0 0 3 4 0 0 0 0 5 1 0 0 0 0 0 0 0 0 6 5 0 0 0 7 0 3 0 0 0 8 0 0 0 3 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 5 8 0 0 0 0 9 0 0 6 9 0 0 0 0 0 0 0 And this is my output: 7 4 9 2 3 8 6 1 5 1 5 2 6 9 7 8 3 4 8 3 6 4 5 1 2 7 9 2 1 8 9 7 6 5 4 3 9 7 5 3 2 4 1 8 6 4 6 3 8 1 5 7 9 2 3 2 1 5 8 9 4 6 7 5 8 4 7 6 3 9 2 1 6 9 7 1 4 2 3 5 8 Now I intend to add a new condition to this Sudoku which is can do this process for 4 more 3*3 boxes in the board like this (which is named Hyper-Sudoku): That for my puzzle it returns: 9 4 6 8 3 2 7 1 5 1 5 2 6 9 7 8 3 4 7 3 8 4 5 1 2 9 6 8 1 9 7 2 6 5 4 3 4 7 5 3 1 9 6 8 2 2 6 3 5 4 8 1 7 9 3 2 7 9 8 5 4 6 1 5 8 4 1 6 3 9 2 7 6 9 1 2 7 4 3 5 8 Is there any way to add this option to my Sudoku or not, I have to change my whole algorithm? Thanks for your answers.
tagged with: python
tagged with: backtracking
accepted answer: http://stackoverflow.com/a/48349797
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48349797
has title: How to add another condition to Sudoku puzzle
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: algorithm

http://stackoverflow.com/a/48359763
score: 1
answers question: http://stackoverflow.com/q/48359325
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Using Pandas one can: import pandas as pd def group_consequent_elements(list_of_ints): '''Returns a nested list for the numerically consequent elements''' df = pd.DataFrame({"vals": list_of_ints}) df["groups"] = ((df['vals'].diff() != 1).cumsum()) return df.groupby("groups")["vals"].apply(list).tolist() # Results group_consequent_elements(A) # [[5, 6, 7, 8]] group_consequent_elements(B) # [[1, 2], [6, 7]] group_consequent_elements(C) # [[3, 4], [6, 7, 8, 9]] To further clarify the logic, here are the intermediate steps printed: df = pd.DataFrame({"vals": C}) df['diff'] = df['vals'].diff() df['not_consequent'] = df['diff'] != 1 df["groups"] = df['not_consequent'].cumsum() # vals diff not_consequent groups # 0 3 NaN True 1 # 1 4 1.0 False 1 # 2 6 2.0 True 2 # 3 7 1.0 False 2 # 4 8 1.0 False 2 # 5 9 1.0 False 2
accepted answer of: http://stackoverflow.com/q/48359325
type: Answer

http://stackoverflow.com/q/48377214
has answer: http://stackoverflow.com/a/48389451
score: 29
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/68616083
linked to: http://stackoverflow.com/q/34240703
has answer: http://stackoverflow.com/a/69137517
upvote count: 29
has title: RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74554139
has answer: http://stackoverflow.com/a/75035662
favorite count: 0
has body: Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it. The Unet model i have picked up from somewhere else, and i am using the cross-entropy loss as a loss function but i get this dimension out of range error, RuntimeError Traceback (most recent call last) &lt;ipython-input-358-fa0ef49a43ae&gt; in &lt;module&gt;() 16 for epoch in range(0, num_epochs): 17 # train for one epoch ---&gt; 18 curr_loss = train(train_loader, model, criterion, epoch, num_epochs) 19 20 # store best loss and save a model checkpoint &lt;ipython-input-356-1bd6c6c281fb&gt; in train(train_loader, model, criterion, epoch, num_epochs) 16 # measure loss 17 print (outputs.size(),labels.size()) ---&gt; 18 loss = criterion(outputs, labels) 19 losses.update(loss.data[0], images.size(0)) 20 /usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in _ _call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) &lt;ipython-input-355-db66abcdb074&gt; in forward(self, logits, targets) 9 probs_flat = probs.view(-1) 10 targets_flat = targets.view(-1) ---&gt; 11 return self.crossEntropy_loss(probs_flat, targets_flat) /usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /usr/local/lib/python3.5/dist-packages/torch/nn/modules/loss.py in f orward(self, input, target) 599 _assert_no_grad(target) 600 return F.cross_entropy(input, target, self.weight, self.size_average, --&gt; 601 self.ignore_index, self.reduce) 602 603 /usr/local/lib/python3.5/dist-packag…
type: Question
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/48389451
answer count: 5
possible better answer: http://stackoverflow.com/a/68616083
downvote count: 0

http://stackoverflow.com/comment/83758316
has text: That worked fine indeed in my test case. I'll test it in my larger actual use-case later today and also comment here what kind of speed-up it provides there compared to the row-by-row solution in my question.
comment on: http://stackoverflow.com/a/48385128
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48456933
accepted answer of: http://stackoverflow.com/q/48448577
has body: I would like to get the client killed whenever CTRL+C is pressed, but it gets stuck with the current code. How can it be done properly? The KeyboardInterrupt should be enough to terminate the client application. Probably the process is hanging on the stub.unsubscribe. If you use the client disconnection callback, perhaps you don't need to unsubscribe explicitly. How does the server realize that the client has stopped listening? You can add a callback to the context object that gets passed to your Messenger.subscribe method. The callback is called on client disconnection. By the way, you can look in using empty.proto in place of your Null type.
upvote count: 3
has comment: http://stackoverflow.com/comment/84007060
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83919400
has comment: http://stackoverflow.com/comment/83921904
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83918939
answers question: http://stackoverflow.com/q/48448577

http://stackoverflow.com/comment/83895987
has text: @rankind converting to an array does not make regular python operations faster. There are _loads_ of numpy methods that exist specifically for arrays.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48451425

http://stackoverflow.com/q/48347331
type: Question
duplicate of: http://stackoverflow.com/q/9942594
tagged with: encoding
tagged with: python
has title: Python UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128)
has answer: http://stackoverflow.com/a/48347424
score: 8
has comment: http://stackoverflow.com/comment/83680576
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
accepted answer: http://stackoverflow.com/a/48347549
linked to: http://stackoverflow.com/q/9942594
downvote count: 2
possible better answer: http://stackoverflow.com/a/48347424
has body: In Python 2.7, see the following error, when trying to cast type to ensure it matches the output schema. UnicodeEncodeError: 'ascii' codec can't encode character in position 0: ordinal not in range(128) Tried to find why and reproduced the error in Jupiter. By simply typing in. str(u'\u2013') What is the way to cast type to string that can handle this type of error? Thanks!
has answer: http://stackoverflow.com/a/48347549
has comment: http://stackoverflow.com/comment/83680846
tagged with: string
upvote count: 10
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/48347543

http://stackoverflow.com/q/48390196
has title: UnsatisfiableError: The following specifications were found to be in conflict: conda 4.0.8* -> conda-env <2.5 -> python 2.7* - python 3.6*
favorite count: 0
has answer: http://stackoverflow.com/a/48445595
tagged with: python-3.x
type: Question
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: graphlab
has comment: http://stackoverflow.com/comment/83798823
tagged with: anaconda
has body: I am new to Python. I am trying to use Graphlab create launcher to import Graphlab libraries in my python notebook. I already have Anaconda installed on my MacBook Pro(OSX). When I start to run Graphlab create launcher, I get following error, UnsatisfiableError: The following specifications were found to be in conflict: - conda 4.0.8* -&gt; conda-env &lt;2.5 -&gt; python 2.7* - python 3.6* Use "conda info &lt;package&gt;" to see the dependencies for each package. You can find the detail of the log at https://github.com/jaysara/Python-ML/blob/master/launcher-install-log.txt Can anyone help, why am I getting this error ?
has answer: http://stackoverflow.com/a/54941624
tagged with: python
score: 1

http://stackoverflow.com/a/48347938
has comment: http://stackoverflow.com/comment/83908678
downvote count: 0
has comment: http://stackoverflow.com/comment/101409202
score: 5
answers question: http://stackoverflow.com/q/48346752
has comment: http://stackoverflow.com/comment/83682685
upvote count: 5
has body: My solution is to create an closure that does the extension checking: import argparse def ext_check(expected_extension, openner): def extension(filename): if not filename.lower().endswith(expected_extension): raise ValueError() return openner(filename) return extension parser = argparse.ArgumentParser() parser.add_argument('outfile', type=ext_check('.txt', argparse.FileType('w'))) # test out args = parser.parse_args() args.outfile.write('Hello, world\n') Notes ext_check basically is a wrapper for argparse.FileType It takes an expected extension to check and an openner For simplicity, the expected extension is in lower case, the filename will be converted to lower case prior to validation openner in this case is an argparse.FileType('w') callable (most likely a function, but I don't care, as long as it is a callable). ext_check returns a callable, which is a function called extension. I name it this way, so that the error will come out as followed (note the word extension bellow, which is the name of the function): error: argument outfile: invalid extension value: 'foo.txt2' Within the extension function, we check the file extension, if passed, we pass the file name to the openner. What I like about this solution Concise Require almost no knowledge of how argparse.FileType works since it just act as a wrapper around it What I don't like about it Caller has to know about closure to understand how it works I have no control over the error message. That is why I have to name my inner function extension to get a somewhat meaningful error message as seen above. Other possible solutions Create a custom action, see the documentation for argparse Subclass argparse.FileType as Martijn Pieters has done Each of these solutions has its own strong points and weaknesses
type: Answer
has comment: http://stackoverflow.com/comment/83687218

http://stackoverflow.com/comment/83972034
comment on: http://stackoverflow.com/q/48483560
type: Comment
type: QuestionComment
has text: I would like to print the 2nd column of data2 based on whether the ID exists in whatever dataframe/dataset I'm working with. (Column 1 of data2 is the ID, and Column 2 of data1 is also the ID)
score: 0

http://stackoverflow.com/a/48445783
score: 4
accepted answer of: http://stackoverflow.com/q/48445426
type: AcceptedAnswer
downvote count: 0
has body: Zipping generator expressions on numpy arrays are efficient for this: import pandas as pd df = pd.DataFrame([[('Country1', (341.123, 4534.123))], [('Country2', (341.123, 4534.123))], [('Country3', (341.123, 4534.123))], [('Country4', (341.123, 4534.123))]], columns=['Series1']) df['Lat'], df['Lon'] = list(zip(*((x[1][0], x[1][1]) for x in df['Series1'].values)))
upvote count: 4
type: Answer
answers question: http://stackoverflow.com/q/48445426

http://stackoverflow.com/q/48345735
tagged with: ctypes
has answer: http://stackoverflow.com/a/50309070
answer count: 1
has comment: http://stackoverflow.com/comment/84091711
tagged with: pyopenssl
has title: Error initializing ctypes in pybuilder
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50309070
has body: A couple of days ago I cloned a git repository and tried to make a build out of that code with PyBuilder; however, I have not been able to do so. Every time I run pyb -X -E jenkins-zipfile-release in Bash I get the following error: BUILD FAILED - Error initializing ctypes. The thing is, none of my colleagues have this problem, we don't know why. The traceback tells me the problem is here: .../pyenv/versions/2.7.14/lib/python2.7/site-packages/oscrypto/_openssl/_libcrypto_ctypes.py We thought the problem that my python was not correctly compiled with SSL. We even had a different SSL version. I replaced LibreSSL with OpenSSL, but the problem persists. Another person told me that maybe the oscrypto libraries are conflicting (one from the environment and the other one from the project's lib directory) How can I check that? I would deeply appreciate if someone could point me in the right direction, I've been trying for two days now.
tagged with: python
has comment: http://stackoverflow.com/comment/84088722
type: Question
tagged with: openssl
score: 0

http://stackoverflow.com/comment/83724724
score: 0
comment on: http://stackoverflow.com/q/48368509
type: QuestionComment
has text: for some reason the directory is not displaying Directory: C:\Users\Ghost\Documents\MalwareTest
type: Comment

aws-api-gateway
tags question: http://stackoverflow.com/q/48379852
tags question: http://stackoverflow.com/q/48412401
type: Tag
tag name: aws-api-gateway
tags question: http://stackoverflow.com/q/48385803

http://stackoverflow.com/a/48411664
answers question: http://stackoverflow.com/q/48411571
type: Answer
accepted answer of: http://stackoverflow.com/q/48411571
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83813243
has body: You assigned DDL twice. The first one '''CREATE TABLE PRODUCT... was overwritten by the second one '''CREATE TABLE SUPPLIER... I would suggest calling conn.execute(DDL) immediately after the first DDL assignment. Keep the second call to conn.execute where it is since both SQL statements need to be executed.

http://stackoverflow.com/comment/83956967
score: 0
type: QuestionComment
has text: yes @James. Basically, I want to permute/shuffle a random 5%.
comment on: http://stackoverflow.com/q/48481902
type: Comment

http://stackoverflow.com/a/78066242
answers question: http://stackoverflow.com/q/48355747
type: Answer
score: 0
has body: Even after doing all things no module named 'hmmlearn' is still showing in jupyter notebook. first try to directly install or run below code In single Cell of opened file in your jupyter notebook. pip install hmmlearn Then you can run: from hmmlearn import hmm #or import hmm
has comment: http://stackoverflow.com/comment/137627466
has comment: http://stackoverflow.com/comment/137624884

http://stackoverflow.com/comment/83844663
comment on: http://stackoverflow.com/a/48426958
type: Comment
type: AnswerComment
score: 0
has text: This seems to be the only correct option for my current situation. Since I'm adding this code on 96kb RAM device, memory management is a critical issue. Even a few bytes are too much for the device. Thanks for writing the answer.

http://stackoverflow.com/a/48526348
downvote count: 0
answers question: http://stackoverflow.com/q/48471688
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84050016
type: Answer
has comment: http://stackoverflow.com/comment/84175479
has body: There's no need for tf.py_func in this case, because map_func of Dataset#map works with dictionaries and other structures: map_func: A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to another nested structure of tensors. Here's an example: import tensorflow as tf filelist = ['fileA_6', 'fileB_10', 'fileC_7'] def map_element_counts(fnames): return {'elementA': b'test', 'elementB': 10, 'file': fnames['filenames']} ds = tf.data.Dataset.from_tensor_slices({'filenames': filelist}) ds = ds.map(map_func=map_element_counts) element = ds.make_one_shot_iterator().get_next() with tf.Session() as sess: print(sess.run(element)) print(sess.run(element)) print(sess.run(element)) Output: {'elementA': 'test', 'elementB': 10, 'file': 'fileA_6'} {'elementA': 'test', 'elementB': 10, 'file': 'fileB_10'} {'elementA': 'test', 'elementB': 10, 'file': 'fileC_7'}
has comment: http://stackoverflow.com/comment/84049901

http://stackoverflow.com/q/48444067
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48444272
answer count: 3
has answer: http://stackoverflow.com/a/48444272
tagged with: pandas
tagged with: python
type: Question
score: 2
upvote count: 2
downvote count: 0
has title: Filtering websites based on specific string
tagged with: string
has answer: http://stackoverflow.com/a/48444853
possible better answer: http://stackoverflow.com/a/48444192
has body: I am currently working on an analysis of urls and want to find urls which match a specific word. Those URLs are in an pandas DataFrame column and I want to filter for specific words in the title of the URL. What I did so far: data['new'] = data['SOURCEURL'].str.extract("(" + "|".join(filter3) +")", expand=False) The problem about this is that the filter that I apply is an abbreviation ('ecb') which is often also used in the end of a link. http://www.ntnews.com.au/news/national/senate-president-stephen-parry-believes-he-is-a-british-citizen/news-story/b2d3a3442544937f85508135401a3f84?nk=f19e52d2acd9588ecb494c03f21fed8c-1509598074 In the last '/'-section. How can I just filter for 'ecb' occurences which occur in textish surrounding? Something like www.xyz.com/news/national/ecb-press-realease/b2dse332313 and which does not extract the occurence of ecb in a hash or something similar as above. Is this possible in an easy way? Thanks a lot!
favorite count: 0
has answer: http://stackoverflow.com/a/48444192

http://stackoverflow.com/comment/83740512
comment on: http://stackoverflow.com/a/48373788
score: 0
type: AnswerComment
has text: I did, man! But this shows me a message saying upvotes from users with reputation less than 15 are recorded but not displayed or something. Haha, I signed up in StackOverflow today just to ask this question. Until now I was an incognito user :)
type: Comment

http://stackoverflow.com/comment/83680740
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48339767
has text: The example code works fine for me using python-2.7. What do you mean by: "it won't work"? What exactly happens? Do you see error messages? Have you checked the csv file to make sure it is not an empty file?
score: 0

http://stackoverflow.com/comment/83806405
type: AnswerComment
comment on: http://stackoverflow.com/a/48372593
has text: Both should work actually. But I'll update the answer
type: Comment
score: 0

http://stackoverflow.com/q/48410012
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48416509
has answer: http://stackoverflow.com/a/48410251
has comment: http://stackoverflow.com/comment/83809672
has comment: http://stackoverflow.com/comment/83809839
linked to: http://stackoverflow.com/q/171765
upvote count: 7
downvote count: 1
score: 6
linked to: http://stackoverflow.com/q/47298543
accepted answer: http://stackoverflow.com/a/48410156
has body: I am currently solving a mathematical problem in which I need to count the number of reduced proper fractions with both numerator and denominator more more than 1000000 (10^6). I have code that works fine for small numbers; the example given (value=8) gives the correct (given) answer 21. But this code seems to be very slow for big numbers for reasons I don't know. I read a whole bunch of similar questions on SO, but couldn't find anything that was useful. I had a closer look at this and this, but that didn't really help me out. My code works with acceptable speed for values until 1000, then it gets super-super-slow. import math def is_prime(n): if n == 2: return True if n % 2 == 0 or n &lt;= 1: return False sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: return False return True def get_divisors(n): liste = [1] if n % 2 == 0: liste.append(2) for divisor in range(3, n+1): if n % divisor == 0: liste.append(divisor) return liste def intersect(a, b): return list(set(a) &amp; set(b)) until = 1000 primes = list() for i in range(int(until)): if i != 1 and i != 0: if is_prime(i): primes.append(i) pos = 0 for i in range(1, until+1): if i%50 == 0: print(i) if is_prime(i): pos += (i-1) else: di = get_divisors(i) di.remove(1) for j in range(1, i): dj = get_divisors(j) if intersect(di, dj)==[]: pos+=1 print(pos) I want to know which parts of my program are reducing the speed and how to fix these issues.
favorite count: 0
has answer: http://stackoverflow.com/a/48422182
type: Question
has comment: http://stackoverflow.com/comment/83810630
has answer: http://stackoverflow.com/a/48412924
has answer: http://stackoverflow.com/a/48410165
possible better answer: http://stackoverflow.com/a/48410165
tagged with: performance
has comment: http://stackoverflow.com/comment/119903087
has comment: http://stackoverflow.com/comment/83875882
tagged with: algorithm
tagged with: python
has answer: http://stackoverflow.com/a/48410156
answer count: 6
linked to: http://stackoverflow.com/q/47229270
linked to: http://stackoverflow.com/q/10941479
has comment: http://stackoverflow.com/comment/83809755
has title: How to count the number of reduced proper fractions fast enough?
has comment: http://stackoverflow.com/comment/83810418
has comment: http://stackoverflow.com/comment/83809736

http://stackoverflow.com/comment/84613331
type: Comment
comment on: http://stackoverflow.com/a/48478396
score: 0
type: AnswerComment
has text: I use threads because I need to calculate values from api in background.

http://stackoverflow.com/q/48389675
has body: I have python 2.7 installed. I installed pip install py2-ipaddress. Ran the following in powershell. The issue is No Output import ipaddress def ipEntered(): while True: try: val = input("Please enter the ip address of the server you wish to connect with:") return ipaddress.ip_address(val) except ValueError: print("Not a valid IP address")
accepted answer: http://stackoverflow.com/a/48389838
answer count: 1
type: Question
has title: Python- IP address module
has comment: http://stackoverflow.com/comment/83767327
tagged with: python
has answer: http://stackoverflow.com/a/48389838
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83943796
type: Comment
comment on: http://stackoverflow.com/a/48466647
type: AnswerComment
score: 0
has text: Indeed! 1. Because you edited your code sample and 2. because you have this line `self.txtFeaturesPath.SetValue = pathname` directly before `self.txtFeaturesPath.SetValue( pathname)`. Remove `self.txtFeaturesPath.SetValue = pathname` and it works!

http://stackoverflow.com/a/48426066
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48386740
upvote count: 2
answers question: http://stackoverflow.com/q/48386740
type: Answer
score: 2
has body: I ended up restructuring the space, which solved the problem: def para_space(): space_paras = {'model_type': hp.choice('model_type', ['features_and_hours', 'features_only', 'hours_only', 'no_features_no_hours']), 'output_units': hp.uniform('output_units', 1, 10), 'kernel_reg': hp.choice('kernel_reg', ['l1', 'l2', 'l1_l2']), 'kernel_reg_value': hp.uniform('kernel_reg_value', 0.0, 0.5), 'activity_reg': hp.choice('activity_reg', ['l1', 'l2', 'l1_l2']), 'activity_reg_value': hp.uniform('activity_reg_value', 0.0, 0.5), 'optimizer': hp.choice('optimizer', ['adadelta', 'adam', 'rmsprop']), 'attention': hp.choice('attention', ['before', 'after', 'none'])} return space_paras

http://stackoverflow.com/comment/83952526
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48461510
type: QuestionComment
has text: Go there to find the working solution: [Link_To_the_solution](https://stackoverflow.com/questions/48479115/getting-200-response-but-not-logging-in-using-python-requests-library). I've already tested that.

http://stackoverflow.com/q/48463629
has title: “first” and “last” functions to columns while using group by in pandas fails
linked to: http://stackoverflow.com/q/15001237
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48463659
has body: I tried to implement the solution provided here and I am getting "invalid syntax" I am trying to get the max value + firs/last value. and my code looks like this: groups = df[df['isTrade'] == 1].groupby('dateTime_s') print(groups.agg({ 'Volume': np.sum, 'tradePrice':[np.max,lambda x: x.iloc[0]], }).head(160)) Thanks for your help!
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48463659

http://stackoverflow.com/comment/83827388
comment on: http://stackoverflow.com/q/48418486
type: QuestionComment
has text: @rocksteady I think this is because it would be redundant with the `command` option. The event that exists is `<<MenuSelect>>` and is triggered when the active (i.e. under the mouse) menu item changes.
score: 1
type: Comment

http://stackoverflow.com/a/48362451
answers question: http://stackoverflow.com/q/48362370
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48362370
type: AcceptedAnswer
downvote count: 0
has body: This sort of thing lends itself very nicely to a generator: Code: def find_triplets(data): data = iter(data) while True: name = next(data) demo = next(data) officer = demo == 'OFFICER' if officer: demo = next(data) yield name, officer, demo Test Code: info = [ 'Joe Schmoe', 'W / M / 64', 'Lillian Schmoe', 'W / F / 60', 'Richard Johnson', 'OFFICER', 'W / M /48', 'Adrian Stevens', '? / ? / 27' ] for x in find_triplets(info): print(x) Results: ('Joe Schmoe', False, 'W / M / 64') ('Lillian Schmoe', False, 'W / F / 60') ('Richard Johnson', True, 'W / M /48') ('Adrian Stevens', False, '? / ? / 27') Converting tuples triplets to dict: import re def fix_demographic(info): # W / M / ?? --&gt; W / M / NaN # ?/M/? --&gt; NaN / M / NaN # Keep as str NaN rather than np.nan for now race, gender, age = re.split('\s*/\s*', re.sub('\?+', 'NaN', info)) return dict(race=race, gender=gender, age=age) data_dict = {name: dict(officer=officer, **fix_demographic(demo)) for name, officer, demo in find_triplets(info)} print(data_dict) Results: { 'Joe Schmoe': {'officer': False, 'race': 'W', 'gender': 'M', 'age': '64'}, 'Lillian Schmoe': {'officer': False, 'race': 'W', 'gender': 'F', 'age': '60'}, 'Richard Johnson': {'officer': True, 'race': 'W', 'gender': 'M', 'age': '48'}, 'Adrian Stevens': {'officer': False, 'race': 'NaN', 'gender': 'NaN', 'age': '27'} }
score: 4

http://stackoverflow.com/q/48477818
type: AnsweredQuestion
has title: Auto suggest choosing input matched selection in selenium python doesnt work
score: 0
answer count: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/48482475
type: Question
has answer: http://stackoverflow.com/a/48482475
has body: I have tried several ways to get autocomplete for selecting input value but not succeeded. It is selecting only first value in drop list. Please help to fix this. first_field = Select(WebDriverWait(browser,20).until(EC.visibility_of_element_located(By.XPATH, "//*[@id='bdy']/div[4]/ul/li")))) #option_select = (browser.find_elements_by_xpath( "//*[@id='bdy']/div[4]ul/li")) for elm in first_field: if(elm.text == (campus_name)): elm.click() WebDriverWait(browser, 20).until(EC.invisibility_of_element_located ((By.XPATH, "//*[@id='campus_result']"))) I am giving input to id :autoCampusId and wants to select from Dropdown list names, which matches my input string. And select only matched string input in dropdown list. Click here to view the source code screen shot
tagged with: python
tagged with: jquery

http://stackoverflow.com/comment/83921465
type: QuestionComment
has text: `{n for n in s if n in '1234567890'} == {'%i' % i for i in range(10)}`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48464062

http://stackoverflow.com/comment/83771133
comment on: http://stackoverflow.com/q/48391502
type: Comment
score: 0
has text: This must be done either with a for-loop or a dict-comprehension where either a filtered version of the second dict (without empty values) or a completely new combined dictionary is created.
type: QuestionComment

http://stackoverflow.com/q/48443525
tagged with: python
tagged with: sqlalchemy
favorite count: 0
score: 4
upvote count: 4
has title: Custom migrations for PostgreSQL Materialized View with SQLAlchemy
type: Question
tagged with: alembic
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I'm trying to auto-generate migrations for materialized views in SQLAlchemy, and the only thing that's not working is detecting changes between revisions. More specifically, it always generates a change, even when the model hasn't changed. I think the problem is, and I could just be using the wrong approach here, is the difference between the SQL generated by schema.compile(compile_kwargs={'literal_binds': True}) and the SQL returned by inspector.get_view_definition(name). Backing up, here's what the model definition looks like, just a simple adjacency list tree. The goal of using the materialized view is the automatically generate a node's depth and path in such a way that it can be queried against: from app.extensions import db # Flask-SQLAlchemy @db.slugify('name') class Node(db.Model): id = db.Column(db.BigInteger, primary_key=True) name = db.Column(db.String, index=True) slug = db.Column(db.String, index=True) parent_id = db.foreign_key('Node', nullable=True) parent = db.relationship('Node', back_populates='children', remote_side=id) children = db.relationship('Node', back_populates='parent') mv = db.relationship('NodeMV', uselist=False, foreign_keys='NodeMV.id', primaryjoin='Node.id == NodeMV.id') depth = db.association_proxy('mv', 'depth') path = db.association_proxy('mv', 'path') _cte = (db.select([Node.id.label('id'), literal(0).label('depth'), literal('/').label('path')]) .where(Node.parent_id is None) .cte(name='nodes_cte', recursive=True)) _union = _cte.union_all( db.select([ Node.id.label('id'), label('depth', _cte.c.depth + 1), label('path', case([(_cte.c.depth == 0, _cte.c.path + Node.slug)], else_=_cte.c.path + '/' + Node.slug))]) .select_from(db.join(_cte, Node, _cte.c.id == Node.parent_id)) ) class NodeMV(db.Model): __tablename__ = 'node_mv' __table__ = create_materialized_view('node_mv', db.select([_union])) db.Index('ix_node_mv_id', NodeMV.id, unique=True) Where the create_materialized_view factory method looks like this: def create_materialized_…

http://stackoverflow.com/a/48368298
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48368201
score: 2
has body: try something like for year in range(2000,2017): file_name = "file_{year}".format(year=year) with open(file_name) as file: file_data = file.read() see the documentation about how to work with files here https://docs.python.org/3/tutorial/inputoutput.html
has comment: http://stackoverflow.com/comment/83724627
type: Answer
answers question: http://stackoverflow.com/q/48368201
upvote count: 2

http://stackoverflow.com/comment/83968708
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48487716
has text: i try changing "default=0" to "default=999". but save value is 0.

negative-number
type: Tag
tags question: http://stackoverflow.com/q/48405046
tag name: negative-number

http://stackoverflow.com/q/48379405
has body: I have extended the Parent class with the Override class. I have have overridden the method() method to fix a bug that occurs in the Parent class. I fixed the said bug and this fix has been tested in the Override class. I use the Override class through an External class. By testing the External class to see if the previous bug is fixed, I discovered that it is not and that the traceback does not go through the Override class. class Parent(): def method(self, param): # Bugged do_stuff() class Override(Parent): def method(self, param): # Fixed (tested) param = fix_param(param) super(Parent, self).method(param) class External(): def processing(): # Same bug as in `Parent` param = get_param() obj = Override() obj.method(param) It seems to me that the External class uses the Parent.method() method instead of the Override.method() method. Any clue on how to fix it or on where this problem comes from? I'm a beginner and have not been confronted inheritance a lot so, please, forgive my ignorance and my lack of experience. EDIT Test that fails in External : import os import collections import envtpl from acquisition.configargparse_confparser import StepConfigFileParser from configparser_extended import ExtendedConfigParser from unittest import TestCase from acquisition.utils import set_custom_environment class ConfigFileParserTestCase(TestCase): def test_parse_extended(self): # x = StepConfigFileParser("test_plugin_name", "test") plugin_name = "test_plugin_name" step_name = "test" set_custom_environment(plugin_name, step_name) config = os.environ.get('MFCONFIG', 'GENERIC') filename = os.path.dirname(os.path.realpath(__file__)) + "/test.ini" with open(filename, 'r') as stream: config_parser = ExtendedConfigParser( config=config, inheritance='im', interpolation=None) content = stream.read() config_parser.read_string(content) # Fails here section = "step_%s" % step_name res = collections.OrderedDict() for key in config_parser.options(section): if not key.startswith('arg_'): con…
has answer: http://stackoverflow.com/a/48379627
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83745612
score: -1
has title: Python library using parent method instead of overriden method
has comment: http://stackoverflow.com/comment/83745922
downvote count: 2
upvote count: 1
tagged with: inheritance
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48337628
downvote count: 0
has body: Using %matplotlib notebook Instead of the inline backend, you may use the notebook backend. This will allow to call figure.canvas.draw() as expected from running the code as a script. Replace the line %matplotlib inline by %matplotlib notebook and restart the Kernel. Using display You may display the newly changed figure after it has been changed. The drawback is that it creates the output twice. A workaround would then be to put interact in a new cell and capture the output from the first cell. %%capture %matplotlib inline from ipywidgets import interact, widgets from IPython.display import display import matplotlib.pyplot as plt import warnings from skimage.morphology import disk from skimage.filters import rank from skimage.color import rgb2gray import skimage.data def f(Median_Size): selem = disk(int(Median_Size)) with warnings.catch_warnings(): warnings.simplefilter("ignore") img_median = rank.median(img_gray, selem=selem) ax_neu.imshow(img_median, cmap="gray") fig.canvas.draw() display(fig) image = skimage.data.camera() #plt.imread("Test.png") img_gray = rgb2gray(image) fig = plt.figure(figsize=(6, 4)) ax_orig = fig.add_subplot(121) ax_neu = fig.add_subplot(122) ax_orig.imshow(img_gray, cmap="gray") ax_neu.imshow(img_gray, cmap="gray") In a new cell interact(f, Median_Size=widgets.IntSlider(min=1,max=21,step=2,value=1)); The output would then look like:
has comment: http://stackoverflow.com/comment/101870398
has comment: http://stackoverflow.com/comment/90261821
answers question: http://stackoverflow.com/q/48335240
type: Answer
score: 13
accepted answer of: http://stackoverflow.com/q/48335240
has comment: http://stackoverflow.com/comment/101870538
upvote count: 13
type: AcceptedAnswer

python-requests
tags question: http://stackoverflow.com/q/48372543
tags question: http://stackoverflow.com/q/48476737
tags question: http://stackoverflow.com/q/48336828
tags question: http://stackoverflow.com/q/48432029
tags question: http://stackoverflow.com/q/48396944
tags question: http://stackoverflow.com/q/48374608
tags question: http://stackoverflow.com/q/48351418
tags question: http://stackoverflow.com/q/48463807
tags question: http://stackoverflow.com/q/48391695
tags question: http://stackoverflow.com/q/48479115
tags question: http://stackoverflow.com/q/48347290
tags question: http://stackoverflow.com/q/48429257
type: Tag
tags question: http://stackoverflow.com/q/48483507
tags question: http://stackoverflow.com/q/48399287
tags question: http://stackoverflow.com/q/48424371
tags question: http://stackoverflow.com/q/48461510
tags question: http://stackoverflow.com/q/48374582
tags question: http://stackoverflow.com/q/48336723
tags question: http://stackoverflow.com/q/48466455
tags question: http://stackoverflow.com/q/48412401
tags question: http://stackoverflow.com/q/48484962
tags question: http://stackoverflow.com/q/48342556
tags question: http://stackoverflow.com/q/48343358
tags question: http://stackoverflow.com/q/48410064
tags question: http://stackoverflow.com/q/48392998
tags question: http://stackoverflow.com/q/48412684
tags question: http://stackoverflow.com/q/48463754
tags question: http://stackoverflow.com/q/48464358
tags question: http://stackoverflow.com/q/48482703
tags question: http://stackoverflow.com/q/48435052
tags question: http://stackoverflow.com/q/48448005
tags question: http://stackoverflow.com/q/48388552
tags question: http://stackoverflow.com/q/48402634
tags question: http://stackoverflow.com/q/48376543
tag name: python-requests
tags question: http://stackoverflow.com/q/48485387
tags question: http://stackoverflow.com/q/48475925
tags question: http://stackoverflow.com/q/48371056
tags question: http://stackoverflow.com/q/48348910
tags question: http://stackoverflow.com/q/48345953
tags question: http://stackoverflow.com/q/48400374
tags question: http://stackoverflow.com/q/48477688
tags question: http://stackoverflow.com/q/48354491
tags question: http://stackoverflow.com/q/48460549
tags question: http://stackoverflow.com/q/48447709
tags question: http://stackoverflow.com/q/48431187
tags question: http://stackoverflow.com/q/48435769
tags question: http://stackoverflow.com/q/48370918
tags question: http://stackoverflow.com/q/48391750
tags question: http://stackoverflow.com/q/48406930
tags question: http://stackoverflow.com/q/48473871
tags question: http://stackoverflow.com/q/48394018
tags question: http://stackoverflow.com/q/48454161
tags question: http://stackoverflow.com/q/48435200
tags question: http://stackoverflow.com/q/48370174

http://stackoverflow.com/comment/83777999
comment on: http://stackoverflow.com/a/48394435
score: 0
type: AnswerComment
has text: Exactly what I'm looking for! The blocking feature of Connection makes it unsuitable to be placed in the main thread.
type: Comment

http://stackoverflow.com/q/48379290
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83746954
tagged with: pytest
has body: I have a base class and two different subclasses (they are in 3 different modules). In the base class I have test methods which I use for the subclasses. I want that the test methods in the base class to use the defined variables from the subclass. But I cannot access to the variables from the subclass, when I run the test methods in subclass. Can someone help me to resolve this problem? P.S.: I cannot use a __init__ constructor (cannot collect test class)! Error with __init__ contructor: No tests found ============================== warnings summary =============================== src/test_icd_operation.py::TestICDFields cannot collect test class 'TestICDFields' because it has a __init__ constructor -- Docs: http://doc.pytest.org/en/latest/warnings.html ========================= 1 warnings in 16.80 seconds ========================= Process finished with exit code 0 Code: class BaseClassExample: table_name = None def test_field_for_both_devices(self): firstname = get_field(table_name) class SubClass1(BaseClassExample): table_name = 'Pacer' def test_field1(): field1 = get_field(table_name) class SubClass2(BaseClassExample): table_name = 'ICD' def test_field2(self): field2 = get_field(table_name) So, when I run the tests in the class SubClass1, I want that variable table_name on the BaseClassExample to take the value Pacer from the variable in subclass SubClass1.
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83746373
has comment: http://stackoverflow.com/comment/83745476
has comment: http://stackoverflow.com/comment/83745267
upvote count: 0
accepted answer: http://stackoverflow.com/a/48381940
answer count: 1
has title: Use defined variable in subclass for methods in base class
has answer: http://stackoverflow.com/a/48381940
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48481972
has comment: http://stackoverflow.com/comment/83957696
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48481889
has body: To communicate between scripts you need to import test_1 as a module: from test_1 import * and change the way you call A to like this: if self.key ==1: self.call_Method_A1 = A.Method_A1(self) else: self.call_Method_A2 = A.Method_A2(self)
answers question: http://stackoverflow.com/q/48481889
type: Answer
has comment: http://stackoverflow.com/comment/83957768
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48383916
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/48384512
has answer: http://stackoverflow.com/a/48384512
score: 0
answer count: 1
has body: I have Django 1.11 app with PostgreSQL. Take a look at code below. Is it possible to have race condition there? I am afraid I could get race condition on diff=-account.hours. Does transaction.atomic save from race condition? from django.db import transaction def write_off(account_ids): accounts = Account.objects.filter(id__in=account_ids) for account in accounts: with transaction.atomic(): MyLog.objects.create( hours=0, operation_type=LOG_OPERATION_WRITE_OFF, diff=-account.hours, ) Account.objects.filter(pk=account.pk).update(hours=0)
has comment: http://stackoverflow.com/comment/83755264
has comment: http://stackoverflow.com/comment/83755660
type: Question
has comment: http://stackoverflow.com/comment/83755009
has title: Django race condition inside a transaction
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83755370
type: AnsweredQuestion

http://stackoverflow.com/q/48467339
has comment: http://stackoverflow.com/comment/83931606
type: Question
type: UnansweredQuestion
has title: Django tutorial 8 pip install Errno 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83930223
has comment: http://stackoverflow.com/comment/83930777
score: 0
answer count: 0
has body: Hello I am following the Django tutorial 8 but then I reach the point where I must pip install --user django-polls/dist/django-polls-0.1.tar.gz I get the error Processing path\django-polls\dist\django-polls-0.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "c:\users\Name\appdata\local\programs\python\python36-32\lib\tokenize.py", line 452, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Name\AppData\Local\Temp\pip-uqc76lp7-build\setup.py' Command "python setup.py egg_info" failed with error code 1 in C:\Users\Name\AppData\Local\Temp\pip-uqc76lp7-build\ I have tried to update pip, setuptools, easyinstall but nothing is working I still get the error. Any help will be greatly appreciated.
has comment: http://stackoverflow.com/comment/83928199
tagged with: pip
has comment: http://stackoverflow.com/comment/83928363

http://stackoverflow.com/a/48485808
type: Answer
has comment: http://stackoverflow.com/comment/84024966
score: 0
answers question: http://stackoverflow.com/q/48485759
has body: A class with so many optional arguments in its constructor is probably a "code smell" and a redesign is in order. I suggest writing some parameter group classes: class ParamSetA: def __init__(param2="someVal", param4="someOtherVal"): self.param2 = param2 self.param4 = param4 class ParamSetB: def __init__(param3, param4): self.param3 = param3 self.param4 = param4 class MyClass(): def __init__(self, params): self.params = params Now it is obvious how to pass the parameters to other related classes: just pass the entire object which encapsulates one valid set of parameters. This also makes validation easier: it is more difficult to construct MyClass with a nonsensical set of parameters (e.g. mutually exclusive parameters, or related parameters).
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83908947
type: Comment
type: QuestionComment
score: 0
has text: Try import os as a whole.
comment on: http://stackoverflow.com/q/48457887

http://stackoverflow.com/comment/84270384
score: 0
comment on: http://stackoverflow.com/q/48340631
has text: updated the script with more details
type: QuestionComment
type: Comment

events
tags question: http://stackoverflow.com/q/48393921
tags question: http://stackoverflow.com/q/48353121
tags question: http://stackoverflow.com/q/48448678
tag name: events
tags question: http://stackoverflow.com/q/48431070
type: Tag

http://stackoverflow.com/comment/83792077
has text: Run the shared code but got below errror >>> import pip Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pip ImportError: No module named 'pip'
type: Comment
comment on: http://stackoverflow.com/a/48401448
score: 0
type: AnswerComment

http://stackoverflow.com/a/48451193
answers question: http://stackoverflow.com/q/48451167
score: 11
type: Answer
upvote count: 11
has body: There's an out parameter, which updates the array in-place: numpy.abs(A, out=A) And also happens to be a lot faster because you don't have to allocate memory for a new array. A = np.random.randn(1000, 1000) %timeit np.abs(A) 100 loops, best of 3: 2.9 ms per loop %timeit np.abs(A, out=A) 1000 loops, best of 3: 647 µs per loop
accepted answer of: http://stackoverflow.com/q/48451167
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48382610
type: Question
tagged with: python-3.x
has title: Custom widget properties in GTK3
upvote count: 2
downvote count: 0
tagged with: python
has body: I have a widget like so: class MyWidget(Gtk.Grid): pass I need to add a custom property to it so that it can be accessed as so: my_widget = MyWidget() my_widget.props.my_custom_property = 12 I could use a property decorator in MyWidget and access it like my_widget.my_custom_property = 12 but I'd like for the widget's interface to be consistent with the other library widgets.
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48382865
answer count: 1
tagged with: gtk3
has answer: http://stackoverflow.com/a/48382865
favorite count: 0

http://stackoverflow.com/q/48406143
tagged with: python
tagged with: rabbitmq
upvote count: 6
has title: integration testing rabbitmq consumer
answer count: 0
has body: I have a simple consumer written in python using pika and rabbitmq. The consumer connects to rabbitmq and listens on a queue. When a message arrives it transforms the message and publishes it on another queue. Presented here: https://bitbucket.org/snippets/fbanke/8e7zbX I would like to make test cases to test the interaction between the consumer and the queue. For example, I would like to make sure that when a message is consumed the "basic_ack" function is called to let rabbitmq know that the message was processed. Another test case is if the consumer reconnects to rabbitmq if the connection gets dropped. And so on. I want to test the interaction between the consumer and the queue not the actual business logic in the consumer. If I mock the pika objects it requires me to understand 100% how the API behaves and any misunderstanding of the API will result in faulty code. Code that passes the tests, but actually doesn't work. I would rather test the consumer using a live queue, and manipulate it from the test to see if the consumer behaves as expected. For example 1. setup the queue 2. start the consumer 3. publish a valid message to the queue 4. assert that the message was consumed by the worker or setup the queue start the consumer kill the queue assert that the worker terminated as expected Does there exist any best-practice on how to do this? I can find many examples of similar tests on databases, but not for queues. It seems that I need to start the consumer in a separate thread and work with it, but it seems that there is no infrastructure to support this.
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/102895743
tagged with: unit-testing
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/83903124
type: Comment
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ: this is different from what you suggested because it works on the externally generated `DataFrame`, as opposed to creating a generic DF from scratch.
comment on: http://stackoverflow.com/a/48453250
score: 0

http://stackoverflow.com/comment/83771360
comment on: http://stackoverflow.com/q/48391636
type: Comment
type: QuestionComment
score: 1
has text: Take the `while` out of the functions, and use another function that calls these alternatively inside an infinite `while`?

http://stackoverflow.com/comment/116102004
has text: Both links still take me to 404 pages.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48379628

opentripplanner
tag name: opentripplanner
tags question: http://stackoverflow.com/q/48410686
type: Tag

http://stackoverflow.com/a/48462750
upvote count: 16
score: 16
accepted answer of: http://stackoverflow.com/q/48461989
answers question: http://stackoverflow.com/q/48461989
has body: So, start with the fact that in Python, ordinarily functions are callable, and classes are callable. Leaving apart the mechanisms that mark functions as callable, Python classes have, as you know, special methods. The method that makes instances of a class callable is __call__. So, if your class has an explicit __call__ method, its instances are callable and end of story: when you call the instance, it is the __call__ method that is called. That answers half your question - now let's check what the __call__ method on the class of classes does. Classes in Python are themselves also first class objects - but they have to be an instance of type. That is, calling type as one calls a class to create an instance, creates a new class. The Python runtime does this automatically when a class body block is met in code. (but one can also create new classes programmaticaly by explicitly calling type in its three+ parameter form) As type itself is a subclass of object - its __new__ method is what it has of special, as it creates a new class, filling up all needed data structures as required by the cPython ABI, allocating memory, and putting values into fields that are not accessible from pure Python codes. As it is the class for any kind of class-object in Python it is called a metaclas. One can derive other classes from type and create custom metaclasses, to run code,r insert attributes, register data and so on at the moment classes are created - but that is optional. Any class created goes through type's __new__. And when you instantiate a class? I wrote above that what makes an object callable in Python is the presence of a __call__ method in its class. type being the class of all classes, it does feature a __call__ method - and it contains the code needed to orchestrate the call to the class' __new__ and __init__ methods. And that is why classes are callable, and why Python can use the same syntax for function calls and object instantiation. is A.__call__() being called each…
type: Answer
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83677501
comment on: http://stackoverflow.com/a/48345836
score: 0
type: AnswerComment
type: Comment
has text: @glibdud I realise that, I was trying to indicate that this answer doesn't really make reference to that, it's more of a "how to fix broken floats"

http://stackoverflow.com/comment/83844387
type: QuestionComment
comment on: http://stackoverflow.com/q/48426401
score: 0
type: Comment
has text: @tgdn, thanks, that worked! Makekigrations worked, but migrate command gave me this: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'

http://stackoverflow.com/a/48435631
has comment: http://stackoverflow.com/comment/83865199
type: Answer
answers question: http://stackoverflow.com/q/48435479
score: 0
downvote count: 2
has body: This will likely work with sep='","' like: spark.read.csv('file.csv', sep='","')
upvote count: 2

http://stackoverflow.com/comment/83756750
type: AnswerComment
comment on: http://stackoverflow.com/a/48384512
type: Comment
has text: Updating all accounts at once is not a good idea, because if one update fails, all updates would be rolled back.
score: 0

http://stackoverflow.com/a/48509913
type: Answer
score: 2
has body: You should make use of the built-in Endpoints JSON code. This is not exact, but something like this: from endpoints import protojson p = protojson.EndpointsProtoJson() p.decode_message(Address, '{...}')
downvote count: 0
answers question: http://stackoverflow.com/q/48485293
upvote count: 2

http://stackoverflow.com/comment/84010940
type: Comment
has text: See if this helps - https://stackoverflow.com/q/6832554/2650427
type: QuestionComment
comment on: http://stackoverflow.com/q/48464565
score: 2

http://stackoverflow.com/comment/83707007
comment on: http://stackoverflow.com/a/48359943
type: AnswerComment
has text: I forget for separator is `sep=';'`
score: 1
type: Comment

http://stackoverflow.com/q/48441698
has title: OpenCV get subimages by mask
answer count: 1
tagged with: python
score: -1
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48443070
downvote count: 1
has body: Have you any ideas how can I with python and OpenCV get subimages on original image by that mask? I need separated subimages of every white area. Because it's not rects it's hard to get them separated.
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48443070
upvote count: 0

http://stackoverflow.com/comment/83907379
has text: Where is your code? What exactly are you trying?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48456624

http://stackoverflow.com/comment/83933260
type: QuestionComment
comment on: http://stackoverflow.com/q/48469708
score: 0
has text: For any returned value, you can act on it with a subsequent function. `something().dosomethingwiththatthing().again().etc()`
type: Comment

http://stackoverflow.com/comment/83826468
comment on: http://stackoverflow.com/q/48415382
has text: Had a look at that earlier, seems good. @sal Thanks
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/83902282
type: Comment
type: QuestionComment
score: 0
has text: The mathematical median of three values would be `(max + min) / 2`...
comment on: http://stackoverflow.com/q/48454373

atom-editor
tags question: http://stackoverflow.com/q/48434112
tags question: http://stackoverflow.com/q/48433978
type: Tag
tag name: atom-editor
tags question: http://stackoverflow.com/q/48481203
tags question: http://stackoverflow.com/q/48383433
tags question: http://stackoverflow.com/q/48433878
tags question: http://stackoverflow.com/q/48429246
tags question: http://stackoverflow.com/q/48468686

pyqt5
tags question: http://stackoverflow.com/q/48390893
tags question: http://stackoverflow.com/q/48348491
tags question: http://stackoverflow.com/q/48343322
type: Tag
tags question: http://stackoverflow.com/q/48415208
tags question: http://stackoverflow.com/q/48433529
tags question: http://stackoverflow.com/q/48357440
tags question: http://stackoverflow.com/q/48347409
tags question: http://stackoverflow.com/q/48353398
tags question: http://stackoverflow.com/q/48349587
tags question: http://stackoverflow.com/q/48433481
tags question: http://stackoverflow.com/q/48419373
tags question: http://stackoverflow.com/q/48374487
tags question: http://stackoverflow.com/q/48399579
tags question: http://stackoverflow.com/q/48357025
tags question: http://stackoverflow.com/q/48341411
tags question: http://stackoverflow.com/q/48405646
tags question: http://stackoverflow.com/q/48366776
tags question: http://stackoverflow.com/q/48451061
tags question: http://stackoverflow.com/q/48416110
tags question: http://stackoverflow.com/q/48386253
tags question: http://stackoverflow.com/q/48416936
tags question: http://stackoverflow.com/q/48407081
tags question: http://stackoverflow.com/q/48461452
tags question: http://stackoverflow.com/q/48454086
tags question: http://stackoverflow.com/q/48341631
tags question: http://stackoverflow.com/q/48370525
tags question: http://stackoverflow.com/q/48488308
tag name: pyqt5
tags question: http://stackoverflow.com/q/48441863
tags question: http://stackoverflow.com/q/48425994
tags question: http://stackoverflow.com/q/48367665
tags question: http://stackoverflow.com/q/48433383
tags question: http://stackoverflow.com/q/48370347
tags question: http://stackoverflow.com/q/48451224
tags question: http://stackoverflow.com/q/48437262
tags question: http://stackoverflow.com/q/48425074
tags question: http://stackoverflow.com/q/48447053
tags question: http://stackoverflow.com/q/48379373

http://stackoverflow.com/q/48411890
has answer: http://stackoverflow.com/a/48459958
possible better answer: http://stackoverflow.com/a/48459958
tagged with: flask
has answer: http://stackoverflow.com/a/48490931
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48490931
score: 0
answer count: 2
tagged with: validation
tagged with: formfield
type: Question
has title: Flask Validation Error 'NoneType is not iterable' from RadioField in FormList of FormFields?
has body: I'm dynamically populating a form in Flask using a FormList of FormFields but am at a loss with an error from the validation function. On this form, the user provides an entry name and then for each game queried from a database table, picks one from a RadioField and ranks their confidence in their pick 1-N. I've tested the validation with a test that was hard-coded, and I've gotten the dynamic field generation below to work, but when I try to validate the below it fails when iterating through games-#-pick with 'NoneType' is not iterable. I believe this is because the loop keeps going beyond my bounds. In my test I only have three entries in games, so idx is 0,1,2 and I should see three PickForms generated. When validate fails I see self.name is games-3-pick, so validate is checking one more FormField in my FormList than I though should have been generated. How do I validate this? Is it an issue with the FormField validation, or how I'm dynamically appending_entry() to the FormList? @bp.route('/pick', methods=['GET', 'POST']) def pick(): games = Game.query.order_by(Game.game_date.asc()).all() form = EntryForm() for idx, g in enumerate(games): form.games.append_entry() form.games[idx].pick.label = g.bowl_name form.games[idx].pick.choices = [('away', g.away), ('home', g.home)] if form.validate_on_submit(): ...database writes and redirect if validated... class PickForm(FlaskForm): pick = RadioField(validators=[DataRequired()]) weight = IntegerField('Weight', validators=[DataRequired()]) class EntryForm(FlaskForm): name = StringField('Entry Name', validators=[DataRequired()]) games = FieldList(FormField(PickForm)) submit = SubmitField('Submit') def validate(self): if not super(EntryForm, self).validate(): return False result = True seen = set() for pick in self.games: if (pick.weight.data in seen and pick.weight.data &lt;= len(self.games)): pick.errors.append('Please rank reach pick from 1 to {} with no repeats.'.format(len(self.games))) result = False else: seen.add(pic…
tagged with: wtforms
tagged with: python

http://stackoverflow.com/q/48448005
has comment: http://stackoverflow.com/comment/83888636
downvote count: 0
has comment: http://stackoverflow.com/comment/83888929
upvote count: 1
tagged with: python-requests
favorite count: 0
accepted answer: http://stackoverflow.com/a/48448141
type: Question
possible better answer: http://stackoverflow.com/a/48448268
has answer: http://stackoverflow.com/a/48448141
has answer: http://stackoverflow.com/a/48448268
tagged with: lxml.html
tagged with: python
has body: I am trying to get the hidden elements in twitter login page. I followed a procedure which simply gets the hidden elements in that page. But the problem is when i try to get value of those elements, i am getting key error. the code is: import requests, lxml.html from bs4 import BeautifulSoup s = requests.session() login = s.get('https://twitter.com/login') login_html = lxml.html.fromstring(login.text) hidden_inputs = login_html.xpath(r'//form//input[@type="hidden"]') form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs} print(form) I am getting error at x.attrib['value']. How to rectify this?
has answer: http://stackoverflow.com/a/48448110
has comment: http://stackoverflow.com/comment/83888422
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/83888376
score: 1
has title: KeyError in python saying KeyError : 'value'

http://stackoverflow.com/comment/83760689
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48386418
has text: Have you checked the following: https://stackoverflow.com/questions/35961371/pip-install-django-error/39618607#39618607 https://stackoverflow.com/questions/8951862/installing-python-and-distribute-on-windows-7-gives-writing-failed-permissi ?
score: 0

http://stackoverflow.com/q/48403504
linked to: http://stackoverflow.com/q/17778372
duplicate of: http://stackoverflow.com/q/17778372
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/83795327
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83795417
tagged with: python
has body: I would like to create a Python class which should have a dynamic iterator function. That is, I would like to send the iterator function as a parameter instead of hardcoding it inside the class. Here is an example class: class fib: def __init__(self, items, iter_function): self.iter_function = iter_function self.items = items def __iter__(self): self.iter_function(self.items) with two example iterator functions: def iter_func(items): for item in items: yield item def iter_func2(items): for item in items: yield item*2 When I create an object with the following, I get an error: a = fib([1,2,3],iter_func) next(iter(a)) The error prints as: ----&gt; 1 next(iter(a)) TypeError: iter() returned non-iterator of type 'NoneType' Any ideas are appreciated.
has title: Python class with dynamic __iter__ function
has comment: http://stackoverflow.com/comment/83795324
score: 0
tagged with: iterator
answer count: 0

http://stackoverflow.com/q/48335367
has comment: http://stackoverflow.com/comment/83655797
tagged with: scikit-learn
tagged with: roc
has title: Changing the colours and styles of the curves on an ROC Graph
has comment: http://stackoverflow.com/comment/83658353
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/7799156
tagged with: python
has comment: http://stackoverflow.com/comment/83655821
linked to: http://stackoverflow.com/q/7799156
has comment: http://stackoverflow.com/comment/83658736
type: Question
answer count: 0
type: UnansweredQuestion
score: 0
has body: I'm currently doing a project on Fake News Detection, and trying to compare the accuracies of different algorithms that I have utilized. Now I have the ROC curves, which look like this: So far what I have managed to code is this: plt.figure(0).clf() for model, name in [ (mn_count_clf, 'multinomial nb count'), (mn_tfidf_clf, 'multinomial nb tfidf'), (pa_tfidf_clf, 'passive aggressive'), (svc_tfidf_clf, 'svc'), (sgd_tfidf_clf, 'sgd')]: if 'count' in name: pred = model.predict_proba(count_test)[:,1] elif 'multinomial' in name: pred = model.predict_proba(tfidf_test)[:,1] else: pred = model.decision_function(tfidf_test) fpr, tpr, thresh = metrics.roc_curve(y_test.values, pred, pos_label='REAL') plt.plot(fpr,tpr,label="{}".format(name)) plt.legend(loc=0) which is in python, used from scikit-learn. The curves are of different colours, which is partially what I'd hoped for. Now, what I'm trying to do, for the sake of clarity, is to change the styles of the different plots that are , i.e. use dotted lines, dashed lines and lines of different colours for different plots. Any help is appreciated.

http://stackoverflow.com/a/48453225
downvote count: 0
has comment: http://stackoverflow.com/comment/83899612
type: Answer
has comment: http://stackoverflow.com/comment/83899544
has comment: http://stackoverflow.com/comment/83899745
has body: Initialise as an object DataFrame (at your peril...): df = pd.DataFrame({"a":[1,None],"b":[None,"foo"]}, dtype=object) df a b 0 1 None 1 None foo In the first column, pandas attempts to infer the dtype, and guesses float. You can prevent that by forcing it to remain object thereby suppressing any type of conversion at all.
score: 3
has comment: http://stackoverflow.com/comment/83899571
upvote count: 3
has comment: http://stackoverflow.com/comment/83899640
has comment: http://stackoverflow.com/comment/83899524
has comment: http://stackoverflow.com/comment/83899601
has comment: http://stackoverflow.com/comment/83899659
answers question: http://stackoverflow.com/q/48453186
has comment: http://stackoverflow.com/comment/83899974

http://stackoverflow.com/comment/83708956
has text: And make sure to use an OS that will cache the files (e.g. Linux). That'll eliminate repeated HDD/SSD transactions. SSDs are fast, but they're no where near as fast as your machine's RAM. With enough RAM spare there's a good chance that all of A (and less importantly B) would effectively be held in RAM.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48360840

http://stackoverflow.com/comment/84058134
score: 0
has text: @camel_case nop, it returns the column, a `std::vector<int>`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48504114

http://stackoverflow.com/comment/83935538
score: 0
type: QuestionComment
has text: `all(list1[index] == list2[len(list2) - index - 1] for index in range(len(list1)))`
comment on: http://stackoverflow.com/q/48470778
type: Comment

http://stackoverflow.com/q/48377506
tagged with: matlab
has comment: http://stackoverflow.com/comment/83741809
has body: I have a variable named mesh of type object extracted from a MATLAB .mat file. (EDIT: Reproducible example below) In [1]: mesh Out[1]: array([[ array([[ (array([[ 89, 108]], dtype=uint8), array([[-131.659809], [-131.659809], [-131.659809], ..., [ 52.022239], [ 52.022239], [ 52.022239]]), array([[ 189.358345], [ 187.271049], [ 185.183753], ..., [ -29.807736], [ -31.895032], [ -33.982328]]))]], dtype=[('dim', 'O'), ('x', 'O'), ('y', 'O')])]], dtype=object) How can I access the individual arrays dim, x and y? Reproducible example: I am unable to assign dtype=uint8 to an array as in the imported object. Also, the imported object has object size (1,1) while this example has object size (1,1,1,1). import numpy as np mesh = np.array([[ np.array([[ (np.array([[ 6, 6]], dtype=float), np.array([[-131.659809], [-131.659809], [-131.659809], [ 52.022239], [ 52.022239], [ 52.022239]]), np.array([[ 189.358345], [ 187.271049], [ 185.183753], [ -29.807736], [ -31.895032], [ -33.982328]]))]], dtype=[('dim', 'O'), ('x', 'O'), ('y', 'O')])]], dtype=object)
type: AnsweredQuestion
tagged with: object
score: 0
has comment: http://stackoverflow.com/comment/83743240
has comment: http://stackoverflow.com/comment/83742303
has comment: http://stackoverflow.com/comment/83742951
tagged with: python
has title: Extract array from object in Python
has comment: http://stackoverflow.com/comment/83743122
type: Question
tagged with: mat
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48378752
has comment: http://stackoverflow.com/comment/83742551
has answer: http://stackoverflow.com/a/48378752

http://stackoverflow.com/comment/83764097
score: 0
type: Comment
type: QuestionComment
has text: No, they are multi-column
comment on: http://stackoverflow.com/q/48388144

http://stackoverflow.com/q/48429743
has comment: http://stackoverflow.com/comment/83851882
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83852253
linked to: http://stackoverflow.com/q/30813044
answer count: 1
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/48431566
tagged with: scikit-learn
has title: Why is scikit learn's average precision score returning nan?
has body: My Keras model is designed to take in two input time series, concatenate them, feed them through an LSTM, and do multilabel prediction on the next time step. There are 50 training samples, with 24 time steps each, and 5625 labels each. There are 12 validation samples, with 24 time steps each, and 5625 labels each. When I try to validate the model, I get 'nan' for average_precision_score. Why? I've prepared an MWE below, illustrating the problem: import numpy as np from sklearn.metrics import average_precision_score from keras.models import Model from keras.layers import Input, LSTM, Dense, Concatenate, multiply from keras import optimizers import tensorflow as tf def model_definition(): tr_hours, val_hours = [], [] for i in np.arange(a_tr.shape[0]): for j in np.arange(a_tr.shape[1]): tr_hours.append(i+j) for i in np.arange(a_val.shape[0]): for j in np.arange(a_val.shape[1]): val_hours.append(i+j) tr_hours = np.asarray(tr_hours).reshape(a_tr.shape[0], a_tr.shape[1], 1) val_hours = np.asarray(val_hours).reshape(a_val.shape[0], a_val.shape[1], 1) num_time = a_tr.shape[2] + tr_hours.shape[2] hours_in = Input(shape=(1,), batch_shape = (1, 1, tr_hours.shape[2]), name='hours_in') seq_model_in = Input(shape=(1,), batch_shape=(1, 1, a_tr.shape[2]), name='seq_model_in') t_concat = Concatenate(axis=-1)([seq_model_in, hours_in]) lstm_layer = LSTM(4, batch_input_shape=(1, 1, num_time), stateful=True)(t_concat) dense_merged = Dense(a_tr.shape[2], activation="sigmoid", name='dense_after_lstm')(lstm_layer) model = Model(inputs=[seq_model_in, hours_in], outputs=dense_merged) return tr_hours, val_hours, model def train_and_validate(a_tr, a_old_tr, a_val, a_old_val): a_tr = a_tr[:, :-1, :] y_tr = a_tr[:, -1, :] a_val = a_val[:, :-1, :] y_val = a_val[:, -1, :] a_old_tr = a_old_tr[:, :-1, :] y_old_val = a_old_val[:, -1, :] y_old_tr = a_old_tr[:, -1, :] seq_length = a_tr.shape[1] tr_hours, val_hours, model = model_definition() print model.summary() model.compile(loss='binary_crossentropy…
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/83852233
type: Question
has comment: http://stackoverflow.com/comment/83852354
has comment: http://stackoverflow.com/comment/83852081
has answer: http://stackoverflow.com/a/48431566
tagged with: time-series
has comment: http://stackoverflow.com/comment/83852402
has comment: http://stackoverflow.com/comment/83852153
tagged with: python

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

http://stackoverflow.com/q/48475858
answer count: 1
favorite count: 0
type: Question
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/83945458
has comment: http://stackoverflow.com/comment/83947998
has comment: http://stackoverflow.com/comment/83945023
has comment: http://stackoverflow.com/comment/83948033
score: 1
tagged with: python
has title: Creating Objects with Different Environment Variables
has comment: http://stackoverflow.com/comment/83944939
has answer: http://stackoverflow.com/a/48477398
accepted answer: http://stackoverflow.com/a/48477398
type: AnsweredQuestion
downvote count: 0
tagged with: environment-variables
upvote count: 1
tagged with: multithreading
has comment: http://stackoverflow.com/comment/83947754
has body: class SomeThing(object): def __init__(self, name): self.name = name #to parallelizing os.environ['FOO'] = "http://localhost:1135" + str(self.name) + '/' def run(self): ... I want that every time I create object with different 'name' (name is 'int' input), my object runs with different environment variable. I tried to call as follows: some2 = Something(9) some1 = Something(1) #job2 = lambda: some2.run() t2 = threading.Thread(target=some2.run(), name = 'job2') t2.start() #job1 = lambda: some1.run() t1 = threading.Thread(target=some1.run(), name = 'job1') t1.start() But both thread are working with the environment variable of the some2 (the first created object's variable).

http://stackoverflow.com/comment/84245431
score: 0
type: Comment
has text: Thanks a lot! It helps!
type: AnswerComment
comment on: http://stackoverflow.com/a/48379664

http://stackoverflow.com/comment/83696653
comment on: http://stackoverflow.com/a/48353869
score: 0
type: AnswerComment
type: Comment
has text: so what needs to be done on this. I've written all my logic on xlsxwriter and now I've to use openpyxl. any luck how to use it?

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/48337339

http://stackoverflow.com/q/48360749
has title: Executing code after waiting for time in background (Python)
accepted answer: http://stackoverflow.com/a/48360904
has body: I'm making a personal assistant like Google Assistant or Siri, and I want the user to be able to set reminders. For example, if they type "Remind me to wash the dishes at 5pm" I would like it to pop up later and remind them. However I also want code to be able to run while waiting, so you could set multiple reminders or check the weather. time.sleep simply stops the program. I'm pretty sure there's a way to do it with threads but I'm not sure how. Please help!
type: Question
has answer: http://stackoverflow.com/a/48360904
tagged with: time
tagged with: multithreading
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/48454543
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83908129
answers question: http://stackoverflow.com/q/48454484
score: 3
has comment: http://stackoverflow.com/comment/83902612
has comment: http://stackoverflow.com/comment/83902796
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48454484
has body: The easiest way is probably to use a dict for the constructor: In [17]: data = [array([2, 1, 4, 1]), array([2, 4, 4, 2]), array([2, 2, 4, 0])] In [18]: pd.DataFrame({'4x1 Vectors':data}) Out[18]: 4x1 Vectors 0 [2, 1, 4, 1] 1 [2, 4, 4, 2] 2 [2, 2, 4, 0] Note, pandas is not designed with the use-case of arrays as elements in mind. That is why the constructor is trying to interpret your data-argument as a 3x4 dataframe instead of a 3x1 Alternatively, change the "shape" of your list and make your columns argument a sequence of lists: In [21]: pd.DataFrame([[d] for d in data], columns=['4x1 vectors']) Out[21]: 4x1 vectors 0 [2, 1, 4, 1] 1 [2, 4, 4, 2] 2 [2, 2, 4, 0] But I repeat: you almost certainly don't want to do this. DataFrames don't work well with arrays as elements.
has comment: http://stackoverflow.com/comment/83902190

http://stackoverflow.com/comment/83763421
comment on: http://stackoverflow.com/q/48387758
score: 0
has text: Would you please help me understand more where I didnot fix the indentation and Ri being empty? Trust me, I am just learning python so some of these terms are hard to understand. I did fix the indentation of the entire code on my side.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48455021
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48515051
has comment: http://stackoverflow.com/comment/83910341
has answer: http://stackoverflow.com/a/48455376
favorite count: 0
has title: How to handle an extremely big table in a search?
has body: I'm looking for suggestions on how to go about handling the following use case scenario with python django framework, i'm also open to using javascript libraries/ajax. I'm working with pre-existing table/model called revenue_code with over 600 million rows of data. The user will need to search three fields within one search (code, description, room) and be able to select multiple search results similar to kendo controls multi select. I first started off by combining the codes in django-filters as shown below, but my application became unresponsive, after waiting 10-15 minutes i was able to view the search results but couldn't select anything. https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html I've also tried to use kendo controls, select2, and chosen because i need the user to be able to select as many rev codes as they need upward to 10-20, but all gave the same unresponsive page when it attempted to load the data into the control/multi-select. Essentially what I'm looking for is something like this below, which allows the user to select multiple selections and will handle a massive amount of data without becoming unresponsive? Ideally i'd like to be able to query my search without displaying all the data. https://petercuret.com/add-ajax-to-django-without-writing-javascript/ Is Django framework meant to handle this type of volume. Would it be better to export this data into a file and read the file? I'm not looking for code, just some pointers on how to handle this use case.
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48455376
type: Question
has answer: http://stackoverflow.com/a/48515051
answer count: 2
linked to: http://stackoverflow.com/q/5350581
downvote count: 0
tagged with: django
tagged with: javascript

http://stackoverflow.com/comment/83651072
score: 0
comment on: http://stackoverflow.com/q/48332632
type: Comment
type: QuestionComment
has text: I recently had trouble with Excel reading and writing, and traced it ultimately to an incompatibility between my version of pandas and my version of *xlrd* (not the engine you are using, but the concept is the same). In my case, I used the keyword argument *sheetname=1* only to find that the keyword had been changed to *sheet_name*, and the reader would not read. So perhaps your writer is failing in a similar strange way. In the end, I had to use the PyDev debugger to follow the execution into the engine code.

http://stackoverflow.com/comment/83901830
type: Comment
has text: @kmario23 I rewrote main statement in a more explicit way.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48454041

http://stackoverflow.com/a/48537722
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48484403
type: Answer
has body: I believe inputs are dictionaries of lists: d1 = {'Class A' : ['Section A', 'Section B', 'Prem 1'], 'Class B' : ['Section C', 'Section D', 'Section E'], 'Class C': ['Section F', 'Prem 2', 'Prem 3']} d2 = {'Premiums' : ['Prem 1', 'Prem 2', 'Prem 3']} Swap values of lists with keys and filter out Prem values for first dict: d11 = {k: oldk for oldk, oldv in d1.items() for k in oldv if not 'Prem' in k} d21 = {k: oldk for oldk, oldv in d2.items() for k in oldv} Join dictionaries together: d3 = {**d11, **d21} Group by columns with final dictionary and aggregate sum: df1 = df.groupby(d3, axis=1).sum() Last add column for count non 0 Premium columns: df1['no_of_prem']= df'Prem 1','Prem 2','Prem 3'.ne(0).sum(axis=1) print (df1) Class A Class B Class C Premiums no_of_prem 0 12 25 45 21 2 1 28 73 24 35 3 2 43 46 17 20 1 3 37 58 4 54 3 4 37 20 14 48 3 Another solution is create tuples from dictinaries, join them together: L1 = [(oldk, k) for oldk, oldv in d1.items() for k in oldv if not 'Prem' in k] L2 = [(oldk, k) for oldk, oldv in d2.items() for k in oldv] Then create MultiIndex by MultiIndex.from_tuples, reindex columns for first level used for aggregate sum: mux = pd.MultiIndex.from_tuples(L1 + L2) df1 = df.reindex(columns=mux, level=1).sum(level=0, axis=1) df1['no_of_prem']= df'Prem 1','Prem 2','Prem 3'.ne(0).sum(axis=1) print (df1) Class B Class C Class A Premiums no_of_prem 0 25 45 12 21 2 1 73 24 28 35 3 2 46 17 43 20 1 3 58 4 37 54 3 4 20 14 37 48 3
accepted answer of: http://stackoverflow.com/q/48484403
downvote count: 0
score: 1

http://stackoverflow.com/a/48419524
type: Answer
score: 0
has body: You can also delete documents with matching multiple fields. curl -XDELETE 'http://localhost:9200/mqtt-index-*/logs/_query' -d '{ "query" : { "bool": { "must":[ {"match" : {"device_id":31}}, {"match": {"datastream_name": "test"}} ] } }' -i
answers question: http://stackoverflow.com/q/48394493

http://stackoverflow.com/q/48360544
type: UnansweredQuestion
has title: Tkinter Variable Out Of Scope
linked to: http://stackoverflow.com/q/39438573
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/17466561
has comment: http://stackoverflow.com/comment/83707868
has comment: http://stackoverflow.com/comment/83707917
has body: I have a toplevel window that pops up off of root. It builds all the necessary widgetes on creation, which I then want to be filled and submitted. The problem is, all the variables I define in the new window go out of scope when I call the submit command. I really don't want to call everything a global because this window will be destroyed and recreated several times. Here's my relevent code: def add_item(): window = Toplevel(root) window.title("Add Item") window.geometry("400x150") name = Entry(window, width=40) name.grid(row=0, column=1, sticky=W) name.insert(0, "Name") Button(window,text="Submit Item",command=submit_item).place(relx=0.5,rely=0.9,anchor=S) def submit_item(): print(name.get()) I end up with the error: print(name.get()) NameError: name 'name' is not defined
has comment: http://stackoverflow.com/comment/83707895
has comment: http://stackoverflow.com/comment/83707842
score: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83707874
answer count: 0
has comment: http://stackoverflow.com/comment/83709570
has comment: http://stackoverflow.com/comment/83711937
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83707991
upvote count: 2

http://stackoverflow.com/q/48354279
tagged with: sql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83697145
has comment: http://stackoverflow.com/comment/83698249
has title: How do I split the "rating" field
tagged with: excel
has body: so I'm looking at this dataset using Excel. Is there anyway to split it so that : I have the string "Funny", "Beautiful" as column names and the value of "count" for every row ? I was able to split the column so that I have all the genres in the rows. But, they way I want is for the genres to be column names and the value of count in the rows. Thanks.
tagged with: python
type: Question
score: 0
answer count: 0

http://stackoverflow.com/comment/84230453
comment on: http://stackoverflow.com/a/48581391
type: Comment
score: 0
type: AnswerComment
has text: it's automatic log of requests module... i can't separate it with my own.

http://stackoverflow.com/a/48430361
downvote count: 0
upvote count: 1
has body: From pytest cannot import module while python can Remove __init__.py in the test folder. That way, the test will use the liba installed in the system instead of liba within the source code.
type: Answer
answers question: http://stackoverflow.com/q/48430042
accepted answer of: http://stackoverflow.com/q/48430042
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48450649
accepted answer of: http://stackoverflow.com/q/48450555
has comment: http://stackoverflow.com/comment/83894348
answers question: http://stackoverflow.com/q/48450555
has comment: http://stackoverflow.com/comment/83894501
type: Answer
has comment: http://stackoverflow.com/comment/83894412
upvote count: 2
score: 2
downvote count: 0
has body: Yes. Django comes with an in-built testing module/framework which is very much useful in mocking your api/routes and also redirects as well. This has extensive use of Django Testcase and uses TDD model of development Here is an example. from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from django import forms from accounts.forms import RegistrationForm, LoginForm class AccountsTests(TestCase): def setUp(self): self.register_data = { 'email': 'xyz@gmail.com', 'username': 'new_user1', 'password': 'test', 'password_confirmation': 'test' } User.objects.create_user('test', 'test@example.com', 'test') def tearDown(self): User.objects.get(username='test').delete() def test_get_register(self): response = self.client.get(reverse('auth:register')) self.assertTemplateUsed(response, 'accounts/register.html') self.assertIsInstance(response.context['form'], RegistrationForm) def test_get_login(self): response = self.client.get(reverse('auth:login')) self.assertTemplateUsed(response, 'accounts/login.html') self.assertIsInstance(response.context['form'], LoginForm) def test_register(self): response = self.client.post( reverse('auth:register'), data=self.register_data ) self.assertRedirects(response, '/auth/login/') # new user was created
has comment: http://stackoverflow.com/comment/83894257
type: AcceptedAnswer

http://stackoverflow.com/a/48353197
has body: You need to do the indexing in one step. For what you're trying to do, this will work: a[b[:, np.newaxis], b] += 1 print(a) # array([[ 1, 2, 3], # [ 4, 6, 7], # [ 7, 9, 10]]) When you index an array with multiple lists of indices, those lists are broadcast together to index into the array. So if you have a 2x1 index and a 1x2 index, the resulting array slice is 2x2, and in this case references the 2x2 section of the array you were hoping to modify.
score: 0
answers question: http://stackoverflow.com/q/48353164
type: Answer

http://stackoverflow.com/comment/83923671
type: QuestionComment
comment on: http://stackoverflow.com/q/48449045
score: 0
has text: @TerryJanReedy Yes, I'm using a global `if sys.version_info[0] < 3:` `else:` format for importing Python2 and Python3 tk modules in the same script. Both windows were on the same screen at the same time when the screenshot was taken; one from IDLE, one from Terminal. Thank you for your feedback on aesthetics, perhaps I should up the contrast on the image I'm using to pull out those colors more. Regardless, the image I preferred prior to your valued feedback was the one on the left (IDLE).
type: Comment

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

http://stackoverflow.com/comment/83733582
score: 0
type: Comment
has text: I understand that, is it possible to grab the file just using requests in Python though?
comment on: http://stackoverflow.com/q/48373164
type: QuestionComment

http://stackoverflow.com/q/48411582
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83813048
has comment: http://stackoverflow.com/comment/83812970
has body: Apologies if this is a duplicate at all, but, I can't seem to get my head around some of the rules around mutability. I have a scenario which is similar to the one below: from multiprocessing import Pool; class myObj: def __init__(self): self.results = []; def doThing(self): self.results.append(1); def wrapDoThing(o): o.doThing(); return o; objList = [myObj(),myObj()]; map(wrapDoThing,objList); print(len(objList[0].results)); #prints 1 tPool = Pool(2); tPool.map(wrapDoThing,objList); print(len(objList[0].results)); #prints 1 - why? I have a class which has an instance field, and a method that updates that instance field, thereby updating the objects state. if I use the builtin map (I'm using a function declared at the top level as a wrapper - clearer later) the method call happens for each object and updates the state, as the results field in the class has a length of 1. When I use the Pool.map (which is why I used the wrapper, as I don't believe I can use a lambda, can I?), the method's effect doesn't seem to take hold, and I'm not sure as to why this is happening?
has title: Pool.map vs map
score: 0
has comment: http://stackoverflow.com/comment/83813083
has comment: http://stackoverflow.com/comment/83812939
has answer: http://stackoverflow.com/a/48411856
answer count: 1
type: Question

http://stackoverflow.com/comment/83715715
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48364250
type: Comment
has text: Please add the full error traceback and the code of `downliadFile()` to your question!

http://stackoverflow.com/a/48450797
upvote count: 8
type: Answer
has body: Use shutdown() Tell the serve_forever() loop to stop and wait until it does. New in version 2.6. docs.python.org/2/library/socketserver.html For your code it should be as simple as httpd.serve_forever() print('httpd server has been successfully started ') httpd.shutdown() httpd.server_close() print('httpd server has been successfully stopped') I will leave it to the OP to better use this and the example at the bottom of the linked page appropriatly for the desired requirment.
score: 8
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48450053
answers question: http://stackoverflow.com/q/48450053

http://stackoverflow.com/comment/83905531
score: 0
type: Comment
type: QuestionComment
has text: When you are a beginner (and probably an experienced programmer as well), all your program names should start with 'my', e.g.`my_matplotlib1.py`
comment on: http://stackoverflow.com/q/48456028

http://stackoverflow.com/q/48408751
has body: I have a list of dictionaries: some_list = [ { item1:'a', item2:['1', '2'] }, { item1:'b', item2:['1', '2'] }, { item1:'a', item2:['1'] } ] I would like to get: ['a 1', 'a 2', 'b 1', 'b 2'] where each value from item 1 is paired with value from item 2 for each dictionary, and then only the unique strings are left. I can think of an obvious way to do it, namely: iterate through the some_list; for each dictionary, get a each['item_1'] and each['item_2'] for member of each['item_2'] do each['item_1'] + ' ' + member Now, make the list into a set and I have my unique values I am wondering if these is a more elegant way to do it using list comprehension.
has answer: http://stackoverflow.com/a/48408878
has comment: http://stackoverflow.com/comment/83807075
tagged with: python
tagged with: dictionary
score: 4
accepted answer: http://stackoverflow.com/a/48408920
upvote count: 4
type: AnsweredQuestion
tagged with: list
answer count: 3
has title: Elegant way of finding unique string pairs from dictionary values in a list of dictionaries
has answer: http://stackoverflow.com/a/48409374
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/83807030
possible better answer: http://stackoverflow.com/a/48408878
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48408920

http://stackoverflow.com/comment/84011032
type: AnswerComment
has text: It's running on a shared GPU server and someone else is running a high memory application now so I'll try again later and should work. Thanks very very much!!!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48500993

http://stackoverflow.com/a/48414013
has body: Dictionaries have unique keys. This does what I think you want: data = {'a': ['b', 'c'], 'b': ['c']} data_tuples = tuple((k, i) for k, v in data.items() for i in v) # output: (('a', 'b'), ('a', 'c'), ('b', 'c'))
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83818071
has comment: http://stackoverflow.com/comment/83818096
answers question: http://stackoverflow.com/q/48412437

http://stackoverflow.com/q/48441861
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48446678
tagged with: plot
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47891531
has title: Bokeh Server with 3 y axes doesn't plot,but does for 2 y axes.Why?
tagged with: python
tagged with: bokeh
duplicate of: http://stackoverflow.com/q/47891531
has body: My objective is to plot live data on multiple y axes(different ranges). The following code worked with 2 y axes but when I added a 3rd one, the browser was just blank.An earlier basic bokeh plot with 4 y axes worked fine but this server version is not working.I dont know what mistake I am doing,please guide me. The follwing code plots 2 temporary points then a 3rd permanent point. Uses 'patch' and 'stream' from ColumnDataSource to achieve this. from bokeh.io import curdoc from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.models import LinearAxis, Range1d import numpy as np def plotcharts(source,x,a,b,c): fig=figure(y_range=(0, 500)) fig.circle(source=source, x=x,y=a,size=12,color='red') fig.extra_y_ranges = {"foo1": Range1d(start=0, end=50)} fig.circle(source=source,x=x, y=b, size=12, color="blue", y_range_name="foo1") fig.add_layout(LinearAxis(y_range_name="foo1"), 'left') # configure 3rd axis fig.extra_y_ranges = {"foo2": Range1d(start=0, end=25)} fig.circle(source=source, x=x, y=c, color="magenta", y_range_name="foo2") fig.add_layout(LinearAxis(y_range_name="foo2"), 'right') return fig count=(-1) dct=dict(x=[],a=[],b=[],c=[]) #Just a and b work fine but when 3rd axis c was added it doesnt ! source=ColumnDataSource(dct) fig=plotcharts(source,'x','a','b','c') #c==3rd axis def update_data(): global count count=count+1 y1 = np.random.randint(low=0, high=500) y2 = np.random.randint(low=0, high=50) y3 = np.random.randint(low=0, high=25) #y3==3rd axis if count%3==0: new_data = { 'x': [count/3], 'a': [y1], 'b': [y2], 'c': [y3] #c==3rd axis } source.stream(new_data,rollover=20) else: l = len(df['a']) new_data = { 'a': [(l - 1,y1)], 'b': [(l - 1, y2)], 'c': [(l - 1, y3)] #c==3rd axis } source.patch(new_data) curdoc().add_root(fig) curdoc().add_periodic_callback(update_data,1000)
type: AnsweredQuestion
tagged with: multiple-axes
score: 1
accepted answer: http://stackoverflow.com/a/48446678

http://stackoverflow.com/q/48417764
upvote count: 1
score: 1
tagged with: recurrent-neural-network
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48419553
has title: How to modify the initial value in BasicLSTMcell in tensorflow
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48420721
tagged with: python
has body: I want to initial the value for weight and bias in BasicLSTMcell in Tensorflow with my pre-trained value (I get them by .npy). But as I use get_tensor_by_name to get the tensor, it seems that it just returns a copy for me and the raw value is never changed. I need your help!
tagged with: lstm
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83859256
comment on: http://stackoverflow.com/a/48433640
type: AnswerComment
score: 0
type: Comment
has text: Ahhhhh, that is a nice (evil) hack.

http://stackoverflow.com/q/48358037
has comment: http://stackoverflow.com/comment/83703252
score: 0
has comment: http://stackoverflow.com/comment/83703028
answer count: 1
accepted answer: http://stackoverflow.com/a/48365834
has comment: http://stackoverflow.com/comment/83702859
has answer: http://stackoverflow.com/a/48365834
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83702819
tagged with: shapely
tagged with: multilinestring
tagged with: python
has comment: http://stackoverflow.com/comment/83702948
has title: Optimize python code used for LineStrings intersection
has comment: http://stackoverflow.com/comment/83702876
has body: I am trying to find the intersections of multiple LineStrings that are in a list. Do you know how I could optimize this? I'm not sure on how to make it go faster(provided a small example): from shapely.geometry import LineString l1 = LineString([Point(-122.238615,37.78376699999999), Point(-122.237455,37.78220799999999)]) l2 = LineString([Point(-122.236899, 37.77980199999999), Point(-122.232146, 37.77611)]) l3 = LineString([Point(-122.232452, 37.775956), Point(-122.236212, 37.775573)]) l4 = LineString([Point(-122.234843, 37.77336199999999), Point(-122.231641, 37.77664699999999)]) l5 = LineString([Point(-121.908187, 37.67754099999999),Point(-121.908409, 37.67810899999999)]) linestrings = [l1,l2,l3,l4,l5,l1,l2,l3,l4,l5,l1,l2,l3,l4,l5,l1,l2,l3,l4,l5,l1,l2,l3,l4,l5,l1,l2,l3,l4,l5] import time the_time = time.time() [ x.intersection(y) for idx1,x in enumerate(linestrings) for idx2,y in enumerate(linestrings) if idx1&lt;idx2 and x.intersects(y)] print("TIME:",time.time()-the_time) Output: TIME: 0.026987314224243164 This is a small example, but I have way more data, any idea how I can make it go faster?

http://stackoverflow.com/q/48426624
accepted answer: http://stackoverflow.com/a/48427037
has answer: http://stackoverflow.com/a/69469929
answer count: 7
tagged with: python
has body: I am trying to scrape one of the free proxy listings website but, I just couldn't be able to scrape the proxies. Below is my code: import requests import re url = 'https://free-proxy-list.net/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Cafari/537.36'} source = requests.get(url, headers=headers, timeout=10).text proxies = re.findall(r'([0-9]{1,3}\.){3}[0-9]{1,3}(:[0-9]{2,4})?', source) print(proxies) I would highly appreciate if someone could help me without the use of additional libraries/modules like BeautifulSoup.
upvote count: 10
has answer: http://stackoverflow.com/a/57162541
possible better answer: http://stackoverflow.com/a/48431336
score: 9
type: Question
has answer: http://stackoverflow.com/a/78059359
has answer: http://stackoverflow.com/a/61831367
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48427037
has title: Scraping free proxy listing website
has answer: http://stackoverflow.com/a/74141451
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48431336

http://stackoverflow.com/q/48391075
upvote count: 15
has body: I know how to visualize a tensorflow graph after training with tensorboard. Now, is it possible to visualize just the forward part of the graph, i.e., with no training operator defined? The reason I'm asking this is that I'm getting this error: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables [ ... list of model variables here ... ] and loss Tensor("Mean:0", dtype=float32). I'd like to inspect the graph to find out where the gradient tensor flow (pun intended) is broken.
accepted answer: http://stackoverflow.com/a/48391232
has title: Is it possible to visualize a tensorflow graph without a training op?
tagged with: tensorboard
tagged with: machine-learning
tagged with: python
score: 15
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/120177680
tagged with: visualization
has answer: http://stackoverflow.com/a/48391232
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/a/48392563
has body: The simplest solution here would be having a Value (which is basically an object in shared memory) in both processes. If you intend to do anything non-atomic with it (you likely do), you also need a Lock to synchronise access to this memory. You don't need to make anything global. from multiprocessing import Process, Lock, Value from ctypes import c_bool import time def func1(n, lock): while True: with lock: print(n.value) time.sleep(1) def func2(n, lock): while True: with lock: n.value = True time.sleep(1) n = Value(c_bool, False) lock = Lock() Process(target=func1, args=(n, lock)).start() Process(target=func2, args=(n, lock)).start()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48392096

http://stackoverflow.com/comment/83965626
type: QuestionComment
has text: Maybe you want to edit your question to make it clearer what the expected outcome would be. Also a clear problem description may help, in how far are the suggested steps not giving you the desired result. Also, making this reproducible for others, see [mcve].
comment on: http://stackoverflow.com/q/48468148
score: 0
type: Comment

http://stackoverflow.com/comment/83824871
has text: Can you post the rest of the code? because I can't recreate your problem.
score: 0
comment on: http://stackoverflow.com/a/48416979
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83796084
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48403767
score: 0
has text: Your question title is wholly inadequate; a very large percentage of Python questions deal with string issues. In future, please come up with one that better covers *your specific situation*.

http://stackoverflow.com/comment/83952931
has text: Yeah that's true. It's cool to ask further questions but if it's totally different it's better to ask a new question so other people can contribute :-)
score: 0
comment on: http://stackoverflow.com/a/48466886
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48379782
has body: First you need to have a column for the seconds (since epoch), then groupby using that column, and then do an aggregation on the columns you want. You want to floor the timestamp down to one second accuracy, and group using that. Then apply an aggregation to get the mean/sum/std what ever you need df = pd.read_csv('data.csv') df['dateTime'] = df['dateTime'].astype('datetime64[s]') groups = df.groupby('dateTime') groups.agg({'ask1': np.mean, 'tradeVolume': np.sum}) I modified the data to make sure there are actually different seconds in it, SecurityID,dateTime,ask1,ask1Volume,bid1,bid1Volume,ask2,ask2Volume,bid2,bid2Volume,ask3,ask3Volume,bid3,bid3Volume,tradePrice,tradeVolume,isTrade 2318276,2017-11-20 08:00:09.052240,12869.0,1,12868.0,3,12870.0,19,12867.5,2,12872.5,2,12867.0,1,0.0,0,0 2318276,2017-11-20 08:00:09.052260,12869.0,1,12868.0,3,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12861.0,1,1 2318276,2017-11-20 08:00:09.052260,12869.0,1,12868.0,2,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052270,12869.0,1,12868.0,2,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,1 2318276,2017-11-20 08:00:09.052270,12869.0,1,12868.0,1,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052282,12869.0,1,12868.0,1,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,1 2318276,2017-11-20 08:00:09.052282,12869.0,1,12867.5,2,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052291,12869.0,1,12867.5,2,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12867.5,1,1 2318276,2017-11-20 08:00:09.052291,12869.0,1,12867.5,1,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12867.5,1,0 2318276,2017-11-20 08:00:09.052315,12869.0,1,12867.5,1,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12867.5,1,1 2318276,2017-11-20 08:00:09.052315,12869.0,1,12867.5,1,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12867.0,1,1 2318276,2017-11-20 08:00:10.052315,12869.0,1,12867.5,1,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12865.5,1,1 2318276,2017-11…
has comment: http://stackoverflow.com/comment/83841036
type: Answer
answers question: http://stackoverflow.com/q/48379224
accepted answer of: http://stackoverflow.com/q/48379224
has comment: http://stackoverflow.com/comment/83750948
has comment: http://stackoverflow.com/comment/83851887
score: 2
has comment: http://stackoverflow.com/comment/83785666
upvote count: 2
has comment: http://stackoverflow.com/comment/83752107
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83767569
has comment: http://stackoverflow.com/comment/83788739
has comment: http://stackoverflow.com/comment/83754305

http://stackoverflow.com/q/48461074
accepted answer: http://stackoverflow.com/a/48462147
has title: Django Forms Nested If - Second Condition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48462147
score: 0
has comment: http://stackoverflow.com/comment/83915030
tagged with: django
has comment: http://stackoverflow.com/comment/83915100
answer count: 1
has comment: http://stackoverflow.com/comment/83916161
has body: I have a django form that checks if a postcode is valid and if valid it will perform a check against postcodes that are permitted for delivery. I cant get the second condition working in the nested if structure (works fine independently). This is the code: from django import forms import requests class PostCodeForm (forms.Form): pcode = forms.CharField() def clean_pcode(self): pcode = self.cleaned_data['pcode'].lower() permitted = {'gu15','GF34','FG34','BT25'} url = 'https://api.postcodes.io/postcodes/{}/validate'.format(pcode) r = requests.get(url) is_correct = r.json()['result'] if not is_correct: raise forms.ValidationError("Your postcode is invalid. Please re-enter a valid entry.") if not pcode[:4] in (permitted): raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.") return pcode
type: Question
tagged with: python
tagged with: django-forms

http://stackoverflow.com/comment/83722565
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48367645
has text: @user202729 It is not as convenient to code in C to start with because it does not have scikit-learn and the like, and we would have to completely define all models ourselves. Better to do hyperparameter and model search in python and then recapitulate only what we select as best. And we need to ship in C because this is going on a bird with power/space constraints.
type: Comment

http://stackoverflow.com/comment/83780332
comment on: http://stackoverflow.com/q/48396419
type: Comment
score: 0
type: QuestionComment
has text: For some starting guidance, you'll want to check out the [input/output python tutorial](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) followed by the [python JSON API docs](https://docs.python.org/2/library/json.html).

http://stackoverflow.com/comment/83945820
comment on: http://stackoverflow.com/q/48474274
score: 0
has text: @CedricH. Have your matrix `d` in **C-order** and `D.T` in **fortran order** for some more optimization. That should make your code at least 2x faster :)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/75560314
score: 0
has body: When using FastAPI on Windows, we can be limited by the number of concurrent connections, as the default is 64 (defined by the var FD_SETSIZE). More info at https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-select?redirectedfrom=MSDN Despite defining ProactorEventLoop (that uses IOCP), on Python versions, prior to 3.7, the select() routines are used, leading to exceptions. One alternative is to use Andrei's answer to limit the number of concurrent connections in an ML/DL context. Using asyncio + hypercorn + FastAPI, the code is the following: from hypercorn.config import Config from hypercorn.asyncio import serve from fastapi import FastAPI import asyncio import json import time import sys app = FastAPI() conn_limit = 10 async def gather_with_concurrency(n, *coros): """ From Andrei's answer """ semaphore = asyncio.Semaphore(n) async def sem_coro(coro): async with semaphore: return await coro return await asyncio.gather(*(sem_coro(c) for c in coros)) @app.get('/app/test') def req_test(): time.sleep(1) return {"test": "ok"} if __name__ == "__main__": # Start the loop config = Config() config.bind = [f"0.0.0.0:12000"] config.workers = 1 if sys.platform == 'win32': logger.info("Setting proactor event loop for Windows platform.") loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(gather_with_concurrency(conn_limit, serve(app, config))) loop.close() Obs: This script was tested on Python 3.7.16 against 1000 workers on Apache JMeter.
type: Answer
answers question: http://stackoverflow.com/q/48483348

http://stackoverflow.com/q/48448318
has body: I discovered a difference between medcouple() implementation in R and Python. Consider an array comprised from 10 repeated 480 times and trailed with [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]. For this array medcouple() in R and Python returns different results. The following R code returns 0: library(mrfDepth) values = c(rep(10, 480), c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21)) medcouple(values, FALSE) However the following Python code: from statsmodels.stats.stattools import medcouple arr=[10.0]*480 + [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] medcouple(arr) returns 1! IMHO R is right here, but is there any original developers who can comment on this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/97094579
upvote count: 2
has title: Difference between `medcouple()` implementation in R and Python
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48709118
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/84416483
tagged with: statsmodels
score: 2

http://stackoverflow.com/comment/83653489
has text: You don't want the empty () when defining `eap` do you?
score: 0
comment on: http://stackoverflow.com/q/48333445
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83948033
comment on: http://stackoverflow.com/q/48475858
score: 0
type: QuestionComment
has text: @ascripter I have already tried this with Thread, but it could not change env. var.
type: Comment

http://stackoverflow.com/comment/83925150
has text: @DanielRoseman, thanks! I said I might using the wrong terminology... I'll research python composition and see what I can figure out!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48465448
type: QuestionComment

http://stackoverflow.com/q/48387224
has comment: http://stackoverflow.com/comment/83762845
has answer: http://stackoverflow.com/a/48387540
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83762867
has comment: http://stackoverflow.com/comment/83762616
type: UnansweredQuestion
tagged with: timezone
has title: convert a string to datetime format
tagged with: datetime
has body: How should I fix this? error is: ValueError: time data '2016-10-20 03:43:11+00:00' does not match format '%Y-%m-%d %H:%M:%S%z' code is: fmt = "%Y-%m-%d %H:%M:%S%z" dt = datetime.strptime(row['Time'], fmt)
tagged with: python
has comment: http://stackoverflow.com/comment/83763010
score: -1
linked to: http://stackoverflow.com/q/13662789
has comment: http://stackoverflow.com/comment/83762901
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/83768144
comment on: http://stackoverflow.com/a/48389178
type: Comment
type: AnswerComment
has text: Even a definitive explanation of why not is useful so I can know to quit trying.
score: 0

http://stackoverflow.com/comment/93145566
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52300696
has text: Canonical answer, nice. The example notebook is read-only and can't be used directly. Doing File->Save will save a file to drive.

http://stackoverflow.com/a/48368255
answers question: http://stackoverflow.com/q/48366939
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48366939
has body: Your _execute_query method returns a list when your query starts with select or with: if sql_strip.startswith("select ") or \ (sql_strip.startswith("with ") # and "update " not in sql_strip and "insert " not in sql_strip ): # ... rows = self._psql_cur.fetchall() print "FETCHED RESULT: ", rows print sql return rows, True rows is a list, not a cursor, so won't have the attribute. Either return the cursor there, or use len() to get a count of rows.
score: 0
type: Answer

http://stackoverflow.com/comment/83986746
has text: Thanks. That worked. Needed to put the dictionary somewhere.
score: 0
comment on: http://stackoverflow.com/a/48474881
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48375776
tagged with: pandas-groupby
type: AnsweredQuestion
tagged with: bar-chart
accepted answer: http://stackoverflow.com/a/48376308
downvote count: 0
has comment: http://stackoverflow.com/comment/83740463
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48376308
answer count: 1
has comment: http://stackoverflow.com/comment/83738729
favorite count: 0
has body: I have the results of a group by statement display(df.groupby(['originating_system_id'])['state'].count().reset_index(name='count').sort_values(['count'], ascending=False)) Output originating_system_id count _________________________________ RBCL 11607 YBAU 2743 TWEU 2638 TWAU 846 VOIX 5 0 1 I would like to produce a barplot showing originating_system_id on the x axis and the counts of each on the y axis. df_BarPlot = df.groupby(['originating_system_id'])['state'].count() sns.barplot(x='originating_system_id',y='count',data=df_BarPlot) I'm not sure how to reference the count column in the dataframe. is there a way to ensure all the originating_system_id field names display in the resulting graph? On my other the plots the numeric values are displaying in scientific notation. Can we introduce an automatic format for barplots and distplot which shows numeric fields as as say 1000, 000, 000 etc.
has comment: http://stackoverflow.com/comment/83739930
has comment: http://stackoverflow.com/comment/83740164
type: Question
has comment: http://stackoverflow.com/comment/83739036
has title: Display a count field from a group by statement in a barplot / Axis formatting
has comment: http://stackoverflow.com/comment/83739970
tagged with: python
has comment: http://stackoverflow.com/comment/83739872
has comment: http://stackoverflow.com/comment/83740569

http://stackoverflow.com/q/48454161
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83901933
has comment: http://stackoverflow.com/comment/83927315
answer count: 1
downvote count: 0
has body: Granted, I'm fairly new to Python so bear with me. I just installed this successfully using pip and can verify that it's in the correct location (C:\Python27\Lib\site-packages). However, when I try to run this very simple script, I get the error in the post title. Can anyone point me in the right direction? Thanks. Version information: Python - 2.7.13 requests - 2.18.4 requests_kerberos - 0.12.0 My script: import requests from requests_kerberos import HTTPKerberosAuth myusername = input('Enter your username: ') mypassword = input('Enter your password: ') proxy = { 'http' : 'x.x.x.x:8080', 'https' : ':x.x.x.x:8080' } auth = HTTPKerberosAuth(myusername, mypassword) r = requests.get("http://www.google.com", proxies=proxy, auth=auth) print('HTTP Status:', r.status_code, '\n') print(r.text)
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83901524
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83927457
has comment: http://stackoverflow.com/comment/83901564
tagged with: proxy
score: 3
has comment: http://stackoverflow.com/comment/83901403
has comment: http://stackoverflow.com/comment/83901418
tagged with: python
has answer: http://stackoverflow.com/a/54095871
has comment: http://stackoverflow.com/comment/83901365
has comment: http://stackoverflow.com/comment/83901550
has title: ModuleNotFoundError: No module named 'requests_kerberos'
has comment: http://stackoverflow.com/comment/83934789
tagged with: kerberos
has comment: http://stackoverflow.com/comment/83927440
has comment: http://stackoverflow.com/comment/83927318
has comment: http://stackoverflow.com/comment/83901452
upvote count: 3

http://stackoverflow.com/a/48351168
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48350833
has body: Use DataFrame.eval() method: Demo: In [17]: df = pd.DataFrame({'a':[1], 'b':[2]}) In [18]: df Out[18]: a b 0 1 2 In [19]: df.eval("c = a + b", inplace=True) In [20]: df Out[20]: a b c 0 1 2 3
score: 1
downvote count: 0

http://stackoverflow.com/q/48394173
answer count: 2
has body: How to filter a filed when it is Null or null character string? I can only to check when it is null: DataDictionary.objects.filter(parentlevel__isnull=True) How about Null or null character string?
tagged with: django
has title: How to filter a filed when it is Null or null character string?
has answer: http://stackoverflow.com/a/48394256
possible better answer: http://stackoverflow.com/a/48394256
has answer: http://stackoverflow.com/a/48394249
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48394249
tagged with: python
type: Question

http://stackoverflow.com/q/48385256
tagged with: h5py
has title: Optimal HDF5 dataset chunk shape for reading rows
linked to: http://stackoverflow.com/q/48842596
linked to: http://stackoverflow.com/q/44881895
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83796550
has body: I have a reasonable size (18GB compressed) HDF5 dataset and am looking to optimize reading rows for speed. Shape is (639038, 10000). I will be reading a selection of rows (say ~1000 rows) many times, located across the dataset. So I can't use x:(x+1000) to slice rows. Reading rows from out-of-memory HDF5 is already slow using h5py since I have to pass a sorted list and resort to fancy indexing. Is there a way to avoid fancy indexing, or is there a better chunk shape/size I can use? I have read rules of thumb such as 1MB-10MB chunk sizes and choosing shape consistent what I'm reading. However, building a large number of HDF5 files with different chunk shapes for testing is computationally expensive and very slow. For each selection of ~1,000 rows, I immediately sum them to get an array of length 10,000. My current dataset looks like this: '10000': {'chunks': (64, 1000), 'compression': 'lzf', 'compression_opts': None, 'dtype': dtype('float32'), 'fillvalue': 0.0, 'maxshape': (None, 10000), 'shape': (639038, 10000), 'shuffle': False, 'size': 2095412704} What I have tried already: Rewriting the dataset with chunk shape (128, 10000), which I calculate to be ~5MB, is prohibitively slow. I looked at dask.array to optimise, but since ~1,000 rows fit easily in memory I saw no benefit.
has comment: http://stackoverflow.com/comment/84955367
answer count: 1
downvote count: 0
tagged with: dataset
tagged with: hdf5
accepted answer: http://stackoverflow.com/a/48405220
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/83783513
has answer: http://stackoverflow.com/a/48405220
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83787442
has comment: http://stackoverflow.com/comment/83793141
has comment: http://stackoverflow.com/comment/83796608
tagged with: performance

http://stackoverflow.com/q/48361467
type: Question
score: 3
has title: xlwings fails to open workbook with ambiguous error
tagged with: pandas
tagged with: python
upvote count: 3
tagged with: xlwings
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I am currently attempting to write several pandas dataframes to an existing excel workbook. I chose xlwings because it was successful with preserving the formulas in the workbook. This code worked for about two days, and then an ambiguous error surfaced. Any idea why this code fails? def write_packaged_outputs(packaged_outputs): print("Writing to template") template_file = './SlotVizTemplate.xlsx' output_file = './SlotVizOutput.xlsx' workbook = xlwings.Book(template_file) for packaged_output in packaged_outputs: df = packaged_output['dataframe'] sheet_name = packaged_output['sheet_name'] cell = packaged_output['cell'] worksheet = workbook.sheets[sheet_name] worksheet.range(cell).options(index=False, header=False).value = df workbook.save(output_file) xlwings.apps[0].quit() The code seems to fail at the workbook assignment: workbook = xlwings.Book(template_file) Here is the error: Traceback (most recent call last): File "C:\Users\philector\Documents\Development\Python\SlotViz\SlotVizTool_v1.py", line 214, in &lt;module&gt; write_packaged_outputs(packaged_outputs) File "C:\Users\philector\Documents\Development\Python\SlotViz\SlotVizTool_v1.py", line 160, in write_packaged_outputs workbook = xlwings.Book(template_file) File "C:\Users\philector\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlwings\main.py", line 479, in __init__ app = App(add_book=False) File "C:\Users\philector\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlwings\main.py", line 204, in __init__ self.impl = xlplatform.App(spec=spec, add_book=add_book) File "C:\Users\philector\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlwings\_xlwindows.py", line 288, in __init__ self._xl = COMRetryObjectWrapper(DispatchEx('Excel.Application')) File "C:\Users\philector\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\__init__.py", line 113, in DispatchEx dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispat…
favorite count: 0

http://stackoverflow.com/a/48455137
has comment: http://stackoverflow.com/comment/83903441
type: Answer
has comment: http://stackoverflow.com/comment/83903428
has comment: http://stackoverflow.com/comment/83903503
has comment: http://stackoverflow.com/comment/83903402
has comment: http://stackoverflow.com/comment/83904715
has comment: http://stackoverflow.com/comment/83903927
has comment: http://stackoverflow.com/comment/83903453
has body: I tried to rewrite your code in a cleaner way import random spans = [120, 125, 240, 380, 315, 320, 405, 450] length = 1000 def addVals(nums,total): vals = [] p = last = sum = 0 while sum &lt;= total: while last == p: p = random.choice(nums) sum += p vals.append(p) last = p return vals valLeft = length while valLeft &gt;= 100: valList = addVals(spans,length) valSum = sum(valList) valLeft = valSum - length print valList print valSum print valLeft I think it works as you were expecting. Your code had one flaw, I don't think you notice that the pop method is actually changing your array, and it will eventually run out of elements. I don't think that was intended. That's why I added another while to keep getting random choices until it gets one different from the last one. Hope you like it.
answers question: http://stackoverflow.com/q/48454969
has comment: http://stackoverflow.com/comment/83903437
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48454969
downvote count: 0
has comment: http://stackoverflow.com/comment/83903424
has comment: http://stackoverflow.com/comment/83903388
upvote count: 1
has comment: http://stackoverflow.com/comment/83904056
has comment: http://stackoverflow.com/comment/83903468
has comment: http://stackoverflow.com/comment/83904139

http://stackoverflow.com/a/48386669
accepted answer of: http://stackoverflow.com/q/48386477
type: AcceptedAnswer
has body: You are asking for other people to do a refactor for you... This is not a question.. You can create a method named reshape_data(x, y) and it can do the for loop: def reshape_data(x, y, other parameters needed): for _ in range(batch_count): rand_index = np.random.choice(len(X_train), size=config.batch_size) batch_X = x[rand_index].reshape((1, config.num_steps, config.input_size)) batch_y = y[rand_index].reshape((1, config.num_steps, config.output_size)) Then you can call it from your main code: reshape_data(X_train, y_train, batch_count, config) reshape_data(X_test, y_test, batch_count, config) You could refactor it even more, of course. PD: Not tested the code, it does not work because scope of variables config and batch_count, etc..
has comment: http://stackoverflow.com/comment/83762186
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48386477
score: 2

http://stackoverflow.com/comment/83699452
comment on: http://stackoverflow.com/q/48356446
score: 2
type: Comment
has text: Well, you have only defined /bajki/bajki/, but you are going to / - what did you expect?
type: QuestionComment

http://stackoverflow.com/a/48438977
has comment: http://stackoverflow.com/comment/83869446
has comment: http://stackoverflow.com/comment/83869252
score: 1
accepted answer of: http://stackoverflow.com/q/48438397
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83869125
answers question: http://stackoverflow.com/q/48438397
has body: What you do: Create an input file that contains the paths, e.g., infiles.txt Read the input file locations from this file use shutil.copy to copy your files to that location Here's a sample code: import os, shutil from argparse import ArgumentParser as argpars parser = argpars(description='') parser.add_argument('--test_data_file', nargs=1, type=str) parser.add_argument('--dest_loc', nargs=1, type=str) args = parser.parse_args() with open(args.test_data_file[0], 'r') as f: file_locations = [ff.strip() for ff in f.readlines()] for loc in file_locations: print(os.path.join(args.dest_loc[0], loc.split('/')[-1])) # shutil.copy(loc, os.path.join(args.dest_loc[0], loc.split('/')[-1])) The command is something like python your_script.py --test_data_file infiles.txt --dest_loc some_folder Edit For the regex question: import re re.findall(r'\d+', 'data/processed/10/blueprint-0.png') # or in the example above re.findall(r'\d+', loc)
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83869017

http://stackoverflow.com/a/62779208
answers question: http://stackoverflow.com/q/48471732
has body: Ive been using this mixin to good success. Most likely not the most efficient thing in the world and I am no expert. I define a date_created column for every table class QueryBuilder: """ This class describes a query builer. """ q_debug = False def query_from_dict(self, db_session: Session, **q_params: dict): """ Creates a query. :param db_session: The database session :type db_session: Session :param q_params: The quarter parameters :type q_params: dictionary """ q_base = db_session.query(type(self)) for param, value in q_params.items(): if param == 'start_date': q_base = q_base.filter( type(self).__dict__.get('date_created') >= value ) elif param == 'end_date': q_base = q_base.filter( type(self).__dict__.get('date_created') <= value ) elif 'like' in param: param = param.replace('_like', '') member = type(self).__dict__.get(param) if member: q_base = q_base.filter(member.ilike(f'%{value}%')) else: q_base = q_base.filter( type(self).__dict__.get(param) == value ) if self.q_debug: print(q_base) return q_base
score: 0
type: Answer

http://stackoverflow.com/q/48449264
has answer: http://stackoverflow.com/a/48449383
downvote count: 0
has comment: http://stackoverflow.com/comment/83891257
possible better answer: http://stackoverflow.com/a/48449342
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48449342
has comment: http://stackoverflow.com/comment/83891568
has body: For a dataframe with no missing values, this would be as easy as df.diff(periods=24, axis=0). But how is it possible to connect the calculations to the index values? Reproducible dataframe - Code: # Imports import pandas as pd import numpy as np # A dataframe with two variables, random numbers and hourly time series np.random.seed(123) rows = 36 rng = pd.date_range('1/1/2017', periods=rows, freq='H') df = pd.DataFrame(np.random.randint(100,150,size=(rows, 2)), columns=['A', 'B']) df = df.set_index(rng) Reproducible dataframe - Screenshot: Desired output - Code: # Running difference step = 24 df = df.diff(periods=24, axis=0) df = df.dropna(axis=0, how='all') Desired output - Screenshot The real challenge The problem is that my real-world examples are full of missing values. So I'll have to connect the difference intervals with the index values, and I have no Idea how. I've tried a few solutions with filling in the missing hours in the index first, and then running the differences like before, but it's not very elegant. Thank you for any suggestions! Edit - As requested in the comments, here's my best attempt for a bit longer time period: df_missing = df.drop(df.index[[2,3]]) newIndex = pd.date_range(start = '1/1/2017', end = '1/3/2017', freq='H') df_missing = df_missing.reindex(newIndex, fill_value = np.nan) df_refilled = df_missing.diff(periods=24, axis=0) Compared to the other suggestions, I would say that this is not very elegant =)
has title: How to find the difference between hour of day of separate days in a pandas dataframe?
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48449383
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/48467905
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48467320
has comment: http://stackoverflow.com/comment/83929479
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48467320
upvote count: 5
score: 5
type: Answer
has body: When I do print(decoded[:20]) I'm actually shown this: b'PK\x03\x04\x14\x00\x08\x00\x08\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00' That PK\x03\x04 is a "magic number" for a zip file. So treat it as such. Either save it to a file named like "mydata.zip" and then extract it like you would extract any zip file, or process it in Python for example like this: ... decoded = base64.decodestring(base64str) import io, zipfile, json, pprint with zipfile.ZipFile(io.BytesIO(decoded)) as zf: for name in zf.namelist(): print(name) with zf.open(name) as f: data = json.loads(f.read().decode()) pprint.pprint(data) With your data, this first prints the file name "o3d3xx.json" and then the data: {'Applications': [{'Description': '', 'ImagerConfiguration': [{'AutoExposureMaxLongShortFactor': 50, 'AutoExposureMinLongShortFactor': 2, (... lots and lots and lots of data ...) 'StaticIPv4SubNetMask': '255.255.255.0', 'UseDHCP': False}}

http://stackoverflow.com/comment/83901972
has text: That would require you to provide a [MCVE], please.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48453151
type: QuestionComment

http://stackoverflow.com/q/48468975
favorite count: 0
type: Question
upvote count: 4
has body: Whenever I try to do anything pip, I get the following error: File "C:\ProgramData\Anaconda2\envs\myenv\lib\site-packages\pip\__init__.py", line 21, in &lt;module&gt; from pip._vendor.requests.packages.urllib3.exceptions import DependencyWarning ImportError: cannot import name 'DependencyWarning' I know this is a problem with the 'requests' package (it's version changed while I was working on something). The problem is, how do I upgrade 'requests' when pip doesn't work? I am working in Windows in a virtualenv.
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/83932282
accepted answer: http://stackoverflow.com/a/48472776
has comment: http://stackoverflow.com/comment/83932036
score: 4
has answer: http://stackoverflow.com/a/48472776
has comment: http://stackoverflow.com/comment/83932195
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83931709
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83932653
has comment: http://stackoverflow.com/comment/83931992
downvote count: 0
has comment: http://stackoverflow.com/comment/83932411
has comment: http://stackoverflow.com/comment/83932725
answer count: 1
has comment: http://stackoverflow.com/comment/83932326
has title: Pip command not working
has comment: http://stackoverflow.com/comment/83932417
has comment: http://stackoverflow.com/comment/83932226

http://stackoverflow.com/comment/83734296
type: QuestionComment
has text: However, one would expect the interpreter would parse `except ValueErro` and bork, even if it's just skipping it. However, Ruby does exactly the same thing: `begin; puts "Hello"; rescue NameErro; puts "Error!"; finally; puts "World!"; end` does not make a fuss. Curious. Probably the lazy evaluation of `except` is an optimisation, for languages where exceptions are commonly used for flow control?
comment on: http://stackoverflow.com/q/48373506
score: 0
type: Comment

http://stackoverflow.com/comment/83657365
comment on: http://stackoverflow.com/q/48336037
type: QuestionComment
has text: I need to work further with each categories hence I need the 'a' part as well @Mad_Scientist
score: 0
type: Comment

http://stackoverflow.com/q/48354276
has title: Appending Python Lists to Dictionary
has answer: http://stackoverflow.com/a/48354431
tagged with: python
has comment: http://stackoverflow.com/comment/83695155
tagged with: dictionary
type: Question
score: 0
tagged with: list
has body: I am trying to find if a tag is present in a list and then map them to a dictionary and add them to the corresponding tag. This is what I came up with. RequiredTags = ['PolicyNumber', 'PaymentAmt', 'PolicyAmt'] ListOfTags = ['Header', 'Version','PolicyNumber', 'PaymentAmt', 'Body', 'PolicyAmt'] ListOfValues = ['', '1.1', '123456', '100.00', '', '1'] values = dict.fromkeys(RequiredTags, []) for key, value in values.items(): if key in ListOfTags: v = ListOfValues[ListOfTags.index(key)] print(key, v) values[key].append(v) The problem is, everytime a value is appended, it is appended to every key in the dictionary and not just the one which I'm trying to append to. Expected output is like values = {'PolicyNumber': ['123456'], 'PaymentAmt': ['100.00'], 'PolicyAmt': ['1']} I have a list of xml files, i want to extract and export values from. This will add the values to the dict for one file but I want to append the values from all XML files to this one dictionary. Hope this clarifies the question better.
answer count: 1
has comment: http://stackoverflow.com/comment/83695543
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48354431

django-sites
type: Tag
tags question: http://stackoverflow.com/q/48346403
tag name: django-sites

http://stackoverflow.com/a/52026446
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48481221
score: 0
accepted answer of: http://stackoverflow.com/q/48481221
has body: Create requirements.txt by using cmd pip freeze &gt; requirements.txt in the desired folder it will define all the required libraries or do it manually in the following format:- Flask==0.9-devdev-20120114 Jinja2==2.6 Werkzeug==0.8.2 wsgiref==0.1.2 And then deploy your app. Let me know if it worked.

intellij-idea
tags question: http://stackoverflow.com/q/48481965
tags question: http://stackoverflow.com/q/48346457
type: Tag
tags question: http://stackoverflow.com/q/48391187
tag name: intellij-idea

http://stackoverflow.com/q/48333550
upvote count: 2
has comment: http://stackoverflow.com/comment/83690782
answer count: 1
downvote count: 0
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48486896
has title: Tkinter Scrollable canvas create additional scroll area on top
has comment: http://stackoverflow.com/comment/83690793
has comment: http://stackoverflow.com/comment/83760399
has body: I'm quite new to Tkinter on python3, and trying to make a scrollable frame on top of a canvas. I'm able to create it for default windows size, with no problem. But when the windows maximized, the canvas suddenly add extra scrollable area on top and I have been looking for way to remove it / keep my scrollable frame on top. import tkinter as tk class MainWindow(tk.Tk): def __init__(self, *args, **kwargs): super().__init__() self.geometry("1500x800") self.configure(background="#303030") class Table(tk.Frame): def __init__(self, master, rows=2, columns=2): tk.Frame.__init__(self, master, background="#36363d") # Set table as list of rows self.table = [] for row in range(rows): # Create list to store cell info in a rows current_row = [] for column in range(columns): label = tk.Label(self, text="", borderwidth=0, width=columns, bg="#474756", ) label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1, ) # Append cell (column) into rows current_row.append(label) # Append rows into whole table self.table.append(current_row) for column in range(columns): self.grid_columnconfigure(column, weight=1) class ScrollablePage(tk.Frame): def __init__(self, master, *args, **kw): super().__init__(master) self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, bg="red") # THIS TO EMPHASIZE THE CANVAS, self.frame = tk.Frame(self.canvas, *args, **kw) self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas_frame = self.canvas.create_window((0, 0), window=self.frame, anchor="nw", tags="self.frame") # Dynamic frame setup self.frame.bind("&lt;Configure&gt;", self.frame_conf) self.canvas.bind("&lt;Configure&gt;", self.frame_width) # Bind canvas to mousewheel self.canvas.bind("&lt;Enter&gt;", self.bound_to_mousewheel) self.canvas.bind("&lt;Leave&gt;", self.unbound_to_mousewheel) def frame_conf(self, eve…
has answer: http://stackoverflow.com/a/48486896
tagged with: python
tagged with: frame
tagged with: scrollbar
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83668396
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83668741
has comment: http://stackoverflow.com/comment/83675197
tagged with: canvas
has comment: http://stackoverflow.com/comment/83668339

http://stackoverflow.com/a/48605187
score: 0
has body: To predict 3 target variables you will want to have 3 outputs in your last layer so you should change m = C.layers.Dense(1)(m) to m = C.layers.Dense(3)(m) The other error is because your X["train"] has shape=(batch, sequence, 2, 1), but when you call create_model you pass something that has shape=(sequence, 1). The best way to fix this is make your X["train"] have shape=(batch, sequence, 2) (e.g. by calling np.squeeze) and then call create_model with C.sequence.input_variable(2).
type: Answer
answers question: http://stackoverflow.com/q/48416439

http://stackoverflow.com/a/48345330
accepted answer of: http://stackoverflow.com/q/48344470
score: 0
answers question: http://stackoverflow.com/q/48344470
type: AcceptedAnswer
has body: I don't think that's a good idea actually - it will make your code much harder to read and maintain for no good reason (and let's not talk about the cost of opening/reading files for each and any query). If your goal is to decouple data access (how you get/store data) from business logic (how you use data), a better solution would be to write a data acces module with the proper functions and call those functions from your main code, ie: # datalayer.py import atexit _conn = &lt;open your connection here&gt; def close_connection(): if _conn: _conn.close() _conn = None atexit.register(close_connection) # FIXME: proper arg names def update_quantity(x, y, z, commit=True): c = _conn.cursor() try: r = c.execute('INSERT OR IGNORE INTO quantity VALUES (?,?,?)', (x, y, z)) except Exception as e: c.close() raise if commit: _conn.commit() return r Then in your code: import datalayer def func(): # do things here datalayer.update_quantities(a, b, c) # etc This is of course a very dumbed down example - depending on your app's complexity you may want to have distinct classes for different sets of operations (depending on which datasets you're working etc), and in all cases you'll probably want to make sure the connection is always properly closed, that it try and reopens when it's been closed by the server etc, but you get the main idea.
type: Answer

http://stackoverflow.com/a/48361046
upvote count: 26
score: 26
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48360763
answers question: http://stackoverflow.com/q/48360763
has body: Change from django.conf.urls import static to from django.conf.urls.static import static and you're good to go.
type: AcceptedAnswer

http://stackoverflow.com/a/48453236
score: 1
type: Answer
has body: You are missing a close-parenthesis on line 5.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83899917
has comment: http://stackoverflow.com/comment/114942010
answers question: http://stackoverflow.com/q/48453231

http://stackoverflow.com/q/48338492
score: 3
accepted answer: http://stackoverflow.com/a/48340802
has title: How to obtain global step when using tf.train.MonitoredTrainingSession
tagged with: python
type: AnsweredQuestion
upvote count: 3
downvote count: 0
tagged with: save
answer count: 1
tagged with: machine-learning
has body: When we specify the global_step in the Saver.save, it will store the global_step as the checkpoint suffix. # save the checkpoint saver = tf.train.Saver() saver.save(session, checkpoints_path, global_step) We can restore the checkpoint and obtain the last global step stored in the checkpoints like this: # restore the checkpoint and obtain the global step saver.restore(session, ckpt.model_checkpoint_path) ... _, gstep = session.run([optimizer, global_step], feed_dict=feed_dict_train) If we use tf.train.MonitoredTrainingSession, what is the equivalent way to save the global step to the checkpoint and obtain gstep? Edit 1 Followed by Maxim's suggestion, I have created the global_step variable before tf.train.MonitoredTrainingSession, and added a CheckpointSaverHook like this: global_step = tf.train.get_or_create_global_step() save_checkpoint_hook = tf.train.CheckpointSaverHook(checkpoint_dir=checkpoints_abs_path, save_steps=5, checkpoint_basename=(checkpoints_prefix + ".ckpt")) with tf.train.MonitoredTrainingSession(master=server.target, is_chief=is_chief, hooks=[sync_replicas_hook, save_checkpoint_hook], config=config) as session: _, gstep = session.run([optimizer, global_step], feed_dict=feed_dict_train) print("current global step=" + str(gstep)) I can see that it generates the checkpoint files similar to what Saver.saver does. However, it is unable retrieve the global step from the checkpoint. Please kindly advise how should I fix this?
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48340802

http://stackoverflow.com/q/48483032
has comment: http://stackoverflow.com/comment/83959490
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83959371
upvote count: 3
has comment: http://stackoverflow.com/comment/83959741
has comment: http://stackoverflow.com/comment/83960376
has title: Storing the last iteration in a loop(python)
has comment: http://stackoverflow.com/comment/83960336
tagged with: poisson
has comment: http://stackoverflow.com/comment/83959457
tagged with: loops
has comment: http://stackoverflow.com/comment/83960188
has comment: http://stackoverflow.com/comment/83960170
has comment: http://stackoverflow.com/comment/83959353
type: Question
has comment: http://stackoverflow.com/comment/83959193
has comment: http://stackoverflow.com/comment/83959320
has comment: http://stackoverflow.com/comment/83959574
downvote count: 0
has comment: http://stackoverflow.com/comment/83959380
answer count: 1
tagged with: python
has body: So I have 2 variables mean and service consisting of the following values: mean=[5.76,6.5,7,5,4.5,6,9,2.5,3,5.5] limit=[90,80,95,96,98,85,82,75,90,91] Now,I have applied poisson function on the variable mean: from scipy.stats import poisson for m in mean: r_v=poisson(m) r_v1.append(r_v) Next what I need to do is obtain the sum of pmfs of all the values of mean(with the number of occurrences starting from 0) and compare those to the corresponding values in limit. I need to obtain the number of occurrence for which the sum of pmfs is greater than or equal to the corresponding value in limit. For example, for mean =5.76, (pmf(0)+pmf(1)...+pmf(9))*100=93.2, which exceeds 90 in the limit variable for 9 occurences. I've run the following code which seems to work fine: for r,s in zip(r_v1, limit): l=[] z=0 while True: y=r.pmf(z) l.append(y) z+=1 if round(sum(l),2)*100&gt;=s: break Store=%z The issue is, when I'm trying to store the last occurrence of z at which round(sum(l),2)*100&gt;=s, I'm getting the following error: ERROR:root:Line magic function `%z` not found. Can somebody please help me rectify the error in the code? Thanks a lot.
has comment: http://stackoverflow.com/comment/83959689
favorite count: 0
has answer: http://stackoverflow.com/a/48483388
accepted answer: http://stackoverflow.com/a/48483388
has comment: http://stackoverflow.com/comment/83959563

http://stackoverflow.com/q/48366469
answer count: 1
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23461352
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83719703
has comment: http://stackoverflow.com/comment/84781852
has title: How to get currency symbol from ISO country code in Django application?
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/69453872
has comment: http://stackoverflow.com/comment/83719544
has comment: http://stackoverflow.com/comment/83719693
has body: I just want to get the Currency symbol for different countries in my Python Django application from the country code I have. For example I have a country code 'US', the output I need is '$' or 'US$'. Now I achieve this with the help of two libraries, namely pycountry and forex-python. Can I achieve this in a more simple way? import pycountry from forex_python.converter import CurrencyCodes code = "US" country = pycountry.countries.get(alpha_2=code) currency = pycountry.currencies.get(numeric=country.numeric) country_codes = CurrencyCodes() country_codes.get_symbol(currency.alpha_3) Output: 'US$'
score: 1

http://stackoverflow.com/comment/83856555
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48432664
type: Comment
has text: Did you do this stuff? https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04

http://stackoverflow.com/a/48413747
has comment: http://stackoverflow.com/comment/83817500
has comment: http://stackoverflow.com/comment/83817563
has body: Some alternatives: (1) Slicing by position: sorted(names, key=lambda x: int(x[5:-6])) (2) Stripping substrings: sorted(names, key=lambda x: int(x.replace('Test-', '').replace('.model', ''))) Or better (Pandas version &gt;3.9): x.removeprefix('Test-').removesuffix('.model') (3) Splitting characters (also possible via str.partition): sorted(names, key=lambda x: int(x.split('-')[1].split('.')[0])) (4) Map with np.argsort on any of (1)-(3): list(map(names.__getitem__, np.argsort([int(x[5:-6]) for x in names])))
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/83817547
has comment: http://stackoverflow.com/comment/132935720
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48413706

http://stackoverflow.com/a/48483374
upvote count: 3
has comment: http://stackoverflow.com/comment/83959754
downvote count: 1
answers question: http://stackoverflow.com/q/48483339
has comment: http://stackoverflow.com/comment/83959671
has comment: http://stackoverflow.com/comment/83959634
has comment: http://stackoverflow.com/comment/83959664
has comment: http://stackoverflow.com/comment/83959700
has comment: http://stackoverflow.com/comment/83959687
type: Answer
has body: you can learn about iteration, it's recursive thinking def n_g(): first_input = input("are you okay?") if first_input == "yes": print("Nice") else: n_g()
score: 2

http://stackoverflow.com/q/48346588
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83680856
has title: " ch.setopt(ch.HTTPPOST, data.items()) TypeError: invalid arguments to setopt" i am getting this error
favorite count: 0
type: Question
type: UnansweredQuestion
has body: When I put all my authorization data into data = { 'token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX', 'content': 'file', 'action': 'import', 'record': '', 'field': 'record_id', 'event': '', 'returnFormat': 'csv', 'file': '(pycurl.FORM_FILE, file)' } I get error at h.setopt(ch.HTTPPOST, data.items()) which says ch.setopt(ch.HTTPPOST, data.items()) TypeError: invalid arguments to setopt` The rest of the code: ch.setopt(ch.POST, 1) ch.setopt(ch.SSL_VERIFYPEER, 0) ch.setopt(ch.HTTPPOST, data.items()) ch.setopt(ch.WRITEFUNCTION, e.write) ch.perform()
tagged with: python
has comment: http://stackoverflow.com/comment/84423687
has comment: http://stackoverflow.com/comment/84422813
tagged with: pycurl
tagged with: curl
has comment: http://stackoverflow.com/comment/84423643
upvote count: 2
score: 2
tagged with: file-import

http://stackoverflow.com/comment/83800279
comment on: http://stackoverflow.com/q/48405741
has text: wait. Is the entirety of the first blurb a list?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/48411742
has comment: http://stackoverflow.com/comment/83815598
has comment: http://stackoverflow.com/comment/83818323
downvote count: 0
has comment: http://stackoverflow.com/comment/83848531
has body: I'm trying to count dendritic spines (the tiny protuberances) in mouse dendrites obtained by fluorescent microscopy, using Python and OpenCV. Here is the original image, from which I'm starting: Raw picture: After some preprocessing (code below) I've obtained these contours: Raw picture with contours (White): What I need to do is to recognize all protuberances, obtaining something like this: Raw picture with contours in White and expected counts in red: What I intended to do, after preprocessing the image (binarizing, thresholding and reducing its noise), was drawing the contours and try to find convex defects in them. The problem arose as some of the "spines" (the technical name of those protuberances) are not recognized as they en up bulged together in the same convexity defect, underestimating the result. Is there any way to be more "precise" when marking convexity defects? Raw image with contour marked in White. Red dots mark spines that were identified with my code. Green dots mark spines I still can't recognize: My Python code: import cv2 import numpy as np from matplotlib import pyplot as plt #Image loading and preprocessing: img = cv2.imread('Prueba.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.pyrMeanShiftFiltering(img,5,11) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh1 = cv2.threshold(gray,5,255,0) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) img1 = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel) img1 = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel) img1 = cv2.dilate(img1,kernel,iterations = 5) #Drawing of contours. Some spines were dettached of the main shaft due to #image bad quality. The main idea of the code below is to identify the shaft #as the biggest contour, and count any smaller as a spine too. _, contours,_ = cv2.findContours(img1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected: "+str(len(contours))) cv2.drawContours(img,contours,-1,(255,255,255),6) plt.imshow(img) plt.show() len…
has comment: http://stackoverflow.com/comment/83815768
tagged with: convexity-defects
answer count: 1
tagged with: convex-hull
upvote count: 4
favorite count: 0
type: Question
has title: How to count protuberances in dendrite with openCV
has answer: http://stackoverflow.com/a/48432358
accepted answer: http://stackoverflow.com/a/48432358
has comment: http://stackoverflow.com/comment/84066761
tagged with: python
score: 4
tagged with: opencv
type: AnsweredQuestion

http://stackoverflow.com/comment/83736563
type: QuestionComment
score: 0
has text: wouldn't the choicelist assignment just create a separate (unrelated) variable?
comment on: http://stackoverflow.com/q/48374664
type: Comment

http://stackoverflow.com/a/48477567
answers question: http://stackoverflow.com/q/48477531
upvote count: 2
has comment: http://stackoverflow.com/comment/102612867
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/102615619
accepted answer of: http://stackoverflow.com/q/48477531
has comment: http://stackoverflow.com/comment/102614066
type: AcceptedAnswer
downvote count: 0
has body: Your array is a three dimensional array, so in case you want to delete the items with index 1 of the last index, you should use: np.delete(array[:][:], 1, axis=2) Note that you do not need the [:][:] part: this will have no effect, so you can use: np.delete(array, 1, axis=2) This will then generate: &gt;&gt;&gt; np.delete(array, 1, axis=2) array([[[1], [3]], [[0], [6]]])

http://stackoverflow.com/comment/83686637
comment on: http://stackoverflow.com/a/48349933
score: 0
has text: is that you are ignoring an event different from the one used by the father, when you pass event through super(Text_Edit, self).keyPressEvent(event) a copy is generated that is the one that is passed internally, so the event that uses the father is a copy of which you ignore.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48342202
favorite count: 0
type: Question
score: 9
tagged with: pipenv
upvote count: 9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83674260
tagged with: python
has title: how to run pipenv in cronjob in ubuntu?
has body: I have installed pipenv by pip3. And it works pipenv -h in script. But after in crontab, it's not work. pip3 show pipenv Location: /home/ubuntu/.local/lib/python3.6/site-packages my cronjob 21 * * * * cd /home/ubuntu/test; /bin/sh test.sh &gt; /home/ubuntu/test.out 2&gt;&amp;1 test.sh #!/bin/bash echo "hi" python -V python3 -V pipenv -h output hi Python 2.7.12 Python 3.6.3 test.sh: : test.sh: pipenv: not found how to run pipenv in cronjob in ubuntu? thanks. Answer: /home/ubuntu/.local/bin/pipen
has answer: http://stackoverflow.com/a/77494480
answer count: 2
tagged with: cron
has answer: http://stackoverflow.com/a/48342290
downvote count: 0
tagged with: shell

http://stackoverflow.com/a/48354909
answers question: http://stackoverflow.com/q/48354773
has body: the file is in 2007-2013 Excel XML format ( according to LibreOffice ) pandas.read_excel() is not working , see the Read Excel XML .xls file with pandas for analysis of the problem and possible solutions ... ( https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html )
type: Answer
has comment: http://stackoverflow.com/comment/83697562
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48354773

http://stackoverflow.com/a/48475184
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48475006
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48475006
has body: Use this this.http.getData({date: this.model.formatted}) And modify your post methot like that let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.post("http://127.0.0.1:5000/schedule", JSON.stringify(model), {headers: headers})

http://stackoverflow.com/q/48365093
type: Question
has title: cant read .gz file from AWS S3 using AWS Lambda
possible better answer: http://stackoverflow.com/a/48366150
tagged with: amazon-s3
tagged with: gzip
tagged with: python
has answer: http://stackoverflow.com/a/48398998
accepted answer: http://stackoverflow.com/a/48398998
tagged with: lambda
has answer: http://stackoverflow.com/a/59502403
type: AnsweredQuestion
has body: i'm trying to read a .gz file from S3 using AWS Lambda. when i try to unzip the file using gzip, i get OSError: Not a gzipped file (b'PK') error. Here is the code... retr = s3_client.get_object(Bucket=bucket, Key=key) print(retr) bytestream = BytesIO(retr['Body'].read()) print(bytestream) got_text = GzipFile(mode='rb', fileobj=bytestream).read().decode('utf-8') print(got_text) Here is the response of the retr file. { 'ResponseMetadata':{ 'RequestId':'aklsfjdlskfj', 'HostId':'kajsdfhdkjfh/+r+i0OLx/adlksfjd/aksfh=', 'HTTPStatusCode':200, 'HTTPHeaders':{ 'x-amz-id-2':'alsdkfjslkfjsalfjflkj/+r+i0OLx/asklfjslk/r9eTM=', 'x-amz-request-id':'hgfhgf', 'date':'Sun, 21 Jan 2018 08:35:28 GMT', 'last-modified':'Sun, 21 Jan 2018 08:32:34 GMT', 'etag':'"aksjdfhdskjfhfkjhf"', 'accept-ranges':'bytes', 'content-type':'application/x-gzip', 'content-length':'2825', 'server':'AmazonS3' }, 'RetryAttempts':0 }, 'AcceptRanges':'bytes', 'LastModified':datetime.datetime(2018, 1, 21, 8, 32, 34, tzinfo=tzutc()), 'ContentLength':2825, 'ETag':'"akjsfhksdjfhsdkfj"', 'ContentType':'application/x-gzip', 'Metadata':{ }, 'Body':&lt;botocore.response.StreamingBody object at adsfdsf08&gt; } How to get that .gz file unzipped? i want to unzip it and read the .txt file in that .gz file. Can anyone guide me?
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48366150

http://stackoverflow.com/a/48362730
has comment: http://stackoverflow.com/comment/83712922
has body: positive=data[data['class']==0] negative=data[data['class']==1].sample(n=positive.shape[0]) final=pd.concat([positive,negative]) or positive_len=np.sum(data['class']==0) #gives the number of rows with class=0 final=data.sort_values('class')[:2*positive_len] #sort values. now rows with class 0 are on the top, rows with class 1 are on the bottom. pick top 2* length of positive.
type: Answer
has comment: http://stackoverflow.com/comment/83712442
has comment: http://stackoverflow.com/comment/83712618
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48362692

http://stackoverflow.com/q/48415300
has answer: http://stackoverflow.com/a/48415597
tagged with: jquery
has body: I have an ajax post posting and image like so, // fileData is canvas.toDataURL(fileType); $.ajax({ type: 'POST', url: 'http://ip/api', data: fileData, contentType: false, processData: false, mimeType:"multipart/form-data", success: function (data) { if (data.success) { alert('Your file was successfully uploaded!'); } else { alert('There was an error uploading your file!'); } }, error: function (data) { alert('There was an error uploading your file!'); } }); In flask I have this, @app.route("/api", methods=["POST"]) def Run(): data = np.fromstring(request.data, dtype=np.uint8) im_gray = cv2.imdecode(data,cv2.IMREAD_GRAYSCALE) I receive a base64 encoded image with request.data like so, [binary] ............ However my img_gray is None always. What am I doing wrong?
type: Question
tagged with: ajax
type: AnsweredQuestion
tagged with: opencv3.0
linked to: http://stackoverflow.com/q/33754935
tagged with: python
accepted answer: http://stackoverflow.com/a/48420196
has answer: http://stackoverflow.com/a/48420196
answer count: 2
possible better answer: http://stackoverflow.com/a/48415597
score: 0
has title: python flask not reading image from ajax POST

http://stackoverflow.com/comment/83696513
score: 0
type: Comment
type: AnswerComment
has text: How do I pass a variable into `re.search` with regular expressions i.e `re.search(r'\b('+key+')\b', str3).start()` where `key = 'you'`
comment on: http://stackoverflow.com/a/48354755

http://stackoverflow.com/comment/83685512
type: AnswerComment
has text: Strange, it must be a dtype problem. The dates do not appear to be in a typical date time format. Have you tried the ID work around? Or possibly trying to do an .astype() to the columns individually to specify the desired dtype explicitly.
score: 0
comment on: http://stackoverflow.com/a/48347859
type: Comment

http://stackoverflow.com/q/48439619
has comment: http://stackoverflow.com/comment/83872178
tagged with: python
has comment: http://stackoverflow.com/comment/83871276
favorite count: 0
has comment: http://stackoverflow.com/comment/83871216
has comment: http://stackoverflow.com/comment/83872948
has comment: http://stackoverflow.com/comment/83873798
has answer: http://stackoverflow.com/a/48442606
has body: The Python docs lists property() as a built-in function. However, the function description has the keyword "class" in front of it in the docs. class property(fget=None, fset=None, fdel=None, doc=None) This also happens with class set([iterable]) and class slice(stop) What does this mean? - why are classes listed under built-in functions. Is this just a documentation issue or is there a technical reason? EDIT: I am not asking about how property() works.
accepted answer: http://stackoverflow.com/a/48442606
has comment: http://stackoverflow.com/comment/83872724
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83872238
has comment: http://stackoverflow.com/comment/83871410
has comment: http://stackoverflow.com/comment/83873158
has comment: http://stackoverflow.com/comment/83873354
has comment: http://stackoverflow.com/comment/83871101
score: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/83871504
has comment: http://stackoverflow.com/comment/83871554
has comment: http://stackoverflow.com/comment/83871594
upvote count: 8
type: Question
linked to: http://stackoverflow.com/q/17330160
has comment: http://stackoverflow.com/comment/83871935
has comment: http://stackoverflow.com/comment/83872427
has comment: http://stackoverflow.com/comment/83871451
has title: Python - Why are classes listed in the list of built-in functions?
answer count: 1
has comment: http://stackoverflow.com/comment/83873927

http://stackoverflow.com/comment/83987685
comment on: http://stackoverflow.com/q/48456125
type: QuestionComment
score: 0
has text: In the future, please ensure you [research your problems thorough](https://meta.stackoverflow.com/q/261592/1394393) before posting a question. Had you Googled the error, you probably would have found the answer yourself. Additionally, be sure you include all the details necessary for someone to help diagnose your problem. You don't tell us what version of Python. You don't tell us your OS. You don't tell us the command you used. These pieces of information are vital to understanding the potential causes.
type: Comment

http://stackoverflow.com/q/48373632
score: 0
has comment: http://stackoverflow.com/comment/83735374
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
tagged with: user-interface
has body: I am currently just beginning to learn python and I thought I may try to build a basic calculator so I can learn a little bit of GUI concepts but also back-end concepts as well. Here is the code I have so far: import tkinter from tkinter import * from tkinter import Button import sys import math mainBox = Tk() ment = StringVar() mainBox.geometry("400x200") mainBox.title("HandyCalc") #Welcome screen buttons welcomeLabel = Label(mainBox, text="Welcome to HandyCalc! Input your first number here: ") welcomeEntry = Entry() welcomeContinue = Button(mainBox, text = "Continue", command = continueFunc) def continueFunc(): if welcomeEntry != int: intErr = Tk() def welcome (): print(welcomeLabel.pack()) print(welcomeEntry.pack()) print(welcomeContinue.pack()) def main(): welcome() main() When I run this program, the window pops up but the console returns an error of "contineFunc is not defined". I have researched numerous articles with similar problems and have had no such luck so far. Appreciate any help.
upvote count: 1
has comment: http://stackoverflow.com/comment/83735449
linked to: http://stackoverflow.com/q/48045401
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83735490
has answer: http://stackoverflow.com/a/48374014
has title: Tying a button to a function in Python (Tkinter)
has comment: http://stackoverflow.com/comment/83734427
has comment: http://stackoverflow.com/comment/83735344
has comment: http://stackoverflow.com/comment/83735434
tagged with: python
has comment: http://stackoverflow.com/comment/83735162
has comment: http://stackoverflow.com/comment/83735512
type: Question
has comment: http://stackoverflow.com/comment/83734865

http://stackoverflow.com/comment/83798408
type: Comment
type: AnswerComment
has text: This gives me something weird, maybe it has to do with encoding. This is an example of what i get: [['ÿþ"\x00D\x00e\x00v\x00i\x00c\x00e\x00 \x00n\x00a\x00m\x00e\x00:\x00U\x00U\x00-\x00C\x00B\x00_\x002\x00 \x00 \x00D\x00e\x00v\x00i\x00c\x00e\x00 \x00t\x00y\x00p\x00e\x00:\x00S\x00U\x00N\x002\ And so on
score: 0
comment on: http://stackoverflow.com/a/48404741

http://stackoverflow.com/q/48333445
has title: Can you apply a function to rows of numpy array without return?
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83652502
answer count: 0
has comment: http://stackoverflow.com/comment/83653632
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83672918
has comment: http://stackoverflow.com/comment/83653514
tagged with: arrays
has comment: http://stackoverflow.com/comment/83653594
has comment: http://stackoverflow.com/comment/83653546
has comment: http://stackoverflow.com/comment/83652848
has comment: http://stackoverflow.com/comment/83653079
has comment: http://stackoverflow.com/comment/83653489
has comment: http://stackoverflow.com/comment/83654729
has comment: http://stackoverflow.com/comment/83653004
linked to: http://stackoverflow.com/q/44239498
has comment: http://stackoverflow.com/comment/83653528
has body: I am looking for an efficient way to apply a function to a numpy array. I know that I can for loop over the rows, and that I can use numpy.apply_along_axis for a function that returns something, but is there a way to do something like apply_along_axis without a return? For example, if I have: a_list_of_strings = [] A = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) def funct (row): global a_list_of_strings a_list_of_strings.append(some_other_complicated_function(row)) is there an analogous way to do numpy.apply_along_axis with A and this function? Edit: The reason I want to do this is so that I can have a better implementation of the following code (which I didn't originally post because I thought it was hard to read. def entropy (array): """calculates the entropy of a static array""" values = [] for i in range(3,len(types)+3): p_s = sum(array[:,0]==i)/array.shape[0] values.append(p_s) return(sum(list(map(helper_ent,values)))) def helper_ent (p): return (-p*np.log2(p+eps)) def calc_entropies (array): entropies = [] eap = entropies.append for i in range(1,len(array)+1): split1 = array[array[:,i]==1.] split2 = array[array[:,i]==0.] if split1.shape[0]&gt;0 and split2.shape[0]&gt;0: E = split1.shape[0]/array.shape[0]*entropy(split1)+split2.shape[0]/array.shape[0]*entropy(split2) eap(E) else: eap(1) return(np.array(entropies))&lt;/pre&gt;
tagged with: python

http://stackoverflow.com/comment/83676094
type: QuestionComment
has text: If you provide a [mcve], which can be run in the question, I can provide an answer. Else you might search for solutions to other questions on that topic.
comment on: http://stackoverflow.com/q/48344566
score: 0
type: Comment

http://stackoverflow.com/q/48483650
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48483813
tagged with: multidispatch
has title: python - lost self while decorating class multimethods
has answer: http://stackoverflow.com/a/48483813
tagged with: python
has body: I am trying to implement a multimethod approach based on this article http://www.artima.com/weblogs/viewpost.jsp?thread=101605. There are two differences from this approach: I only need to look at the first argument of the multimethod, so no need to form tuples of arg classes The multimethods will live in classes, they will not be regular functions. However I mixed up my classes a bit, and the call to self gets lost while dispatching a call to a class method. Here is my code: method_registry = {} class SendMessageMultiMethod(object): """ A class for implementing multimethod functionality """ def __init__(self, name): self.name = name self.typemap = {} def __call__(self, message, extra_payload=None): """ Overrriding method call and dispatching it to an actual method based on the supplied message class """ first_arg_type = message.__class__ function = self.typemap.get(first_arg_type) print( 'Dispatching to function {} with message {} and extra payload {}...' .format(function, message, extra_payload) ) return function(message, extra_payload) def register(self, type_, function): self.typemap[type_] = function def use_for_type(*types): """ A decorator that registers a method to use with certain types """ def register(method): """Creating Multimethod with the method name and registering it at at method_registry dict """ name = method.__name__ mm = method_registry.get(name) if mm is None: mm = method_registry[name] = SendMessageMultiMethod(name) for type_ in types: mm.register(type_, method) return mm return register class Sender(object): def send_messages(self, messages_list): for message in messages_list: # this is supposed to fire different send_message() methods # for different arg types self.send_message(message) @use_for_type(int, float) def send_message(self, message, *args, **kwargs): print('received call for int/float message {} with {}, {}' .format(message, args, kwargs)) print('self is {}'.format(self)) @use_for_type(bool) def send_message(self, message, *args, …
has comment: http://stackoverflow.com/comment/83960642

pexpect
tags question: http://stackoverflow.com/q/48398573
tag name: pexpect
type: Tag
tags question: http://stackoverflow.com/q/48413407
tags question: http://stackoverflow.com/q/48459638

http://stackoverflow.com/a/65409991
upvote count: 2
answers question: http://stackoverflow.com/q/48390258
downvote count: 0
has body: import numpy as np nums_str = ['1','23','345'] nums_str_np = np.asarray(nums_str) nums_int_np = nums_str_np.astype('int') nums_int_np - is now np array of integers.
type: Answer
score: 2

http://stackoverflow.com/comment/83811526
type: Comment
comment on: http://stackoverflow.com/q/48355644
type: QuestionComment
score: 0
has text: I don't know for sure; it just reminds me of work I did earlier.

http://stackoverflow.com/comment/83933322
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48469708
has text: as long as whatever is returned by `thisthing()` has a `thatThing` method, then you're set.

http://stackoverflow.com/comment/83916774
type: AnswerComment
score: 1
has text: Wow, thats exactly what I needed. Thank you! Now I only need to understand it.
comment on: http://stackoverflow.com/a/48461810
type: Comment

http://stackoverflow.com/comment/83795347
comment on: http://stackoverflow.com/q/48403381
type: Comment
type: QuestionComment
score: 0
has text: display the values in labels

http://stackoverflow.com/comment/83844518
type: Comment
score: 0
has text: i tried to add a request after the 'login' request to acess the web page with the same log information but it doesn't work, the second requests seems to block in the login.php. i can't figure out how to make python "remember" the log in i did before.
comment on: http://stackoverflow.com/q/48424977
type: QuestionComment

http://stackoverflow.com/comment/83954972
type: QuestionComment
comment on: http://stackoverflow.com/q/48480974
has text: You can't put a frame _over_ another frame using `pack`. It is literally for stacking widgets horizontally and vertically, whereas the problem requires the 3rd dimension
score: 1
type: Comment

http://stackoverflow.com/comment/83695022
has text: Okay, so I scaled my new data, got my prediction. Is there a way to rescale it back to the original values?
type: Comment
comment on: http://stackoverflow.com/a/48353983
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83774945
score: 0
comment on: http://stackoverflow.com/q/48362856
has text: The reason why I was running Django using 'python3 manage.py runserver' instead of wsgi is because I am a rookie with deploying Django. With the mod_wsgi keyword I have found a helpful DigitalOcean guide and official Django docs. I'll play around with them and return here soon to report my solution.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48475116
has body: It looks like you do not have permission to install it. You could try to run it using the python executable, as explained in pip install access denied on Windows Or you could try to run CMD as Administrator, then try installing again.
accepted answer of: http://stackoverflow.com/q/48475080
score: 0
has comment: http://stackoverflow.com/comment/83961109
answers question: http://stackoverflow.com/q/48475080
has comment: http://stackoverflow.com/comment/83964595
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83945902
type: Answer

http://stackoverflow.com/q/48459447
linked to: http://stackoverflow.com/q/23720875
tagged with: opencv
score: 0
has answer: http://stackoverflow.com/a/54012159
favorite count: 0
has comment: http://stackoverflow.com/comment/83913131
has body: I have data similar to the following : 10-0 = [ [1915, 387, 1933, 402], [3350, 387, 3407, 391], [842, 505, 863, 521], ] 10-0 being the credentials of an image(to find the path) and the values inside are coordinates of a box or rectangle each, the formula i'm working on is cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2) , note that 10-0 is the key of one element of a dictionary. My code : import cv2 for key in my_dict: folder_blueprint = re.findall(r'\d+', key) img = PATH_TO_SOURCE+str(folder_blueprint[0])+'-'+str(folder_blueprint[1])+'.png' for line in key: line_number = 0 cv2.rectangle(img,( my_dict[key][line_number][0],my_dict[key][line_number][1]),(my_dict[key][line_number][2],my_dict[key][line_number][3]),(255,0,0),2) # cv2.imread(img) line_number = line_number + 1 cv2.imwrite(FULL_PATH_TO_DESTINATION, img) cv2.imshow(FULL_PATH_TO_DESTINATION, img) k = cv2.waitKey(0) # 0==wait forever What i finally want is the image with red boxes around the regions of interest in a new destination folder leaving the original image intact. And i have referred to similar questions on here with the same error message but they weren't helpful to my case. EDIT: I adjusted the following : img_path = PATH_TO_SOURCE+str(folder_blueprint[0])+'-'+str(folder_blueprint[1])+'.png' img = cv2.imread(img_path) and put int() where i had to in cv2.rectangle section and now i have this error error: (-2) could not find a writer for the specified extension in function imwrite_
has answer: http://stackoverflow.com/a/48460272
type: Question
tagged with: numpy
has title: error: (-2) could not find a writer for the specified extension in function imwrite_
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83912928

http://stackoverflow.com/q/48476737
has comment: http://stackoverflow.com/comment/83947540
has comment: http://stackoverflow.com/comment/83946701
has body: I'm trying to figure out how Auth0 works. So far I'm not lucky. What I am trying to achieve is simple: POST to the oauth/token endpoint and receive a token in return. With curl this is no problem. I can curl --request POST [...] and receive a token just fine. When I try to do this using python and pythons requests module I'm getting an error stating that I'm not authorized. The data is exactly the same, I double checked. Here's my python code: import json, requests endpoint = 'https://mydomain.auth0.com/oauth/token' data = { 'grant_type': 'password', 'username': 'myuser', 'password': 'mypassword', 'audience': '', 'scope': 'read:sample', 'client_id': 'myclientid', 'client_secret': 'myclientsecret' }, headers = {'content-type': 'application/json'} response = requests.post(url=endpoint, data=json.dumps(data), headers=headers) print("STATUS: ", response.status_code) print("Response: ", response.json()) Working Curl request: curl --request POST \\ --url 'https://mydomain.auth0.com/oauth/token' \\ --header 'content-type: application/json' \\ --data '{"grant_type":"password","username": "myuser","password": "mypassword","audience": "", "scope": "read:sample", "client_id": "myclientid", "client_secret": "myclientsecret"}' I also tried setting the user agent in my python code to "curl/7.51.0", but that also did not work :D I'm happy with any pointer! EDIT: I shamefully have to admit that I did not use the same username afterall. That didn't change the fact though that I could not authorize myself with the python code. The SDK as suggested by @cricket_007 works fine. I find this a little bit weird but well.
has title: Using the auth0 /oauth/token endpoint from python
has comment: http://stackoverflow.com/comment/83947106
tagged with: python
has comment: http://stackoverflow.com/comment/83952976
tagged with: auth0
has comment: http://stackoverflow.com/comment/83946628
type: Question
upvote count: 2
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83946728
downvote count: 0
has comment: http://stackoverflow.com/comment/83975622
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83947357
has answer: http://stackoverflow.com/a/73973348
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83946786
favorite count: 0
has answer: http://stackoverflow.com/a/48477448

http://stackoverflow.com/q/48371683
tagged with: scrapy
type: Question
tagged with: xpath
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83730375
has answer: http://stackoverflow.com/a/48374290
answer count: 1
tagged with: python
has body: I'm using scrapy and trying to extract the text inside an anchor tag using xpaths. The anchor tag has a class called test for example. Example: &lt;a class="test"&gt; This is the text i need &lt;/a&gt; This is what i currently have: //a[@class="test"]/ How can I grab the text inside here using the anchor tag and class?
score: 0
has title: Xpath for finding text inside of an anchor tag using class

http://stackoverflow.com/comment/84655040
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48424385
has text: Thanks for your explanation

http://stackoverflow.com/q/48433529
has comment: http://stackoverflow.com/comment/83859325
has title: How to set property of QTextCharFormat in PyQt?
has comment: http://stackoverflow.com/comment/83859460
tagged with: pyqt5
type: Question
tagged with: pyqt
has body: I am trying to set a custom property of an image inserted into a QTextEdit. I have the following example code which sets then outputs the value of the property to the terminal: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * class TestEditor(QWidget): def __init__(self): QWidget.__init__(self) layout = QVBoxLayout() self.setLayout(layout) self.layout().setSpacing(0) self.layout().setContentsMargins(0, 0, 0, 0) self.textEdit = QTextEdit() self.layout().addWidget(self.textEdit) document = self.textEdit.document() cursor = QTextCursor(document) cursor.insertImage("./testimage.png") f = cursor.charFormat() print(f) prop_id = 0x100000 + 1 f.setProperty(prop_id, 100) print(f.intProperty(prop_id)) print('------') block = document.firstBlock() while block.length() &gt; 0: print(block) it = block.begin() while not it.atEnd(): f = it.fragment() fmt = f.charFormat() print(fmt) print(fmt.intProperty(prop_id)) it += 1 block = block.next() class TestWindow(QWidget): def __init__(self): QWidget.__init__(self) self.initUi() def initUi(self): layout = QVBoxLayout() layout.addWidget(HextEditor()) self.setLayout(layout) self.layout().setSpacing(0) self.layout().setContentsMargins(0, 0, 0, 0) self.setWindowTitle('button tooltip') self.show() def main(): app = QApplication(sys.argv) window = TestWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() The program results in an output of: &lt;PyQt5.QtGui.QTextCharFormat object at 0x107109ba8&gt; 100 ------ &lt;PyQt5.QtGui.QTextBlock object at 0x105448318&gt; &lt;PyQt5.QtGui.QTextCharFormat object at 0x107109ba8&gt; 0 Note that the second time the value is gotten it has a value of 0 rather than 100. It even appears to be the same instance of a QTextCharFormat. How would I accomplish something like this? Am I missing something simple here?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83861160
tagged with: qt
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48447220
has answer: http://stackoverflow.com/a/48447220

http://stackoverflow.com/comment/83947726
type: QuestionComment
comment on: http://stackoverflow.com/q/48476348
has text: I have written a program for this, but it can only be used backward, but I want it forward, appeared letter by letter AFTER the window has turn on
score: 0
type: Comment

http://stackoverflow.com/q/48453816
tagged with: python
has comment: http://stackoverflow.com/comment/83907786
tagged with: kivy
has comment: http://stackoverflow.com/comment/83917548
has answer: http://stackoverflow.com/a/48460928
type: AnsweredQuestion
score: 0
has title: How to add Images into a Kivy StackLayout?
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48460928
has comment: http://stackoverflow.com/comment/83917607
tagged with: mobile
tagged with: android
has body: I'm trying to put some images into a StackLayout in Kivy, but it is not going on well. When I put simple Buttons or Labels, the StackLayout adds the widgets like a stack. But when I add a Label with canvas inside: it didn't work fine. I'm using a on_press() event to do this. My on_press() function does it: # The Label works fine without any widget inside it lb = Label(text='Hi', size_hint=(1., .1)) # It just adds only one image """with lb.canvas: Color(1, 1, 1) Rectangle(size=lb.size, pos=lb.pos, source='images/parking_free.png') """ lb = Label(text='Hi', size_hint=(1., .1)) self.ids.my_stack_layout.add_widget(lb) Ignore the Button in the images, please! I'm using it in my .kv for test. It works fine: When I use a simple Label It doesn't work: When I use canvas inside a Label

http://stackoverflow.com/q/48452959
tagged with: javascript
tagged with: python
tagged with: regex-group
has title: Difference of regex in python and google app script (backend engine related?)
tagged with: regex
has answer: http://stackoverflow.com/a/48457837
tagged with: google-apps-script
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I tried the same regular expression both in python (3.6, jupyter notebook) and Google app script, but it seems like "non-capturing group" is not working in the app script case. # python script: import re text='&lt;a class=""email"" href=""mailto:SOisAwesome@hello.edu""&gt;' regex='(?:&lt;a class=""email"" href=""mailto:)(.+?@hello\.edu)(?:""&gt;)' match=re.search(regex,text) print(match.group(1)) # result is 'SOisAwesome@hello.edu' // Google app script function myFunction() { string='&lt;a class=""email"" href=""mailto:SOisAwesome@hello.edu""&gt;' regex=new RegExp('(?:&lt;a class=""email"" href=""mailto:)(.+?@hello\.edu)(?:""&gt;)') Match=regex.exec(string) Logger.log(Match[1]) // result is 'a class=""email"" href=""mailto:SOisAwesome@hello.edu' } If I am not mistaken, regular expression engine in Google app script should support non-capturing groups (referring to https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines, I suppose I should be looking at "JavaScript (ECMAScript)" and "Shy groups"?), can anyone explain what I'm missing here? Thanks in advance!
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48457837

http://stackoverflow.com/a/61113139
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/129952722
accepted answer of: http://stackoverflow.com/q/48444208
downvote count: 0
answers question: http://stackoverflow.com/q/48444208
score: 3
has body: This is now implemented in skimage.measure.regionprops_table.
type: Answer
has comment: http://stackoverflow.com/comment/129929559
has comment: http://stackoverflow.com/comment/129905126

http://stackoverflow.com/comment/88428056
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48444260
has text: Does the output from with the build info omitted work any better? The build can be found in format package=version=build_info, and generated via `conda env export --no-builds `
type: Comment

http://stackoverflow.com/comment/83800787
score: 0
type: QuestionComment
has text: @quamrana My bad I messed up. The sequence is 13 bytes, so what I need it to be is `b'\0x98\0x98\0x21\0x21\0x18\0x12\0x21\0x12\0x02\0x32\0x11\0x12\0x11`
type: Comment
comment on: http://stackoverflow.com/q/48405799

http://stackoverflow.com/a/48340733
upvote count: 4
has body: I'm not sure what the issue is, and might be telnet related. A workaround it to use another remote debugger that seems to work: #Install on the system pip3 install epdb # Set in the code import epdb; epdb.serve() # Connect to the debugger python3 -c 'import epdb; epdb.connect()' Given that this is just a workaround, won't accept it as an answer.
has comment: http://stackoverflow.com/comment/119318317
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48340732
type: Answer
has comment: http://stackoverflow.com/comment/119304384

http://stackoverflow.com/comment/83730729
comment on: http://stackoverflow.com/q/48371856
score: 2
has text: @PeterWood on the contrary. Booleans _are_ integers.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83686734
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48348827
type: AnswerComment
has text: BTW, is there some documentation that I could read to learn about `QTreeView` and `QFileSystemModel`?

http://stackoverflow.com/q/48407856
has answer: http://stackoverflow.com/a/48408070
accepted answer: http://stackoverflow.com/a/48408070
has body: I'm trying to create CNN model using keras ad tensorflow as backend. below is code for the same.. Cannot understand what input it is expecting... import cv2,os import glob import numpy as np from sklearn.utils import shuffle from sklearn.cross_validation import train_test_split from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten PATH = os.getcwd() data_path = PATH + '/data1/cat/*.PNG' files = glob.glob(data_path) X_data = [] for myFile in files: image = cv2.imread (myFile) image_resize = cv2.resize(image,(128,128)) X_data.append (image_resize) image_data = np.array(X_data) image_data = image_data.astype('float32') image_data /= 255 print('X_data shape:', image_data.shape) #Class ani labels class_num = 2 total_Images = image_data.shape[0] labels = np.ones((total_Images),dtype='int64') labels[0:30] = 0 labels[31:] = 1 Y = to_categorical(labels,class_num) #print(Y); # Shuffle the dataset x, y = shuffle(image_data, Y, random_state=2) # Split the dataset X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2) input_shape = image_data[0].shape #print(input_shape) model = Sequential() conv1 = Convolution2D(32,(3,3),padding='same',activation='relu')(input_shape) conv2 = Convolution2D(32,(3,3),padding='same',activation='relu')(conv1) pool_1 = MaxPooling2D(pool_size=(2,2))(conv2) drop1 = Dropout(0.5)(pool_1) conv3 = Convolution2D(64,(3,3),padding='same',activation='relu')(drop1) conv4 = Convolution2D(64,(3,3),padding='same',activation='relu')(conv3) pool_2 = MaxPooling2D(pool_size=(2,2))(conv4) drop2 = Dropout(0.5)(pool_2) flat = Flatten()(drop2) hidden = Dense(64,activation='relu')(flat) drop3 = Dropout(0.5)(hidden) out = Dense(class_num,activation='softmax')(drop3) model.compile(loss = 'categorical_crossentropy', optimizer= 'adam', metrics=['accuracy']) model.fit(X_train,y_train,batch_size=16,nb_epoch=20, verbose=1, validation_data=(X_…
type: Question
downvote count: 0
answer count: 1
has title: What should be the input to Convolution neural network (CNN) using keras and tensorflow?
upvote count: 1
tagged with: keras
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/q/48373118
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/11253243
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83735945
tagged with: rpy2
tagged with: python
has comment: http://stackoverflow.com/comment/83736124
tagged with: ubuntu
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/83736218
has comment: http://stackoverflow.com/comment/83736134
answer count: 0
has comment: http://stackoverflow.com/comment/83734462
has comment: http://stackoverflow.com/comment/83735874
score: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/11253243
has title: Error installing rpy2 on Ubuntu
has body: I am trying to install rpy2 in Linux and I keep getting these errors. I updated my Python to 3.6 as well. I have Ubuntu 16.4 Collecting rpy2 Using cached rpy2-2.9.2.tar.gz Complete output from command python setup.py egg_info: rpy2 is no longer supporting Python &lt; 3. Consider using an older rpy2 release when using an older Python release. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-yEavWp/rpy2/

http://stackoverflow.com/comment/83830098
type: Comment
comment on: http://stackoverflow.com/q/48339675
type: QuestionComment
has text: In order to get every item Dynamo will need to read every item, no matter if you use Scan or Query. Using a Query improves performance because Dynamo can use indexes to get to a specific subset of your database without having to read everything and then filtering. Since you want everything, it's gonna need to read everything anyway...
score: 0

dbus
type: Tag
tags question: http://stackoverflow.com/q/48347635
tag name: dbus

http://stackoverflow.com/comment/83738621
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48375753
type: Comment
has text: On 3.6.2, I get these numbers in the same order as your tests: `0.05435221083462238` vs `0.05949017032980919` and `0.1505890181288123` vs `0.12044331897050142`. Similar results but in the 3 item case less pronounced.

http://stackoverflow.com/q/48429360
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: Good day to all. Help me please to understand theory of function scipy.ndimage.convolve for 1D arrays. I know the formula from http://lagrange.univ-lyon1.fr/docs/scipy/0.17.1/generated/scipy.ndimage.convolve.html C_i = \sum_j{I_{i+j-k} W_j}, but i can't understand, how can I get results manually. For example: test_1 = scipy.ndimage.convolve([1, 2, 3], [1, 2, 3, 4, 5]) result is [24 24 30] Or test_2 = scipy.ndimage.convolve([1, 2, 3], [3, 4, 5]) result is [15 22 31] If I write here all attempts that I have made, it will take a lot of space. Give me please step by step instructions on what to do with these examples manually.
tagged with: scipy
favorite count: 0
type: Question
has title: Theory and step-by-step instruction of scipy.ndimage.convolve
has answer: http://stackoverflow.com/a/48623352

http://stackoverflow.com/comment/83831088
comment on: http://stackoverflow.com/q/48419066
has text: Check out `Source IP address` inside CloudTrail events.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83892322
type: Comment
comment on: http://stackoverflow.com/a/48435382
type: AnswerComment
has text: I got the same results. I think this is due to the data: iris dataset is too small and simple, so you could try using a bigger dataset.
score: 0

http://stackoverflow.com/comment/83942634
has text: I checked it out, but their last layer contains 1 output node while I want 38 and while I change it to 38 then problems appears again
comment on: http://stackoverflow.com/a/48470788
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83814979
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48412466
has text: I changed the period and editing up here - check it out

http://stackoverflow.com/comment/83844884
has text: Context - For each item, we create a separate model that predicts value and one that predicts cost at different states. Each item can be in one of possible 11 states. Each state has an associated value/reward along with cost and revenue. I need to select one of the state for each item such that sum(value) is maximized and global ROI, i.e. sum(revenue)/sum(cost)>= target_roi. This is very similar to dummy problem I have mentioned above and have also implemented the solution in R using lpSolve. Now I need to implement the same in python and wasn't very clear about syntax.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48424428

http://stackoverflow.com/a/48347357
answers question: http://stackoverflow.com/q/48346897
type: Answer
score: 0
has body: There is a trailing comma after the square bracket in line 39, please remove that and it should work fine To avoid this error in future you can just open your json in an IDE that supports json format checking .. i use eclipse or atom IDE and just opening a json file shows if there are any syntax/formatting errors in the json data. Json with trailing comma removed: { "create": [ { "name": "Woo Single #1", "type": "simple", "status": "draft", "regular_price": "21.99", "virtual": true, "downloadable": true, "downloads": [ { "name": "Woo Single", "file": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/cd_4_angle.jpg" } ], "categories": [ { "id": 11 }, { "id": 13 } ] }, { "name": "New Premium Quality", "type": "simple", "status": "draft", "regular_price": "21.99", "description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.", "short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", "categories": [ { "id": 9 }, { "id": 14 } ] } ] }

http://stackoverflow.com/comment/83886273
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48446875
has text: You should probably take a look at https://stackoverflow.com/questions/588004/is-floating-point-math-broken and the Wikipedia articles on floating point and IEEE-754, eg https://en.wikipedia.org/wiki/Double-precision_floating-point_format

http://stackoverflow.com/comment/83649880
has text: Is there a way to turn the `itertools.chain` into a range? `range(len(itertools.chain(a[1:2], a[4:7], a[9:10])))` doesn't work.
comment on: http://stackoverflow.com/a/48331947
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48461429
tagged with: nlp
tagged with: text
has answer: http://stackoverflow.com/a/48461537
score: 0
has title: What is the best approach to extract keywords from different strings in python?
has body: I am looking to extract important keywords from a set of text pieces which are actually text messages received after any transaction. Below is a sample dataset: {"message": "*boi star sandesh* rs 20 has been debited to your account xx2136 from pos-paytm.com on 08-11-2014.available balance 275.00.", "number": "boiind"} {"message": "your a/c xxxxx388847 debited inr 7,500.00 on 12/08/16 -transferred to mr. rajendra kurmi . a/c balance inr 1,314.45", "number": "amcbssbi"} {"message": "an amount of rs.10,000.00 has been debited from your account number xxxx1152 for an online payment txn done using hdfc bank netbanking.", "number": "dmhdfcbk"} {"message": "your a/c no. xxxxxxxx1152 is debited for rs. 10,000.00 on 11-08-16 and a/c xxxxxxx847 credited (imps ref no 622421331357)", "number": "vkhdfcmp"} {"message": "one time password for netbanking transaction is 785516. please use the password to complete the transaction. pls do not share this with anyone. ref no- xxxx4763", "number": "imhdfcbk"} {"message": "your a/c no. xxxxxxxx3962 is debited for rs.20000.00 on 11-08-16 and a/c of unregistered has been credited (imps ref no 622421342625).", "number": "dmaxisbk"} And I need to extract information from the messages about the transaction amount, the remaining balance, the date, and the type of transaction. What approach should I take and what module will be the best? FYI The messages from the same number have the same message format but I have to deal with a large number of formats so writing code for each number will be repetitive and time consuming.
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: data-extraction
type: UnansweredQuestion
tagged with: python
tagged with: text-processing

http://stackoverflow.com/q/48437262
has title: How do I adjust the image size in the QTableWidget?
score: 0
has comment: http://stackoverflow.com/comment/83902039
has body: I want to adjust the image size in the QTableWidget. But it is size comes out small. (The part that looks like an "이미지") Below is the original image. Please help me by referring to the code below. Thanks. from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * imgPath = "D:\Image\Image1.png" self.tableWidget1 = QTableWidget(self.tab1) self.tableWidget1.setRowCount(30) self.tableWidget1.setColumnCount(3) self.tableWidget1.setHorizontalHeaderLabels(setNameList) self.tableWidget1.resize(1824, 760) self.tableWidget1.move(0, 0) self.tableWidget1.setItem(0, 0, QTableWidgetItem(QIcon(QPixmap(imgPath).scaled(QSize(1280, 640), Qt.KeepAspectRatio)), ''))
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/83901921
has comment: http://stackoverflow.com/comment/83901261
type: Question
has comment: http://stackoverflow.com/comment/83873865
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83901754
tagged with: python
has comment: http://stackoverflow.com/comment/83901727
has comment: http://stackoverflow.com/comment/83901033
has comment: http://stackoverflow.com/comment/83901879

http://stackoverflow.com/comment/83861567
score: 0
has text: @Mitchel0022 It did work insofar as the turtle drew the full square, but now the loop goes on forever. The same goes for (-100,0).
type: Comment
comment on: http://stackoverflow.com/q/48435008
type: QuestionComment

http://stackoverflow.com/a/48457820
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48457754
type: AcceptedAnswer
upvote count: 1
has body: I think you need replace by dictionary with numbers as strings with codes, for replace substrings add regex=True: d = {'1':'a', '2':'b', '3':'c', '4':'d', '7':'e'} df['mycol2'] = df['mycol1'].replace(d, regex=True) print (df) mycol1 mycol2 0 ABC ABC 1 CDE CDE 2 EFG EFG 3 2, GHI b, GHI 4 IJK IJK 5 2,4 KLM b,d KLM 6 MNO MNO 7 1, 2, 3, OPQ a, b, c, OPQ 8 7 QRS e QRS 9 STU STU 10 UWX UWX 11 XYZ XYZ
accepted answer of: http://stackoverflow.com/q/48457754
downvote count: 1

http://stackoverflow.com/comment/83942300
has text: what is non standard string literal macro can you explain it?
type: Comment
comment on: http://stackoverflow.com/a/48465029
type: AnswerComment
score: 1

http://stackoverflow.com/q/48456483
tagged with: keras
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48456970
type: Question
tagged with: pandas
has title: Keras modelling: Do I need one-hot encoding and if so how?
score: 1
has body: I would like to have your help with setting up a model with Keras. I have a dataset which contains interval data like age or salary. Then it also contains e.g. sex (male/female) or department (sales/HR/finance/service). I assume that for e.g. "sex" I might go for 0/1 . But for department 1/2/3/4 I assume I better use one-hot encoding? If so, I'm not clear about how the dataframe should look like. Let's just look at three fields: EmpNo Sex Dept 1 0 [0,0,1,0] 2 1 [0,0,0,1] 3 0 [1,0,0,0] 4 0 [0,0,1,0] Or would it need to look like this: EmpNo Sex Dept_1 Dept_2 Dept_3 Dept_4 1 0 0 0 1 0 2 1 0 0 0 1 3 0 1 0 0 0 4 0 0 0 1 0 As you can see I'm not clear what and how it can be processed in Keras. Of course the second one can be processed but I would find a first setup nicer to control. Any other comments? Am I on the right path?
accepted answer: http://stackoverflow.com/a/48456970
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/83954231
has text: Try passing `dflon.values` and `dflat.values`.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48480510

http://stackoverflow.com/q/48370499
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48487641
answer count: 2
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48372180
has title: Is it possible to limit the number of messages a user can send a day with Django postman?
tagged with: django-apps
tagged with: django
tagged with: python
has body: I have been using Django Postman for a few weeks now, and in order to limit the number of messages sent by each user, I have been wondering what would be the best way to limit the number of messages a user can send a day, a week... using Django-postman? I have been browsing dedicated documentation for weeks too in order to find an answer for the how, but I think this is not a usecase for now, and I do not really know how to manage that. Of course I am not looking for a well cooked answer, but I would like to avoid writing labyrinthine code, so maybe just a few ideas about it could help me to see clear through that problematic. Many thanks for your help on that topic!
possible better answer: http://stackoverflow.com/a/48372180
accepted answer: http://stackoverflow.com/a/48487641

http://stackoverflow.com/comment/83680068
comment on: http://stackoverflow.com/a/48345591
type: AnswerComment
has text: print your `loss` with training and report the loss. Is it `0` or `nan`?
score: 0
type: Comment

http://stackoverflow.com/a/48481551
has comment: http://stackoverflow.com/comment/84142423
has body: I don't think Keras supports the TensorFlow file system which in turn knows how to read from GCS. You could try downloading from GCS to a local path, and then reading from that to load the model.
has comment: http://stackoverflow.com/comment/84392518
type: Answer
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/84147956
answers question: http://stackoverflow.com/q/48392457
downvote count: 0

http://stackoverflow.com/q/48363104
favorite count: 0
has comment: http://stackoverflow.com/comment/83713272
type: Question
has answer: http://stackoverflow.com/a/48363198
accepted answer: http://stackoverflow.com/a/48363198
upvote count: 0
tagged with: python
score: -1
has title: Paying off debt program in Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83713166
has body: I am currently working on a problem which asks to make a program that determines fixed monthly payments to pay off a certain amount of debt. For some reason, this code enters an infinite loop when I increment the MP value by anything less than 70. And if I use a value of 70 and higher, the recommended monthly payment is way off. def NoDebt(balance, annualInterestRate): ''' balance -&gt; int/float, the amount of debt youre in annualInterestRate --&gt; interest rate (divide by % 100 first) ''' balance0 = balance month = 0 MIR = annualInterestRate/12.0 MP = 10 while balance &gt; 0: balance = balance0 MP = MP + 10 while month &lt; 12: MUB = balance - MP balance = MUB + (MIR*MUB) month = month + 1 return MP I've run this and just talked through it for a while -- not sure why it's not working. Does anyone have any advice?
answer count: 1
downvote count: 1

http://stackoverflow.com/q/48444281
has comment: http://stackoverflow.com/comment/83881016
upvote count: 0
type: UnansweredQuestion
answer count: 1
has title: Proper way to close a file object used as stdout argument for Popen
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/34314475
type: Question
has body: In my script, I redirect stdout to a file as below: with open(logFileName, 'w') as fp: proc = Popen([myexe], stdout=fp) # proc.wait() # I don't want to block until process completes. I understand that the fp would be closed even before the process completes. Thus my program does not work as expected. If I do a wait(), it will work but I don't want to block. I am wondering what is the right way to do this. Is a separate thread the only way? Surprisingly, I could not find an answer through google through this requirement should be a very common one. Update: I see that it was not working for a different reason. It works fine even though the file object would be closed even before the process completes. Still not sure if this is right way to do.
tagged with: python
has answer: http://stackoverflow.com/a/48444384
score: -1

http://stackoverflow.com/q/48343828
upvote count: 1
tagged with: python
has body: I have created a list of generators, as follows: x = [1, 2] axes = [] for axis_max in x: axis_grid = (i + axis_max for i in [2, 3, 4]) axes.append(axis_grid) print([list(gen) for gen in axes]) For some reason, the output from this code snippet is as follows: [[4, 5, 6], [4, 5, 6]] whereas I clearly thought it should output this: [[3, 4, 5], [4, 5, 6]] Can you please help me understand why it happens, and how to fix it? (EDIT) I now know why it happens now, but still don't know how to fix it using a generator expression, and not a function. Plainly, I can fix it by turning the generators into lists, as follows: x = [1, 2] axes = [] for axis_max in x: axis_grid = (i + axis_max for i in [2, 3, 4]) axes.append(list(axis_grid)) print([list(gen) for gen in axes]) This snippet returns the needed [[3, 4, 5], [4, 5, 6]] but that is not what I want.
tagged with: generator
linked to: http://stackoverflow.com/q/10733701
has title: Why is the list of generators changing generators?
has comment: http://stackoverflow.com/comment/83674181
score: 1
duplicate of: http://stackoverflow.com/q/10733701
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83958004
score: 0
has text: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: Comment
comment on: http://stackoverflow.com/q/48482466
type: QuestionComment

http://stackoverflow.com/a/48362124
type: AcceptedAnswer
has body: 1) When overwriting: What happens to the old one? Is it still running in the background? You have overwritten only reference to the thread, the thread itself is still running. Is there a way to terminate it? There is no clean way of terminating threads, see: Is there any way to kill a Thread in Python? 2) If you want to stop the thread, you shoud use global var that tells the thread to stop. stop = False def loop_play(sound_file): global stop audio = AudioSegment.from_file(sound_file) while is_playing: if stop: return play(audio) def play_sound(sound_file): global is_playing global sound_thread global stop if not is_playing: stop = True while sound_thread.isAlive(): # Wait for thread to exit sleep(1) stop = False is_playing = True sound_thread = Thread(target=loop_play,args=[sound_file]) sound_thread.daemon = True sound_thread.start() Note, that i have not fully understood meaning of is_playing in your code.
has comment: http://stackoverflow.com/comment/83711185
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48361972
answers question: http://stackoverflow.com/q/48361972
score: 3
upvote count: 3

http://stackoverflow.com/a/48382762
accepted answer of: http://stackoverflow.com/q/48382663
has body: If you have a column of strings, I'd recommend looking here at different ways of parsing it. Here's how I'd do it, using ast.literal_eval. &gt;&gt;&gt; import ast &gt;&gt;&gt; [list(map(str, x)) for x in df['set'].apply(ast.literal_eval)] Or, using pd.eval - &gt;&gt;&gt; [list(map(str, x)) for x in df['set'].apply(pd.eval)] # 100 rows or less Or, using yaml.load - &gt;&gt;&gt; import yaml &gt;&gt;&gt; [list(map(str, x)) for x in df['set'].apply(yaml.load)] [ ['911', '3040'], ['130055', '99832', '62131'], ['19397', '3987', '5330', '14781'], ['76514', '70178', '70301', '76545'], ['79185', '38367', '131155', '79433'] ]
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48382663
type: Answer

http://stackoverflow.com/q/48407865
tagged with: taskscheduler
answer count: 1
type: Question
tagged with: windows
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48408037
has body: I have found several solutions to save a batch file run from task scheduler to a txt file but the same technique of appending a > file.txt doesn't work for a python script which i am triggering through the task scheduler. Also tried >> file.txt How to i save a python script console output to a txt file which is executed from the task scheduler? This is the command that i am executing from the task scheduler, which is running fine except that it doest save the console output to the txt file. Program Script - C:\Python27\python.exe C:\Dropbox\Nightly_SSIM.py > C:\LAF\6.7\Nightly_Debug.txt
has title: Save Scheduled Task (PYTHON Script NOT Batch file) Console Output to a file
score: 0

git
tags question: http://stackoverflow.com/q/48334158
tags question: http://stackoverflow.com/q/48357817
tags question: http://stackoverflow.com/q/48473513
type: Tag
tags question: http://stackoverflow.com/q/48473007
tags question: http://stackoverflow.com/q/48463761
tag name: git
tags question: http://stackoverflow.com/q/48353603
tags question: http://stackoverflow.com/q/48352771
tags question: http://stackoverflow.com/q/48477848
tags question: http://stackoverflow.com/q/48399498
tags question: http://stackoverflow.com/q/48465681
tags question: http://stackoverflow.com/q/48462823

http://stackoverflow.com/q/48445144
linked to: http://stackoverflow.com/q/552744
tagged with: python
tagged with: memory
score: 8
has answer: http://stackoverflow.com/a/53735568
has title: Python hangs for hours on end of functions after creating huge object
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/94324471
has comment: http://stackoverflow.com/comment/83924608
upvote count: 8
has body: I have a function that generates a huge object (about 100-150Gb of memory, on a machine having 500Gb memory). The function runs in about 1h, and writes a file to disk (about 100Mb). But when the function ends, the program hangs there for several hours without doing anything (it doesn't continue instructions after the place where the function was called). I suspect the garbage collector trying to delete the huge object created in this function, but I don't see anything happening (strace prints nothing), and the memory is not decreasing. Do you have any idea of why this is happening and how to solve it ? I'm using python 3.5
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83882053
type: UnansweredQuestion

http://stackoverflow.com/comment/83911062
has text: Not sure if that helps: try to run manual collection (`gc.collect()`) three times, passing it 0, 1, and 2 respectively (to free all generations of objects).
comment on: http://stackoverflow.com/q/48458865
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48466220
has body: A Simpler Way Is To Create A List. example-string = "ap126ks8ar" ar = [] numbers = "0123456789" i=0 while i&lt; len(example-string): if example-string[i] in numbers : ar.append[example-string[i] i+=1
score: 0
answers question: http://stackoverflow.com/q/48465368
type: Answer

http://stackoverflow.com/a/48487979
downvote count: 0
has comment: http://stackoverflow.com/comment/83968962
type: Answer
has body: The problem is your while guard, which checks if the number is less than two times itself. To solve this, save the threshold you want to reach in a variable before the loop, and you have done: threshold = 2 * x count = 0 while x &lt; threshold: x = x * (1 + y) count = count + 1
score: 2
answers question: http://stackoverflow.com/q/48487936
upvote count: 2
has comment: http://stackoverflow.com/comment/83968840

http://stackoverflow.com/q/48387241
upvote count: 0
has body: I am getting a weird "Access denied - \" error\warning when I run the following script: import os import subprocess directory = r'S:\ome\directory' subprocess.run(['find', '/i', '"error"', '*.txt', '&gt;Errors.log'], shell=True, cwd=directory) I have also checked: print(os.access(directory, os.R_OK)) # prints True print(os.access(directory, os.W_OK)) # prints True and they both print True. The error message is printed while the subprocess command is running but the process is not killed; nothing is raised. As a result, wrapping it into a try-except even without specifying the exception is not catching anything. When the process finishes, the file is created (Error.log) but contains the wrong results. Running the exact same command (find /i "fatal" *.txt &gt;Error.log) from a cmd opened in the specified directory produces the correct results. So in which way are the two approaches different? Approach 1 (from Python): subprocess.run(['find', '/i', '"error"', '*.txt', '&gt;Errors.log'], shell=True, cwd=r'S:\ome\directory') Approach 2 (from cmd): S:\ome\directory&gt;find /i "error" *.txt &gt;Errors.log
downvote count: 2
answer count: 3
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/48387515
has answer: http://stackoverflow.com/a/48388338
tagged with: cmd
has answer: http://stackoverflow.com/a/48387965
possible better answer: http://stackoverflow.com/a/48387965
favorite count: 0
type: Question
tagged with: python-3.x
has title: Subprocess.run .vs. running command in the cmd directly
linked to: http://stackoverflow.com/q/7018228
score: -2
has answer: http://stackoverflow.com/a/48387515
has comment: http://stackoverflow.com/comment/83776554
tagged with: windows
has comment: http://stackoverflow.com/comment/83784055
has comment: http://stackoverflow.com/comment/83783575
tagged with: python
has comment: http://stackoverflow.com/comment/83784215
type: AnsweredQuestion

http://stackoverflow.com/q/48482919
has comment: http://stackoverflow.com/comment/83958803
has answer: http://stackoverflow.com/a/48483397
has body: What is -m stands for in python -m unittest? The unittest unit testing framework has other command line options like -v -b -c -t but wondering what does -m stands for? Is it part of unittest or other python command line option?
type: Question
has comment: http://stackoverflow.com/comment/83958810
downvote count: 2
upvote count: 5
linked to: http://stackoverflow.com/q/46319694
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6630822
answer count: 1
score: 3
tagged with: python-unittest
has title: What is `-m` stands for in `python -m unittest`?
has comment: http://stackoverflow.com/comment/83958818
favorite count: 0

http://stackoverflow.com/comment/83806508
type: Comment
type: QuestionComment
has text: @Eric I added the print stats at the bottom. This can also be obtained just by running above code :) Thanks for the reference! I tried setting the backend to `threading` but even that didn't work :( still the original `img_arr` remains unchanged.
comment on: http://stackoverflow.com/q/48387466
score: 0

http://stackoverflow.com/q/48360864
downvote count: 0
accepted answer: http://stackoverflow.com/a/48360899
has comment: http://stackoverflow.com/comment/83708939
favorite count: 0
has comment: http://stackoverflow.com/comment/83708514
type: Question
tagged with: python-3.x
tagged with: python
has body: I have an nested object, a, and want to apply some type of filter on each of its sub-containers: a = [[1, 2], [3, 4, 5, 6], [7, 7, 8]] A function to keep the nested structure but filter to only even elements would look like: def nested_filter(obj): res = [] for sub_obj in obj: even = [i for i in sub_obj if i % 2 == 0] res.append(even) return res nested_filter(a) # [[2], [4, 6], [8]] But I would like to create an equivalent generator that uses some form a nested yield to maintain the nested structure of a. This, for illustration, is exactly what I do not want because it flattens a: def nested_yield(obj): """Will flatten the nested structure of obj.""" for sub_obj in obj: for i in sub_obj: if i % 2 == 0: yield i list(nested_yield(a)) # [2, 4, 6, 8] My understanding was that yield from, introduced in Python 3.3, might allow for nesting that retains the structure of the passed object. But apparently I am misinterpreting: def gen1(obj): for sub_obj in obj: yield from gen2(sub_obj) def gen2(sub_obj): for i in sub_obj: if i % 2 == 0: yield i list(gen1(a)) # [2, 4, 6, 8] So, is there any way I can use two generator functions (i.e. not create intermediate lists) so that calling the generator would give me this: list(nested_generator(a)) # [[2], [4, 6], [8]]
score: 4
has title: Nested generators and yield from?
tagged with: generator
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83708847
has comment: http://stackoverflow.com/comment/83709063
answer count: 1
has answer: http://stackoverflow.com/a/48360899

http://stackoverflow.com/a/48373971
type: AcceptedAnswer
score: 1
upvote count: 1
has body: Emm....I don't know if I catch your question. Do you mean that you want to update element p1 in the object k, and this k in maliste is also update? I would recommend re-writing the acoter method like this: @staticmethod def acoter(nom, b1, b2, maliste): for i, k in enumerate(maliste): if kas.nom == k.nom: k.p1[0] = kas.b1[0] k.p2[0] = kas.b2[0] Because maliste is list() and you just append the object k to the list, so I suspect the for i,k in maliste: will throw out an error. To update a object's property in a list, you can just get the reference of the object and update it's property. So I think you don't need to remove from maliste and insert this updated object into maliste list again. And also, the newlist list is un-needed.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48373747
accepted answer of: http://stackoverflow.com/q/48373747

http://stackoverflow.com/a/61667653
type: Answer
has body: The most simple way: import pandas as pd lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] lst2 = [11, 22, 33, 44, 55, 66, 77] df = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val']) # \1 $1 \g&lt;1&gt; df.replace(regex=r'(\w)(?P&lt;ewe&gt;\w)', value='\g&lt;1&gt;_\g&lt;ewe&gt;=') ## Output Name val 0 G_e=e_k=s 11 1 F_o=r 22 2 G_e=e_k=s 33 3 i_s= 44 4 p_o=r_t=a_l= 55 5 f_o=r 66 6 G_e=e_k=s 77
answers question: http://stackoverflow.com/q/48348095
score: 0

http://stackoverflow.com/comment/83902734
comment on: http://stackoverflow.com/a/48454749
score: 0
has text: thanks you for your prompt answer, can you please explain your code? I do not understand that especially the zip part.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48479384
tagged with: discord
downvote count: 1
has comment: http://stackoverflow.com/comment/83952993
favorite count: 0
has body: I'm currently learning MongoDB using Python and I'm trying my projects with a discord bot. I would like to do some things but I don't know how to do them. The first problem is the following: @bot.command(pass_context=True) async def test(ctx, arg:str=None): db = client.db_test collection = db["test"] cursor = collection.find({"permission" : arg}) if perm is not None: if perm == "x": for y in cursor: await bot.say(y) The bot sends this message: {'_id': '&lt;id&gt;', 'name': '&lt;name&gt;', 'permission': 'x'} But I want it to send like: &lt;name&gt; has permission x The second question is the following: I want to check if a user has permission "x" and print something like: &lt;name&gt; has permission admin How can I resolve and do that?
type: Question
tagged with: discord.py
has title: Problems with PyMongo: Checking a collection
accepted answer: http://stackoverflow.com/a/48480087
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83952092
score: 0
has comment: http://stackoverflow.com/comment/83952743
has answer: http://stackoverflow.com/a/48480087
answer count: 1
tagged with: pymongo
has comment: http://stackoverflow.com/comment/83952395
has comment: http://stackoverflow.com/comment/83952773
has comment: http://stackoverflow.com/comment/83952180
upvote count: 1

http://stackoverflow.com/q/48422874
has comment: http://stackoverflow.com/comment/83835388
type: Question
tagged with: quotes
has answer: http://stackoverflow.com/a/48422911
has body: I have a csv file with the following format 21/10/2017 0:00;123,85;88,8 and i use the command to parse it with open('parseme.csv') as csv_file: reader = csv.reader(csv_file) So I get the values as ['21/10/2017 0:00;123', '85;88', '8'] The problem is I want the value after the date to be altogether because I cannot convert it to integer due to the quote characters in the middle before and after comma. How can I achieve to import it as it was in the CSV, like this: ['21/10/2017 0:00', '123,85', '88,8']
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/83835503
has title: Format the parsed csv file in Python
has comment: http://stackoverflow.com/comment/83835477
has comment: http://stackoverflow.com/comment/83835546
has comment: http://stackoverflow.com/comment/83835713
has comment: http://stackoverflow.com/comment/83837650
score: 0
has comment: http://stackoverflow.com/comment/83835946
has comment: http://stackoverflow.com/comment/83835385
has comment: http://stackoverflow.com/comment/83835609
has comment: http://stackoverflow.com/comment/83835294
answer count: 1
has comment: http://stackoverflow.com/comment/83836023
has comment: http://stackoverflow.com/comment/83835414

http://stackoverflow.com/comment/96805023
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48450050
has text: `gc.get_objects()` will not return a list of all objects. also numpy arrays will not be found by this function.

http://stackoverflow.com/q/48369425
score: 1
upvote count: 1
answer count: 1
has title: Animated Line Graph with Matplotlib/Python
has comment: http://stackoverflow.com/comment/83726043
has comment: http://stackoverflow.com/comment/83725907
linked to: http://stackoverflow.com/q/45155014
type: Question
has comment: http://stackoverflow.com/comment/83730423
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83725770
has comment: http://stackoverflow.com/comment/83725698
has comment: http://stackoverflow.com/comment/83726102
tagged with: python
has answer: http://stackoverflow.com/a/48369795
duplicate of: http://stackoverflow.com/q/45155014
favorite count: 0
has comment: http://stackoverflow.com/comment/83730781
has comment: http://stackoverflow.com/comment/83726007
has comment: http://stackoverflow.com/comment/83730350
type: AnsweredQuestion
has body: I'm having trouble getting my line graph to animate. Background: I'm working on a program that will handle simulating network latency and I'm trying to graph the latency so I can see how well my program is keeping up with the load of commands coming out of the controller. I've setup my figure: # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0,2), ylim = (-2,2)) line, = ax.plot([], [], lw=2) setup an init() and animate() function # initialization function: plot the background of each frame def init(): line.set_data([], []) return line, def animate(i): line.set_data(x[i], y[i]) return line, then in my DelayedTask.process() function (where I measure the time between the intended execution and actual execution) I append the values and index to my x,y lists. delta = self.time - datetime.now() lock = threading.Lock() lock.acquire() x.append(len(x)) y.append(delta.total_seconds()) lock.release() finally at the bottom of my program, I create the animation function. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) Unfortunately, the graph shows up, but the numbers won't plot. I've put a breakpoint in the animate() function and in the deltas are filling in the list, but it won't show any lines on the graph. Here is the full code: import multiprocessing, requests, threading import decimal import random import time import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from queue import Queue from multiprocessing.dummy import Pool as ThreadPool from threading import Thread from datetime import datetime, timedelta class WorkQueue: def __init__(self, threads=6): self.threads = threads def process(self, work): pool = ThreadPool(self.threads) results = pool.map(DelayedTask.process, work) pool.close() pool.join() class DelayedTask: def __init__(self, func, delay, message): print("DelayTask.__init__: {0}".format((func.__name__, delay, me…
has comment: http://stackoverflow.com/comment/83725769
has comment: http://stackoverflow.com/comment/83725865
accepted answer: http://stackoverflow.com/a/48369795
downvote count: 0
tagged with: animation

http://stackoverflow.com/comment/83835477
type: QuestionComment
score: 0
has text: @MadPhysicist I don't think that's what OP wants but I also don't see why they would want is as `['21/10/2017 0:00;123,85;88,8']` They maybe meant: `['21/10/2017', '0:00;123,85;88,8']`
type: Comment
comment on: http://stackoverflow.com/q/48422874

http://stackoverflow.com/a/48347516
has body: After a long search (because searching on "%", "mod", "modulo" etc. gives a thousand of results), I finally found that, surprisingly, this is intended: There are some small differences between arithmetic on Decimal objects and arithmetic on integers and floats. When the remainder operator % is applied to Decimal objects, the sign of the result is the sign of the dividend rather than the sign of the divisor: &gt;&gt;&gt; (-7) % 4 1 &gt;&gt;&gt; Decimal(-7) % Decimal(4) Decimal('-3') I don't know the reason for this, but it looks like it's not possible to change this behaviour (without patching).
downvote count: 0
answers question: http://stackoverflow.com/q/48347515
has comment: http://stackoverflow.com/comment/83693610
has comment: http://stackoverflow.com/comment/83685183
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/87463832
has comment: http://stackoverflow.com/comment/87464961

http://stackoverflow.com/comment/83868760
comment on: http://stackoverflow.com/q/48438859
score: 1
has text: Every second? Are you sure those sites are happy for you to do that?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83772181
type: Comment
has text: I do that right at the start, so `u` doesn't run all the way to `2*pi`. You must have done something like that to show the gap in the 3rd figure.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48373269

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/48468115
tags question: http://stackoverflow.com/q/48450566
tag name: decision-tree

http://stackoverflow.com/comment/83679901
type: QuestionComment
has text: `x` and `y` never change, so your loop is either endless or ends during the first iteration.
comment on: http://stackoverflow.com/q/48347002
score: 1
type: Comment

http://stackoverflow.com/q/48390732
tagged with: pandas-apply
score: 2
has comment: http://stackoverflow.com/comment/83776086
has comment: http://stackoverflow.com/comment/83804398
tagged with: pandas-groupby
answer count: 0
upvote count: 2
tagged with: pandas
tagged with: aggregate
has body: I have a MultiIndex pandas DataFrame of this schematic form (although the real dataframe I'm working with has millions of rows): import pandas as pd df = pd.DataFrame([['Alpha', 'a', 1,10], ['Alpha', 'a', 2,20],['Alpha', 'a', 3,30], ['Alpha', 'b', 1,50],['Alpha', 'b', 2,60],['Alpha', 'b', 3,10], ['Alpha', 'c', 1,10],['Alpha', 'c', 2,70],['Alpha', 'c', 3,80], ['Beta', 'a', 1,30], ['Beta', 'a', 2,40],['Beta', 'a', 3,50], ['Beta', 'b', 1,80],['Beta', 'b', 2,70], ['Beta', 'b', 3,60], ['Beta', 'c', 1,10],['Beta', 'c', 2,30], ['Beta', 'c', 3,40]], columns=['Product', 'Scenario', 'Time','Price'])\ .set_index(['Product', 'Scenario']) Grouping by product and time, I would like the rank autocorrelation of 'Price' across scenarios, defined schematically as follows (product by product): (rank autocorrelation at time t) = rank correlation('Price' at time t , 'Price' at time t+1) where ('Price' at time t) is a vector with as many entries as scenarios (and we have one such vector for each product). For example, for product 'Alpha' at time t=2, the desired quantity is import scipy from scipy import stats as ss ss.spearmanr([20,60,70] , [30,10,80])[0] which gives 0.5. For the last time step (t=3 in this case) it should simply give NaN back (because there's no data for t+1). All in all, the desired resulting dataframe should be: import numpy as np df_result = pd.DataFrame([['Alpha',1,0], ['Alpha',2,0.5],['Alpha',3,np.nan], ['Beta',1,1], ['Beta',2,1],['Beta',3,np.nan]], columns=['Product', 'Time','Autocorrelation'])\ .set_index(['Product']) Time Autocorrelation Product Alpha 1 0.0 Alpha 2 0.5 Alpha 3 NaN Beta 1 1.0 Beta 2 1.0 Beta 3 NaN I thought to start with something like df.groupby(['Product','Time']).agg(autocorrelation function) but then the aggregation operation requires data from two different groups (i.e. groups for different times), and I haven't found a way to do that so far. Any ideas?
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83804422
has comment: http://stackoverflow.com/comment/83773583
linked to: http://stackoverflow.com/q/26083293
favorite count: 0
type: Question
has title: Time-dependent rank autocorrelation in pandas
tagged with: python
linked to: http://stackoverflow.com/q/28988627

http://stackoverflow.com/q/48342183
answer count: 1
has comment: http://stackoverflow.com/comment/83670066
tagged with: django
has comment: http://stackoverflow.com/comment/83669653
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48342234
has body: So I have this Lecture class. Now for this class, I have 2 choices: "Classes" and "Seminars", and I want that each time I add a lecture to either one, the template will shows firstly the choice and then all the lectures. Example: Classes will have Lecture1, Lecture2, Lecture3 etc. Problem is that right now when I iterate, choice shows each time, for every lecture and I want each choice to show only ONCE. class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) lecture_title = models.CharField(max_length=100) content = models.TextField() link = models.URLField(blank=True) file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.lecture_title {% for c in lectures %} {{ c.get_lecture_category_display }} ....................... {{ c.lecture_title }} {{ c.content }} {% if c.link %} {{ c.link }} {% if c.file %} download {% endif %} {% endif %} {% endfor %}
has answer: http://stackoverflow.com/a/48342234
has title: Django template doesn't render models as I would expect
tagged with: python
type: Question
score: 0

http://stackoverflow.com/q/48354778
tagged with: pygame
has title: Python cx_freeze error
has comment: http://stackoverflow.com/comment/83699093
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: cx-freeze
score: 0
has body: Python version: 3.6 Latest versions of packages Hello, i need help with my setup, I have setup file but it doesn't work and i don't know why import cx_Freeze import sys import matplotlib base = None if sys.platform =="win32": base = "Win32GUI" executables = [cx_Freeze.Executable("python.py", base=base,)] cx_Freeze.setup( name = "music-Client", options = {"build_exe": {"packages":["tkinter","matplotlib","Pygame"]}}, version = "1", description = "hello", executables = executables ) and when i try to build it with cmd, this really long error come Traceback (most recent call last): File "setup.py", line 17, in &lt;module&gt; executables = executables File "E:\Projekty\venv\lib\site-packages\cx_Freeze\dist.py", line 349, in setup distutils.core.setup(**attrs) File "E:\Python\Lib\distutils\core.py", line 148, in setup dist.run_commands() File "E:\Python\Lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "E:\Python\Lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "E:\Python\Lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "E:\Python\Lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "E:\Python\Lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "E:\Projekty\venv\lib\site-packages\cx_Freeze\dist.py", line 219, in run freezer.Freeze() File "E:\Projekty\venv\lib\site-packages\cx_Freeze\freezer.py", line 616, in Freeze self.finder = self._GetModuleFinder() File "E:\Projekty\venv\lib\site-packages\cx_Freeze\freezer.py", line 342, in _GetModuleFinder finder.IncludePackage(name) File "E:\Projekty\venv\lib\site-packages\cx_Freeze\finder.py", line 659, in IncludePackage module = self._ImportModule(name, deferredImports) File "E:\Projekty\venv\lib\site-packages\cx_Freeze\finder.py", line 311, in _ImportModule deferredImports, namespace = namespace) File "E:\Projekty\venv\lib\site-packages\cx_Freeze\finder.py", line 404, in _InternalImportModule paren…
has answer: http://stackoverflow.com/a/48413372
tagged with: python

http://stackoverflow.com/comment/83838926
type: AnswerComment
score: 0
has text: @Ev. Kounis Thank you for your answer. Your list comprehension approach is very elegant and I do really appreciate it. However, I am trying to understand why those `for` and `if` loops are not working: please note that if I substitute `&` by `and`, I still get an infinite loop. Could you please help me to understand where is the problem in the above code? Thanks again for all the effort
type: Comment
comment on: http://stackoverflow.com/a/48424050

http://stackoverflow.com/q/48394280
type: AnsweredQuestion
score: 2
answer count: 3
has answer: http://stackoverflow.com/a/48394338
upvote count: 2
tagged with: pandas
downvote count: 0
has body: I have a pandas dataframe df that looks like this (Input): Item Color Car 1 Car 2 Bike 3 Bike 1 Train 4 Train 1 I want to find every Color value that commonly occurs at least once for every Item value (Output): Item Color Car 1 Bike 1 Train 1 My current approach is based on a loop and admittedly ugly. I am sure there is a more pythonic/efficient way, ideally a one-liner. all_colors = df.Color.unique().tolist() for single_color in all_colors: df_slice = df[df.Color = single_color] if len(df_slice) = len(df.Item.unique().tolist()): print "Shared Color", single_color print df_slice else: continue How to find pandas cell values that are present in every subset defined by the column before? Edit: The question title is also bulky - if someone has better phrasing, feel free
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48394474
accepted answer: http://stackoverflow.com/a/48394306
has answer: http://stackoverflow.com/a/48394306
tagged with: python
possible better answer: http://stackoverflow.com/a/48394338
has title: How to find pandas cell values that are present in every subset defined by the column before?

http://stackoverflow.com/comment/83950938
type: Comment
comment on: http://stackoverflow.com/a/48478924
type: AnswerComment
has text: You should use 'import pyaes' as you don't want to install it, yes?
score: 0

http://stackoverflow.com/comment/83922061
score: 0
has text: I don’t think this question should be closed as a duplicate, it is about using flask in particular, while the question it’s marked as a duplicate of is solely using python, and has a very different solution. @Zach, does it say which function is not defined? If it’s render_template (as I suspect it might be), did you remember to use “from flask import render_template” near the beginning of your code?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48453474

http://stackoverflow.com/comment/83869174
score: 3
comment on: http://stackoverflow.com/q/48439059
type: Comment
type: QuestionComment
has text: uneven parentheses on previous line

http://stackoverflow.com/q/48475696
upvote count: 1
tagged with: python
tagged with: entropy
has title: How can I manually generate entropy with a python program?
answer count: 2
tagged with: random
has answer: http://stackoverflow.com/a/48479805
has answer: http://stackoverflow.com/a/78264224
has body: The most commonly cited source of randomness is CrypAPI in Windows systems. Can I generate my own entropy from different sources without using this API in python? Any such library? I want to tinker with the generation process and learn a bit about RNG.
score: -1
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/48365481
type: AnsweredQuestion
score: 0
answer count: 2
has body: I am trying to understand the callstack of the code below and I can't answer it. Why does this line return 4: 7. return z and why is this line 5: 16 x = x + m1(x) Hope you can help me. 1 def m1(x): 2 x = x + 1 3 z = m2(x, 4) 4 x = x + 1 5 z = z + 1 6 print(x) 7 return z 8 9 def m2(x, y): 10 x = x + 1 11 y = y + 1 12 print(x, y) 13 return x 14 15 x = 1 16 x = x + m1(x)
has answer: http://stackoverflow.com/a/48365652
has title: python trying to understand callstacks
type: Question
has answer: http://stackoverflow.com/a/48366207
accepted answer: http://stackoverflow.com/a/48366207
tagged with: python
tagged with: callstack
possible better answer: http://stackoverflow.com/a/48365652

http://stackoverflow.com/comment/83728829
type: QuestionComment
comment on: http://stackoverflow.com/q/48363237
has text: the trouble was passing on queue items one after another to each worker's webdriver, while it was open. The solution below accomplishes exactly what i was looking for. tested and working as expected
score: 0
type: Comment

http://stackoverflow.com/a/48454236
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48442786
type: Answer
accepted answer of: http://stackoverflow.com/q/48442786
has body: To place the legend in a 3D plot using data coordinates, one may first get the projected coordinates of a point in 3D space using mpl_toolkits.mplot3d.proj3d.proj_transform(x,y,z, ax.get_proj()) and provide those to the bbox_to_anchor argument of the legend. Than changing the bbox_transform to the data coordinate system produces the desired plot. The following places the lower left corner of the legend at position (70,1000,80) in data coordinates. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D, proj3d import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = 25 * r * np.sin(theta) y = 350* r * np.cos(theta) ax.plot(x, y, 70*z, label='parametric curve') ax.plot(x*.6, y*0.5, 70*z, label='parametric curve 2') f = lambda x,y,z: proj3d.proj_transform(x,y,z, ax.get_proj())[:2] ax.legend(loc="lower left", bbox_to_anchor=f(70,1000,80), bbox_transform=ax.transData) plt.show()

http://stackoverflow.com/comment/83896037
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48450804
has text: is there a way we can get 0 if the value we're looking for is not in the df instead of getting an error? For example, if I apply df.loc[('a', 'a'), 'Value1'], I would get 0 since 'a' can't be found.
type: Comment

http://stackoverflow.com/comment/83732327
type: QuestionComment
type: Comment
score: 0
has text: @hoefling running with connection to PostgreSQL via psycopg2.
comment on: http://stackoverflow.com/q/48372357

http://stackoverflow.com/comment/83703202
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48354958
type: AnswerComment
has text: @Kar Of course, line-clipping allows for partial overlaps - classic usage is to draw a part of segment inside rectangular window. I expanded answer a bit.

http://stackoverflow.com/comment/83727166
has text: In this case I am getting an error: -bash: permission denied. After changing rights of the .txt file and doing this command the whole file is empty
comment on: http://stackoverflow.com/a/48370246
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48463108
has comment: http://stackoverflow.com/comment/83920045
has comment: http://stackoverflow.com/comment/83919711
answers question: http://stackoverflow.com/q/48462951
type: Answer
has comment: http://stackoverflow.com/comment/83919613
score: 2
upvote count: 2
has body: Because the empty product is 1 by convention. 1 is the identity operation for products. I would expect the product of a series to behave as exponentiation, when all numbers in the series are equal. E.g. product([3,3,3,3]) = 3^4. With this reasoning product([]) = 3^0 = 1. Lucky for us we don't need to know the base for this case. It seems pandas developers have a similar understanding. This is also why The sum of an empty or all-NA Series is now 0 The empty sum is the identity operation for the sum. Which is 0.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83919920
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48462951
has comment: http://stackoverflow.com/comment/83921007

http://stackoverflow.com/comment/83947265
score: 1
type: Comment
type: AnswerComment
has text: @user2314737, oh my bad. [Now I see](https://english.stackexchange.com/questions/293520/split-horizontally-or-vertically-which-one-is-which) ... :-)
comment on: http://stackoverflow.com/a/48476787

http://stackoverflow.com/comment/83771689
comment on: http://stackoverflow.com/q/48391849
type: Comment
type: QuestionComment
score: 0
has text: What do you even mean by "jump to the top of stack"? The top of the stack isn't an instruction, so jumping there makes no sense. Are you trying to read jump targets from integers on the stack?

http://stackoverflow.com/comment/83690074
score: 2
type: Comment
comment on: http://stackoverflow.com/a/48351342
type: AnswerComment
has text: If you had used their variable name, then you'd now have 10 upvotes for 10 characters :-) (very surprising, btw... I guess this somehow isn't well-known?)

http://stackoverflow.com/comment/83905252
type: QuestionComment
has text: What are the permissible "states" (entries) of your matrices? just small integers?
comment on: http://stackoverflow.com/q/48456145
type: Comment
score: 1

http://stackoverflow.com/comment/83690839
score: 0
has text: How do I use the Makefile like how do I compile it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48350932

http://stackoverflow.com/comment/83850076
type: QuestionComment
has text: try to understand what the error means first.
comment on: http://stackoverflow.com/q/48429114
score: 1
type: Comment

http://stackoverflow.com/a/48463387
has comment: http://stackoverflow.com/comment/83921025
score: 0
answers question: http://stackoverflow.com/q/48463236
has body: You can convert date using the following code: CheckDATE = datetime.datetime.strptime("2017-12-01", "%Y-%m-%d").date() ToDAY = datetime.datetime.now().strftime("%Y-%m-%d") CheckDATE = CheckDATE.strftime("%Y-%m-%d") Adding date at the end only outputs the date part and omits time. I hope this answers your question. Edit: Updated based on additional information.
type: Answer
has comment: http://stackoverflow.com/comment/83920477

http://stackoverflow.com/a/48372547
has body: Sort by all columns in their current order: df.sort_values(by=df.columns.tolist(), ascending=False) # a b c d e f g h i j k l m n o #6 1 0 0 1 0 1 0 1 0 0 1 0 0 1 0 #3 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 #5 0 0 1 1 0 1 0 1 0 0 1 0 0 1 0 #10 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0 #12 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 #15 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 #4 0 0 0 0 0 1 0 1 0 0 1 0 0 1 0 #2 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 #11 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 #8 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 #13 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 #9 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 #16 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 #7 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 #14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 #1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
has comment: http://stackoverflow.com/comment/83771594
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83771582
answers question: http://stackoverflow.com/q/48372501
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48372501
downvote count: 0
has comment: http://stackoverflow.com/comment/83771590

http://stackoverflow.com/q/48363673
tagged with: plotly-dash
tagged with: werkzeug
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: flask
has title: Combining Flask, Bootstrap and Dash apps
score: 2
downvote count: 0
answer count: 1
tagged with: flask-bootstrap
has answer: http://stackoverflow.com/a/49853981
favorite count: 0
type: Question
has body: I will briefly explain my current situation. app1 &amp; app2 are dash app and reloaded every 5 seconds. And basically, everything works fine. But when I move to app2 tab by clicking the app2 button on my bootstrap navigation menu, I still can see the message below. 127.0.0.1 - - [21/Jan/2018 01:17:00] "POST /app1/_dash-update-component HTTP/1.1" 200 - 127.0.0.1 - - [21/Jan/2018 01:17:00] "POST /app2/_dash-update-component HTTP/1.1" 200 - 127.0.0.1 - - [21/Jan/2018 01:17:03] "POST /app1/_dash-update-component HTTP/1.1" 200 - 127.0.0.1 - - [21/Jan/2018 01:17:03] "POST /app2/_dash-update-component HTTP/1.1" 200 - 127.0.0.1 - - [21/Jan/2018 01:17:05] "POST /app1/_dash-update-component HTTP/1.1" 200 - The problem is, app1 seems to keep refreshing even though I've already left the app1 menu. Actually, I'm lost here and nothing comes to my mind anymore. Should I change the way combine dash apps and flask app? or is there any brilliant way to pause app1 whilst the user watching app2 dash app? Thank you. app_main.py from werkzeug.wsgi import DispatcherMiddleware from flask_bootstrap import Bootstrap import app1 import app2 flask_app = flask.Flask(__name__) server = DispatcherMiddleware(flask_app, { '/app1': app1.app_dash.server, '/app2': app1.app_dash.server, }) Bootstrap(flask_app) index.html ... &lt;div id="app1" class="tab-pane fade"&gt; &lt;object data="/basic_chart"&gt;&lt;/object&gt; &lt;/div&gt; &lt;div id="app2" class="tab-pane fade"&gt; &lt;object data="/balance_chart"&gt;&lt;/object&gt; &lt;/div&gt; ... app1.py ... app_dash.layout = html.Div([ dcc.Interval( id='interval-component', interval=5e3, # in milliseconds n_intervals=0 ), html.Div([ dcc.Graph( id='graph_stream', ), ]), ...

http://stackoverflow.com/comment/83805984
has text: @hpaulj Thanks for the pointer! So the second way should always be equivalent to or more efficient then.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48408264
type: Comment

http://stackoverflow.com/comment/83678665
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48346288
has text: @Hakaishin: In fact, I'm almost certain you must be using Python 3 otherwise you'd have had decoding errors.
type: AnswerComment

http://stackoverflow.com/comment/138104151
type: AnswerComment
has text: Just a note that `Result.Scalars()` was added in 1.4, so if you're using an older version, it's not available.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/74452716

http://stackoverflow.com/q/48360670
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83708405
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/16878315
has body: I am relatively new to Python and I am trying to solve the following problem at the moment. I am writing a script which parses command line arguments with argparse. Besides some other things I have a verbosity flag, which I want to make available for some objects. Currently I am passing it to the constructor and I am wondering if there is a more elegant way for doing this. class MyClass(object): def __init__(self, verbosity=False): self.verbosity = verbosity def do_something(self): if self.verbosity: print("Doing something ...") . import argparse import myclass def main(): parser = argparse.ArgumentParser(description='Testing.') parser.add_argument('-v', '--verbosity', action='store_true', help="Produce verbose output") args = parser.parse_args() object = myclass.MyClass(verbosity=args.verbosity) object.do_something() if __name__ == "__main__": main() Any help would really be appreciated.
has answer: http://stackoverflow.com/a/48361405
score: 0
answer count: 1
has title: Python: How to make command line arguments available for objects?

http://stackoverflow.com/a/48398248
score: 2
upvote count: 2
has body: Try this def bubble_sort(L): """(list)-&gt;list sort the items of list and return list &gt;&gt;&gt; LL=[7,3,5,2] &gt;&gt;&gt; bubble_sort(LL) [2, 3, 5, 7] """ #index of last element of the list end=len(L)-1 while end!=0: # buuble sort passes to the list and move one large item at end of list for i in range(end): if L[i]&gt;L[i+1]: L[i],L[i+1]=L[i+1],L[i] end=end-1 return L &gt;&gt;&gt; students= [ ('tiffany','A',15), ('jane','B',10), ('ben','C',8), ('simon','A',15), ('john','A',21), ('jimmy','F',1), ('charles','C',9), ('freddy','D',4), ('dave','B',12)] &gt;&gt;&gt; bubble_sort(students) It give output [('ben', 'C', 8), ('charles', 'C', 9), ('dave', 'B', 12), ('freddy', 'D', 4), ('jane', 'B', 10), ('jimmy', 'F', 1), ('john', 'A', 21), ('simon', 'A', 15), ('tiffany', 'A', 15)] Data Structure is list of tuple
downvote count: 0
answers question: http://stackoverflow.com/q/48397745
type: Answer

http://stackoverflow.com/a/48339556
has comment: http://stackoverflow.com/comment/83664215
has comment: http://stackoverflow.com/comment/83664243
answers question: http://stackoverflow.com/q/48339497
upvote count: 2
has body: You can use: dicty = [defaultdict(list) for _ in range(2)] When using [defaultdict(list)] * (2), all your dicts point to the same object in memory.
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83698545
comment on: http://stackoverflow.com/q/48355809
score: 1
type: Comment
type: QuestionComment
has text: What does `df.allmz.str.len().eq(0).any()` print?

http://stackoverflow.com/q/48465311
has comment: http://stackoverflow.com/comment/83924051
has answer: http://stackoverflow.com/a/48465923
has title: Best way to return value in instance method
has comment: http://stackoverflow.com/comment/83924017
tagged with: coding-style
has answer: http://stackoverflow.com/a/48465414
has comment: http://stackoverflow.com/comment/83924119
score: 0
answer count: 2
has body: I'm curious about the recommended way to return a value for instance methods in Python. I'm sorry if this comes across as a rather trivial question, but I can't seem to find a proper answer on google/sx/so. Option 1: class Cla: def __init__(self): self.var = False def _inst_mtd(self): var = True return var def calc_var(self): self.var = self._inst_mtd() # or in init if desired def return_var(self): return self.var Option 2: class Cla: def __init__(self): self.var = False def _inst_mtd(self): self.var = True def calc_var(self): self._inst_mtd() def return_var(self): return self.var Option 3: class Cla: def __init__(self): self.var = False def _inst_mtd(self): self.var = True return self.var def calc_var(self): self.var = self._inst_mtd() def return_var(self): return self.var The intention of _inst_mtd is to calculate a value for self.var. A separate public method to return self.var will provide the return function to an outside caller . _inst_mtd is meant to be called within the class, perhaps in a loop, and perhaps with a public method calc_var if for instance it'll take a while to run . My concerns are that 1 might result in confusion between local and instance variables, if the whole point of _inst_mtd is to modify self.var and not actually deal with another variable called var. For 2, I'm under the impression that (considering only _inst_mtd) this constitutes a side-effect, which should be avoided? But 3 just seems unnecessary, although it does work well with return type annotations, especially when the type (not recommended) or elements within are changed in _inst_mtd.
tagged with: python-3.5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83924551
has comment: http://stackoverflow.com/comment/83924439
type: Question
has comment: http://stackoverflow.com/comment/83923986
has comment: http://stackoverflow.com/comment/83924080
linked to: http://stackoverflow.com/q/1301346
tagged with: python

http://stackoverflow.com/q/48472961
score: 1
downvote count: 1
has title: How to replace this triple For loop with a single numpy array operation?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83939712
has comment: http://stackoverflow.com/comment/83940116
tagged with: python
accepted answer: http://stackoverflow.com/a/48474268
has comment: http://stackoverflow.com/comment/83940760
has answer: http://stackoverflow.com/a/48474268
tagged with: numpy
type: AnsweredQuestion
tagged with: graph-theory
has body: For a turn based game I would like to compute the maximum number of units each player can move or spawn on each zone of a map. All the datas I need to compute this are already stored in several numpy arrays but I'm struggling to find the advanced array indexing techniques to do the computation as fastest as possible. To help figure out this problem, I've rewritten the function in the simplest way with some For loops: import numpy as np def get_max_units_on_zone_per_player(unitCountPerPlayer, zoneOwner, playerAvailableUnits, zoneLinks, blockedMovesPerPlayer): """ Parameters ---------- unitCountPerPlayer: np.array((zoneCount, playerCount), dtype=int) How many units each player has on a zone zoneOwner: np.array(zoneCount, dtype=int) Which player is owning a zone (-1 for none) playerAvailableUnits: np.array(playerCount, dtype=int) How many units each player can spawn zoneLinks: np.array((zoneCount, zoneCount), dtype=int) &gt; 0 if zone1 is connected to zone2 (directed and weighted graph) blockedMovesPerPlayer: np.array((playerCount, zoneCount, zoneCount), dtype=bool) True if player can not move from zone1 to zone2 Returns ------- np.array((zoneCount, playerCount), dtype=int) Maximum count of units each player can have on each zone """ zoneCount, playerCount = unitCountPerPlayer.shape # Adding units already on zone result = np.zeros((zoneCount, playerCount), dtype=int) + unitCountPerPlayer for p in xrange(playerCount): for z1 in xrange(zoneCount): if zoneOwner[z1] in (-1, p): # Player can spawn on neutral or owned zones result[z1, p] += playerAvailableUnits[p] for z2 in xrange(zoneCount): if zoneLinks[z1, z2] &gt; 0 and not blockedMovesPerPlayer[p, z1, z2]: # If z1 and z2 are connected and player can move from z1 to z2, adding units count on z1 to z2 result[z2, p] += unitCountPerPlayer[z1, p] return result The problem is I can't use this function which takes around 30ms on each call and I know for sure it's rewritable as some numpy operations which should take less than …
upvote count: 2
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/83941249
has comment: http://stackoverflow.com/comment/83939934

http://stackoverflow.com/comment/83958513
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48482757
has text: It happens in place. print `v`
type: Comment

http://stackoverflow.com/a/48464047
has body: This may work for you. VLAN_clean = [v[0:v.find(' ')] for v in VLANList if v.find(' ') != -1]
type: Answer
answers question: http://stackoverflow.com/q/48463933
has comment: http://stackoverflow.com/comment/83922409
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48463933
has comment: http://stackoverflow.com/comment/83921910

http://stackoverflow.com/a/48371129
upvote count: 2
downvote count: 0
has body: This will be too long for a comment: As an aside, you should really be learning on Python 3. Python 2 is on the way out. Everything below works in Python 3. Why is your DiceShaker a subclass of Die? This makes no sense. Subclassing is for is a relationships. DiceShaker isn't a type of Die (just like a ShoppingCart isn't a type of CartItem). Your relationship is compositional. DiceShaker has Dies (which you reflect with your dieList). In this case dieList is all you need here. You don't need to inherit from Die. The underlying reason why you get the same number rolled is because you inherited from die. By subclassing Die, you made DiceShaker behave like a Die. That means you could've called ds.roll() and ds.get() (where ds = DiceShaker()) and it would behave exactly the same as if you called it on a Die. This is effectively what you've done when you've wrote Dice.get(self). That's equivalent to self.get() (since DiceShaker extends Dice). But DiceShaker is only one Die, not multiple. So calling get() will always return the same thing. What you've effectively done is the following: die = Die() die.roll() for other_die in self.dieList: self.dieList2.append(die.get()) # note you're getting the same die each time So to fix this, you don't need to inherit from Die. In fact you shouldn't. Instead compose DieShaker and Die. This means DieShaker should delegate to the Dies it contains (by calling get on them, not itself). from random import randint class Die: def __init__(self, sides=6): self.sides = sides def roll(self): self._rolled_value = randint(1, self.sides) def get_value_rolled(self): return self._rolled_value class DieShaker: def __init__(self, num_die=1, num_die_sides=6): self.dice = [Die(num_die_sides) for _ in range(num_die)] def shake(self): for die in self.dice: die.roll() def get_values_rolled(self): return [die.get_value_rolled() for die in self.dice] Note how in get_values_rolled (equivalent to your DieShaker.getIndividualRolls), we call get_value_rolled (equ…
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48370952

http://stackoverflow.com/comment/83835546
type: QuestionComment
comment on: http://stackoverflow.com/q/48422874
score: 0
has text: Yes ['21/10/2017 0:00', '123,85', '88,8'] is what I mean. I added the question mark but after that I get this is time: 0:00' this is the day: ['21 so I still get characters I don't want. I want to make 21 day an integer, and python interprets the [' also, so I am getting an error. I want to ommit [' from this and get only the 21
type: Comment

http://stackoverflow.com/a/48366940
accepted answer of: http://stackoverflow.com/q/48366903
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48366903
type: AcceptedAnswer
has body: You can create a list of (x, y) tuples from the CSV data using a list comprehension. Then use zip to separate the tuples into x an y values and pass to plt.scatter(): with open('Infosys.csv','r') as csv_file : csv_reader = csv.reader(csv_file) next(csv_reader) data = [(row[2], row[5]) for row in csv_reader] plt.scatter(*zip(*data), label='pt.', color='red') This requires a only single pass over the file.

http://stackoverflow.com/comment/83669878
type: QuestionComment
comment on: http://stackoverflow.com/q/48339129
has text: I found that the training was with different optimizers, now they are identical. I re-set the numpy random seed every time, but I didn't check if I get identical initial weights
score: 0
type: Comment

http://stackoverflow.com/q/48387268
possible better answer: http://stackoverflow.com/a/48387470
has answer: http://stackoverflow.com/a/48387399
accepted answer: http://stackoverflow.com/a/48387399
tagged with: group-by
tagged with: dataframe
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
has title: How to retrieve element from a groupby DataFrame given index
tagged with: pandas
has body: Context: my DataFrame contains the following columns: HapID, Marker, Start_position, End_position. For each HapID, I'd like to get: - the marker having the minimum Start_position (that is called leftMarker) - the marker having the maximum End_position (that is called rightMarker) - Interval being the difference (maximum End_position - minimum Start_position) My issue is how to retrieve the marker names now that I know their index. I got the error below and I'm not sure how to sort it out although I've spent hours on it. Here is the error message AttributeError: Cannot access callable attribute 'iloc' of 'SeriesGroupBy' objects, try using the 'apply' method Below is the data HapID Marker Start_position End_position hap_1 mk1 1107207 1107256 hap_1 mk2 1104711 1104760 hap_1 mk3 1106845 1106894 hap_2 mk4 11901413 11901462 hap_2 mk5 206031250 206031299 hap_2 mk6 11498893 11498942 hap_2 mk7 17236023 17236072 hap_2 mk8 11692209 11692258 hap_2 mk9 11691512 11691561 hap_2 mk10 11615664 11615713 this is the expected output HapID leftMarker rightMarker Start_position End_position Interval hap_1 mk2 mk1 1104711 1107256 2545 hap_2 mk6 mk5 11498893 206031299 194532406 Code: import pandas as pd data = { 'HapID':['hap_1','hap_1','hap_1','hap_2','hap_2','hap_2','hap_2','hap_2','hap_2','hap_2'], 'Marker':['mk1','mk2','mk3','mk4','mk5','mk6','mk7','mk8','mk9','mk10'], 'Start_position':[1107207,1104711,1106845,11901413,206031250,11498893,17236023,11692209,11691512,11615664], 'End_position':[1107256,1104760,1106894,11901462,206031299,11498942,17236072,11692258,11691561,11615713]} df = pd.DataFrame(data) haplotypes = df.groupby(df['HapID']) posi_1 = haplotypes.Start_position.min() posi_2 = haplotypes.End_position.max() diff_posi = posi_2 - posi_1 a = haplotypes.Start_position.idxmin()#index at minimum Start_position b = haplotypes.End_position.idxmax() #index at maximum End_position #print('{} {} {}'.format(posi_1,posi_2,diff_posi)) #print('{} {}'.format(a,b)) #just to se if I'm getting …
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48387470

http://stackoverflow.com/comment/83945476
type: AnswerComment
comment on: http://stackoverflow.com/a/48476132
has text: Apologies, my Python environment is not operative at the moment, I can only explain, not code.
type: Comment
score: 0

http://stackoverflow.com/comment/83938174
comment on: http://stackoverflow.com/q/48472029
has text: Additionally, If these are IP addresses, then they are IPv4.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48414404
has comment: http://stackoverflow.com/comment/83818712
favorite count: 0
has body: I am trying to write a function which chooses integers randomly from arbitrarily nested lists while maintaining order and the structure of the lists (though empty lists can be ignored). The number of samples should be uniformly random from 0 to the number of integers in the nested list. For example, running listrand([1,2,3,[3,4],[65,[3]]]) 3 times might give: [1, 3, [3], [65, [3]]] [1, 2, [[3]]] [[3, 4], [65]] The catch is I need it to be uniformly distributed, so I can't use something like sample = [[random.sample(mylist)] for mylist in listoflists] because that would be binomial. At a minimum I need this to work for single-level nesting. I thought about sampling from a flattened list but then I'm not sure how to use those to construct the desired output.
has comment: http://stackoverflow.com/comment/83818805
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83818974
tagged with: list
accepted answer: http://stackoverflow.com/a/48414741
tagged with: random
has answer: http://stackoverflow.com/a/48414741
linked to: http://stackoverflow.com/q/10823877
score: 1
has comment: http://stackoverflow.com/comment/83818843
has comment: http://stackoverflow.com/comment/83819113
type: Question
has comment: http://stackoverflow.com/comment/83819091
has comment: http://stackoverflow.com/comment/83819067
has title: Randomly sample from arbitrarily nested lists while maintaining structure
has comment: http://stackoverflow.com/comment/83818776
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/83911725
comment on: http://stackoverflow.com/q/48459361
score: 2
type: Comment
has text: You throw away the carry when either bit is `0`. Are you sure that is okay?
type: QuestionComment

http://stackoverflow.com/q/48350607
downvote count: 0
linked to: http://stackoverflow.com/q/56378872
possible better answer: http://stackoverflow.com/a/48350778
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/46629519
has answer: http://stackoverflow.com/a/48350778
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48350803
duplicate of: http://stackoverflow.com/q/46629519
tagged with: python
has answer: http://stackoverflow.com/a/48350942
upvote count: 4
score: 4
has title: How to replace set or group of characters with string in Python
has body: I am trying to make a simple script replacing all occurrences of certain group or set of characters (or set of strings) in text. In this case I will try to replace all letters "a,e,i,o,u" with certain string. My script: def replace_all(text, repl): text1 = text.replace("a", repl) text2 = text1.replace("e", repl) text3 = text2.replace("i", repl) text4 = text3.replace("o", repl) text5 = text4.replace("u", repl) return text5 Is there any simpler way of doing it? What if I need to replace bigger group of chars or strings? Chaining it like this does not seem to be really effective then. This is maybe a primitive question. However, I am still in learning phase so maybe I get it in later lessons. Thank you in advance for any advice.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48350803
answer count: 3

http://stackoverflow.com/q/48406926
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/48407066
answer count: 1
has answer: http://stackoverflow.com/a/48407066
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83802801
has title: Are my telnetlib imports wrong?
tagged with: python
tagged with: telnetlib
has body: Been having an issue with this code: from telnetlib import Telnet class doTelnet: def login(self): # Configure login variables for input self.user = self.user.encode('ascii') + b'\n' self.password = self.password.encode('ascii') + b'\n' self.terminal_type = self.terminal_type.encode('ascii') + b'\n' # Do login # TODO Add functionality for user control of expected login prompt (some servers send 'Username: ', I'm sure theres other options) self.telnet.read_until('login: ') self.telnet.write(self.user) self.telnet.read_until('Password: ') try: self.telnet.write(self.password) print('[*]\tSuccessfully authenticated to {0}:{1}'.format(self.host, self.port)) self.login_status = 1 except Exception as self.e: print('[!]\tError authenticating to {0}:{1}\n{2}'.format(self.host, self.port, self.e) # Set terminal type self.telnet.write(self.terminal_type) It consistently fails on the "self.telnet.write" section, which I can't understand why that might be. Anyone a wizard? File "C:\Users\user\Downloads\CiscoIOSSNMPToolkit\doTelnet.py", line 45 self.telnet.write(self.terminal_type) ^ SyntaxError: invalid syntax Is the error. https://github.com/GarnetSunset/CiscoIOSSNMPToolkit/blob/master/doTelnet.py
score: -1

http://stackoverflow.com/q/48478100
has answer: http://stackoverflow.com/a/48478272
type: Question
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48478272
has body: I'm doing some machine learning on Kaggle (https://www.kaggle.com/c/house-prices-advanced-regression-techniques#description) and am given a train CSV and a test CSV. I want to drop columns in my data where at least 30% of values are null. If I were just doing this for my training set, I would do this: train_df = pd.read_csv("train.csv") train_len = len(train_df) test_df = pd.read_csv("test.csv") threshold = int(0.7 * train_len) train_df.dropna(axis=1, thresh=threshold, inplace=True) This works. However, I want to drop these columns in my test set as well. So specifically, I'd like to find the columns in my training set that have 30% or more null values and drop them from train and test sets. I was thinking of combining my DataFrames like this: combined_df = pd.concat([train_df, test_df], axis=0) If combined_df[:train_len, :] has more than 30% nulls, drop that column from combined_df. How would I do this? To be clear, I don't want to loop through train, find columns with more than 30% nulls, drop from train, then drop from test. Thanks!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48478221
possible better answer: http://stackoverflow.com/a/48478221
has title: Pandas: Drop Column If Submatrix Has Enough Nulls
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/48446599
has body: I am answering rather than editing because I have solved the lost plot problem, and that might be a help to someone else. The solution is to move the plt.imshow line AFTER the ax.yaxis.set_ticks line. However, I am still not getting the expected Y axis ticks with no decimal point. The first block of code below produces a plot with Y ticks: 0.0,1000.5,2001.0,3001.5,4002.0 import matplotlib import matplotlib.pyplot as plt outgrid=[[x*y for x in range(4)] for y in range (5)] height = [v*1000.5 for v in range (5)] cmap=plt.cm.get_cmap('terrain') norm=matplotlib.colors.Normalize(clip=False) m=plt.cm.ScalarMappable(cmap=cmap,norm=norm) m.set_array(outgrid) plt.imshow(outgrid,cmap=cmap, norm=norm, aspect=0.5) plt.yticks([s for s in range(5)],[height[t] for t in range(5)]) plt.show() This second block of code tries to format these ticks with no decimal point but just produces one Y tick of 0 import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter ax=plt.axes() outgrid=[[x*y for x in range(4)] for y in range (5)] height = [v*1000.5 for v in range (5)] cmap=plt.cm.get_cmap('terrain') norm=matplotlib.colors.Normalize(clip=False) m=plt.cm.ScalarMappable(cmap=cmap,norm=norm) m.set_array(outgrid) ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f')) ax.yaxis.set_ticks([height[t] for t in range(5)]) plt.imshow(outgrid,cmap=cmap, norm=norm, aspect=0.5) plt.show()
has comment: http://stackoverflow.com/comment/83894437
type: Answer
answers question: http://stackoverflow.com/q/48406200
score: 0

http://stackoverflow.com/comment/83895310
type: QuestionComment
comment on: http://stackoverflow.com/q/48450004
has text: Nope, same behavior. The relation is being built, at the end of update_tags() I can put in `print(instance.tags.all())` or `print(self.tags.all())` depending on implementation and it outputs the correct tags.
type: Comment
score: 0

image-processing
tags question: http://stackoverflow.com/q/48409525
tags question: http://stackoverflow.com/q/48416771
type: Tag
tags question: http://stackoverflow.com/q/48487945
tags question: http://stackoverflow.com/q/48454055
tags question: http://stackoverflow.com/q/48427792
tags question: http://stackoverflow.com/q/48352638
tags question: http://stackoverflow.com/q/48373944
tags question: http://stackoverflow.com/q/48437443
tags question: http://stackoverflow.com/q/48413398
tags question: http://stackoverflow.com/q/48437179
tags question: http://stackoverflow.com/q/48414823
tags question: http://stackoverflow.com/q/48444208
tags question: http://stackoverflow.com/q/48428337
tags question: http://stackoverflow.com/q/48392438
tags question: http://stackoverflow.com/q/48331211
tags question: http://stackoverflow.com/q/48470671
tags question: http://stackoverflow.com/q/48430597
tags question: http://stackoverflow.com/q/48377332
tags question: http://stackoverflow.com/q/48463250
tags question: http://stackoverflow.com/q/48468536
tags question: http://stackoverflow.com/q/48355891
tags question: http://stackoverflow.com/q/48434258
tag name: image-processing
tags question: http://stackoverflow.com/q/48355267
tags question: http://stackoverflow.com/q/48356874
tags question: http://stackoverflow.com/q/48356398

http://stackoverflow.com/comment/83914790
type: QuestionComment
has text: but this is not a vector of probabilities. By definition, `Probabilities` must sum to one. Else it's wrong to call it as probabilities
score: 1
comment on: http://stackoverflow.com/q/48457469
type: Comment

http://stackoverflow.com/q/48389667
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/83767186
has comment: http://stackoverflow.com/comment/83772686
upvote count: 1
tagged with: spyder
downvote count: 1
has comment: http://stackoverflow.com/comment/83767170
has comment: http://stackoverflow.com/comment/83767097
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83767136
has body: When I try the following code I get some issue about button click event: from Tkinter import * def hello(event): print("Single Click, Button-l") widget = Button(None, text='Mouse Clicks') widget.pack() widget.bind('&lt;Button-1&gt;', hello) widget.mainloop() In the first click nothing happens, in the second click, it writes to kernel two times "Single Click", in the third click nothing happens, in the fourth click and following clicks everything is OK. Why do the first 3 clicks have this issue? Edit: Problem is that i was using Spyder IDE. Went back to good old terminal and everything is OK.
type: UnansweredQuestion
has title: Why do the first 3 mouse clicks behave odd?
has comment: http://stackoverflow.com/comment/83767236
tagged with: python
score: 0

http://stackoverflow.com/comment/83652778
has text: I believe `pip install -r requirements.txt` is what you're looking for
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48332867

http://stackoverflow.com/a/48347010
has comment: http://stackoverflow.com/comment/83711841
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48346861
has body: Hard to say without a complete example, but the first line word = [r.choice(WORDS).lower()] this is a list with one element in it. Thus your code below is adding one underscore for each element in this list. I expect that removing the [] is enough to make this work word = r.choice(WORDS).lower() However you don't need the for loop to get the number of underscores, you can just do newWord = '_' * len(word)
answers question: http://stackoverflow.com/q/48346861
type: Answer
has comment: http://stackoverflow.com/comment/83736871

http://stackoverflow.com/q/48350196
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48350265
tagged with: django
has title: Django template renders all my files at once
tagged with: python
has body: I am stuck with this issues for a while now. It goes like this: I have a model with lectures. I want that for every lecture to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files would be displayed and downloadable as well. The Issue is that every lecture displays all the files that have ever been uploaded in the admin panel. Here is my code: class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.OneToOneField('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "download" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' {% regroup lectures by get_lecture_category_display as category_list %} Lectures {% for category in category_list %} {{ category.grouper }} {% for c in category.list %} ............. {{ c.lecture_title }} {{ c.content }} {% for file in files %} {% if file.files %} download {% endif %} {% endfor %} {% endfor %} {% endfor %} def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), 'files': FileUpload.objects.all(), } return render(request, 'courses/courses.html', context) Here is the current output: https://i.sstatic.net/YxC6K.png

http://stackoverflow.com/comment/83804398
comment on: http://stackoverflow.com/q/48390732
score: 0
type: QuestionComment
has text: You can shift the `Price`: `df['price_shifted'] = df.Price.shift(-1)`, then use a Spearman correlation: `df.groupby(['Product', 'Time']).corr(method = 'spearman')`. However, this does not return `NaN`s correctly, and I'm not sure why.
type: Comment

http://stackoverflow.com/comment/83931870
comment on: http://stackoverflow.com/a/48468927
score: 0
type: Comment
type: AnswerComment
has text: Dictionaries might actually make a lot of sense for what im trying to do in both this example and in my program, I'll try and convert my lists (that would benefit) into dicts and i'll let you know if that works, thanks!

http://stackoverflow.com/comment/83938072
score: 0
type: QuestionComment
has text: @Son Are those version strings or IP addresses that you are comparing. Would a max IP address make any sense? I presumed no, hence why I am assuming version numbers.
comment on: http://stackoverflow.com/q/48472029
type: Comment

http://stackoverflow.com/comment/83840320
comment on: http://stackoverflow.com/q/48413641
has text: So just replace your `exception.message` with `exception.code`.
score: 1
type: QuestionComment
type: Comment

pandas-groupby
tags question: http://stackoverflow.com/q/48471648
tags question: http://stackoverflow.com/q/48375776
tags question: http://stackoverflow.com/q/48465287
tags question: http://stackoverflow.com/q/48421062
type: Tag
tags question: http://stackoverflow.com/q/48351811
tags question: http://stackoverflow.com/q/48379224
tags question: http://stackoverflow.com/q/48341009
tags question: http://stackoverflow.com/q/48373984
tags question: http://stackoverflow.com/q/48404453
tags question: http://stackoverflow.com/q/48390128
tags question: http://stackoverflow.com/q/48331802
tags question: http://stackoverflow.com/q/48465633
tags question: http://stackoverflow.com/q/48393336
tags question: http://stackoverflow.com/q/48390732
tags question: http://stackoverflow.com/q/48470878
tags question: http://stackoverflow.com/q/48427921
tags question: http://stackoverflow.com/q/48397514
tags question: http://stackoverflow.com/q/48405569
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/48395721
tags question: http://stackoverflow.com/q/48478780
tags question: http://stackoverflow.com/q/48373395
tags question: http://stackoverflow.com/q/48434391
tags question: http://stackoverflow.com/q/48397171
tags question: http://stackoverflow.com/q/48395740

http://stackoverflow.com/q/48372753
possible better answer: http://stackoverflow.com/a/48372961
downvote count: 0
has answer: http://stackoverflow.com/a/48372961
has answer: http://stackoverflow.com/a/48372782
score: 4
has answer: http://stackoverflow.com/a/48373302
favorite count: 0
accepted answer: http://stackoverflow.com/a/48372783
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48372783
has title: Get common elements majority of lists in python
tagged with: python
answer count: 4
upvote count: 4
has body: Given 4 lists, I want to get elements that are common to 3 or more lists. a = [1, 2, 3, 4] b = [1, 2, 3, 4, 5] c = [1, 3, 4, 5, 6] d = [1, 2, 6, 7] Hence, the output should be [1, 2, 3, 4]. My current code is as follows. result1 = set(a) &amp; set(b) &amp; set(c) result2 = set(b) &amp; set(c) &amp; set(d) result3 = set(c) &amp; set(d) &amp; set(a) result4 = set(d) &amp; set(a) &amp; set(b) final_result = list(result1)+list(result2)+list(result3)+list(result4) print(set(final_result)) It works fine, and give the desired output. However, I am interested in knowing if there is an easy way of doing this in Python, ie: are there any built in functions for this?

http://stackoverflow.com/q/48436211
has answer: http://stackoverflow.com/a/48436441
has comment: http://stackoverflow.com/comment/83863792
downvote count: 1
possible better answer: http://stackoverflow.com/a/48514127
tagged with: nodes
favorite count: 0
has body: So this is the node part of a singly linked list. I am not supposed to change the way it has been coded, but I dont know how this type of structure would work. Self.link cannot event be accessed to point towards another part of the list. Does anyone know how to work with such a Node class? class Node: def __init__(self, inval=None): self.val = inval if inval==None: self.link = self print (self) def __str__(self): if self.val == None: return '' else: return str(self.val) def __repr__(self): return str(self)
has answer: http://stackoverflow.com/a/48514127
has title: How does a node with return self work?(Python)
type: Question
upvote count: 0
answer count: 2
tagged with: python
tagged with: data-structures
has comment: http://stackoverflow.com/comment/83864136
tagged with: singly-linked-list
has comment: http://stackoverflow.com/comment/83864119
score: -1
tagged with: linked-list
accepted answer: http://stackoverflow.com/a/48436441
has comment: http://stackoverflow.com/comment/83863826
has comment: http://stackoverflow.com/comment/83863874
type: AnsweredQuestion

http://stackoverflow.com/a/48454271
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48454156
upvote count: 1
has body: A=[14, 5, 4, 3, 2] B=[14, 7, 4, 3, 2] for x in range(0,len(A)): if A[x]>B[x]: print("A is bigger") break elif A[x]<B[x]: print("B is bigger") break elif x==len(A)-1: print("The arrays are equal") Edit: Straightforward way: A=[14, 5, 4, 3, 2] B=[14, 7, 4, 3, 2] if A>B: print("A is bigger") elif A<B: print("B is bigger") else: print("Both are the same")
type: Answer

http://stackoverflow.com/a/48345769
has comment: http://stackoverflow.com/comment/83677423
has body: try this def __str__(self): return str(self.file) you can also return unicode version for filename def __unicode__(self): return self.file
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83678261
answers question: http://stackoverflow.com/q/48345658

http://stackoverflow.com/a/48417059
has body: The dis module in the python helps you to see whats going under the hood &gt;&gt;&gt; from dis import dis &gt;&gt;&gt; def bo(a=2,b=3): ... print a,b==2,3 ... &gt;&gt;&gt; dis(bo) 2 0 LOAD_FAST 0 (a) 3 PRINT_ITEM 4 LOAD_FAST 1 (b) 7 LOAD_CONST 1 (2) 10 COMPARE_OP 2 (==) 13 PRINT_ITEM 14 LOAD_CONST 2 (3) 17 PRINT_ITEM 18 PRINT_NEWLINE 19 LOAD_CONST 0 (None) 22 RETURN_VALUE &gt;&gt;&gt; bo() 2 False 3 &gt;&gt;&gt; def bo(a=2,b=3): ... print a,b==3,2 ... &gt;&gt;&gt; bo() 2 True 2 if we use a,b==3,2 when a=2 and b=3 the tuple `s middle element will have True value First a and b are pushed onto the stack the popped of the stack and compared with corresponding values and then made into a tuple . So in effect the comparison is done in the reverse order So reversing the order of elements provides us a correct value in the resulting tuple In short def bo(a=1,b=2,c=3,d=4): print a,b,c,d==4,3,2,1 bo() will print 1 2 3 True 3 2 1 So we can access the tuples middle element for correct value
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48416460

http://stackoverflow.com/q/48346918
linked to: http://stackoverflow.com/q/44102422
has comment: http://stackoverflow.com/comment/83685108
tagged with: python
type: UnansweredQuestion
has body: I have the same question as TensorFlow saver - Saving an ordinary Python variable. I need to save and restore a python variable in tensorflow. But I can't find a way to do it. I need to restore my python variable, and then restore and use it to compute something else in the restored model, like: accuracy = ('accuracy:0', feed_dict = {'data:0':my_data, '????:0':my_python_variable, 'label:0':my_labels}) 'my_python_variable' is an input to compute the accuracy of the original training model. When I look at all the nodes, and also all the saved variables in the restored model, I can't find any node associated with this ordinary python variable. Any idea?
has comment: http://stackoverflow.com/comment/83689065
score: 0
answer count: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85237111
has title: Saving a python variable (non - tensorflow variable) in tensorflow?
type: Question
has comment: http://stackoverflow.com/comment/83696213
has comment: http://stackoverflow.com/comment/83687088

http://stackoverflow.com/q/48433076
has answer: http://stackoverflow.com/a/48433600
has comment: http://stackoverflow.com/comment/83857684
type: Question
has title: f_oneway when data in the form of list
tagged with: anova
linked to: http://stackoverflow.com/q/3518778
tagged with: arrays
has comment: http://stackoverflow.com/comment/83857966
tagged with: python
has body: if this is the source code.. how will you edit the f_oneway function line such that you dont have to manually specify the archer name each time import numpy as np from scipy import stats data = np.rec.array([ ('Pat', 5), ('Pat', 4), ('Pat', 4), ('Pat', 3), ('Pat', 9), ('Pat', 4), ('Jack', 4), ('Jack', 8), ('Jack', 7), ('Jack', 5), ('Jack', 1), ('Jack', 5), ('Alex', 9), ('Alex', 8), ('Alex', 8), ('Alex', 10), ('Alex', 5), ('Alex', 10)], dtype = [('Archer','|U5'),('Score', '&lt;i8')]) f, p = stats.f_oneway(data[data['Archer'] == 'Pat'].Score, data[data['Archer'] == 'Jack'].Score, data[data['Archer'] == 'Alex'].Score) print ('P value:', p, '\n') I tried the following but it errors out saying 'no field of name Pat' f, p = stats.f_oneway(data[data['Archer']].Score) help!
tagged with: statistics
has comment: http://stackoverflow.com/comment/83857483
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83857548
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83857844
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48433600
tagged with: scipy
favorite count: 0

http://stackoverflow.com/comment/83650633
comment on: http://stackoverflow.com/a/48332416
type: AnswerComment
has text: I totally forgot to set the mode to read. Thanks so much!
score: 0
type: Comment

http://stackoverflow.com/q/48453046
has comment: http://stackoverflow.com/comment/83899437
has title: Printing tuples in for loops python
favorite count: 0
type: Question
tagged with: tuples
tagged with: for-loop
has body: Hi I'm learning Python via a Youtube Tutorial series and the tutorial I just viewed explained how to print tuples embedded within a list. The publisher of video explains two ways, specifically: &gt;&gt;&gt; a = [(1,2,3), (4,5,6), (7,8,9)] &gt;&gt;&gt; for (b, c, d) in a: ... print(b,c,d) ... 1 2 3 4 5 6 7 8 9 &gt;&gt;&gt; for nums in a: ... a,b,c = nums ... print(a,b,c) ... 1 2 3 4 5 6 7 8 9 I attempted a third way: &gt;&gt;&gt; for nums in a: ... a,b,c = nums ... print(nums) but received this error "Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable" I sense that the takeaway is that I should make sure to always print tuples in tuple form but that seems like if could be really tedious if it were a really long tuple (or list of tuples). What is wrong with my attempt?
has comment: http://stackoverflow.com/comment/83899246
has answer: http://stackoverflow.com/a/48453188
accepted answer: http://stackoverflow.com/a/48453188
tagged with: python
has comment: http://stackoverflow.com/comment/83899779
type: AnsweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/48453125
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83899267
has answer: http://stackoverflow.com/a/48453103
possible better answer: http://stackoverflow.com/a/48453103

http://stackoverflow.com/q/48486291
has answer: http://stackoverflow.com/a/48486320
tagged with: python
duplicate of: http://stackoverflow.com/q/27658877
type: AnsweredQuestion
score: 0
tagged with: list
accepted answer: http://stackoverflow.com/a/48486320
has comment: http://stackoverflow.com/comment/83965247
has body: single = [1,5,6] single[:][0] += 5 print(single) I am unable to understand why is the element at index position 0 [0] not changing and also this code doesn't give out any type of error?
answer count: 1
type: Question
tagged with: indexing
has title: Python List : Why does the element not changed at the index position?
linked to: http://stackoverflow.com/q/27658877

http://stackoverflow.com/comment/83762921
type: Comment
has text: because you used `ax.add_artist`, it appears in the `ax.artists` list.
comment on: http://stackoverflow.com/q/48387480
type: QuestionComment
score: 2

http://stackoverflow.com/a/48396707
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83790575
has comment: http://stackoverflow.com/comment/83785688
answers question: http://stackoverflow.com/q/48396550
type: Answer
has body: The problem is that each row in the RDD is a single string (i.e. one column) and your schema contains 7 columns. The RDD is not actually converted into a dataframe until you use an action (like show) which is why it does not crash immediately. Since you want to have the data in a dataframe, the easiest solution would be to read the data as a dataframe in the beginning: geioIP = SparkS.read.csv("C:\\Users\\...\\RawData\\nasdaq.csv", schema=schema) Or if you want to continue to use RDD and createDataFrame, you could use the split function (possibly with strip if you have spaces). raw_data = raw_data.map(lambda x: [c.strip() for c in x.split(',')]) geioIP = SparkS.createDataFrame(raw_data,schema)

http://stackoverflow.com/a/48398288
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48398211
accepted answer of: http://stackoverflow.com/q/48398211
type: Answer
has body: ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "'-i origin AS32934'"])# Wrong your attempt to quote the last aegument is redundant with the quoting done by Popen. I can't test, but you have to remove the extra quotes you've thrown in: ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "-i origin AS32934"]) Popen detects that there are spaces in the argument and quotes it automatically if needed. Adding more quotes makes Popen add even more quotes and the arguments of your commands are wrong. unless you need to pass each argument separately but your attempt in doing this also fails because you left the quotes in the first &amp; last argument. That doesn't cut it: ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "'-i", "origin", "AS32934'"]# Wrong should be ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "-i", "origin", "AS32934"]
has comment: http://stackoverflow.com/comment/83785163
downvote count: 0
has comment: http://stackoverflow.com/comment/83785076

http://stackoverflow.com/comment/83813316
type: QuestionComment
comment on: http://stackoverflow.com/q/48411344
type: Comment
has text: The question is already closed as a duplicate, sorry.
score: 0

http://stackoverflow.com/q/48474681
tagged with: python
has answer: http://stackoverflow.com/a/48474991
accepted answer: http://stackoverflow.com/a/48628268
has comment: http://stackoverflow.com/comment/83942928
has title: NetworkX - reference and implementation mismatch
has comment: http://stackoverflow.com/comment/83942820
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48474991
tagged with: networkx
tagged with: python-3.x
has body: I'm working on a NetworkX code. I'm trying to learn the basics and following the software official reference and doing some simple projects. as a part of this process, i created an empty graph and tried to add a path using "networkx.classes.function.add_path". the problem rises when i use the reference notation and compile the source example , presented below : G = nx.Graph() nx.add_path(G, [0, 1, 2, 3]) i get the error: AttributeError: 'module' object has no attribute 'add_path' which i tried dir(nx) and figured out the error was pointing correct as nx does not have a method for adding paths, but doing the same it i found out Graph has this method: dir(G) so i changed the code to : G = nx.Graph() G.add_path([0,1,2,3]) which worked correctly. so, my question is : was the reference wrong about this example or am i missing something here?
has answer: http://stackoverflow.com/a/48628268
type: Question
has comment: http://stackoverflow.com/comment/83942981
has comment: http://stackoverflow.com/comment/83942930

http://stackoverflow.com/comment/83679297
comment on: http://stackoverflow.com/q/48346675
type: QuestionComment
has text: You need to pass `r` and `c` to the superclass's `__init__()`, not to `super()`.
type: Comment
score: 0

http://stackoverflow.com/q/48413388
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
has body: Right now I have two dataframes (let's call them A and B) built from Excel imports. Both have different dimensions as well as some empty/NaN cells. Let's say A is data for individual model numbers and B is a set of order information. For every row (unique item) in A, I want to search B for the (possibly) multiple orders for that item number, average the corresponding prices, and append A with a column containing the average price for each item. The item numbers are alphanumeric so they have to be strings. Not every item will have orders/pricing information for it and I'll be removing those at the next step. This is a large amount of data so efficiency is ideal so iterrows probably isn't the right choice. Thank you in advance! Here's what I have so far: avgPrice = [] for index, row in dfA.iterrows(): def avg_unit_price(item_no, unit_price): matchingOrders = [] for item, price in zip(item_no, unit_price): if item == row['itemNumber']: matchingOrders.append(price) avgPrice.append(np.mean(matchingOrders)) avg_unit_price(dfB['item_no'], dfB['unit_price']) dfA['avgPrice'] = avgPrice
upvote count: 1
tagged with: match
favorite count: 0
type: Question
tagged with: indexing
accepted answer: http://stackoverflow.com/a/48413539
has title: Append pandas dataframe with column of averaged values from string matches in another dataframe
has answer: http://stackoverflow.com/a/48413539
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83857751

http://stackoverflow.com/comment/83896210
type: Comment
type: QuestionComment
has text: what is `save_virtual_workbook` ? a function of yours?
comment on: http://stackoverflow.com/q/48451317
score: 1

http://stackoverflow.com/q/48465576
has comment: http://stackoverflow.com/comment/83924760
has comment: http://stackoverflow.com/comment/83926099
has comment: http://stackoverflow.com/comment/83924862
has comment: http://stackoverflow.com/comment/83925424
has title: How can I add different set of dictionaries into one
has comment: http://stackoverflow.com/comment/83926162
duplicate of: http://stackoverflow.com/q/5946236
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/83925921
type: Question
has answer: http://stackoverflow.com/a/48465799
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83926198
has body: How can I merge three different set of dictionary to new one suppose if input is d1 = {'name':'tom', 'age':'14', 'sex':'m'} d2 = {'color':'w', 'weight':'58','style':'good'} d3 = {'sports':'cricket','music':'rock','dance':'disco'} Output should be d = {'name':'tom', 'age':'14', 'sex':'m','color':'w', 'weight':'58','style':'good','sports':'cricket','music':'rock','dance':'disco'} I tried using update method, it is suitable for only two dictionary, if I use 3 set it results in repetation,so how can I merge three dictionary into single one
has comment: http://stackoverflow.com/comment/83926148
answer count: 5
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48465753
has answer: http://stackoverflow.com/a/48465787
upvote count: 1
has answer: http://stackoverflow.com/a/48465706
tagged with: python
linked to: http://stackoverflow.com/q/9415785
has answer: http://stackoverflow.com/a/48475990

http://stackoverflow.com/comment/83859708
comment on: http://stackoverflow.com/q/48433172
score: 0
has text: @BillBell yes I have tried doing a conda update conda again. I am getting CondaHTTPError: HTTP None None for url <https://repo.continuum.io/pkgs/free/win-64/repodata.json.bz2> as an error
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48948107
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48368219
has body: All i had to do was connect to cookies changed signal. def cookies_change(self): print("Updating Cookies") self.cookies.connect("changed", cookies_change)
answers question: http://stackoverflow.com/q/48368219
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48362828
answer count: 3
has answer: http://stackoverflow.com/a/48362956
upvote count: 1
type: Question
has body: My task is to write a function, drawCircle(radius,fillColor), that asks a user for the specific radius of the circle and which color they'd like the circle to be filled. I have the circle-drawing down, but I'm struggling with getting the circle to fill with the user-defined color. Any help would be greatly appreciated. import turtle def drawCircle(radius, fillColor): x=360/300 #This gives the angle r=radius#This is the radius of the circle. c=fillColor c=str("") z=1 #Placeholder for the while loop. win=turtle.Screen() tom=turtle.Turtle() fillColor=tom.color() tom.begin_fill() while (z&lt;=300): tom.forward(r) tom.right(x) tom.forward(r) z=z+1 win.exitonclick() tom.end_fill() This is my function call: drawCircle(1,"red")
tagged with: python-3.x
has title: Writing a function that asks a user to input a color and then fills a shape with that color
tagged with: turtle-graphics
has answer: http://stackoverflow.com/a/65879281
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/48371305
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83712553
score: 0

http://stackoverflow.com/q/48392261
has answer: http://stackoverflow.com/a/48392568
type: UnansweredQuestion
has body: My python code produces a condition (such as Up, Down, Left, Right), the start time when that condition occurs, and at some point in the future an end time for that condition ending. Presently, the code produces the following output in the database. Current State condition | start_time | end_time Up | NULL | NULL NULL | 44:03.1 | NULL NULL | NULL | 44:05.2 Down | NULL | NULL NULL | 44:05.2 | NULL NULL | NULL | 44:20.4 Right | NULL | NULL NULL | 44:20.4 | NULL NULL | NULL |44:21.6 This is my current code for logging the first value, the condition direction: c.execute('INSERT INTO conditionsAndTimesToPlot (condition_direction) VALUES (?)', (condition,)) conn.commit() After some other stuff has to happen, the start_time is then recorded with: c.execute('INSERT INTO conditionsAndTimesToPlot (start_time) VALUES (?)', (start_time_full,)) conn.commit() Then after some arbitrary time that condition ends and the end time is recorded with: c.execute('INSERT INTO conditionsAndTimesToPlot (end_time) VALUES (?)', (end_time_full,)) conn.commit() What I Want To Achieve condition | start_time | end_time Up | 44:03.1 | 44:05.2 Down | 44:05.2 | 44:20.4 Right | 44:20.4 | 44:21.6 What I Tried I tried using UPDATE for the time arguments. I thought that INSERT for the condition direction would insert a new line and UPDATE for the start and end times would then naturally backfill the 2nd and 3rd columns but now I get this error in the terminal: sqlite3.OperationalError: near "INTO": syntax error Questions Is there something obvious that I am missing here to make this happen? Should I create 3 tables (one for each value [condition, start_time, end_time] and then write code that combines the three tables by row into a single table for every cycle through my loop? Thanks for your help on my first ever stackoverflow question, David
downvote count: 0
has comment: http://stackoverflow.com/comment/83772472
upvote count: 1
tagged with: python
has title: How to add partial row data in sqlite3, one column at a time in python
score: 1
tagged with: sqlite
answer count: 1
favorite count: 0
type: Question

sorting
tags question: http://stackoverflow.com/q/48343822
tags question: http://stackoverflow.com/q/48413706
tags question: http://stackoverflow.com/q/48418556
tags question: http://stackoverflow.com/q/48373186
tags question: http://stackoverflow.com/q/48463500
tags question: http://stackoverflow.com/q/48439745
tags question: http://stackoverflow.com/q/48390960
tags question: http://stackoverflow.com/q/48452533
tags question: http://stackoverflow.com/q/48383591
tags question: http://stackoverflow.com/q/48385692
tags question: http://stackoverflow.com/q/48408487
tags question: http://stackoverflow.com/q/48408866
tags question: http://stackoverflow.com/q/48436707
tag name: sorting
tags question: http://stackoverflow.com/q/48393336
tags question: http://stackoverflow.com/q/48476773
tags question: http://stackoverflow.com/q/48360377
tags question: http://stackoverflow.com/q/48458330
tags question: http://stackoverflow.com/q/48389320
tags question: http://stackoverflow.com/q/48358320
tags question: http://stackoverflow.com/q/48397745
tags question: http://stackoverflow.com/q/48469254
tags question: http://stackoverflow.com/q/48372501
tags question: http://stackoverflow.com/q/48393640
tags question: http://stackoverflow.com/q/48455182
tags question: http://stackoverflow.com/q/48483398
tags question: http://stackoverflow.com/q/48463459
type: Tag
tags question: http://stackoverflow.com/q/48359150

http://stackoverflow.com/q/48464321
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83922041
has comment: http://stackoverflow.com/comment/83922554
has answer: http://stackoverflow.com/a/48464759
has title: What is pythonic way to update custom list of object variables?
accepted answer: http://stackoverflow.com/a/48464786
tagged with: python
has comment: http://stackoverflow.com/comment/83922608
has comment: http://stackoverflow.com/comment/83922060
has comment: http://stackoverflow.com/comment/83922755
has body: Cannot clearly understand right way to create CRUD interface for entity. For example: I've got entity Event with variables date, place and name. I've got basic constructor for this entity with default (nullablle) values. class Event: def __init__(self, date=None, name=None, place=None): self.date = date self.name = name self.place = place Trying to figure out pythonic way to create update handler for this entity, which allows me to update custom number of entity fields (for example: update name and place, without specifying date). How I see this: Use list of custom attributes in update method like update_event(**kwargs), then parse **kwargs list and match them with entity using .hasattr() or .getattr() functions. Its seems working (and able to find actual diff between entities, which is useful too), but looking pretty harsh. Basic version with setting all values from kwargs looks like this: def update_event(self, **kwargs): for key, value in kwargs.items(): self.__setattr__(key, value) return self If we need to check if for diff, we already got: def update_event(self, **kwargs): for key, value in kwargs.items(): if self.__getattribute__(key) != value: # We got diff self.__setattr__(key, value) else: # We got same value stored already return self Maybe im missing something and there are more elegant and simple solutions to this problem, or some design patterns to look for? Tnx for answers and sorry for dummy questions. UPD: One more point I see: simple __setattr__ doesn't check that such variable exists. So, if **kwargs contains invalid argument name I get Attribute Error. The obvious fix for that is to create check for .hasattr() but as I see it will return False if variable declared but has None value.
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/48464759
score: 1
has answer: http://stackoverflow.com/a/48464786
downvote count: 0

http://stackoverflow.com/a/48334563
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: The error message says: jinja2.exceptions.TemplateNotFound: template\profile.html The templates folder should be named templates (in plural) and saved in the root path of the application. That is how Flask works by default.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48334437
answers question: http://stackoverflow.com/q/48334437

http://stackoverflow.com/comment/83789471
has text: If 'Betrag' is a DataFrame column you have to use the second variation.
type: Comment
comment on: http://stackoverflow.com/a/48399057
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83930500
type: Comment
type: QuestionComment
score: 0
has text: i run tcpdump, and if i do process.kill() i loose packet captured, received or dropped information. Which is why i need process.terminate(). If i run ffmpeg, i need process.kill() otherwise python is not able to end it. Which is why i need both depending if i want to kill ffmpeg or terminate tcpdump
comment on: http://stackoverflow.com/q/48468274

http://stackoverflow.com/comment/83854950
type: QuestionComment
has text: This doesn't really have anything to do with backwards relations. `values_list` takes a `flat=True` parameter.
score: 0
comment on: http://stackoverflow.com/q/48431871
type: Comment

http://stackoverflow.com/comment/83690228
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48351338
has text: CPU times of `do_nothing` are equal to those of `my_mean`, in my results, using my random i, but the same appens with -1.
score: 0

http://stackoverflow.com/q/48433985
has title: Why does sending consecutive UDP messages cause messages to arrive late?
tagged with: python
tagged with: http://stackoverflow.com/tag/c
possible better answer: http://stackoverflow.com/a/48435087
has comment: http://stackoverflow.com/comment/83860540
favorite count: 0
has answer: http://stackoverflow.com/a/48435087
has comment: http://stackoverflow.com/comment/83860335
upvote count: 2
has comment: http://stackoverflow.com/comment/83859732
answer count: 2
downvote count: 0
tagged with: multithreading
has comment: http://stackoverflow.com/comment/83860470
has answer: http://stackoverflow.com/a/50865819
accepted answer: http://stackoverflow.com/a/50865819
type: Question
score: 2
type: AnsweredQuestion
tagged with: linux
has body: I've written a server python script in Windows 7 to send Ethernet UDP packets to a UNIX system running a C client receiving program that sends the message back to the server. However, sometimes (not always) a message in the last port (and always the last port) that python sends to won't arrive until the next batch of 4 messages is sent. This causes the timing of the message received for the last port incorrect to when it was sent, and I cannot have two messages back to back on the same port. I have been able to verify this in Wireshark by locating two messages that arrived around the same time because the one that wasn't received was processed with the other. I have also checked the timing right after the recv() function and it shows a long delay and then a short delay because it basically had two packets received. Things I have done to try to fix this, but has help me explain the problem or how to solve it: I can add a delay in between each sendto() and I will successfully send and receive all messages with correct timing but I want the test to work the way I've written it below; I've increased the priority of the receive thread thinking that my Ethernet receive was not getting signal to pick up the package or that some process was taking too long, but this didn't work and 20ms should be WAY more than necessary to process the data; I have removed ports C and D, then port B misses messages (Only having one port doesn't caause issues), I thought reducing the number of ports would improve timing; Sending to a dummy PORTE immediately after PORTD lets me receive all of the messages with correct timing (I assume the problem is transferred to PORTE); I have also reproduced the python script in a UNIX environment and C code and have had the same issue, pointing me to a receiving issue; I've also set my recv function to time out every 1ms hoping that it could recover somehow even though the timing would be off a bit, but I still saw messages back to back. I've also checked …
tagged with: sockets
has comment: http://stackoverflow.com/comment/83859618

http://stackoverflow.com/q/48388833
answer count: 1
has title: sed not working on large file [Looking for other options]
favorite count: 0
type: Question
has body: I have a gigantic json file that was accidentally output without a newline character in between all the json entries. It is being treated as one giant single line. So what I did was try and take a find an replace with sed and insert a newline. sed 's/{"seq_id"/\n{"seq_id"/g' my_giant_json.json It doesn't output anything However, I know my sed expression is working if I operate on just a small part of the file and it works fine. head -c 1000000 my_giant_json.json | sed 's/{"seq_id"/\n{"seq_id"/g' I have also tried using python with this gnarly one liner '\n{"seq_id'.join(open(json_file,'r').readlines()[0].split('{"seq_id')).lstrip() But this loads into memory thanks to readlines() method. But I don't know how to iterate through a giant single line of characters (iterate in chunks) and do a find and replace. Any thoughts?
has comment: http://stackoverflow.com/comment/83765779
has comment: http://stackoverflow.com/comment/83765695
has comment: http://stackoverflow.com/comment/83765689
tagged with: gnu
tagged with: sed
has answer: http://stackoverflow.com/a/48389034
accepted answer: http://stackoverflow.com/a/48389034
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/2988211
type: AnsweredQuestion
upvote count: 3
tagged with: bash
has comment: http://stackoverflow.com/comment/83765449
tagged with: http://stackoverflow.com/tag/json
downvote count: 1

http://stackoverflow.com/q/48406251
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/83802201
type: Question
type: AnsweredQuestion
has title: How do I get a mean of exactly 0 when standardizing?
has comment: http://stackoverflow.com/comment/83801358
accepted answer: http://stackoverflow.com/a/48406854
tagged with: python
has answer: http://stackoverflow.com/a/48406854
has comment: http://stackoverflow.com/comment/83819458
has comment: http://stackoverflow.com/comment/83802470
score: 0
has body: array = preprocessing.scale(array) Im using the preprocessing module from sklearn in python, to change the mean of my array to 0. Problem is, I am getting really small numbers as my mean along the lines of 10^16, instead of 0. Problem is that I truly need a mean of 0, else I cannot compute a covariance matrix for my signal. How can I solve this? Thanks a lot in advance.
tagged with: scale
tagged with: mean

http://stackoverflow.com/q/48404453
has answer: http://stackoverflow.com/a/48404599
accepted answer: http://stackoverflow.com/a/48404491
has body: I have two pandas dataframes with names df1 and df2 such that ` df1: a b c d 1 2 3 4 5 6 7 8 and df2: b c 12 13 I want the result be like result: b c 2 3 6 7 Here it should be noted that a b c d are the column names in pandas dataframe. The shape and values of both pandas dataframe are different. I want to match the column names of df2 with that of column names of df1 and select all the rows of df1 the headers of which are matched with the column names of df2.. df2 is only used to select the specific columns of df1 maintaining all the rows. I tried some code given below but that gives me an empty index. df1.columns.intersection(df2.columns) The above code is not giving me my resut as it gives index headers with no values. I want to write a code in which I can give my two dataframes as input and it compares the columns headers for selection. I don't have to hard code column names.
has comment: http://stackoverflow.com/comment/83797496
possible better answer: http://stackoverflow.com/a/48404663
has answer: http://stackoverflow.com/a/48404491
downvote count: 0
score: 10
tagged with: python
has comment: http://stackoverflow.com/comment/83797480
type: AnsweredQuestion
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/83797646
has answer: http://stackoverflow.com/a/48404663
upvote count: 10
favorite count: 0
type: Question
has title: Matching the column names of two pandas data-frames in python

http://stackoverflow.com/q/48444246
type: AnsweredQuestion
has body: How can I tweak this so that if xyz17 is selected from the Menu the function xyz17() is run? I'm aware of command = xyz17 but I'm not sure how to make that dynamic so that it depends on the menu selection. from tkinter import * def xyz17(): print('xyz17') def abc27(): print('abc27') def qwe90(): print('qwe90') def uio19(): print('uio19') def jkl09(): print('jkl09') def zxc28(): print('zxc28') class Menu(OptionMenu): def __init__(self, master, status, *options): self.var = StringVar(master) self.var.set(status) OptionMenu.__init__(self, master, self.var, *options) def main(): TopFrame = Frame(root) TopFrame.pack() Menu1 = Menu(TopFrame, 'xyz', 'xyz17','abc27','qwe90') Menu2 = Menu(TopFrame, 'uio', 'uio19','jkl09','zxc28') Menu1.pack() Menu2.pack() root = Tk() main() root.mainloop() Please note that the functions each priniting the value is just for an example, I would like the code to run the function itself. I'm aware of this: class Menu(OptionMenu): def __init__(self, master, status, *options): self.var = StringVar(master) self.var.set(status) OptionMenu.__init__(self, master, self.var, *options, command=self.func) def func(self,value): print (value) But, this isn't relevant to my scenario as it simply just gets the value and prints it, and I would like it to actually run the function itself.
accepted answer: http://stackoverflow.com/a/48444949
possible better answer: http://stackoverflow.com/a/48444965
has answer: http://stackoverflow.com/a/48444949
tagged with: optionmenu
tagged with: python
has answer: http://stackoverflow.com/a/48444965
has comment: http://stackoverflow.com/comment/83880907
has comment: http://stackoverflow.com/comment/83881148
has comment: http://stackoverflow.com/comment/83880794
favorite count: 0
has comment: http://stackoverflow.com/comment/83881023
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83880098
downvote count: 0
tagged with: drop-down-menu
has comment: http://stackoverflow.com/comment/83880527
has title: Running commands based on OptionMenu's selection
score: 4
has comment: http://stackoverflow.com/comment/83880729
has comment: http://stackoverflow.com/comment/83880555
has comment: http://stackoverflow.com/comment/83880595

http://stackoverflow.com/comment/83824985
has text: Or actually, like you said, `[mp3 @ 0x7faf18809400] pad 576 940` this pad statement accounts for the discrepancy. It's 1516 = 576 + 940. So will it always be 576 samples in the front and 940 in the back? Is there a formula to compute these pad values?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48415930
type: AnswerComment

syntax-error
tags question: http://stackoverflow.com/q/48350916
tags question: http://stackoverflow.com/q/48356041
type: Tag
tags question: http://stackoverflow.com/q/48338413
tag name: syntax-error
tags question: http://stackoverflow.com/q/48378916

http://stackoverflow.com/comment/83686096
type: Comment
comment on: http://stackoverflow.com/a/48346567
has text: Sorry @DarkCygnus I forgot to say thank you! Anyway I mean training batch, I know it may sound weird...
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83666162
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48340494
has text: Fine, but that doesn't explain why they need to be in a separate model.
type: Comment

http://stackoverflow.com/comment/83706983
type: QuestionComment
comment on: http://stackoverflow.com/q/48356946
score: 0
has text: @ekhumoro This comes in return: Edited above because of space reason ...
type: Comment

http://stackoverflow.com/comment/83720513
has text: We need to see `self._execute_query`, as it appears to be that method that returned a list, not a cursor with `rowcount` attribute.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48366939

http://stackoverflow.com/a/48389579
type: Answer
score: -1
upvote count: 1
has body: Try: pattern = r"abc_def_[\d]+(\.json)" Match: "abc_def_" literally one or more digits ".json" literally See the pattern on regex101.
has comment: http://stackoverflow.com/comment/107495323
answers question: http://stackoverflow.com/q/48389507
downvote count: 2

http://stackoverflow.com/a/48471489
has comment: http://stackoverflow.com/comment/83937080
has body: Let's go over your conditions. What we want to do is redefine low and high based on the answer the program received. if check_ans == 'h': # We know that ans is lower, so we set our higher bound to slightly below ans high = ans - 1 elif check_ans == 'l': # We know that ans is higher, so we set our lower bound to slightly above ans low = ans + 1 Then at the beggining of your loop you want to get ans based on the interval by doing ans = (high + low)//2. Overall this gives user_num = (int(input("Please think of a number between 0 and 100! "))) low = 0 high = 100 while True: ans = (high + low)//2 print("is your secret number " + str(ans)) check_ans = input(""" enter 'h' to indicate if the guess is too high. enter 'l' to indicate if the guess is too low. enter 'c' if I guessed correctly.""") if check_ans == 'h': high = ans - 1 elif check_ans == 'l': low = ans + 1 elif check_ans == 'c' and check_ans == user_num: print("Game over. Your secret number was: " + str(ans)) break else: print("I do not understand your command")
has comment: http://stackoverflow.com/comment/83936952
has comment: http://stackoverflow.com/comment/83936948
has comment: http://stackoverflow.com/comment/122199086
type: Answer
answers question: http://stackoverflow.com/q/48471434
has comment: http://stackoverflow.com/comment/83937070
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83937432

http://stackoverflow.com/a/48350336
has comment: http://stackoverflow.com/comment/83695564
type: Answer
score: 4
upvote count: 4
has body: Have you tried initializing the columns as nan, iterating through the dataframe by row, and assigning the values with loc? import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0, 20, (10, 5))) df[5] = np.nan df[6] = np.nan for i, row in df.iterrows(): df.loc[i, 5] = row[1] + row[4] df.loc[i, 6] = row[3] * 2 print(df) yields 0 1 2 3 4 0 17 4 3 11 10 1 16 1 14 11 16 2 4 18 12 19 7 3 11 3 7 10 5 4 11 0 10 1 17 5 5 17 10 3 8 6 0 0 7 3 6 7 7 18 18 13 8 8 16 4 12 11 16 9 13 9 15 8 19 0 1 2 3 4 5 6 0 17 4 3 11 10 14.0 22.0 1 16 1 14 11 16 17.0 22.0 2 4 18 12 19 7 25.0 38.0 3 11 3 7 10 5 8.0 20.0 4 11 0 10 1 17 17.0 2.0 5 5 17 10 3 8 25.0 6.0 6 0 0 7 3 6 6.0 6.0 7 7 18 18 13 8 26.0 26.0 8 16 4 12 11 16 20.0 22.0 9 13 9 15 8 19 28.0 16.0
has comment: http://stackoverflow.com/comment/83697032
downvote count: 0
answers question: http://stackoverflow.com/q/48344958

http://stackoverflow.com/a/48438291
has body: You need to put an ampersand in front of your application name (here its python.exe) &amp; "C:\Program Files\Python36\python.exe" .\setup.py install PowerShell needs the ampersand to interpret the string as a filename.
accepted answer of: http://stackoverflow.com/q/48438231
upvote count: 8
score: 8
answers question: http://stackoverflow.com/q/48438231
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83803464
has text: Thanks I Was Downloaded Python On Visual Studio(.)I'll Download It in Original Site With Path Thanks (A)gain
comment on: http://stackoverflow.com/a/48407228
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83844626
type: AnswerComment
comment on: http://stackoverflow.com/a/48426856
has text: You're welcome. Please accept the answer if it's correct.
type: Comment
score: 0

http://stackoverflow.com/q/48448414
tagged with: logging
has answer: http://stackoverflow.com/a/77430145
type: Question
tagged with: inspection
type: AnsweredQuestion
has title: Display source code causing an exception in Python
linked to: http://stackoverflow.com/q/10115022
tagged with: python
possible better answer: http://stackoverflow.com/a/77430145
favorite count: 0
has body: How to retrieve the line of code (not the line number) that causes an exception? This is an attempt. import sys, inspect try: 1 / 0 except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() code = str(inspect.getsourcelines(exc_tb.tb_frame.f_code)) print(code) It returns the first line of the script, not the line that causes the exception. (['import sys, inspect\n'], 1)
upvote count: 4
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/48448977
has answer: http://stackoverflow.com/a/48448977
downvote count: 0
score: 4

http://stackoverflow.com/comment/83731500
has text: Ah OK i have it on my github:https://github.com/Landixus/multipleDS18B20WeeWX/blob/master/ds18b20.py
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48371975

http://stackoverflow.com/a/48427317
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48426128
downvote count: 0
upvote count: 1
has body: Try running the application from a console so that you can view the error messages associated with the failed launch; if you click the .exe to open it, the console will disappear as soon as the application closes, which makes it difficult to see these errors. Most likely, you will see that the application failed to launch because it is missing packages, which you can add to the .spec file under the hiddenimports list. Check out this post for a description of why this might be necessary.
has comment: http://stackoverflow.com/comment/83921151

http://stackoverflow.com/q/48412362
score: -1
has comment: http://stackoverflow.com/comment/83814678
tagged with: loops
has comment: http://stackoverflow.com/comment/83814620
type: Question
upvote count: 0
answer count: 2
tagged with: for-loop
tagged with: max
has answer: http://stackoverflow.com/a/48412391
possible better answer: http://stackoverflow.com/a/48412391
has comment: http://stackoverflow.com/comment/83814712
has body: I'm trying to find the largest value for a variable, where the variable must be contained in one of the list values. My code is the following and seems to work fine, however I encounter a problem. Basically the code is overwriting the values with the last value found instead of keeping the highest one. d_list = ['a','b','c'] for value in values: name = value['name'] category = value['category'] rank = value['rank'] largest = None for x in d_list: if x in name: if largest is None or rank &gt; largest: largest = rank info[x + ' ' + 'Rank'] = largest Any suggestions on how to keep just the highest score for each x? Thank you
downvote count: 1
has title: Find largest value and print it in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/83814727
has answer: http://stackoverflow.com/a/48412457
accepted answer: http://stackoverflow.com/a/48412457
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83815393
tagged with: python

http://stackoverflow.com/q/48350948
has body: I'm working on two pandas Timeseries object (the second coming from a group by on 30 minutes): df_lookup = pd.DataFrame(np.arange(10, 16), index=('2017-12-15 17:58:00', '2017-12-15 17:59:00', '2017-12-15 18:00', '2017-12-15 18:01:00', '2017-12-15 18:02:00', '2017-12-15 18:03:00', ) ) df_lookup.index = pd.to_datetime(df_lookup.index) avg_30min = pd.DataFrame([0.066627, 0.1234, 0.0432, 0.234], index=("2017-12-15 18:00:00", "2017-12-15 18:30:00", "2017-12-15 19:00:00", "2017-12-15 19:30:00", ) ) avg_30min.index = pd.to_datetime(avg_30min.index) I need to iterate over the second, avg_30min, and lookup into the first, df_lookup in order to extract the value at index idx. for idx, row in avg_30min.iterrows(): value_in_lookup_df = df_lookup.loc[idx] # Here I'd use the object from the lookup to add a detail into a plot. I tried using loc and iloc, the former returns: KeyError: 'the label [2017-12-15 18:00:00] is not in the [index]' while the latter: TypeError: cannot do positional indexing on &lt;class 'pandas.core.indexes.base.Index'&gt; with these indexers [2017-12-15 18:00:00] of &lt;class 'pandas._libs.tslib.Timestamp'&gt; The expected result would be the row from df_lookup which index matches idx, somewhat similar to a dictionary lookup in plain python (row_from_lookup = lookup_df[idx]). What's the right method to have an exact match on a pandas Timeseries?
has comment: http://stackoverflow.com/comment/83688650
tagged with: python
has answer: http://stackoverflow.com/a/48357384
has comment: http://stackoverflow.com/comment/83703201
has comment: http://stackoverflow.com/comment/83701903
has comment: http://stackoverflow.com/comment/83701078
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83688655
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48357384
has comment: http://stackoverflow.com/comment/83688872
has comment: http://stackoverflow.com/comment/83701517
possible better answer: http://stackoverflow.com/a/48351111
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83703367
has title: Pandas: exact indexing on timeseries
has answer: http://stackoverflow.com/a/48351111

http://stackoverflow.com/comment/84044256
has text: You're missing the point. If the language is *allowed* to alias A and B, then there is no reliable way to differentiate them, even if they happen to be separate instances at runtime.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48472254
type: AnswerComment

http://stackoverflow.com/a/53268516
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48364447
type: Answer
has body: Here's a benchmarked answer. Note that I do some transposing so that this will work no matter whether that matrix is tall and thin (gives column-orthonormal) or short and wide (gives row-orthonormal). def qr_method(n, m): X = np.random.normal(0,1,(n,m)) if n &lt; m: X = X.T Q, _ = np.linalg.qr(X) if n &lt; m: Q = Q.T return Q def orth_method(n, m): X = np.random.normal(0,1,(n,m)) if n &lt; m: X = X.T Q = scipy.linalg.orth(X) if n &lt; m: Q = Q.T return Q def ortho_group_method(n, m): Q = scipy.stats.ortho_group.rvs(max(n, m))[:min(n, m),:] if m &lt; n: Q = Q.T return Q The ortho_group method (aka make a square matrix and then take a subset) was so slow that I didn't benchmark it along with the others: %timeit ortho_group_method(500, 20) 2.73 s ± 57.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Of the other two, the difference is negligible, by QR is slightly faster. %timeit qr_method(10000, 200) 168 ms ± 3.78 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit orth_method(10000, 200) 193 ms ± 4.09 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Does it make a difference how tall the matrix is? For a very tall matrix, they are close to equivalent. %timeit qr_method(100000, 20) 122 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit orth_method(100000, 20) 130 ms ± 6.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) For a square matrix, QR is much faster. %timeit qr_method(500, 500) 47.5 ms ± 202 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit orth_method(500, 500) 137 ms ± 1.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
downvote count: 0

http://stackoverflow.com/q/48388564
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48698666
score: 0
has title: Google Sheets query in Python
has body: I have a Google sheet that grabs data from a website using the =IMPORTXML function. I also have a Python script that grabs data from the Google sheet. The whole thing is working, but I'm now trying to streamline it. This whole thing started as a manual process in Google Sheets. It's now automated, but it's not pretty. Two specific questions: 1) What is the best way to scrape a website using Python? I'd like to get this all running in a single script. Would something like Beautiful Soup be a good solution? 2) Currently the query to the google API is coded to run separately each query (it's not a sub function, but I'd like to turn it into one). It essentially copies the quickstart script: spreadsheetId = 'xxxx' rangeName = 'xxxx' result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId,range=rangeName).execute() values = result.get('values', []) variable = '' for row in values: variable = '%s' % (row[0]) if variable != storedVariable: print ('Condition not met...') return; #Do a thing My code has various versions of setting a variable, checking it against a stored value, and proceeding if the correct conditions exist. Is there an easier way to parse the values returned from the API call so that it's set as a variable?
tagged with: web-scraping
answer count: 1
tagged with: beautifulsoup
tagged with: google-sheets-api
type: Question
tagged with: google-sheets

http://stackoverflow.com/comment/83773303
score: 1
has text: Anaconda is very nice in that it makes it easy to create virtual environments. Virtual environments enabled me to run both python 2.13 and python 3.6 on my Mac.
type: Comment
comment on: http://stackoverflow.com/a/48392546
type: AnswerComment

http://stackoverflow.com/comment/83840245
comment on: http://stackoverflow.com/q/48425148
score: 2
type: QuestionComment
type: Comment
has text: You should subclass [`AbstractUser`](https://github.com/django/django/blob/master/django/contrib/auth/models.py#L288), not [`AbstractBaseUser`](https://github.com/django/django/blob/master/django/contrib/auth/base_user.py#L47). The latter only has two fields: password and last_login, while the former is essentially the default `User`, but abstract.

http://stackoverflow.com/a/48421422
has body: You need to change your ini file format to [Default] Mykey:['123,456,789', '+234,567,891', '+345,678,912'] After this you can access it like print conf["Default"]["Mykey"] Result: ['123,456,789', '+234,567,891', '+345,678,912']
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48421292
type: Answer
has comment: http://stackoverflow.com/comment/83833378

http://stackoverflow.com/q/48408341
has comment: http://stackoverflow.com/comment/88302560
has title: Python Wand PDF to List of Images TypeError
upvote count: 3
has comment: http://stackoverflow.com/comment/83809134
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/83817793
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83816775
has comment: http://stackoverflow.com/comment/88716001
has body: I'm trying to make a python program that takes a PDF and converts it to a list of images, but I'm getting the issue: TypeError: object of type 'NoneType' has no len() Python from wand.image import Image as Ima images = [] pdf = Ima(filename="./sample.pdf") jpeg = pdf.convert('jpeg') for img in jpeg.sequence: img_page = Image(image=img) images.append(img_page.make_blob('jpeg')) print(images) Terminal Output File "OCR.py", line 9, in &lt;module&gt; pdf = Ima(filename="./sample.pdf") File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/wand/image.py", line 2744, in __init__ self.read(filename=filename, resolution=resolution) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/wand/image.py", line 2822, in read self.raise_exception() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/wand/resource.py", line 222, in raise_exception raise e wand.exceptions.DelegateError: FailedToExecuteCommand `'gs' -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 '-sDEVICE=pngalpha' -dTextAlphaBits=4 -dGraphicsAlphaBits=4 '-r72x72' '-sOutputFile=/var/folders/ll/vhx7d69s27l_766f7fh0w8t80000gn/T/magick-17265E7LIPpQmRZ4H%d' '-f/var/folders/ll/vhx7d69s27l_766f7fh0w8t80000gn/T/magick-17265VZNfoxE7irl0' '-f/var/folders/ll/vhx7d69s27l_766f7fh0w8t80000gn/T/magick-17265OAxHJmx1Guv6'' (1) @ error/pdf.c/InvokePDFDelegate/292 Exception ignored in: &lt;bound method Resource.__del__ of &lt;wand.image.Image: (empty)&gt;&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/wand/resource.py", line 232, in __del__ File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/wand/image.py", line 2767, in destroy TypeError: object of type 'NoneType' has no len()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50855722
tagged with: python
linked to: http://stackoverflow.com/q/37927247
score: 3
tagged with: imagemagick
tagged with: wand

http://stackoverflow.com/comment/83707863
type: QuestionComment
has text: This might explain why you are having issues: https://github.com/Z3Prover/z3/issues/63 I just googled your error + z3-solver
comment on: http://stackoverflow.com/q/48360543
score: 0
type: Comment

http://stackoverflow.com/comment/83877618
type: QuestionComment
score: 1
has text: What about `12`?
type: Comment
comment on: http://stackoverflow.com/q/48443151

http://stackoverflow.com/q/48393976
has comment: http://stackoverflow.com/comment/83780634
has answer: http://stackoverflow.com/a/48396583
has comment: http://stackoverflow.com/comment/83775969
accepted answer: http://stackoverflow.com/a/48396583
has body: I am trying to use multiple where conditions(mentioned below) in order to output a final date. np.where( (loan_plans.days_since_end.astype('timedelta64[D]')&gt;0.0) &amp; (loan_plans.principal_outstanding.astype('float')&lt;1000.0), loan_plans.max_repaid_date, (np.where( (loan_plans.days_since_end.astype('timedelta64[D]')&gt;0.0) &amp; (loan_plans.principal_outstanding.astype('float')&gt;1000.0), pd.to_datetime('today') (np.where( loan_plans.days_since_end.astype('timedelta64[D]')&lt;0.0, loan_plans.final_repayment_date, 0.0))))) These are the datatypes for the other variables loan_plans.max_repaid_date=datetime64[ns] loan_plans.final_repayment_date = datetime64[ns] I am getting the following error: TypeError: invalid type promotion I think the problem is regarding the data types and is a relatively small error, but I have been searching and can't find information to help me solve the problem
tagged with: python
has title: Numpy with multiple where conditions [TypeError: invalid type promotion]
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/48486254
score: 4
tagged with: geometry
has comment: http://stackoverflow.com/comment/83999195
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83969681
has comment: http://stackoverflow.com/comment/84000826
has comment: http://stackoverflow.com/comment/83979692
downvote count: 1
has answer: http://stackoverflow.com/a/48536077
has comment: http://stackoverflow.com/comment/83965353
favorite count: 0
type: Question
upvote count: 5
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/83965420
tagged with: python
has body: Let (0,0) and (Xo,Yo) be two points on a Cartesian plane. We want to determine the parabolic curve, Y = AX^2 + BX + C, which passes from these two points and has a given arc length equal to S. Obviously, S > sqrt(Xo^2 + Yo^2). As the curve must pass from (0,0), it should be C=0. Hence, the curve equation reduces to: Y = AX^2 + BX. How can I determine {A,B} knowing {Xo,Yo,S}? There are two solutions, I want the one with A>0. I have an analytical solution (complex) that gives S for a given set of {A,B,Xo,Yo}, though here the problem is inverted... I can proceed by solving numerically a complex system of equations... but perhaps there is a numerical routine out there that does exactly this? Any useful Python library? Other ideas? Thanks a lot :-)
has title: Determine parabola with given arc length between two known points

http://stackoverflow.com/comment/83738731
comment on: http://stackoverflow.com/a/48334763
score: 0
type: Comment
has text: In web driver in selenium python i use above code to fetch potential error that occur in console in browser and it works too but problem is Reusing same code after automate browse to another page i get empty
type: AnswerComment

http://stackoverflow.com/q/48398158
has body: When I am trying to run the command pyinstaller myscript.py I get the following error whatever my script contains, I tried with a script with a single line of code like x=1 or print('Hello'). Everything gives the same error. 139 INFO: PyInstaller: 3.3.1 139 INFO: Python: 3.6.4 140 INFO: Platform: Windows-10-10.0.16299-SP0 Traceback (most recent call last): File "c:\anaconda3\envs\py\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\anaconda3\envs\py\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Anaconda3\envs\py\Scripts\pyinstaller.exe__main__.py", line 9, in File "c:\anaconda3\envs\py\lib\site-packages\PyInstaller__main__.py", line 92, in run spec_file = run_makespec(**vars(args)) File "c:\anaconda3\envs\py\lib\site-packages\PyInstaller__main__.py", line 39, in run_makespec spec_file = PyInstaller.building.makespec.main(filenames, **opts) File "c:\anaconda3\envs\py\lib\site-packages\PyInstaller\building\makespec.py", line 385, in main specfile.write(onedirtmplt % d) File "c:\anaconda3\envs\py\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 127-137: character maps to &lt; undefined >
score: 0
answer count: 1
type: Question
has title: PyInstaller gives the same encoding error
has answer: http://stackoverflow.com/a/48398408
tagged with: encoding
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83827534
comment on: http://stackoverflow.com/a/48407016
type: Comment
score: 2
has text: Something is calling your function like so: `.render(name=..., value=..., attrs=...)`, but you've named the arguments you expect `_name` and `_attrs`.
type: AnswerComment

http://stackoverflow.com/comment/83935370
type: Comment
has text: And how do your imports look like in `question.py`?
score: 0
comment on: http://stackoverflow.com/q/48469667
type: QuestionComment

http://stackoverflow.com/comment/84029763
comment on: http://stackoverflow.com/a/48470096
type: AnswerComment
score: 1
has text: with some minor modifications your idea of re-wiring `pd.read_csv` worked perfectly. thanks
type: Comment

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/48418169
tags question: http://stackoverflow.com/q/48370150

http://stackoverflow.com/q/48409237
favorite count: 0
type: Question
has title: Pandas - calculate percent of total given ranges
has body: I'd like get a percentage of the occurrences of speed data falling into a range as a percentage. As an example, 5% of the speed data is between 0 and 5, 10% is between 5 and 10, etc. I'd also like the ability to resample the output into any frequency (entire period, daily, monthly, etc) I have a DataFrame that looks like this: df = pd.DataFrame({'id': '1234', 'datetime': pd.date_range('2017-01-01', '2018-01-01', freq='H'), 'speed': np.random.randint(0, 5000, df.shape[0])}) df['speed'] = df['speed'] / 100.0 speedintervals = [0,3,5,9,15,21] frequency = 'D' # for daily aggregation of data # or frequency = 'P' for entire period DataFrame looks like this: datetime id speed 0 2017-01-01 00:00:00 1234 17.08 1 2017-01-01 01:00:00 1234 16.30 2 2017-01-01 02:00:00 1234 12.74 3 2017-01-01 03:00:00 1234 39.89 4 2017-01-01 04:00:00 1234 34.33 5 2017-01-01 05:00:00 1234 22.76 6 2017-01-01 06:00:00 1234 13.72 ... I'm imagining that I'd set datetime to index and do a resample of sorts, but not sure how to build out the data. Ultimately, I want the data to look like this: For entire period: id start_date end_date 0&lt;=3 3&lt;=9 9&lt;=15 15&lt;=21 &gt;21 1234 1/1/17 0:00 1/1/18 23:00 0.49 0.13 0.18 0.17 0.00 For daily frequency: id periodEnd 0&lt;=3 3&lt;=9 9&lt;=15 15&lt;=21 &gt;21 1234 1/1/18 0.49 0.13 0.18 0.17 0.00 1234 1/2/18 0.50 0.14 0.17 0.16 0.00 1234 1/3/18 0.25 0.10 0.25 0.25 0.15 ... any thoughts?
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48409604
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83808218
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48409604

http://stackoverflow.com/a/48404292
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48404125
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83798747
has comment: http://stackoverflow.com/comment/83798315
has body: Have a look on This introduction to the multiprocessing package. for example, try: import multiprocessing as mp import os def process_csv(csv): % process the csv return {csv: collected_debug_information} pool = mp.Pool(processes=4) results = pool.map(process_csv, os.listdir(path_to_csv_folder)) with the returned dict, you can have a look on the results to evaluate some parsing errors or so. It will be a list of dicts with the csv names as keys. Also a good package for that is joblib, have a look on that too, under the hood it uses the multiprocessing package.

http://stackoverflow.com/comment/83877665
has text: have you looked into [`sympy`](http://docs.sympy.org/latest/tutorial/calculus.html#derivatives)?
score: 0
comment on: http://stackoverflow.com/q/48443095
type: Comment
type: QuestionComment

utf-8
tags question: http://stackoverflow.com/q/48404294
tags question: http://stackoverflow.com/q/48439821
tags question: http://stackoverflow.com/q/48419346
tags question: http://stackoverflow.com/q/48340622
tag name: utf-8
tags question: http://stackoverflow.com/q/48427958
tags question: http://stackoverflow.com/q/48352804
tags question: http://stackoverflow.com/q/48421974
type: Tag
tags question: http://stackoverflow.com/q/48357759
tags question: http://stackoverflow.com/q/48430825
tags question: http://stackoverflow.com/q/48453332
tags question: http://stackoverflow.com/q/48394669

http://stackoverflow.com/q/48455518
has comment: http://stackoverflow.com/comment/83904018
answer count: 2
has body: The code uses the matrix and arrpow functions to calculate the fibonacci numbers for the elements in my list, num. Oddly, right after a.append(float(row[0])) is completed, the error I get is IndexError: list index out of range Which is obviously coming from b.append. Here's the file I want to pull from import time import math import csv import matplotlib.pyplot as plt def arrpow(arr, n): yarr=arr if n&lt;1: pass if n==1: return arr yarr = arrpow(arr, n//2) yarr = [[yarr[0][0]*yarr[0][0]+yarr[0][1]*yarr[1][0],yarr[0][0]*yarr[0][1]+yarr[0][1]*yarr[1][1]], [yarr[1][0]*yarr[0][0]+yarr[1][1]*yarr[1][0],yarr[1][0]*yarr[0][1]+yarr[1][1]*yarr[1][1]]] if n%2: yarr=[[yarr[0][0]*arr[0][0]+yarr[0][1]*arr[1][0],yarr[0][0]*arr[0][1]+yarr[0][1]*arr[1][1]], [yarr[1][0]*arr[0][0]+yarr[1][1]*arr[1][0],yarr[1][0]*arr[0][1]+yarr[1][1]*arr[1][1]]] return yarr def matrix(n): arr= [[1,1],[1,0]] f=arrpow(arr,n-1)[0][0] return f num = [10,100,1000,10000,100000,1000000] with open('matrix.dat', 'w') as h: for i in num: start_time = 0 start_time = time.time() run = matrix(i) h.write(str(math.log10(i))) h.write('\n') h.write((str(math.log10(time.time()-start_time)))) h.write('\n') a = [] b = [] with open('matrix.dat','r+') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: a.append(float(row[0])) b.append(float(row[1])) plt.plot(a,b,label = " ")
has answer: http://stackoverflow.com/a/48455661
possible better answer: http://stackoverflow.com/a/48455661
has comment: http://stackoverflow.com/comment/83904142
has answer: http://stackoverflow.com/a/48455672
accepted answer: http://stackoverflow.com/a/48455672
type: Question
has comment: http://stackoverflow.com/comment/83904164
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83904059
has title: Unable to pull data from a file and place into two arrays
tagged with: python
has comment: http://stackoverflow.com/comment/83904222
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/48332667
has comment: http://stackoverflow.com/comment/83651444
answers question: http://stackoverflow.com/q/48331589
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48331589
has comment: http://stackoverflow.com/comment/83651681
has comment: http://stackoverflow.com/comment/83651362
score: 0
type: Answer
has body: First of all, it seems like you are confused about the RESTful concept and your thought process and design seem to be more like the RPC API pattern. There's a great article about this by the author of REST where he explain the differences. Basically, with a REST API you should let the HTTP verbs define the action you want to do, while in RPC you have different URL's for each action that you want to make, e.g. Edit, Delete, Update etc. This seems to be the approach that you're doing. If you use Django Rest Framework, I suggest you don't do it like this and instead follow the RESTful pattern. Solution to your specific problem Your filtered view is a list view, not a detailed view. You filter a list of objects by query parameters and your response is a list of objects [{...}, {...}, {...}]. PUT requests that update the object should be done against a detailed view, not a list view. In your case, the list view would be http://localhost:8080/PriceMaster/ and the detailed view would be http://localhost:8080/PriceMaster/1 where the number in the end is the primary key of the object you want to view. The List View accept POST (create) and GET (read) while the Detailed View accept DELETE, PUT (update) and PATCH (partial update). The ModelViewSet will set up the routing for both the list view and the detailed view by default. There's nothing you have to do to make it work.

http://stackoverflow.com/a/48373910
has comment: http://stackoverflow.com/comment/83735628
answers question: http://stackoverflow.com/q/48373181
type: Answer
has comment: http://stackoverflow.com/comment/83735340
score: 2
upvote count: 2
has body: np.array takes a iterable like a list, but not an iterator or generator. In [26]: red_points = np.array(zip(x_red,y_red,z_red)) In [27]: red_points Out[27]: array(&lt;zip object at 0xab7d9b2c&gt;, dtype=object) The result is a 0d array containing one item, that zip object. In Py2, zip produced a list, in Py3 you have to list it. In [28]: red_points = np.array(list(zip(x_red,y_red,z_red))) In [29]: red_points Out[29]: array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) np.array(...) takes a list of lists like that displayed in Out[29]. That's one of the most common ways of using it. Using zip(...) like this is effectively a way of transposing the inputs. numpy can also do that transpose: In [31]: red_points = np.array((x_red,y_red,z_red)) In [32]: red_points Out[32]: array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) In [33]: red_points.T Out[33]: array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) np.stack also works. With the default axis=0 it acts just like np.array. In [34]: red_points = np.stack((x_red,y_red,z_red),axis=1) In [35]: red_points Out[35]: array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) While 0d arrays aren't common, it helps to understand them when they do occur. Get in the habit of checking the shape and dtype of arrays when you get errors or unexpected results. There is a fromiter that works with an iterator, but it requires a dtype - and only produces a 1d array. In [39]: np.fromiter(zip(x_red,y_red,z_red),'i,i,i') Out[39]: array([(1, 1, 1), (2, 2, 2), (3, 3, 3)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4'), ('f2', '&lt;i4')]) Part of why np.array expects a full list, is that it looks at the whole thing before deciding things like dtype and shape.
downvote count: 0

http://stackoverflow.com/a/64441830
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/136708079
type: Answer
answers question: http://stackoverflow.com/q/48435774
has body: Solution 1 I consider that an easier solution is: Close the launch.json on the editor group Open the python file such as main.py to be debugged [Run]-[Start Debugging] (F5) As Nick mentioned, when focusing on the launch.json in the editor, the debug system runs on the launch.json itself, not a python file. Solution 2 Modify the "program" in the launch.json as below: "program": "${workspaceFolder}/main.py", It corresponds to the program key to always point to main.py as Nick said. Note that the above modification may not work well if the main.py places in a deep directory.
downvote count: 0

http://stackoverflow.com/comment/83674351
has text: Try instead with `a1[:] = [2, 3, 4]`. That will give you `[2, 3, 4]`, because by the time execution reaches `for c in a1`, `a1` is `[2, 3, 4]`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48344129
type: QuestionComment

http://stackoverflow.com/comment/83806754
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48402035
type: Comment
has text: How this new column(c) can be converted to mutable?

http://stackoverflow.com/a/64116446
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48450352
has body: What about trying: df.printSchema() This will return something like: root |-- id: integer (nullable = true) |-- col1: string (nullable = true) |-- col2: string (nullable = true) |-- col3: integer (nullable = true) |-- col4: date (nullable = true) |-- col5: long (nullable = true)

http://stackoverflow.com/a/48482429
has body: Looks like you are running reports from the SF instance directly, this will always return HTML as it is not an API call. To access Reports through an API please refer to the documentation for Salesforce Reports and Dashboards REST API: https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/sforce_analytics_rest_api_intro.htm Below is a link to the resources specifically for reports: https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/sforce_analytics_rest_api_get_reportdata.htm When using Simple Salesforce you can easily call the API, like this: from simple_salesforce import Salesforce import requests import base64 import json sf = Salesforce(username=[username],password=[password],security_token=[token]) reportId = '00OR0000000K2UeMAK' reportRESTPath = ('analytics/reports/{id}'.format(id='00OR0000000K2UeMAK') # Synchronous report get reportJSON = sf.restful(reportRESTPath, {'includeDetails': 'true'}) # Asynchronous report create asyncJobJSON = sf.restful(reportRESTPath, {'includeDetails': 'true'}, 'POST') # Asynchronous report get reportJSON = sf.restful(('{basePath}/instances/{instanceId}'.format(basePath=reportRESTPath,instanceId=asyncJobJSON.Id), {'includeDetails': 'true'})
downvote count: 0
has comment: http://stackoverflow.com/comment/84004683
answers question: http://stackoverflow.com/q/48443107
has comment: http://stackoverflow.com/comment/84017856
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/83961990
comment on: http://stackoverflow.com/a/48484534
has text: I tried you way and it works but only if i manually enter:html_text = """ 11,511.31 USD "". However as this element is always updating, i need the prgram to featch this. do u know how to do this?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83914653
type: QuestionComment
has text: Thanks, i have just one more question: The byte-order is little-endian or big-endian?
comment on: http://stackoverflow.com/q/48458520
score: 0
type: Comment

http://stackoverflow.com/q/48477644
has answer: http://stackoverflow.com/a/48477766
tagged with: python
tagged with: method-resolution-order
tagged with: attributes
type: Question
tagged with: python-3.x
has body: During attribute resolution, does Python check for each attribute if it exists in the class? If so, doesn't it incur a large overhead? For example, checking the attribute a.x. Python must first check if A.__dict__["x"] is a data descriptor (as they override normal attribute lookups), meaning it should check the entire __mro__ for data descriptors. This in turn means that every attribute lookup in an instance dict, makes a lookup in the entire class mro which sounds like it's a HUGE overhead. Is this cached? And even if it is, what prevents the modification of one of the base classes, by dynamically adding a data descriptor? How will this theoretical cache get invalidated?
has title: Python attribute resolution overhead
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48477766
type: AnsweredQuestion

http://stackoverflow.com/comment/83761331
type: QuestionComment
comment on: http://stackoverflow.com/q/48385577
score: 0
type: Comment
has text: At this point I am only aiming to download the data in a way I can easily visualize with Pandas, so what I meant was just that I dont' want to overcomplicate things, mainly because I am not an advanced programmer either.

http://stackoverflow.com/comment/83832908
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48421733
has text: Still output is None
score: 0

http://stackoverflow.com/comment/83667478
score: 0
has text: What could be the possible path for php is it path to `php` file from root?. I have xxamp installed on my computer. (Sorry my question might be silly)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48341053

http://stackoverflow.com/q/48406906
has comment: http://stackoverflow.com/comment/83802885
tagged with: binaryfiles
has comment: http://stackoverflow.com/comment/83802728
score: 0
has comment: http://stackoverflow.com/comment/83802649
has body: I have a program that reads in binary data. The data represents numbers in the form of a character (value between 0 and 256). I am able to read in the file in Python. However, I would like to extract from the file one particular cells value. This is where I'm stuck. How do I do this? So I want for example the character on place 100 made readable in an integer or float. The code I currently have: def read_data(filename): if filename.endswith(".gz"): f = gzip.open(filename, "rb") else: f = open(filename, "rb") content = f.read() f.close() # HERE SHOULD BE A COMMAND THAT PRINTS OUT THE VALUE OF AN ELEMENT IN THE FILE return content Any help would be appreciated. It seems like a basic question, but I couldn't find an answer anywhere on the site. A link to a working solution is therefore also fine.
has comment: http://stackoverflow.com/comment/83803021
downvote count: 1
has comment: http://stackoverflow.com/comment/83803479
has comment: http://stackoverflow.com/comment/83803335
favorite count: 0
has comment: http://stackoverflow.com/comment/83803071
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/83803281
answer count: 0
has comment: http://stackoverflow.com/comment/83802757
type: UnansweredQuestion
has title: How to convert binary input to characters?
has comment: http://stackoverflow.com/comment/83802951
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83802964
tagged with: type-conversion

http://stackoverflow.com/a/48459583
type: Answer
has comment: http://stackoverflow.com/comment/83912425
has comment: http://stackoverflow.com/comment/83913204
score: 0
answers question: http://stackoverflow.com/q/48459357
has body: Let me assume that you are not in Western Europe or USA and the default encoding is not UTF-8 or something usually very compatible like iso-8859-1. From the comments above data = json.load(open(jsonDirectory + filename)) If you separate that statement in: f = open(jsonDirectory + filename) fdata = f.read() data = json.loads(fdata) You will see that the error happens in fdata = f.read(). The suggestion is to do: f = open(jsonDirectory + filename, encoding='my-encoding') fdata = f.read() data = json.loads(fdata) If you are unsure, try to force open to ignore/bypass the errors. From the Python docs at: https://docs.python.org/3/library/functions.html#open errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include: 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect. 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss. 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding. 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &amp;#nnn;. 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences. 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences. …

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

http://stackoverflow.com/comment/83767598
type: Comment
type: AnswerComment
score: 0
has text: I did not think of that. Thank you very much. It did the job.
comment on: http://stackoverflow.com/a/48389850

http://stackoverflow.com/a/48471310
answers question: http://stackoverflow.com/q/48466784
score: 0
has comment: http://stackoverflow.com/comment/84009675
has comment: http://stackoverflow.com/comment/84004319
has comment: http://stackoverflow.com/comment/84003397
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84010451
accepted answer of: http://stackoverflow.com/q/48466784
has comment: http://stackoverflow.com/comment/84050066
has comment: http://stackoverflow.com/comment/84050912
has comment: http://stackoverflow.com/comment/84051424
has comment: http://stackoverflow.com/comment/84009903
has comment: http://stackoverflow.com/comment/84052259
has comment: http://stackoverflow.com/comment/84051737
has comment: http://stackoverflow.com/comment/84009384
type: Answer
has comment: http://stackoverflow.com/comment/83982572
has body: You can get the tables elements from the pane class div. The 4th table is the main product &amp; the 5th (when existing) is the additionnal products. In the following example, I use list comprehension to output list of tuples with title, description, product n°, category n° &amp; price : from bs4 import BeautifulSoup import requests product_urls = [ 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-precursor-assays/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assay-plate/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assays/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/real-time-pcr-enzymes-and-kits/miscript-target-protectors/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/real-time-pcr-enzymes-and-kits/two-step-qrt-pcr/miscript-sybr-green-pcr-kit/#orderinginformation' ] session = requests.Session() for URL in product_urls: response = session.get(URL) soup = BeautifulSoup(response.content, "html.parser") tables = soup.find_all("div", {"class":"pane"})[0].find_all("table") if (len(tables) &gt; 4): product_list = [ ( t[0].findAll("div", {"class":"headline"})[0].text.strip(), #title t[0].findAll("div", {"class":"copy"})[0].text.strip(), #description t[1].text.strip(), #product number t[2].text.strip(), #category number t[3].text.strip() #price ) for t in (t.find_all('td') for t in tables[4].find_all('tr')) if t ] elif (len(tables) == 1): product_list = [ ( t[0].findAll("div", {"class":"catNo"})[0].text.strip(), #catNo t[0].findAll("div", {"class":"headline"})[0].text.strip(), #headline t[0].findAll("div", {"class":"price"})[0].text.strip(), #price t[0].findAll("div", {"class":"copy"})[0].text.strip() #description ) for t in (t.find_all('td') for t in tables[0].find_all('tr')) if t ] else: print("could not parse main product") print(product_list) if len(tables) &gt; 5: add_product_list = [ ( t[0].findAll("div", {"class":"title"})[0].text.strip(), #title t[0].…
has comment: http://stackoverflow.com/comment/84343773
has comment: http://stackoverflow.com/comment/84006614
has comment: http://stackoverflow.com/comment/83983438

http://stackoverflow.com/a/48344675
answers question: http://stackoverflow.com/q/48344302
has comment: http://stackoverflow.com/comment/83691108
has comment: http://stackoverflow.com/comment/84128147
accepted answer of: http://stackoverflow.com/q/48344302
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84037533
has comment: http://stackoverflow.com/comment/84143899
has comment: http://stackoverflow.com/comment/83680857
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84056082
has body: This answer has been updated for SQLAlchemy 2.0 to reflect the 2.0 style while maintaining the original intent of this prior revision which was written in the 1.x style. If you want specific columns (prior to the edit that included the intended statement, it wasn't clear what you meant by a tuple of (User, Address), as that implies the entire class which is what is being returned already), simply pass the desired attributes to select as documented in the ORM querying guide. For your intended part, you need to make use of the subquery's email address attribute as the query parameter instead of the main Address class, and with manual joins as specified again in the tutorial under the joining to subqueries section. The address_subq in your question can be used as is, but if you want to replace your inner query to be more like the intended subquery, try: subq = (select(Address.email_address, Address.user_id) .where(Address.email_address.like('%@foo.com')) .subquery() ) address_subq = aliased(Address, subq, name="address") The final query that satisfies your requirement will be: q = (select(User.name, address_subq.email_address) .outerjoin(address_subq, User.id==address_subq.user_id) ) Printing and executing the query (the print output has been modified for readability) >>> print(q) SELECT users.name, anon_1.email_address FROM users LEFT OUTER JOIN ( SELECT address.email_address AS email_address, address.user_id AS user_id FROM address WHERE address.email_address LIKE :email_address_1 ) AS anon_1 ON users.id = anon_1.user_id >>> with Session(engine) as session: ... print(session.execute(q).all()) [('ed', 'ed@foo.com'), ('wendy', None), ('mary', None), ('fred', None), ('jack', None)]

http://stackoverflow.com/a/58049211
has body: Basically, there are two issues. First, in both Python and JS code secret_bytes should be base64 encoded string. Second, in JavaScript code secret_bytes was not correctly decoded from base64 string. Please find below corrected Python and JavaScript examples. Python: import hmac import time import uuid import base64 import hashlib import urllib.parse def sign_api_request(api_secret, api_key, method, url): encoded_url = urllib.parse.quote(url.lower(), '').lower() # timestamp = int(time.time()) # nonce = str(uuid.uuid4()) timestamp = str(1569158586); nonce = '708b7df1-7494-49fa-812c-e5f6c24aeab6' signature = api_key + method + encoded_url + timestamp + nonce # print(signature) secret_bytes = base64.standard_b64decode(api_secret) # print(secret_bytes) signature_bytes = signature.encode('UTF8') signature_hash = hmac.new(secret_bytes, signature_bytes, hashlib.sha256).digest() base64_signature_hash = base64.b64encode(signature_hash).decode() return base64_signature_hash base64_signature_hash = sign_api_request('MTIzNDU2NzgxMjM0NTY3ODEyMzQ1Njc4MTIzNDU2Nzg=', '0987654321', 'POST', '/signin') print(base64_signature_hash) JavaScript: const CryptoJS = require('crypto-js'); function epochTime() { var d = new Date(); var t = d.getTime(); var o = t + ""; return o.substring(0, 10); } function newGuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : r &amp; 0x3 | 0x8; return v.toString(16); }); } let api_secret = 'MTIzNDU2NzgxMjM0NTY3ODEyMzQ1Njc4MTIzNDU2Nzg='; let api_key = '0987654321'; let method = 'POST'; let url_path = '/signin'; let encoded_url = encodeURIComponent(url_path.toLowerCase()).toLowerCase(); let timestamp = '1569158586'; let nonce = '708b7df1-7494-49fa-812c-e5f6c24aeab6'; let signature = api_key + method + encoded_url + timestamp + nonce; // console.log(signature); let secret_bytes = new Buffer.from(api_secret, 'base64'); secret_bytes = secret_bytes.toString('ascii'); // console.log(…
answers question: http://stackoverflow.com/q/48430211
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48347569
tagged with: python
has answer: http://stackoverflow.com/a/48370274
answer count: 3
has title: Kivy - Limit Values on InputText
upvote count: 5
tagged with: kivy
favorite count: 0
type: Question
tagged with: kivy-language
has answer: http://stackoverflow.com/a/79205018
score: 5
has body: I'm trying to make an input text that only accept float values. In addition, the value entered must be between two values. I created a class that contain a 'validate' method. If the value is not between two values, a Popup is showed. But I have a problem. The method is only called when the user hit 'Enter'. I tried call the method when the text is changed, but it is annoying for the user, because the Popup appears all the time while the user is entering the data. There is another approach to do something like this? Python file: class BoundedInput(BoxLayout): value = NumericProperty() def validate(self, min_value, max_value): status = min_value &lt;= self.value &lt;= max_value if not status: message = f'Value must be between {min_value} and {max_value}' popup = Popup(title='Warning', content=Label(text=message), size_hint=(None, None), size=(300, 200)) popup.open() Kv file: &lt;NumericInput@TextInput&gt;: input_filter: 'float' multiline: False &lt;BoundedInput&gt;: orientation: 'horizontal' Label: text: 'Value' NumericInput: text: str(root.value) on_text_validate: root.value = float(self.text) root.validate(5, 100)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48370416
downvote count: 0

http://stackoverflow.com/a/48385353
score: 2
has body: It sounds like you want the zip() function: accounts = input('Accounts : ').split() passwords = input('Passwords : ').split() for account, password in zip(accounts, passwords): #do stuff with account and password
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48385275
answers question: http://stackoverflow.com/q/48385275

http://stackoverflow.com/q/48475440
tagged with: python
downvote count: 5
tagged with: regex
has answer: http://stackoverflow.com/a/48475476
has title: Replacing a string using regex in python
type: AnsweredQuestion
score: -5
has answer: http://stackoverflow.com/a/48475542
has comment: http://stackoverflow.com/comment/83944157
has body: I am working on a python code piece. The problem is I have a list of words that have to be replaced if they occur in the input string. Below are few samples of the words to be replaced: block1 with block 1 block2 with block 2 block3 with block 3 sector1 with sector 1 sector2 with sector 2 phase1 with phase 1 pocket1 with pocket 1 and so on, this goes on for a lot of numbers. I was wondering if I there is a regex that could detect these replace it. This ways I won't need to maintain a dictionary of a lot words Is it possible to do so in python?
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48475542
upvote count: 0
possible better answer: http://stackoverflow.com/a/48475476

http://stackoverflow.com/q/48383288
has comment: http://stackoverflow.com/comment/83754898
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83753416
has answer: http://stackoverflow.com/a/48385993
has title: How to Open csv file with pandas data frame
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83765529
tagged with: python
has comment: http://stackoverflow.com/comment/83753893
has answer: http://stackoverflow.com/a/48384701
has comment: http://stackoverflow.com/comment/83753575
score: 3
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/55687157
tagged with: http://stackoverflow.com/tag/csv
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83753715
has body: There is a CSV format file with three column dataframe. The third column has long text. This error message occurred, when i tried to open the file using pandas.read_csv message : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 0: invalid start byte. But there is no problem opening the file with with open('file.csv', 'r', encoding='utf-8', errors = "ignore") as csvfile: I don't know how converting this data to dataframe and i don't think pandas.read_csv handle this error properly. So, how can i open this file and get dataframe?
favorite count: 0
type: Question

http://stackoverflow.com/a/48432251
answers question: http://stackoverflow.com/q/48419346
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Col2 looks like a single JSON formatted list. Not sure if this is what you need, but the following will re-write the shown input.csv as the output.csv. The code assumes the input.csv is encoding in UTF-8. input.csv Col1|Col2 rénovation thermique|["consommation \u00e9nerg\u00e9tique de b\u00e2timents publics"] rewrite.py import csv import json with open('input.csv','r',newline='',encoding='utf8') as inf, \ open('output.csv','w',newline='',encoding='utf8') as outf: r = csv.reader(inf,delimiter='|') w = csv.writer(outf,delimiter='|') header = next(r) w.writerow(header) for col1,col2 in r: newcol = json.loads(col2) # Converts JSON to a list w.writerow([col1,newcol[0]]) # Replaces col2 with the list element. output.csv Col1|Col2 rénovation thermique|consommation énergétique de bâtiments publics
accepted answer of: http://stackoverflow.com/q/48419346
upvote count: 1

http://stackoverflow.com/a/48465324
type: AcceptedAnswer
has body: There is also a mathematical solution (which is probably what you used): def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result def paths(w, h): return factorial(w + h) / (factorial(w) * factorial(h)) This works because the number of paths is the same as the number of ways to choose to go right or down over w + h steps, where you go right w times, which is equal to w + h choose w, or (w + h)! / (w! * h!). With missing grid squares, I think there is a combinatoric solution, but it's very slow if there are many missing squares, so dynamic programming would probably be better there. For example, the following should work: missing = [ [0, 1], [0, 0], [0, 0], ] def paths_helper(x, y, path_grid, missing): if path_grid[x][y] is not None: return path_grid[x][y] if missing[x][y]: path_grid[x][y] = 0 return 0 elif x &lt; 0 or y &lt; 0: return 0 else: path_count = (paths_helper(x - 1, y, path_grid, missing) + paths_helper(x, y - 1, path_grid, missing)) path_grid[x][y] = path_count return path_count def paths(missing): arr = [[None] * w for _ in range(h)] w = len(missing[0]) h = len(missing) return paths_helper(w, h, arr, missing) print paths()
has comment: http://stackoverflow.com/comment/83924819
answers question: http://stackoverflow.com/q/48464979
type: Answer
accepted answer of: http://stackoverflow.com/q/48464979
has comment: http://stackoverflow.com/comment/83924559
score: 0

http://stackoverflow.com/a/48476954
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48476827
answers question: http://stackoverflow.com/q/48476827
score: 3
upvote count: 3
type: Answer
has body: import pandas as pd import numpy as np df = pd.read_csv('train.csv') df['Age'].fillna(df.groupby(["Sex"])["Age"].transform(np.mean), inplace=True) Maybe this was something you were trying to do? I didn't get any warning though. Have a look at my blog post too if necessary.
has comment: http://stackoverflow.com/comment/83948109

http://stackoverflow.com/a/77486952
answers question: http://stackoverflow.com/q/48370668
score: 1
downvote count: 1
upvote count: 2
type: Answer
has body: Try this: from wtforms.form import Form

http://stackoverflow.com/q/48482787
downvote count: 0
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/67112290
has answer: http://stackoverflow.com/a/52392869
tagged with: multidimensional-array
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48483811
has answer: http://stackoverflow.com/a/54260202
favorite count: 0
has answer: http://stackoverflow.com/a/72680694
has title: PyTorch memory model: "torch.from_numpy()" vs "torch.Tensor()"
tagged with: numpy
type: Question
has comment: http://stackoverflow.com/comment/83959437
tagged with: pytorch
upvote count: 69
score: 69
has body: I'm trying to have an in-depth understanding of how PyTorch Tensor memory model works. # input numpy array In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2) # input tensors in two different ways In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr) # their types In [93]: type(arr), type(t1), type(t2) Out[93]: (numpy.ndarray, torch.FloatTensor, torch.FloatTensor) # ndarray In [94]: arr Out[94]: array([[ 0., 1.], [ 2., 3.], [ 4., 5.], [ 6., 7.], [ 8., 9.]], dtype=float32) I know that PyTorch tensors share the memory buffer of NumPy ndarrays. Thus, changing one will be reflected in the other. So, here I'm slicing and updating some values in the Tensor t2 In [98]: t2[:, 1] = 23.0 And as expected, it's updated in t2 and arr since they share the same memory buffer. In [99]: t2 Out[99]: 0 23 2 23 4 23 6 23 8 23 [torch.FloatTensor of size 5x2] In [101]: arr Out[101]: array([[ 0., 23.], [ 2., 23.], [ 4., 23.], [ 6., 23.], [ 8., 23.]], dtype=float32) But, t1 is also updated. Remember that t1 was constructed using torch.Tensor() whereas t2 was constructed using torch.from_numpy() In [100]: t1 Out[100]: 0 23 2 23 4 23 6 23 8 23 [torch.FloatTensor of size 5x2] So, no matter whether we use torch.from_numpy() or torch.Tensor() to construct a tensor from an ndarray, all such tensors and ndarrays share the same memory buffer. Based on this understanding, my question is why does a dedicated function torch.from_numpy() exists when simply torch.Tensor() can do the job? I looked at the PyTorch documentation but it doesn't mention anything about this? Any ideas/suggestions?

http://stackoverflow.com/q/48390601
has answer: http://stackoverflow.com/a/48398977
downvote count: 1
score: 19
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48406666
upvote count: 20
has comment: http://stackoverflow.com/comment/119776277
has title: Explicitly specifying test/train sets in GridSearchCV
has body: I have a question about the cv parameter of sklearn's GridSearchCV. I'm working with data that has a time component to it, so I don't think random shuffling within KFold cross-validation seems sensible. Instead, I want to explicitly specify cutoffs for training, validation, and test data within a GridSearchCV. Can I do this? To better illuminate the question, here's how I would to that manually. import numpy as np import pandas as pd from sklearn.linear_model import Ridge np.random.seed(444) index = pd.date_range('2014', periods=60, freq='M') X, y = make_regression(n_samples=60, n_features=3, random_state=444, noise=90.) X = pd.DataFrame(X, index=index, columns=list('abc')) y = pd.Series(y, index=index, name='y') # Train on the first 30 samples, validate on the next 10, test on # the final 10. X_train, X_val, X_test = np.array_split(X, [35, 50]) y_train, y_val, y_test = np.array_split(y, [35, 50]) param_grid = {'alpha': np.linspace(0, 1, 11)} model = None best_param_ = None best_score_ = -np.inf # Manual implementation for alpha in param_grid['alpha']: ridge = Ridge(random_state=444, alpha=alpha).fit(X_train, y_train) score = ridge.score(X_val, y_val) if score &gt; best_score_: best_score_ = score best_param_ = alpha model = ridge print('Optimal alpha parameter: {:0.2f}'.format(best_param_)) print('Best score (on validation data): {:0.2f}'.format(best_score_)) print('Test set score: {:.2f}'.format(model.score(X_test, y_test))) # Optimal alpha parameter: 1.00 # Best score (on validation data): 0.64 # Test set score: 0.22 The process here is: For both X and Y, I want a training set, validation set, and testing set. The training set is the first 35 samples in the time series. The validation set is the next 15 samples. The test set is the final 10. The train and validation sets are use to determine the optimal alpha parameter within Ridge regression. Here I test alphas of (0.0, 0.1, ..., 0.9, 1.0). The test set is held out for the "actual" testing as unseen data. Anyway…
has answer: http://stackoverflow.com/a/48406666
linked to: http://stackoverflow.com/q/44007496
tagged with: grid-search
tagged with: python
linked to: http://stackoverflow.com/q/46732748
linked to: http://stackoverflow.com/q/31948879
has answer: http://stackoverflow.com/a/53944052
type: AnsweredQuestion
answer count: 3
linked to: http://stackoverflow.com/q/42228735
accepted answer: http://stackoverflow.com/a/48398977
tagged with: scikit-learn

http://stackoverflow.com/comment/83865944
type: Comment
comment on: http://stackoverflow.com/q/48418648
has text: Same here. Code seems correct, did you check that all dependencies are in the manifest file? hr_payroll module is the one who add hr.payslip so in your project it has to be as dependency.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48432926
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48430069
answers question: http://stackoverflow.com/q/48430069
has body: This is a misconception. Sometimes you see what you want to see, not what is actually there. The data plot is indeed different and the scale is correct. For sure there is no major difference since the data range is much less than a decade (unlike in the lower plot where it is two decades), but you might observe that in the lower part of the first plot the data is a bit more bumpy and the curvature is different. If not, here is an overlay of both images from which you can see the difference.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/83906790
has text: Any simpler than that - I don't think so. But correct version would be: `if lastMonthAllowed.year > lastUserUploadMonth.year or (lastMonthAllowed.year == lastUserUploadMonth.year and lastMonthAllowed.month > lastUserUploadMonth.month):` (months only matter if years are equal).
comment on: http://stackoverflow.com/q/48457027
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/comment/84177016
has text: I don't know why Jeff closed that issue so quickly, maybe he didn't understand the issue? You can still comment in the issue (I think) and it could be re-opened. Perhaps if a few people commented there it would increase the odds of the issue being re-opened? I agree with Dark's suggestion that an optional argument would be nice there.
comment on: http://stackoverflow.com/q/48471648
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83948448
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48477666
has text: Why not just use `requests`? Sorry sort of off topic though.

python-jira
tags question: http://stackoverflow.com/q/48348863
tag name: python-jira
tags question: http://stackoverflow.com/q/48388459
type: Tag

http://stackoverflow.com/q/48485629
upvote count: 1
tagged with: python
has title: What does the 'graft' command do in a MANIFEST.in file?
tagged with: flask
tagged with: manifest
duplicate of: http://stackoverflow.com/q/41661616
score: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: setup.py
has body: I am currently following the tutorial shown on the Flask documentation website here. In step 3, a MANIFEST.in file is created to specify additional files to include in my application's package. It says to include the following in the file: graft flaskr/templates graft flaskr/static include flaskr/schema.sql I am having trouble finding out how the MANIFEST.in file works and what its commands do. Is graft used for folders and include for individual files? Any references to documentation websites would be much appreciated.
linked to: http://stackoverflow.com/q/41661616
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48486137

cython
tags question: http://stackoverflow.com/q/48374049
tags question: http://stackoverflow.com/q/48373192
tags question: http://stackoverflow.com/q/48362432
tags question: http://stackoverflow.com/q/48371251
tags question: http://stackoverflow.com/q/48363425
tags question: http://stackoverflow.com/q/48384054
tags question: http://stackoverflow.com/q/48373403
tags question: http://stackoverflow.com/q/48486764
tags question: http://stackoverflow.com/q/48400682
tags question: http://stackoverflow.com/q/48425658
tags question: http://stackoverflow.com/q/48389750
tags question: http://stackoverflow.com/q/48447427
type: Tag
tag name: cython

http://stackoverflow.com/q/48482466
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48482632
has title: Python Socket Received ASCII convert to actual numbers (float)
accepted answer: http://stackoverflow.com/a/48482632
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83958004
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has body: While using a Python socket connection and I received the following from the server (simulator): 'C\xbc\x7fZC\xbc\x7f5C\xbc\x7f&amp;C\xbc\x7f!C\xbc\x7f\x14C\xbc\x7f\x16C\xbc\x7f!C\xbc\x7f\x12C\xbc\x7f\x19C\xbc\x80\x03C\xbc\x81~C\xbc\x80FC\xbc\x7f\xd1C\xbc~\xcdC\xbc~\xd7C\xbc\x7f$;4\xe0\xb8;\x81\xf6\xd7;R\xf4T:\xc5v\xb4:\xc1&gt;\xc1:\xd9\x15\x9a:\xa8M7;K\xde{:\xfb\\\xcd\xbc\tR\xd4\xba\xe1\xb6\xf3\xbb\xc9\xb8\xf4\xbby\x8a\x199\x9dH\x009\x0cp\x00:\xeb&lt;\x00' But my actual output should be (size 32x1): 376.99493 376.99380 376.99335 376.99319 376.99280 376.99286 376.99319 376.99274 376.99295 377.00009 377.01166 377.00214 376.99857 376.99063 376.99094 376.99329 0.0027599763 0.0039661932 0.0032189088 0.0015065284 0.0014743434 0.0016562224 0.0012840395 0.0031107950 0.0019177437 -0.0083815642 -0.0017220661 -0.0061560813 -0.0038076697 0.00029999018 0.00013393164 0.0017946959 How can I convert the ASCII codes to get those numbers in Python 2.7.

http://stackoverflow.com/comment/83747036
has text: Hi unfortunately it doesn't work: it gives me the same error as before: "name 'F' is not defined"
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48375903

http://stackoverflow.com/q/48383829
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: pytest
tagged with: python
has body: I have a "conceptual" question regarding pytest and how I should handle multiple tests. Let's say I need to test something for a bunch of strings: names = [" ", "a ", " a", " a "]. I could create multiple test_ functions to test them individually, but they would be exactly the same, but with different input. I was thinking on doing something like: def test_names(): names = [" ", "a ", " a", " a "] for name in names: with pytest.raises(errors.MyFooError) as ex: random_method(name) The problem is: doing this, in case one element doesn't raise errors.MyFooError, I would receive this: Failed: DID NOT RAISE &lt;class 'errors.MyFooError' The message is generic, I have no idea in which element this occurred. I would probably just split into 4 tests, one for each element of the list, I guess this is the correct way to do it? What happens if the list is huge?
has answer: http://stackoverflow.com/a/48384685
upvote count: 11
has title: Multiple tests in one pytest function
accepted answer: http://stackoverflow.com/a/48384685
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 11

http://stackoverflow.com/a/48431095
type: AcceptedAnswer
has body: the return in line 18 what does it mean? It's returning the function object g itself. shouldn't it be return g() for example? Not necessarily. It's perfectly acceptable to pass around functions as they're just objects like anything else in Python. Both return g and return g() are valid, and mean different things. what does g means here is it a variable? g is the name bound to a function object, which when called prints x=abc and then returns None. Yes, g is a variable (it's a local variable). the output is z=function g at 0x15b43b0 , what does this mean? It means the name z is bound to a function named g at memory location 0x15b43b0. (Hint: It's actually the same function object that was bound to the name g in the inner scope) one last thing , what does z() in the last line measn? It means call the object that the name z is bound to. i.e. it calls the function that was returned by f. there is no function called z There is no function with the __name__ attribute equal to z here. But the name z can still be bound to a function object. Remember that objects can have more than one name (or no names at all).
answers question: http://stackoverflow.com/q/48430955
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48430955
type: Answer
downvote count: 0

http://stackoverflow.com/a/48456280
has body: You might not have installed setuptools correctly, or it may not be upgraded. Try this first pip install --upgrade setuptools And then, try with pip, or sometimes pip2/3 also might work. pip install matplotlib pip2 install matplotlib On another note, you should really try to search your error before you post a question, since this has happened before, Python pip install gives "Command "python setup.py egg_info" failed with error code 1"
has comment: http://stackoverflow.com/comment/83905753
accepted answer of: http://stackoverflow.com/q/48456125
type: Answer
has comment: http://stackoverflow.com/comment/83905404
has comment: http://stackoverflow.com/comment/83987698
has comment: http://stackoverflow.com/comment/83905671
score: 12
has comment: http://stackoverflow.com/comment/83981841
answers question: http://stackoverflow.com/q/48456125
upvote count: 14
downvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83987539
has comment: http://stackoverflow.com/comment/83949273
has comment: http://stackoverflow.com/comment/83905450

http://stackoverflow.com/a/48510453
score: -1
upvote count: 0
downvote count: 1
has body: You have to zip the contents of the src folder, not the src folder itself. Your python module (lambda_function.py) should be at the first level in you zip. See documentation: Zip the directory content, not the directory. The contents of the Zip file are available as the current working directory of the Lambda function.
type: Answer
answers question: http://stackoverflow.com/q/48470644

http://stackoverflow.com/q/48401356
accepted answer: http://stackoverflow.com/a/62439638
has answer: http://stackoverflow.com/a/62439638
type: AnsweredQuestion
tagged with: time-and-attendance
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I'm using Python 2.7, and I use PyZk to communicate with ZKTime (Time Attendence software) on Linux OS, And I can't set user with 'Card Number'. Below the method that allows to add a user in the device, how can I add the card number for user? set_user(uid=1, name='Fanani M. Ihsan', privilege=const.USER_ADMIN, password='12345678', group_id='', user_id='123') Thanks.
has title: Add user with card numer to ZKTime Device
tagged with: python

http://stackoverflow.com/q/48486807
has answer: http://stackoverflow.com/a/48509577
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: android
has body: My Kivy app crashes on Android immediately. I guess this is some Python2/Python3 incompatibility, but I've got no idea what is the actual reason for this error (adb logcat output): 01-28 14:00:39.421 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/app/main.py", line 5, in <module> 01-28 14:00:39.421 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/platform/build/dists/pfadfinder/private/lib/python2.7/site-packages/kivy/app.py", line 802, in run**strong text** 01-28 14:00:39.421 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/app/pfadfinder/hauptmenue.py", line 152, in build 01-28 14:00:39.422 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/platform/build/dists/pfadfinder/private/lib/python2.7/site-packages/kivy/lang/builder.py", line 382, in load_string 01-28 14:00:39.422 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/platform/build/dists/pfadfinder/private/lib/python2.7/site-packages/kivy/lang/builder.py", line 496, in _apply_rule 01-28 14:00:39.422 7457 7492 I python : File "/home/kivy/Pfadfinder/.buildozer/android/platform/build/dists/pfadfinder/private/lib/python2.7/site-packages/kivy/lang/parser.py", line 281, in create_missing 01-28 14:00:39.423 7457 7492 I python : TypeError: Argument 'name' has incorrect type (expected str, got unicode) The app was developed with Python 3.6 on Windows. On Android, it is running in Python 2.7.2 (Kivy v1.10.0). Note: I'm German, so the app should work with umlauts ä ö ü. I am loading the KV file like this: def build(self): with io.open(os.path.join(THIS_DIR, "hauptmenue.kv"), encoding='utf-8') as f: screen_management = Builder.load_string(f.read()) The last line is line 152 mentioned in the stack trace. The KV file looks like this: :kivy 1.1.0 ScreenManagement: hauptmenue: hauptmenue MainMenu: id: hauptmenue <LevelButton>: font_size: "40dp" <MainMenu>: name: "hauptmenue" level_auswahl: level_auswahl BoxLayout: orientation: "vert…
tagged with: python
tagged with: kivy
has title: Kivy on android: Exception in parser.py create_missing: TypeError: Argument 'name' has incorrect type (expected str, got unicode)
tagged with: kivy-language
score: 0

http://stackoverflow.com/comment/83690220
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48351742
has text: You're missing parents around the class to `Image.open`. And why not make a function that does this and then use it in a loop?
score: 1

http://stackoverflow.com/q/48464805
tagged with: django-models
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83922963
has answer: http://stackoverflow.com/a/48464925
type: Question
has title: Importing Django Custom User Model From Another App Model
has body: So I have an app called profiles and it has model named Profile from poros.abstracts.models import Model from django.db import models from poros.users.models import User class Profile(Model): user = models.OneToOneField( to=User, on_delete=models.CASCADE, related_name='profile', ) the Profile model has a field name user which has OneToOneField relationship with my Django custom user User. The problem now is it returns me an error: ImportError: cannot import name 'User' How can I solve this issue?
accepted answer: http://stackoverflow.com/a/48464925
tagged with: django

http://stackoverflow.com/a/48463730
has comment: http://stackoverflow.com/comment/83923151
has comment: http://stackoverflow.com/comment/83922582
upvote count: 3
has comment: http://stackoverflow.com/comment/83922681
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48462927
downvote count: 0
has comment: http://stackoverflow.com/comment/83922862
has comment: http://stackoverflow.com/comment/83923094
accepted answer of: http://stackoverflow.com/q/48462927
score: 3
has body: I would suggest a solution where you do not kill the parent process, but use the exit code instead. shell script: #!/bin/sh while python3 my_py_script.py; do :; done python script: if ..something..: sys.exit('python script ends with errorcode 1') The default exit code of a python script is 0. So when it exits at the end, then the shell-loop will run again. when it exits with sys.exit('python script ends with errorcode 1'), than the shell-loop will stop. https://docs.python.org/3/library/sys.html#sys.exit: [...] If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs. In case there are other error, that should not cause the shell script to exit from the loop, a precise error code can be used with sys.exit(123) and python3 my_py_script.py; lastexitcode=$?.
has comment: http://stackoverflow.com/comment/83922481
type: Answer
has comment: http://stackoverflow.com/comment/83922961

http://stackoverflow.com/comment/132312678
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).
score: 1
type: Comment
comment on: http://stackoverflow.com/a/74977097
type: AnswerComment

http://stackoverflow.com/a/48474521
score: 3
upvote count: 3
downvote count: 0
has body: You can create DataFrame by filtering with Counter and then convert to lists: from collections import Counter df = pd.DataFrame({'text':[["hello", "world"], ["hello", "stackoverflow", "hello"]]}) L = ["hello", "world", "stackoverflow"] f = lambda x: Counter([y for y in x if y in L]) df['new'] = (pd.DataFrame(df['text'].apply(f).values.tolist()) .fillna(0) .astype(int) .reindex(columns=L) .values .tolist()) print (df) text new 0 [hello, world] [1, 1, 0] 1 [hello, stackoverflow, hello] [2, 0, 1]
type: Answer
answers question: http://stackoverflow.com/q/48474442

http://stackoverflow.com/q/48466959
has comment: http://stackoverflow.com/comment/83928517
tagged with: sqlalchemy
favorite count: 0
linked to: http://stackoverflow.com/q/9486180
type: Question
has answer: http://stackoverflow.com/a/50946620
accepted answer: http://stackoverflow.com/a/48467116
has comment: http://stackoverflow.com/comment/99819511
tagged with: python
has answer: http://stackoverflow.com/a/48467116
has answer: http://stackoverflow.com/a/74452716
has answer: http://stackoverflow.com/a/57832233
has body: I'm querying for the ids of a model, and get a list of (int,) tuples back instead of a list of ids. Is there a way to query for the attribute directly? result = session.query(MyModel.id).all() I realize it's possible to do results = [r for (r,) in results] Is it possible for the query to return that form directly, instead of having to process it myself?
possible better answer: http://stackoverflow.com/a/50946620
has title: Query for list of attribute instead of tuples in SQLAlchemy
answer count: 4
type: AnsweredQuestion
upvote count: 59
score: 59
downvote count: 0

http://stackoverflow.com/comment/83804243
has text: It looks like you just need to assign to `t1` and `t2` the result of the `cond` in `body`? But I'd also note that only ops _created_ inside a `lambda` passed to `cond` have conditional execution. Capturing them in a closure means they always get executed. In this case none of the ops are stateful, so it won't affect the result.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48374339

http://stackoverflow.com/comment/83947630
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48477229
has text: Only a new line? Or all escaped characters?

http://stackoverflow.com/q/48410832
type: UnansweredQuestion
tagged with: string
has answer: http://stackoverflow.com/a/48411569
has comment: http://stackoverflow.com/comment/83811729
has comment: http://stackoverflow.com/comment/83812328
has comment: http://stackoverflow.com/comment/83812552
has comment: http://stackoverflow.com/comment/83811447
has title: Cascading FOR loop outputs is there a better python 3 way
tagged with: cascade
has comment: http://stackoverflow.com/comment/83812774
has comment: http://stackoverflow.com/comment/83812947
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/83813857
tagged with: python
has comment: http://stackoverflow.com/comment/83812595
has answer: http://stackoverflow.com/a/48411229
has comment: http://stackoverflow.com/comment/83812994
tagged with: for-loop
type: Question
has body: Right now, I have a word that I'm search for in a larger string if the word is not found then I insert the word in the larger sting. The output of the first FOR loop is cascaded into a second FOR loop. This work's ok, with one or two but if I had 100's or 1000's of searchs it would be a pain to do this each time is there a better python 3 way? As you can see from the example I'm looking for Monday in the first string monday is there so it just skips the second string does not have Monday so it adds monday in. I would have a new list at that point. So I put the output of the first loop into the input of the second loop to update the input. Example: Input: - addstring_sign = ["Monday was a snowing day", "Wednesday no snow"] string_test1 = [] string_test2 = [] dictlines1 = ("Monday") for loopblock in (addstring_sign): if addstring_sign.count(dictlines1) &lt; 1: string_test1.append(loopblock[:len(loopblock)] + dictlines1 +'\n'+loopblock[len(loopblock):]) else: string_test2.append(loopblock) addstring_sign1 = string_test1 + string_test2 OutPut of addstring_sign1 = ["Monday was a snowing day", "Wednesday no snow Monday"] string_test3 = [] string_test4 = [] dictlines2 = ("Tuesday") for loopblock2 in (addstring_sign1): if addstring_sign.count(dictlines2) &lt; 1: string_test3.append(loopblock2[:len(loopblock2)] + dictlines2 +'\n'+loopblock2[len(loopblock2):]) else: string_test4.append(loopblock) addstring_sign2 = string_test3 + string_test4` output of addstring_sign2 = ["Monday was a snowing day Tuesday", "Wednesday no snow Monday Tuesday"] I am lost on how to make this more efficient.
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83817131

http://stackoverflow.com/q/48482373
has answer: http://stackoverflow.com/a/48482598
linked to: http://stackoverflow.com/q/18172257
accepted answer: http://stackoverflow.com/a/48482399
favorite count: 0
has answer: http://stackoverflow.com/a/48482399
type: AnsweredQuestion
tagged with: python
has body: Hey I am trying to get a Fibonacci sequence to output with a single variable in the mix. normally if I was using 2 variables I would have it set up like this: nmbr1 = nmbr2 = 1 while nmbr1 &lt; 100: nmbr1, nmbr2 = nmbr1 + nmbr2, nmbr1 print (nmbr1) but how would I get it complete the sequence with only one variable in python?
score: 4
has title: can you output a Fibonacci sequence with one variable?
has answer: http://stackoverflow.com/a/48482395
answer count: 4
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48484637
downvote count: 0
possible better answer: http://stackoverflow.com/a/48482395

http://stackoverflow.com/comment/83880098
has text: @Nae I have fixed the error, please see the edit.
comment on: http://stackoverflow.com/q/48444246
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83798438
type: Comment
score: 0
type: AnswerComment
has text: `a2 = {'a1':{'name':'pks/xa0/xa0', 'age':'12/xa0/xa0'},'a3':{'name':'kps/xa0/xa0', 'age':'23/xa0/xa0'}}` and i applied `ans ={k : {k2 : re.sub(r'[^\x00-\x7F]',' ', v2) for k2, v2 in v.items()} for k, v in a2.items()}`
comment on: http://stackoverflow.com/a/48403884

http://stackoverflow.com/a/48388306
upvote count: 1
has comment: http://stackoverflow.com/comment/83771749
answers question: http://stackoverflow.com/q/48388232
accepted answer of: http://stackoverflow.com/q/48388232
downvote count: 0
type: Answer
has body: I guess the simplest solution would be def function(something, what_to_delete, what_to_substitute): return something.replace(what_to_delete, what_to_substitute) Of course you would not need to write your own function here at all... See https://docs.python.org/2/library/string.html#string.replace
has comment: http://stackoverflow.com/comment/83771747
has comment: http://stackoverflow.com/comment/83771781
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48347705
has comment: http://stackoverflow.com/comment/83681510
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48347547
score: 1
has comment: http://stackoverflow.com/comment/83681569
downvote count: 0
has body: This is how I would do it (based on what you have provided so far): from random import * number = 4; def myFunc(length): value = '' while length &gt; 0: rndNumber = randint(0, 51) value += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'[rndNumber] length -= 1 return value mod = myFunc(number) print (mod)

http://stackoverflow.com/q/48336165
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83666996
tagged with: numpy
has comment: http://stackoverflow.com/comment/83670366
has comment: http://stackoverflow.com/comment/83657983
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83667081
has comment: http://stackoverflow.com/comment/83668037
downvote count: 0
answer count: 0
has body: I have a binary square sparse matrix A that can be seen as an adjacency matrix of a Graph. Now consider a second binary square sparse matrix B that could have a different dimension. I would like to build an algorithm that reorder the matrix A, or a set of elements of matrix A, in order to maximize the overlap with matrix B. Below is an example: I create a random sparse matrix B in python: import scipy.spatial as spatial import matplotlib.pyplot as plt import numpy coords_B = numpy.random.uniform(size=(20,3))*20 pdistmat = spatial.distance.squareform(spatial.distance.pdist(coords_B)) B = (pdistmat &lt;= 8) matshow(B) colorbar() Now I build the matrix A by adding noise to B and adding some rows and columns: coords_A = numpy.r_[numpy.random.uniform(size=(5,3))*20, coords_B + numpy.random.uniform(size=(20,3))*4, numpy.random.uniform(size=(6,3))*20] pdistmat = spatial.distance.squareform(spatial.distance.pdist(coords_A)) A = (pdistmat &lt;= 8) matshow(A) colorbar() Now I randomized the matrix A: random_order = numpy.random.choice(A.shape[0], replace=False, size=A.shape[0]) A_randomized = A[random_order][:, random_order] matshow(A_randomized) colorbar() I would like to reorder A_randomized to maximize the overlap with B as below: x, y = numpy.where(A==1) scatter(y,30-x, label='A') x, y = numpy.where(B==1) x+=5 y+=5 scatter(y,30-x, marker='.', label='B') legend() I would like to implement the algorithm in python using numpy and scipy.sparse libraries.
linked to: http://stackoverflow.com/q/39500649
has title: Reordering a sparse matrix to maximize the overlap on a reference sparse matrix
tagged with: scipy
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/83670847
favorite count: 0
has comment: http://stackoverflow.com/comment/83670277
type: Question
tagged with: matrix
has comment: http://stackoverflow.com/comment/83668226
tagged with: python

http://stackoverflow.com/q/48413907
downvote count: 1
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48414033
tagged with: tfidfvectorizer
has answer: http://stackoverflow.com/a/48414033
tagged with: python
has body: I have built a TfidfVectorizer and fit it to my dataset tfidf = TfidfVectorizer(tokenizer=ner_tokenizer, stop_words='english') tfidf.fit(documents) I now want to do tfidf.transform() in multiple threads. Is this safe to do?
favorite count: 0
type: Question
has title: Is Sklearn TFIDF vectorizer thread safe?
answer count: 1
upvote count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/83875677
type: QuestionComment
has text: Afraid I'm having trouble extracting the Wagtail-specific details from this code snippet - it looks like there's a lot happening in this code (testing `kb_active_revision`, mentions of API calls...) that isn't directly related to your question. Could you distil this down to a minimal, complete and verifiable example (https://stackoverflow.com/help/mcve), please?
score: 0
comment on: http://stackoverflow.com/q/48432006
type: Comment

http://stackoverflow.com/q/48381371
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48465260
tagged with: python
score: -1
has title: Open Developer Command Promt from Python and write commands
has body: I tried to open "Developer Command Prompt for VS 2017" from Python, write some command within like cd .., and then run an exe. However it doesn't let me to write commands at all. I have tried: process = subprocess.Popen('C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Common7\\Tools\\VsDevCmd.bat', shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None) process.stdin.write('1.txt'.encode(encoding='utf_8', errors='strict')); output = process.stdout.readlines() print(output) When I open the developer command promtpt on my own it is directed to c:\&gt;. So, I saved c:\ in a text file called 1.txt to know if it's run the command within Python. However, in the Python console I only get the welcome text: [b'**********************************************************************\r\n', b'** Visual Studio 2017 Developer Command Prompt v15.5.2\r\n', b'** Copyright (c) 2017 Microsoft Corporation\r\n', b'**********************************************************************\r\n']
upvote count: 0
downvote count: 1

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/48388217
tags question: http://stackoverflow.com/q/48424622
tags question: http://stackoverflow.com/q/48388849
tag name: matplotlib-basemap

http://stackoverflow.com/comment/83732540
score: 0
type: Comment
has text: I am reading some document: pd.join is actually using pd.merge. Why it is causing a performance difference?
type: AnswerComment
comment on: http://stackoverflow.com/a/48372474

http://stackoverflow.com/comment/83794897
has text: Ok i just had to install gunicorn... Thanks for the help hansTheFranz you the Manz
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48402868
type: QuestionComment

http://stackoverflow.com/a/48413734
score: 7
downvote count: 0
answers question: http://stackoverflow.com/q/48413706
upvote count: 7
type: Answer
has body: the key is ... the key sorted(names, key=lambda x: int(x.partition('-')[2].partition('.')[0])) Getting that part of the string recognized as the sort order by separating it out and transforming it to an int.

http://stackoverflow.com/comment/83908925
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48450337
has text: Yes I have. I tried it again now,: python-mysqldb is already the newest version (1.3.7-1build2). Good to know that it is instralled, but there is no /usr/bin/python directory to import MySGLdb from. using sudo ls -aRl | grep MySQLdb gave hits, and 1 that makes sense: /usr/lib/python2.7/dist-packages/MySQLdb and there is a script (among others) called connections.py. BUT: #!/usr/lib/python3/dist-packages/MySQLdb import MySQLdb as mdb ModuleNotFoundError: No module named 'MySQLdb' i.e. no response in my simple test program. So I am grateful for further suggestions.
score: 0

http://stackoverflow.com/q/48359729
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: How do I refresh/update QLabel with data from USB serial (from Arduino)?
has body: I know this is a NOOB question; forgive me. I built a Pinewood Derby race timer (small car track) for Cub Scouts using a combination of an Arduino to control timing and RasPi for GUI display of lane place (1st, 2nd, 3rd, etc.) and run time in seconds (e.g. "2.1234"). I have the basic shell GUI setup in QT Creator and have successfully connected the Arduino & RasPi via USB. I am also successfully pulling the Arduino serial data into RasPi (tested with separate small Python code). Problem I am having is the dynamic update of the QLabels in the GUI once the Arduino fires the race result strings via USB. in other words, when a race starts the Arduino sends "B" for begin (need GUI to blank previous results); when race is finished, Arduino sends "F" and then sends place "1" along with time "2.1234" and I need Python to update/change respective QLabels for each lane place and lane time. I am sure there is an easy way to do this, but I am unable to find how via searching this awesome website and others. Thanks much in advance and I apologize for what is probably FUBAR coding that follows! The sample below only shows one lane vs. the 4x lanes I will use once I figure out how to do this. There two Python codes I am working with: Python code to interface with QT Creator generated XML code: import sys import time import serial from PyQt4 import QtCore, QtGui, uic global ser ser=serial.Serial("/dev/ttyUSB1",115200) ser.flushInput() qtCreatorFile = "PinewoodDisplay.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MyApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MyApp() window.show() sys.exit(app.exec_()) while True: if ser.inWaiting()>0: inputValue = (ser.readline().strip()) self.Lane1_Place.setText(inputValue) XML generated from QT Creator (not sure if I am posting this right) --…
tagged with: pyqt4
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48362335
tagged with: pyqt
tagged with: pyserial
has answer: http://stackoverflow.com/a/48362335
answer count: 1
tagged with: arduino
downvote count: 0

http://stackoverflow.com/comment/83947709
score: 0
comment on: http://stackoverflow.com/q/48477154
type: Comment
type: QuestionComment
has text: Thanks for the comments! @Jean-FrançoisFabre, this info is much appreciated! glenfant, any pointers on when to use 'rb' and 'rt' with bzip2? Meanwhile, my hunch is that another process messed with the currently processed file and thus broke the strem... I'm still investigating.

http://stackoverflow.com/a/48480269
score: 0
has comment: http://stackoverflow.com/comment/83970364
has comment: http://stackoverflow.com/comment/84204198
has comment: http://stackoverflow.com/comment/84204587
has comment: http://stackoverflow.com/comment/83970892
answers question: http://stackoverflow.com/q/48477845
type: Answer
has body: This is a bug introduced in Kivy master, which is fixed in python-for-android's master branch. You can probably work around it by setting p4a.branch = master in the buildozer.spec, or using an older version of Kivy than the master branch (ideally Kivy 1.10).
has comment: http://stackoverflow.com/comment/84218806
has comment: http://stackoverflow.com/comment/84218952

http://stackoverflow.com/comment/83857499
has text: I tried this. (v is a list in my function with [1, 2, 3, 8, 5]) wavg_trans = np.array([wavg]) val= np.array([v]) diff1 = val - wavg_trans.T. But I am getting the error wavg_trans = np.array([wavg]) ValueError: cannot copy sequence with size 5 to array axis with dimension 1
type: Comment
comment on: http://stackoverflow.com/a/48432727
type: AnswerComment
score: 0

http://stackoverflow.com/q/48480192
tagged with: format
possible better answer: http://stackoverflow.com/a/48480221
accepted answer: http://stackoverflow.com/a/48480227
score: 1
has title: Formatting to two decimal places in python
has answer: http://stackoverflow.com/a/48480221
tagged with: python
has answer: http://stackoverflow.com/a/48480227
has answer: http://stackoverflow.com/a/48480224
has body: Fairly new to coding and having some confusion with my homework. I want to have the printed results only go to two decimal places and not any farther. I have been messing around with some format options and trying to find the answer online but couldn't understand what I needed to do, any help is much appreciated, thanks! #Ingredients per 48 cookies sugar = 1.5 butter = 1 flour = 2.75 #what percent of 48 are the ingredients sugar1 = (1.5/48) butter1 = (1/48) flour1 = (2.75/48) #ask for amount of cookies from user cookies = int (input('How many cookies would you like to bake? ')) #calculate ingredient amounts sugar2 = (sugar1 * cookies) format(sugar2, '.2f') butter2 = (butter1 * cookies) format(butter2, '.2f') flour2 = (flour1 * cookies) format(flour2, '.2f') print ('To make', cookies, ' you need', sugar2, 'cups of sugar,', butter2, 'cups of butter, and', flour2, ' cups of flour.')
tagged with: python-3.x
answer count: 3
has comment: http://stackoverflow.com/comment/83953404
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2389846
type: AnsweredQuestion

http://stackoverflow.com/a/48376818
accepted answer of: http://stackoverflow.com/q/48358162
upvote count: 8
type: Answer
score: 8
has body: For appending to JSONField or any other JSON in python : my_json = {'key_one' : 'val_one', 'key_two' : 'val_two'} same as : my_json = Model.objects.get(pk=id).my_json_field Append to json : my_json['new_key'] = 'new_val' print (my_json) {'key_one' : 'val_one', 'key_two' : 'val_two', 'new_key' : 'new_val'} Delete from json : my_json.pop('new_key') print (my_json) {'key_one' : 'val_one', 'key_two' : 'val_two'}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48358162

http://stackoverflow.com/comment/83750840
has text: @ThePadawan drf-yasg is new package, and for it's age it's amazing how beautiful it is. You can raise new issue and maybe make contribution to it for making it more readable. Glad i helped!
type: AnswerComment
comment on: http://stackoverflow.com/a/48377373
score: 1
type: Comment

http://stackoverflow.com/q/48479761
has title: Django Python "TypeError: view must be callable or a list/tuple in the case of include()" with urls
score: 0
has comment: http://stackoverflow.com/comment/83952577
tagged with: django-urls
has comment: http://stackoverflow.com/comment/83952698
answer count: 1
tagged with: python-3.x
type: Question
has body: I'm getting a "TypeError: view must be callable or a list/tuple in the case of include()" for the subscribe url below for Weather_App/urls.py import signupform.urls import signupform.views as views app_name = "Weather_App" urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^subscribe/', signupform.urls, name='signup'), ] In my other urls file signupform/urls.py, I had a similar issue but fixed it using a views import from django.conf.urls import url from . import views as Weather_App_views urlpatterns = [ url(r'^$', Weather_App_views.index, name='index'), url(r'confirm/$', Weather_App_views.confirm, name='confirm'), ] Views looks like from django.http import HttpResponse import json from urllib.request import urlopen from django.template import loader from django.shortcuts import get_object_or_404, render from django.http import * from django.core.exceptions import ValidationError from django.db import IntegrityError from .models import WeatherSubscription # Create your views here. def index(request): return render(request, 'signupform/index.html', {'location_set':WeatherSubscription.city_choices}) def confirm(request): ws = WeatherSubscription(email=request.POST['email_input'], location=request.POST['location_input']) render_kwargs = {} try: ws.clean_fields() ws.save() except ValidationError as e: render_kwargs['invalid_message'] = 'Email not in a standard form.' except IntegrityError as e: render_kwargs['invalid_message'] = 'Email already subscribed.' return render(request, 'signupform/confirm.html', render_kwargs) Models just has a WeatherSubscription function And my structure is signedupform -init -apps -models -settings -urls -views Weather_App -init -settings -urls -wsgi
tagged with: django
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48479871
tagged with: django-views

http://stackoverflow.com/q/48433383
linked to: http://stackoverflow.com/q/43037582
linked to: http://stackoverflow.com/q/42802181
has answer: http://stackoverflow.com/a/48433550
answer count: 2
linked to: http://stackoverflow.com/q/42920602
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/48433480
score: 0
tagged with: pyqt5
has answer: http://stackoverflow.com/a/48433480
possible better answer: http://stackoverflow.com/a/48433550
type: Question
tagged with: numpy
has title: numpy array reorder values in single dimension
has body: I'm still new to numpy and having trouble writing a lambda to do what I want in this case. It could be that the lambda is not working because of the data in the array? I've got some pixel values from a QImage in Qt5 using PyQT in Python: ptr = self.myPhoto.bits() ptr.setsize(self.myPhoto.byteCount()) pixels = np.asarray(ptr).reshape(self.myPhoto.height(), self.myPhoto.width(), 4) The pixel data looks like this [B G R A]: [[[ 100 0 2 255] [ 100 0 2 255] [ 100 1 1 255] ..., [ 2 3 0 255] [ 1 2 0 255] [ 1 2 0 255]]] I want it to look like this [R G B A]: [[[ 2 0 100 255] [ 2 0 100 255] [ 1 1 100 255] ..., [ 0 3 2 255] [ 0 2 1 255] [ 0 2 1 255]]] EDIT: removed commas from array Also, is it possible to do this right from reshape call instead of using a lambda post process? These questions are interesting, but I'm still having trouble glueing them together to get what I want: How to optimize changing the value of 3d numpy.array if meet a condition Numpy 3d array indexing Calling a lambda with a numpy array
tagged with: python
tagged with: qimage
type: AnsweredQuestion

http://stackoverflow.com/comment/83945767
has text: Independent of what `markevery` is set to, the line itself has (and should of course have) the same number of points. I do not understand the problem of using `_mark_every_path()`.
comment on: http://stackoverflow.com/q/48476275
type: Comment
type: QuestionComment
score: 0

flask-sqlalchemy
tags question: http://stackoverflow.com/q/48358619
tags question: http://stackoverflow.com/q/48390207
type: Tag
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/48367887
tags question: http://stackoverflow.com/q/48408520
tags question: http://stackoverflow.com/q/48443084
tags question: http://stackoverflow.com/q/48401951
tags question: http://stackoverflow.com/q/48403903
tags question: http://stackoverflow.com/q/48367683

http://stackoverflow.com/q/48388357
score: 0
has answer: http://stackoverflow.com/a/48388690
type: UnansweredQuestion
answer count: 1
tagged with: pip
has title: Strategies for upgrading multiple Python packages
has body: I have a big legacy Django project that I need to upgrade to some newer Django version. The project has about 70 dependencies saved in the requirements.txt file. Some of the packages are dependencies for several other packages. What are the best ways to upgrade the dependencies so, that some of them get freezed to some specific version, for example, Django 1.8, but others would be upgraded to the maximal possible version? Are there any helper tools or pip switches for that? If not, what would be the optimal strategy to do that manually? (Here I am not questioning the database migrations that I will need to execute at each iteration)
tagged with: upgrade
tagged with: python
type: Question

http://stackoverflow.com/q/48379965
downvote count: 0
upvote count: 1
has title: Finding the number of elements in an array to be replaced by a given number such that the sum of the array is smaller than another given number
favorite count: 0
has answer: http://stackoverflow.com/a/48380160
type: Question
has comment: http://stackoverflow.com/comment/83746955
has comment: http://stackoverflow.com/comment/83746846
has comment: http://stackoverflow.com/comment/83746596
tagged with: python
has comment: http://stackoverflow.com/comment/83746547
accepted answer: http://stackoverflow.com/a/48380160
type: AnsweredQuestion
has body: I need help with a certain problem.Suppose you are given a sorted array "A", which has "N" elements and two integers "X" and "Y". Now you are asked two find the number of elements in "A" you have to replace with "X" such that the sum of the array "A" is less than "Y". The given problem can be easily solved in O(n^2) using the following technique.(Only the code snippet for this is specific operation). sum = None count = None for i in range(N): for j in range(i): A[j] = X count += 1 for k in range(N): sum += A[k] if sum==Y: print(count) count = 0 break But I want to do this in a more efficient way,can someone suggest a more efficient way? Thanks In Advance
score: 1
tagged with: arrays
answer count: 1

http://stackoverflow.com/q/48415690
type: Question
tagged with: pandas
linked to: http://stackoverflow.com/q/43758224
has comment: http://stackoverflow.com/comment/83827340
tagged with: data-visualization
has comment: http://stackoverflow.com/comment/83848951
has comment: http://stackoverflow.com/comment/83848119
tagged with: python
has answer: http://stackoverflow.com/a/76575110
type: UnansweredQuestion
tagged with: jupyter-notebook
tagged with: pivottable.js
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83827842
has title: pivottablejs does not display any result in the jupyter notebook
answer count: 1
has body: pivottablejs does not display any result in the jupyter notebook. Clicking on the hyperlink(pop out), displays an empty page. from pivottablejs import pivot_ui from IPython.display import IFrame from IPython.core.display import display import pandas as pd df = pd.read_csv('sample.csv',encoding='utf-8')
favorite count: 0
has comment: http://stackoverflow.com/comment/83828198

http://stackoverflow.com/a/48337236
downvote count: 0
score: 1
upvote count: 1
has body: Check if you've handled the case for last element. first = alist[i] second = alist[i + 1] The second line uses i+1. So, when i points to the last index of the list, the second element alist[i+1] seems to be out of list index.
answers question: http://stackoverflow.com/q/48337195
type: Answer

http://stackoverflow.com/a/48367451
has comment: http://stackoverflow.com/comment/83721478
downvote count: 0
has comment: http://stackoverflow.com/comment/83728608
has comment: http://stackoverflow.com/comment/83728435
has comment: http://stackoverflow.com/comment/83728189
has comment: http://stackoverflow.com/comment/83729012
answers question: http://stackoverflow.com/q/48367293
has body: You can try this: command = input() if command not in {'l','h','c'}: print("Please insert l, h or c: ") command = input("l, h or c: ") else: print("working") The in will check if the command is inside that list of strings
has comment: http://stackoverflow.com/comment/83728415
has comment: http://stackoverflow.com/comment/83729108
type: Answer
has comment: http://stackoverflow.com/comment/83734131
has comment: http://stackoverflow.com/comment/83728643
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/83727485

http://stackoverflow.com/q/48347722
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83681680
has answer: http://stackoverflow.com/a/48347920
has answer: http://stackoverflow.com/a/48347971
tagged with: python
has comment: http://stackoverflow.com/comment/83681505
has comment: http://stackoverflow.com/comment/83682227
has title: How do you read the input from subprocess.check_output() in Python?
score: 0
has body: In my test runner run_tests.py (not suppose to modify) output = subprocess.check_output("python main.py", universal_newlines=True, input="foo bar baz").strip() And in my main.py import sys import json print(json.dumps(sys.argv)) # I only get ['main.py'] How can I retrieve "foo bar baz" from the input that was passed to the subprocess? I tried checking sys.stdin and no luck there too.
type: Question
answer count: 2

http://stackoverflow.com/comment/83925568
type: QuestionComment
type: Comment
has text: might be a duplicate of https://stackoverflow.com/questions/9764913/how-do-i-restart-celery-workers-gracefully, specifically the answer regarding stopping workers with the `HUP` signal
comment on: http://stackoverflow.com/q/48465993
score: 0

http://stackoverflow.com/q/48443746
answer count: 0
score: 1
has title: Is it OK to change __name__ of a function to use as description?
downvote count: 0
has body: I want to test a couple of similar functions and would like to have a neater output (in a plot) than the actual variable name. Is this what 'name' is intended for or are there technical reasons not to do this? An example would be def add2(x): return x + 2 add2.__name__ = 'Add 2' test(add2)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83879158
has comment: http://stackoverflow.com/comment/83878916
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83879395
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83878919
has comment: http://stackoverflow.com/comment/83879304
has comment: http://stackoverflow.com/comment/83879001
has comment: http://stackoverflow.com/comment/83879083
has comment: http://stackoverflow.com/comment/83878937

http://stackoverflow.com/q/48473574
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: scikit-learn
has title: What is the value of X and y from imblearn.over_sampling import ADASYN
linked to: http://stackoverflow.com/q/2084069
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48531701
has body: I am working on hepatitis dataset from UCI repository. It has imbalanced class. Class Distribution: DIE: 32 LIVE: 123 I am trying to use the ADASYN oversampling method to balance the class. In the examples they have generated a dataset and passed it to ADASYN. Can someone explain me in that format the value of x and y should be based on the dataset? I am referring to the example from below link. https://561-36019880-gh.circle-artifacts.com/0/home/ubuntu/imbalanced-learn/doc/_build/html/generated/imblearn.over_sampling.ADASYN.html#imblearn.over_sampling.ADASYN Please help me in splitting the dataset as X and Y value as required to pass to ADASYN
tagged with: python
score: -1
downvote count: 2

http://stackoverflow.com/comment/83707525
type: Comment
has text: I'd iterate on `row` first. and index with `matrix[row, col]`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48358477

http://stackoverflow.com/a/48477398
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48475858
downvote count: 0
upvote count: 1
has body: Problem is solved, here is the code: class SomeThing(object): def __init__(self, name): self.name = name def run(self): #to parallelizing os.environ['FOO'] = "http://localhost:1135" + str(self.name) + '/' and some2 = Something(9) some1 = Something(1) t2 = multiprocessing.Process(target=some2.run()) t1 = multiprocessing.Process(target=some1.run()) t1.start() t2.start()
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48475858

http://stackoverflow.com/a/48467258
has body: Try something like this : lst = ['3', '7', 'foo', '2.6', 'bar', '8.9'] for j,i in enumerate(lst): if i.isdigit(): lst[j]=int(i) elif '.' in i: lst[j]=float(i) output: [3, 7, 'foo', 2.6, 'bar', 8.9]
has comment: http://stackoverflow.com/comment/83959503
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48441382

http://stackoverflow.com/q/48479571
has comment: http://stackoverflow.com/comment/83952324
has body: I have tried many solutions like installing from different sources official google link Google.api..., pypi and also building from git repo. But every time I face the same problem ImportError: libcublas.so.9.0: OS: Linux Arch tensorflow: tensorflow-gpu version1.5 Nvidia: Cuda 9.1 and Cudnn 7.0.5 Note: tensorflow cpu is working fine Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/usr/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/usr/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "/usr/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/lib/python3.6/site-packages/tensorflow/python/pywrap_…
upvote count: 3
type: UnansweredQuestion
tagged with: archlinux
has comment: http://stackoverflow.com/comment/83952127
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
has title: While Import python. ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
type: Question
score: 3
has answer: http://stackoverflow.com/a/48481264
tagged with: python
has comment: http://stackoverflow.com/comment/83952304

http://stackoverflow.com/q/48334437
has comment: http://stackoverflow.com/comment/83654133
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/23327293
accepted answer: http://stackoverflow.com/a/48334563
favorite count: 0
possible better answer: http://stackoverflow.com/a/48334576
type: Question
has answer: http://stackoverflow.com/a/48334563
has answer: http://stackoverflow.com/a/48334576
tagged with: python
has comment: http://stackoverflow.com/comment/83654135
has comment: http://stackoverflow.com/comment/83654122
has comment: http://stackoverflow.com/comment/83654193
has comment: http://stackoverflow.com/comment/83654171
tagged with: flask
type: AnsweredQuestion
has title: Flask cannot find template file - jinja2.exceptions.TemplateNotFound
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/23327293
has body: I tried to render an "html" file using Flask(Jinja2) in Python, but it showed me an error. My controller ".py file":- from flask import Flask, render_template app = Flask(__name__) @app.route("/profile/<name>") def profile(name): return render_template('profile.html', name=name) if __name__ == "__main__": app.run(debug=True) My template "profile.html" file: Welcome To Your Profile, {{ name }} When I ran the flask app, it gave me the following exception:- jinja2.exceptions.TemplateNotFound: template\profile.html

http://stackoverflow.com/a/58339792
has body: You need to upgrade h5py and numpy version should be &lt;1.17: pip install --upgrade h5py pip install "numpy&lt;1.17"
type: Answer
has comment: http://stackoverflow.com/comment/103036533
score: 0
answers question: http://stackoverflow.com/q/48340392

http://stackoverflow.com/q/48392079
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83772988
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83772960
tagged with: loops
has body: # df date value 0 2018-01-22 01:01:53.192824 1 1 2018-01-22 01:01:55.042070 2 2 2018-01-22 01:01:56.264234 3 3 2018-01-22 01:01:57.697656 2 4 2018-01-22 01:01:57.831543 2 5 2018-01-22 01:02:00.258684 1 6 2018-01-22 01:02:00.259691 3 7 2018-01-22 01:02:00.260698 2 8 2018-01-22 01:02:00.261683 1 9 2018-01-22 01:02:00.333109 2 My goal is to make a dictionary that has keys that are correspond to each minute and the result of a calcuation of the last 3 values at each time. The calculation is to accumulate 1 if the series of the last 3 values at a moment does not continuously rise or fall. To simply put, if the last 3 values at a moment are like either ↘↗ or ↗↘, you add 1 to its key. For example, at 2018-01-22 01:01:56.264234, the last 3 values are 1, 2, 3 and they are increasing, you don't add 1. But at 2018-01-22 01:01:57.697656, the last 3 values are 2, 3, 2 and they are like ↗↘ and you add 1. The dataframe above will make a dictionary like: dic_result = { np.datetime('2018-01-22 01:01'): 1, # [2, 3, 2] np.datetime('2018-01-22 01:02'): 3 } # [2, 1, 3], [1, 3, 2], [2, 1, 2] This is what I programmed to do this job and it works fine, but it takes too much time if the dataframe is big. I hope to know how I can improve this code and get better performances, for instance, using numpy arrays or better algorithms. # I used deque to store last 3 values deq_3_trs = deque(maxlen=3) dic_result = {} for i in range( len(df) ): date = df.ix[i]['date'] date_min = np.datetime64(date, 'm') value = df.ix[i]['value'] deq_3_trs.append(value) if (date_min not in dic_result) and (len(deq_3_trs) == 3): dic_result[date_min] = 0 # check the deque if the values are like either ↘↗ or ↗↘ if (deq_3_trs[0] &gt; deq_3_trs[1] &lt; deq_3_trs[2]) or (deq_3_trs[0] &lt; deq_3_trs[1] &gt; deq_3_trs[2]): dic_result[date_min] += 1 elif (date_min in dic_result) and (len(deq_3_trs) == 3): # check the deque if the values are like either ↘↗ or ↗↘ if (deq_3_trs[0] &gt; deq_3_trs[1] &lt; deq_3_trs[2]) or (deq_3_t…
has comment: http://stackoverflow.com/comment/83772409
favorite count: 0
type: Question
tagged with: numpy
tagged with: python
has comment: http://stackoverflow.com/comment/83772223
has answer: http://stackoverflow.com/a/48392756
accepted answer: http://stackoverflow.com/a/48392756
has title: How could I replace these FOR and IF statements to get better performances?
score: 2
has answer: http://stackoverflow.com/a/48393240
upvote count: 2
possible better answer: http://stackoverflow.com/a/48393240

http://stackoverflow.com/comment/83948665
comment on: http://stackoverflow.com/q/48477144
has text: No, it is shop.urls.py, main-mysite.urls.py
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/48364969
has comment: http://stackoverflow.com/comment/83716544
type: UnansweredQuestion
tagged with: python
tagged with: php
has title: Php cannot exec python script on - RPI3
has comment: http://stackoverflow.com/comment/83716533
has body: I cannot at all execute a python script via php exec. This is my code &lt;?php $output = shell_exec("python /var/www/html/socket/power_on.py"); $output = shell_exec("sudo python /var/www/html/socket/power_on.py"); $output = shell_exec("/usr/bin/python /var/www/html/socket/power_on.py"); echo $output; ?&gt; I've tried all of the above yet no luck the only command that seems to work that I've also tried is 'ls' How to I give the user www-data access to sudo, as that may work. Since I've tried chmod 777 on the directory and file still no luck
has comment: http://stackoverflow.com/comment/83716662
has comment: http://stackoverflow.com/comment/83717110
has comment: http://stackoverflow.com/comment/83717001
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83716537
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83716910
linked to: http://stackoverflow.com/q/18721066
favorite count: 0
linked to: http://stackoverflow.com/q/35817074
has comment: http://stackoverflow.com/comment/83716671
type: Question
has comment: http://stackoverflow.com/comment/83716621
has comment: http://stackoverflow.com/comment/83716639
has comment: http://stackoverflow.com/comment/83716556
has comment: http://stackoverflow.com/comment/83716579

http://stackoverflow.com/comment/83789573
score: 0
has text: `import`ing a module is different from running the code in the terminal. I suggest you take a look at running your `demo_oled_v01` using the python `Process` module, or take a look at the [`sh` module](http://amoffat.github.io/sh/)
comment on: http://stackoverflow.com/q/48400740
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83725373
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48368968
has text: Please include example data.

http://stackoverflow.com/q/48464597
has comment: http://stackoverflow.com/comment/83923314
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83923022
has answer: http://stackoverflow.com/a/48465279
has body: I am experiencing different results (on 16th least significant bit) while performing a single step of a dot product, implemented differently in TF and numpy. The inputs are float32 5x5 image and 5x5 kernel. i = tf.constant(I2D, dtype=tf.float32, name='i') k = tf.constant(K2D, dtype=tf.float32, name='k') Scenario 1: Tensorflow convolution tf_convolution = tf.nn.convolution(input=i4d, filter=k4d, padding="VALID") Scenario 2: Tensorflow multiplication and sum tf_multiply = tf.multiply(i, k) tf_dot = tf.reduce_sum(tf_multiply) Scenario 3: Numpy multiplication and sum np_multiply = np.multiply(I2D, K2D) np_dot = np.sum(np_multiply) The results of element-wise multiplication in Scenario 2 and 3 are the same, but after the sum they are not. Results remain the same regardless of whether it is executed using tensorflow or tensorflow-gpu. I would like to better understand how it comes to this, what is the format type in which results are calculated (input is always float32, for numpy output is also float32), and whether there is a way to achieve that the results are bit identical. Thank you in advance for your help. EDIT: Actual numbers: I2D = np.array([[ 0.218994140625, 0.30615234375, 0.43115234375, 0.46923828125, 0.515869140625], [0.2880859375, 0.306640625 , 0.361572265625, 0.430419921875, 0.408203125], [0.380615234375 , 0.318359375, 0.278076171875, 0.325927734375, 0.306640625], [0.319580078125, 0.30859375, 0.306640625, 0.28857421875, 0.29345703125], [0.28125, 0.319580078125 , 0.3515625 , 0.3486328125, 0.3349609375]]) K2D = np.array([[0.0890502929687500, 0.0557556152343750, -0.0900573730468750, 0.0840759277343750, 0.1080932617187500], [0.0617370605468750, -0.0567016601562500, 0.0847473144531250, 0.0191040039062500, -0.0368041992187500], [0.1333923339843750, -0.0764160156250000, 0.1204223632812500, -0.1223754882812500, -0.0852966308593750], [0.1645507812500000, -0.0398864746093750, -0.0663452148437500, 0.0543823242187500, 0.1416015625000000], [-0.1589050292968750, -0.1628723…
score: 2
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/83922727
tagged with: convolution
has title: Tensorflow convolution vs. Tensorflow multiplication and sum vs. Numpy multiplication and sum
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83922917

http://stackoverflow.com/a/48404504
has body: That's a very common mistake. Your 'selected' variable holds a list, not a string. You should get the first list value instead, so just change your code like that: transX_value = cmds.textField(w=100, h=22, tx=cmds.getAttr("%s.translateX" % selected[0]))
has comment: http://stackoverflow.com/comment/83802817
answers question: http://stackoverflow.com/q/48344963
upvote count: 2
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83879313

http://stackoverflow.com/comment/128326762
score: 1
has text: `traceback.extract_stack` also returns the list in "traceback order": `stack = StackSummary.extract(walk_stack(f), limit=limit); stack.reverse()`
type: Comment
comment on: http://stackoverflow.com/a/61780616
type: AnswerComment

http://stackoverflow.com/comment/123281064
has text: I did have to restart just the interpreter. Possibly reloading matplotlib would've done the trick too.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48468545
type: AnswerComment

http://stackoverflow.com/comment/83832088
comment on: http://stackoverflow.com/a/48414273
has text: I tried to compare with `None` and gave me the same error but saying that `None != None` ... :/
type: AnswerComment
score: 0
type: Comment

bit
tag name: bit
tags question: http://stackoverflow.com/q/48468365
type: Tag

http://stackoverflow.com/a/48433458
type: Answer
has comment: http://stackoverflow.com/comment/83861507
score: 1
downvote count: 0
upvote count: 1
has body: The purpose if if __name__ == '__main__': is to allow you to either run your program from the command line and have it do something, or use it as a module without having it do anything. With your example function1.py, if you wanted to use CheckUid from another file, it wouldn't be very useful: you could do from function1 import CheckUid userInfo = CheckUid('karn') but you wouldn't get anything: userInfo would always be None, whether the user karn was found or not, and the function may have printed output that you might not want. But if you were to use CheckUid from function2.py instead, userInfo would be None only if the user wasn't found, and a dictionary if it was. So you almost always want to use the style from function2.py and return a value rather than printing it. Since your function sometimes returns a dictionary and sometimes returns None, wherever you use it - in an if __name__ == '__main__' section or in another script - you'll need to check what you get back from it. For example, to skip printing None when a user is not found, you could modify your function2.py as follows: if __name__ == '__main__': with open('hh', mode='rt', encoding='utf-8') as f: for line in f: result = CheckUid(line.strip()) if result: print(result)
answers question: http://stackoverflow.com/q/48386829

http://stackoverflow.com/q/48454818
possible better answer: http://stackoverflow.com/a/48455045
type: Question
has answer: http://stackoverflow.com/a/48463792
has comment: http://stackoverflow.com/comment/83902752
has answer: http://stackoverflow.com/a/48455045
has body: Given this df: Name i j k A 1 0 3 B 0 5 4 C 0 0 4 D 0 5 My goal is to add in a column "Final" that takes value in an order of i j k: Name i j k Final A 1 0 3 1 B 0 5 4 5 C 0 0 4 4 D 0 5 &lt;-- this one is tricky. We do count the null for j column here. Here is my attempt: df['Final'] = df[['i', 'j', 'k'].bfill(axis=1).iloc[:, 0]. This doesn't work since it always takes the value of column 1. Any help would be appreciated. :) Many thanks!
has answer: http://stackoverflow.com/a/48454896
tagged with: python
has title: Pandas taking values in columns order
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48454896
answer count: 3
tagged with: pandas
score: 0

http://stackoverflow.com/comment/83853663
comment on: http://stackoverflow.com/a/48431152
score: 0
has text: then, which method should i use?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48391719
has comment: http://stackoverflow.com/comment/83773143
type: Answer
has comment: http://stackoverflow.com/comment/83771455
has comment: http://stackoverflow.com/comment/83771463
has comment: http://stackoverflow.com/comment/83772061
answers question: http://stackoverflow.com/q/48391636
score: 4
upvote count: 4
has body: Edit: Leave it to @StefanPochmann to shoot down my beautiful answer: It doesn't matter for the question as it is posed, but it is certainly worth mentioning that zip works pair-by-pair. So while you can formally pause alter defined below after an odd number of iterations, at this point 'y' will have been printed already. If you care about this the solution also due to Stefan is &gt;&gt;&gt; alter = map(next, it.cycle((foo1(), foo2()))) which is actually pretty clever. Edit ends You could convert the functions into generators, then zip them. &gt;&gt;&gt; import itertools as it &gt;&gt;&gt; &gt;&gt;&gt; def foo1(): ... while True: ... print("x") ... yield None ... &gt;&gt;&gt; def foo2(): ... while True: ... print("y") ... yield None ... &gt;&gt;&gt; alter = it.chain.from_iterable(zip(foo1(), foo2())) &gt;&gt;&gt; while True: ... next(alter) x y x y ... or: &gt;&gt;&gt; for a in alter: ... pass x y x y ...
downvote count: 0
has comment: http://stackoverflow.com/comment/83772121

http://stackoverflow.com/a/53535633
score: 0
has body: What I have faced today, makes me ambitious to share it with you. As people mentioned above you can used easily: df['Val10-Val1'] = df['Val10']-df['Val1'] but sometimes you might need to use apply function, so you might use the following line: df['Val10-Val1'] = df.apply(lambda row: row['Val10']-row['Val1'])
answers question: http://stackoverflow.com/q/48350850
type: Answer
has comment: http://stackoverflow.com/comment/107398146

http://stackoverflow.com/comment/83780272
type: Comment
comment on: http://stackoverflow.com/q/48396419
type: QuestionComment
has text: Try something after that ask here
score: 0

scapy
tags question: http://stackoverflow.com/q/48377685
tags question: http://stackoverflow.com/q/48460101
tags question: http://stackoverflow.com/q/48479848
type: Tag
tag name: scapy

http://stackoverflow.com/comment/83769204
comment on: http://stackoverflow.com/q/48390268
score: 0
has text: Another approach would be index all neighbors at once with `X[csr_indices]`, Apply `cumsum` to this, and then use `csr_indptr` to calculate the subsums and mean.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48405055
tagged with: plot
downvote count: 0
tagged with: errorbar
tagged with: bokeh
favorite count: 0
type: Question
has title: Bokeh whisker head color
score: 5
upvote count: 5
type: UnansweredQuestion
has body: I would like to plot error bars (std) for my points-line plot. I didn't found the proper answer how to do this but one of the solutions is to use whisker. https://docs.bokeh.org/en/latest/docs/user_guide/annotations.html#whiskers I worked for me pretty well but I have a problem how to change the head color of whisker head. I used the line color property to change the color of line: https://docs.bokeh.org/en/latest/docs/reference/models/annotations.html#bokeh.models.annotations.Whisker but It not changed the color of head (horizontal line). It remains black. Is there a way how to do this? or there is a better way how to plot error bars in color of line? Example code from bokeh with red lines and black heads for errorbars: from bokeh.models import ColumnDataSource, Whisker from bokeh.plotting import figure, show from bokeh.sampledata.autompg import autompg as df colors = ["red", "olive", "darkred", "goldenrod", "skyblue", "orange", "salmon"] p = figure(plot_width=600, plot_height=300, title="Years vs mpg with Quartile Ranges") base, lower, upper = [], [], [] for i, year in enumerate(list(df.yr.unique())): year_mpgs = df[df['yr'] == year]['mpg'] mpgs_mean = year_mpgs.mean() mpgs_std = year_mpgs.std() lower.append(mpgs_mean - mpgs_std) upper.append(mpgs_mean + mpgs_std) base.append(year) source_error = ColumnDataSource(data=dict(base=base, lower=lower, upper=upper)) p.add_layout( Whisker(source=source_error, base="base", upper="upper", lower="lower", line_color='red') ) for i, year in enumerate(list(df.yr.unique())): y = df[df['yr'] == year]['mpg'] color = colors[i % len(colors)] p.circle(x=year, y=y, color=color) show(p)
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48411293

http://stackoverflow.com/q/48389603
has answer: http://stackoverflow.com/a/72226390
has comment: http://stackoverflow.com/comment/127608430
tagged with: pytest
score: 7
answer count: 1
linked to: http://stackoverflow.com/q/12345164
upvote count: 7
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83771834
has title: Running pytest repeatedly on changed test files
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83771929
downvote count: 0
tagged with: python
has body: I want to run pytest multiple times from within Python without restarting the script/interpreter. The problem is that pytest is caching test contents/results. That is, if you modify a test file between two runs, pytest doesn't pick up the changes, showing the same results as before. (Unless you restart the script/exit the interpreter, which you'd naturally do when using pytest from the command line.) Reproduction test_foo.py: def test_me(): assert False In the Python shell: &gt;&gt;&gt; import pytest &gt;&gt;&gt; pytest.main(['test_foo.py']) (...) def test_me(): &gt; assert False E assert False test_foo.py:2: AssertionError Good so far. Now don't exit the interpreter but change the test to assert True and re-run pytest. &gt;&gt;&gt; pytest.main(['test_foo.py']) (...) def test_me(): &gt; assert True E assert False test_foo.py:2: AssertionError Expected result Pytest should have picked up the change in the file and pass the rewritten test. Solutions that don't work Using importlib.reload(pytest) to reload pytest between the runs. Running pytest with cleared caches: pytest.main(['--cache-clear', test_foo.py']) (Running pytest as a subprocess isn't an option because I want have a reference to the pytest module from within my application.) Any hints how to make pytest pick up these changes or how to properly reload the module?

http://stackoverflow.com/a/50240619
has body: I'm not sure, but you phone should show you a notification which say somethink like, connected to a network without internet we two button, "stay connected" and another one. If you use it and click on stay connected it's good
answers question: http://stackoverflow.com/q/48385068
has comment: http://stackoverflow.com/comment/87498787
score: 0
type: Answer

http://stackoverflow.com/comment/83931298
has text: looking through the `Popen` docs, it suggests using `Popen.communicate`. Would that be better? https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
comment on: http://stackoverflow.com/a/48468782
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48431282
has answer: http://stackoverflow.com/a/48432269
accepted answer: http://stackoverflow.com/a/48432269
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 2
tagged with: deep-learning
downvote count: 0
has title: Only evaluate non-zero values of tf.Tensor
has body: I am training to train a Neural Network using Keras and I am using my own metric function as the loss function. The reason for this is that the actual values in the test set have a lot of NaN values. Let me give an example of the actual values in the test set: 12 NaN NaN NaN 8 NaN NaN 3 In the preprocessing of my data, I replaced all the NaN values with zeros, so the above example contains zeros on each NaN row. The Neural Network produces an output like this: 14 12 9 9 8 7 6 3 I only want to calculate the root mean squared error between the non-zero values. So for the example above, it should only calculate the RMSE for rows 1, 5 and 8. To do this, I created the following function: from sklearn.metrics import mean_squared_error from math import sqrt [...] def evaluation_metric(y_true, y_pred): y_true = y_true[np.nonzero(y_true)] y_pred = y_pred[np.nonzero(y_true)] error = sqrt(mean_squared_error(y_true, y_pred)) return error When you test the function by hand, by feeding the actual values from the test set and an output from the neural network that is initialized with random weights, it works well an produces an error value. I am able to optimize the weights using an Evolutionary approach, and I am able to optimize this error measure by adjusting the weights of the network. Now, I want to train the network with evaluation_metric as the loss function using the model.compile function from Keras. When I run: model.compile(loss=evaluation_metric, optimizer='rmsprop', metrics=[evaluation_metric]) I get the following error: TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor. I think this has to do with the usage of np.nonzero. Since I am working with Keras, I should probably use a function of the Keras Backend, or using something like tf.cond to check for the non zero values of y_true. Can someo…
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/115196897
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48437314
tagged with: python
has comment: http://stackoverflow.com/comment/115196790
has comment: http://stackoverflow.com/comment/115196680
has answer: http://stackoverflow.com/a/48437314

http://stackoverflow.com/comment/83777232
has text: This is irrelevant to the question. But FYI, `camelCase` is typically used for class names. It can make it a little confusing when a function parameter is `camelCase`. Up to you, but i'd use `snake_case`
score: 0
comment on: http://stackoverflow.com/q/48394789
type: Comment
type: QuestionComment

http://stackoverflow.com/a/58953665
has comment: http://stackoverflow.com/comment/104163709
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48469614
has body: Trying setting REQUESTS_CA_BUNDLE as mentioned in the doc here: https://github.com/Azure/azure-cli/blob/dev/doc/use_cli_effectively.md#working-behind-a-proxy

http://stackoverflow.com/comment/83753031
has text: I haven't tested your code but as a new user, it was pretty elaborate of you. Keep up the good work! +1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48382635
score: 0

http://stackoverflow.com/comment/83900754
type: Comment
score: 0
type: QuestionComment
has text: The question is now totally different. Please do not change the complete meaning of a question to which you already got an answer. This question is closed anyways. Just leave it as it is (since you already accepted an answer, you cannot delete it anymore). If you now have a different question, ask a different question. Just mind that the problem you apparently face here, has also already been asked about, so if you were to ask this question now, it would be closed again.
comment on: http://stackoverflow.com/q/48413470

http://stackoverflow.com/q/48352480
tagged with: ftp
tagged with: python-3.x
tagged with: ftplib
has body: I am currently working on a python script to upload text files to an FTP server but am getting the following error ConnectionRefusedError: [Errno 61] Connection refused, and for the life of me I can't seem to figure out the issue. I believe it is either an issue with the FTP server (which I can connect to with the same credentials via FileZilla). Which led me to believe it could be a coding issue, but after much research, everything looks to be done correctly. So I decided, against my better judgement, to come here on my knees asking for some help. Even if that help is only determining that the issue is with the server and not my code. That will at least give me the next place to troubleshoot. Thank you in advance for any insight you can provide! Here is the code: import ftplib def ftp_upload(ftp_obj, path, ftype='TXT'): """ A function for uploading files to an FTP server @param ftp_obj: The file transfer protocol object @param path: The path to the file to upload """ if ftype == 'TXT': with open(path) as fobj: ftp.storlines('STOR ' + path, fobj) else: with open(path, 'rb') as fobj: ftp.storbinary('STOR ' + path, fobj, 1024) if __name__ == '__main__': ftp = ftplib.FTP(host='domain or i.p. address') ftp.login(user = 'username', passwd = 'password') path = input('Please provide path to file: ') ftp_upload(ftp, path) pdf_path = '/path/to/something.pdf' ftp_upload(ftp, pdf_path, ftype='PDF') ftp.quit() Here is the complete traceback: Traceback (most recent call last): File "ftp_text_file.py", line 21, in &lt;module&gt; ftp_upload(ftp, path) File "ftp_text_file.py", line 11, in ftp_upload ftp.storlines('STOR ' + path, fobj) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ftplib.py", line 528, in storlines with self.transfercmd(cmd) as conn: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ftplib.py", line 397, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python…
downvote count: 0
tagged with: python
has title: Getting "Connection refused" when transferring a file to FTP server with ftplib in Python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48358911
score: 1
has answer: http://stackoverflow.com/a/48358911
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/55814722
favorite count: 0
type: Question

http://stackoverflow.com/comment/83843336
comment on: http://stackoverflow.com/a/48417250
type: Comment
type: AnswerComment
score: 0
has text: I modify your code and successfully draw a white black line pattern. : )

http://stackoverflow.com/comment/83846653
type: Comment
has text: This gives me clue. Do we have to add routes to allow multicasting? I was not aware regarding this. Can you guide me?
type: QuestionComment
comment on: http://stackoverflow.com/q/48427484
score: 0

http://stackoverflow.com/q/48466298
has comment: http://stackoverflow.com/comment/83926069
accepted answer: http://stackoverflow.com/a/48467368
tagged with: python
has answer: http://stackoverflow.com/a/48467368
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83926331
has answer: http://stackoverflow.com/a/48466685
type: AnsweredQuestion
tagged with: list
score: 1
has body: I have a list of (around 100) values like this list: list = ['40201020', '45102020', '25203020', '20106020', '25301020', '40402030', '20202010'] I need a dictionary that a) lists all parents for each value. The parent has one digit less (from the right): child = '40201020' parent = '4020102' this format would be ideal: dict['4020102parent'] = '40201020' b) I need all parents of parents up to one remaining digit. So parent '4020102' gets this parent: dict['4020102parent"] = '402010' and dict['402010parent"] = '40201' etc. c) I then need all last descendents for each parent as a list. By last descendant, I mean the 8 digit codes of the original list. So the digit '4' would have these codes: dict['4children'] = ['40201020', '45102020', '40402030'] or: dict['40children'] = ['40201020', '40402030']
downvote count: 1
has title: Recursive dictionary from list of hierarchical codes
possible better answer: http://stackoverflow.com/a/48473445
answer count: 4
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48466654
has answer: http://stackoverflow.com/a/48473445
upvote count: 2

http://stackoverflow.com/comment/83852470
comment on: http://stackoverflow.com/a/48430743
score: 0
type: AnswerComment
has text: @PaulH Oh wow, in that case it becomes as simple as `df['variable'].where(df['value'], 'NO')`
type: Comment

http://stackoverflow.com/comment/83864224
type: Comment
has text: No, the `Node` accepts a value at link time, not a link. Does it make more sense now, embedded in a running program?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48436441

http://stackoverflow.com/comment/83814698
type: Comment
type: QuestionComment
has text: `OWNDATA` means "this is a view of something", not that it's a view of the same thing
comment on: http://stackoverflow.com/q/48387466
score: 0

http://stackoverflow.com/q/48400760
answer count: 1
tagged with: python
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: series
type: AnsweredQuestion
has title: output where pandas Series of booleans is True
has answer: http://stackoverflow.com/a/48400777
accepted answer: http://stackoverflow.com/a/48400777
tagged with: pandas
has body: I have a Series created like this s = pd.Series({'a': False, 'b': True, 'c': False, 'd': True, 'e': False}) &gt;&gt; s a False b True c False d True e False dtype: bool Is there a way to neatly extract the names of where it is True, staying within Pandas or NumPy and without going back to ordinary Python? At the moment I am using this: sdict = s.to_dict() for item in list(sdict): if sdict[item] == True: print (item, end=" ") &gt;&gt; b d
score: 1
has comment: http://stackoverflow.com/comment/83789379

http://stackoverflow.com/a/69791056
upvote count: 5
type: Answer
has body: I had the same problem and after many researches I can assume that this works: At first, load your model and assign compile=False. compile your model with your custom loss function. retrain your model. example: def custom_loss(y_true, y_pred): nn = np.square(y_true - y_pred) return nn model = load_model("aaaa.h5", compile=False) model.compile(loss=custom_loss, optimizer='adam', metrics=custom_loss) model.fit(...)
downvote count: 0
has comment: http://stackoverflow.com/comment/134751708
answers question: http://stackoverflow.com/q/48373845
score: 5

http://stackoverflow.com/a/48340787
has body: You definitly don't need a LectureCategory model to filter Lecture queryeset on a category: class Lecture(models.Model): course = models.ForeignKey( 'Course', on_delete=models.CASCADE, default=None, related_name='lectures', null=True, ) CATEGORY_CLASSES = 0 CATEGORY_SEMINARS = 1 CATEGORY_CHOICES = ( (CATEGORY_CLASSES, "Classes"), (CATEGORY_SEMINARS, "Seminars"), ) category = models.IntegerField( choices=CATEGORY_CHOICES ) # select only classes Lecture.objects.filter(category=Lecture.CATEGORY_CLASSES) # select only seminars Lecture.objects.filter(category=Lecture.CATEGORY_SEMINARS) # display the lecture's category readable label # cf https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.get_FOO_display print(lecture.get_category_display()) Also you can use custom managers here to directly have Lecture.seminars.all() and Lecture.classes.all() Having a distinct LectureCategory model makes sense if you want to allow admins to add new categories, but then you will loose custom managers per category and actually anything that requires categories to be known in advance. In this case your LectureCategory model will need some label field: class LectureCategory(models.Model): label = models.CharField( "label", max_length=50 ) def __str__(self): return self.label class Lecture(models.Model): course = models.ForeignKey( 'Course', on_delete=models.CASCADE, default=None, related_name='lectures', null=True, ) category = models.ForeignKey( LectureCategory, related_name="lectures" on_delete=models.PROTECT, ) Then if you want to iterate on categories/lectures: for category in Category.objects.all(): print(category) for lecture in category.lectures.all(): print(lecture)
accepted answer of: http://stackoverflow.com/q/48340494
answers question: http://stackoverflow.com/q/48340494
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48343536
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48343729
tagged with: sigmoid
answer count: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/83672561
type: Question
has comment: http://stackoverflow.com/comment/83672693
tagged with: neural-network
tagged with: python
has body: For learning purposes I have a task to make a linear and sigmoid operations in tensorflow. I managed to do the linear op: def linear_op_forward(X, W): ''' linear operation''' return np.dot(X, W.T) def linear_op_backward(op, grads): ''' Linear gradient realization ''' X = op.inputs[0] W = op.inputs[1] dX = tf.multiply(grads, W) dW = tf.reduce_sum(tf.multiply(X, grads), axis = 0, keep_dims = True) return dX, dW But I'm stuck with sigmoid operation: Is that correct? def sigmoid_op_forward(X): return 1 / (1 + np.exp(-X)) And I have hard time understandind sigmoid gradient def sigmoid_op_backward(op, grads): ??? Can someone please help with this?
has answer: http://stackoverflow.com/a/48343729
has title: Sigmoid operation implementation in Tensorflow

http://stackoverflow.com/q/48378343
has answer: http://stackoverflow.com/a/48378870
has title: Barchart in matplot
tagged with: python
has body: I have a range of values in a column named GRADES Grades count A 38616 B 658 G 16041 P 7590 C 33 I want to visualize column GRADE in my_data dataset in matplot .Am getting a blank a blank subplot with the below code: fig, ax=plt.subplots() ax.set(xlabel="Grade", ylabel="Count", title="Grade Distribution") ax.bar('GRADE', align='center', data=my_data) plt.show()
has comment: http://stackoverflow.com/comment/83743893
score: 0
has comment: http://stackoverflow.com/comment/83747404
tagged with: matplotlib
tagged with: bar-chart
has comment: http://stackoverflow.com/comment/83743344
has comment: http://stackoverflow.com/comment/83743582
has answer: http://stackoverflow.com/a/48378863
type: Question
answer count: 2
type: UnansweredQuestion

python-s3fs
tags question: http://stackoverflow.com/q/48389417
type: Tag
tag name: python-s3fs

http://stackoverflow.com/a/48484756
type: Answer
has body: Seems like you are trying to input image to a classifier which takes 28x28x1 image. But the actual input image unlukcy-13.jpg is of a different shape. You need to resize the image and convert it to b/w (1 channel) image before you can pass it to the classifier. To answer specifically about the error in question, you see error because you are trying to reshape a bigger matrix (300, 210, 3) to (28,28,1) which is not possible.
downvote count: 0
answers question: http://stackoverflow.com/q/48479618
upvote count: 1
score: 1

http://stackoverflow.com/comment/83907018
type: AnswerComment
comment on: http://stackoverflow.com/a/48455826
score: 1
has text: Have a look at rolling ball baseline removal algorithms
type: Comment

twitter
tags question: http://stackoverflow.com/q/48362198
tags question: http://stackoverflow.com/q/48484007
tags question: http://stackoverflow.com/q/48459104
tags question: http://stackoverflow.com/q/48467438
tags question: http://stackoverflow.com/q/48391733
tags question: http://stackoverflow.com/q/48479115
tags question: http://stackoverflow.com/q/48461554
tag name: twitter
tags question: http://stackoverflow.com/q/48436769
tags question: http://stackoverflow.com/q/48435452
tags question: http://stackoverflow.com/q/48461510
tags question: http://stackoverflow.com/q/48355680
type: Tag
tags question: http://stackoverflow.com/q/48436964
tags question: http://stackoverflow.com/q/48392998
tags question: http://stackoverflow.com/q/48385231
tags question: http://stackoverflow.com/q/48442603
tags question: http://stackoverflow.com/q/48485387
tags question: http://stackoverflow.com/q/48487340
tags question: http://stackoverflow.com/q/48407517
tags question: http://stackoverflow.com/q/48438933

http://stackoverflow.com/comment/83852556
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48430750
has text: If OP needs just 3 statuses (but has more), then this wouldn't work.. hmm... maybe you could pre filter somehow.

http://stackoverflow.com/a/48390174
has comment: http://stackoverflow.com/comment/83797030
answers question: http://stackoverflow.com/q/48390079
has comment: http://stackoverflow.com/comment/83779344
score: 0
has body: Depending on where you are calling the unit tests from, you'll need to back up and add the main folder to the path. Try adding this to the top of your unit test file. import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) If your unit tests are two levels deep, then try this... etc import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
type: Answer

http://stackoverflow.com/comment/83834994
type: QuestionComment
comment on: http://stackoverflow.com/q/48422569
type: Comment
score: 0
has text: sorry i am not sure how to return the transformed x,is it "pca.fit(x)" , however this is an excerse, to leave the svd_solver because we will test "random" after "full" @Scratch'N'Purr

minimax
type: Tag
tags question: http://stackoverflow.com/q/48337101
tags question: http://stackoverflow.com/q/48370122
tag name: minimax

http://stackoverflow.com/comment/83923146
score: 0
type: AnswerComment
has text: Does `requests` module rely on urllib3?
type: Comment
comment on: http://stackoverflow.com/a/48461044

http://stackoverflow.com/comment/83813325
type: QuestionComment
score: 0
has text: i don't think it would matter, considering each key is unique and both lists and dicts are iterable
comment on: http://stackoverflow.com/q/48411636
type: Comment

http://stackoverflow.com/q/48341305
score: 0
answer count: 1
type: Question
tagged with: pydev
has body: I am mostly a Java developer learning Python these days. I have PyDev in Eclipse and I've properly configured, I believe. Why? Because I am able to run Python programs in my Eclipse. The problem is that it does not recognize this import of cx_Oracle (even though it runs this program successfully). The way I understand it, this cx_Oracle module is "the Python driver" (in Java terms so to speak) to the Oracle RDBMS. Why is that? Is there a way I can make this warning go away? I am using these days the Anaconda distribution on Windows 10 (but I had the same issue with the official CPython distribution so I don't think it's related to that). This is what I have: C:\&gt;python Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cx_Oracle &gt;&gt;&gt; cx_Oracle.__file__ 'C:\\Programs\\Anaconda3\\lib\\site-packages\\cx_Oracle.cp36-win_amd64.pyd' &gt;&gt;&gt;
type: UnansweredQuestion
has title: Import unresolved ( not recognized ) in PyDev
tagged with: python
has answer: http://stackoverflow.com/a/48347122

http://stackoverflow.com/comment/89389591
type: Comment
type: QuestionComment
has text: related: https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring/51203923#51203923
comment on: http://stackoverflow.com/q/48432300
score: 0

http://stackoverflow.com/comment/129629986
type: AnswerComment
score: 0
has text: I suppose pandas must have their reasons, but I also found this groupby behaviour for categorical fields very perplexing!
type: Comment
comment on: http://stackoverflow.com/a/50579578

http://stackoverflow.com/comment/112071612
type: Comment
type: AnswerComment
has text: I believe instead of `group: ''` it should be `group: None`, b/c otherwise multiple "MCQLabelCheckbox"s will always be in a group and only one of them can be checked.
score: 0
comment on: http://stackoverflow.com/a/48450380

http://stackoverflow.com/comment/83903108
type: AnswerComment
has text: @FritzFABO I have added 1) detailed explanation AND 2) a further simplified/optimized algorithm.
score: 1
comment on: http://stackoverflow.com/a/48454041
type: Comment

http://stackoverflow.com/comment/83732082
has text: The usual definition of "factor" implies that any positive integer is indeed a factor of itself. You would be better off saying that you want to output positive integers that have 4 factors, such as 6 (whose factors are 1,2,3, and 6) and 8 (whose factors are 1,2,4, and 8). Such a number is either a product of two distinct primes (such as 6==2*3) or the cube of a prime (such as 8==2**3).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48371778
score: 0

http://stackoverflow.com/comment/83802168
score: 0
comment on: http://stackoverflow.com/q/48405870
type: Comment
has text: Yeah, I'm already using it but I need to compare the ratio of the two methods
type: QuestionComment

http://stackoverflow.com/comment/83806184
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48408495
has text: I'd say use the `redirect` shortcut with the view name, it does the `reverse` for you, but that's just a convenience thing. https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#redirect

http://stackoverflow.com/a/48454574
has body: Seems like your api returns a stringify json, try: $(document).ready(function() { $.ajax({ type: "GET", url: "http://localhost:5000/api/person", success: function(data){ data=JSON.parse(data) $('.person-id').append(data.id); $('.person-first_name').append(data.first_name); $('.person-status').append('success'); }, error: function(){ $('.person-status').append('failed'); } }); }); or $(document).ready(function() { $.ajax({ type: "GET", dataType:"json", url: "http://localhost:5000/api/person", success: function(data){ $('.person-id').append(data.id); $('.person-first_name').append(data.first_name); $('.person-status').append('success'); }, error: function(){ $('.person-status').append('failed'); } }); });
answers question: http://stackoverflow.com/q/48454540
type: Answer
accepted answer of: http://stackoverflow.com/q/48454540
score: 0
has comment: http://stackoverflow.com/comment/83927756
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83903814
has comment: http://stackoverflow.com/comment/83903725

http://stackoverflow.com/q/48386740
downvote count: 0
tagged with: machine-learning
tagged with: hyperparameters
favorite count: 0
has title: Hyperopt: defining search space
has body: I'm having trouble with the logic of the search space definition. I want to search over these: The type of model to use (features_and_hours, features_only, hours_only, no_features_no_hours) The number of hidden units (output_units) regularization for the kernel matrix (type = l1, l2, or l1l2) regularization values for the kernel matrix (anywhere from 0.0 to 0.5) regularization for the activities (type = l1, l2, or l1l2) regularization values for the activities (anywhere from 0.0 to 0.5) number of epochs (num_epochs, either 1, 5, or 10) optimizer to be used (either adadelta, adam, or rmsprop) whether and how to apply attention (before, after, or none) Here's the way I've set this up, following this example (second post on page, by jacobzweig) def para_space(): space_paras = {'model_type': hp.choice('model_type', ['features_and_hours', 'features_only', 'hours_only', 'no_features_no_hours']), 'output_units': hp.uniform('output_units', 1, 10), 'kernel_reg': hp.choice('kernel_reg', [{'reg_type':'l1', 'reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}, {'reg_type':'l2','reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}, {'reg_type':'l1l2', 'reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}]), 'activity_reg': hp.choice('activity_reg', [{'reg_type':'l1', 'reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}, {'reg_type':'l2','reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}, {'reg_type':'l1l2', 'reg_vals': hp.uniform('reg_vals', 0.0, 0.5)}]), 'num_epochs': hp.choice('num_epochs', [1, 5, 10]), 'optimizer': hp.choice('optimizer', ['adadelta', 'adam', 'rmsprop']), 'attention': hp.choice('attention', ['before', 'after', 'none'])} return space_paras The error I'm getting is: Using TensorFlow backend. Traceback (most recent call last): File "Jan22Model1.py", line 374, in &lt;module&gt; best = fmin(lstm_model_1, params, algo=tpe.suggest, max_evals=5, trials=trials) File "/user/pkgs/anaconda2/lib/python2.7/site-packages/hyperopt/fmin.py", line 307, in fmin return_argmin=return_argmin, File "/user/pkgs/anacon…
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48426066
has answer: http://stackoverflow.com/a/48426066
tagged with: python
has comment: http://stackoverflow.com/comment/83762860
type: AnsweredQuestion
upvote count: 3
answer count: 1

http://stackoverflow.com/q/48390207
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: mysql
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
tagged with: sqlalchemy-migrate
favorite count: 0
has body: I have a website running with a mysql database using the sql-alchemy package that has suddenly broken. I have done some research and found that the expected issue is that the newest sql-alchemy update is handing flask-admin one more value than expected from "cls, key = identity_key(instance=obj)" Source The suggested fix is to edit the files to accept a third item but I am unable to do this with the permissions I have on my environment. Another answer links to a repo on github but I cannot figure out how that helps me. I'm very new to this and I don't know if I am supposed to clone the repo or how exactly to do that if I am. Any help is appreciated! Here is the error dump 2018-01-22 20:01:59,593: [2018-01-22 20:01:59,592] ERROR in app: Exception on /reservation/add [GET] 2018-01-22 20:01:59,594: Traceback (most recent call last): 2018-01-22 20:01:59,594: File "fakepath/flask/app.py", line 1982, in wsgi_app 2018-01-22 20:01:59,594: response = self.full_dispatch_request()2018-01-22 20:01:59,594: File "fakepath/flask/app.py", line 1614, in full_dispatch_request 2018-01-22 20:01:59,594: rv = self.handle_user_exception(e) 2018-01-22 20:01:59,595: File "fakepath/flask/app.py", line 1517, in handle_user_exception2018-01-22 20:01:59,595: reraise(exc_type, exc_value, tb)2018-01-22 20:01:59,595: File "fakepath/flask/_compat.py", line 33, in reraise 2018-01-22 20:01:59,595: raise value2018-01-22 20:01:59,595: File "fakepath/flask/app.py", line 1612, in full_dispatch_request 2018-01-22 20:01:59,595: rv = self.dispatch_request() 2018-01-22 20:01:59,596: File "fakepath/flask/app.py", line 1598, in dispatch_request2018-01-22 20:01:59,596: return self.view_functionsrule.endpoint 2018-01-22 20:01:59,596: File "fakepath/flask_login/utils.py", line 261, in decorated_view 2018-01-22 20:01:59,596: return func(*args, **kwargs) 2018-01-22 20:01:59,597: File "/home/apoalphagammawebmaster/inventory/app/auth/views.py", line 248, in add_reservation 2018-01-22 20:01:59,597: form=form, title='A…
type: Question
accepted answer: http://stackoverflow.com/a/48451165
tagged with: python
has answer: http://stackoverflow.com/a/51868022
possible better answer: http://stackoverflow.com/a/51868022
has title: SQL-alchemy: ValueError too many values to unpack?
has answer: http://stackoverflow.com/a/48451165

http://stackoverflow.com/q/48443753
tagged with: python
tagged with: class
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48443807
downvote count: 0
answer count: 1
has title: Find min in list - python
has body: I'm doing a kind of Dijkstra as homework. This is how the class Vertex looks. class Vertex: def __init__(self, id, name): self.id = id self.name = name self.minDistance = float('inf') self.previousVertex = None In other class I have a list of unvisited vertexes and I want to find a minimum distance, so I can recursively work with the Vertex having that minDistance. e.g. unvisited = [Vertex1, Vertex2,...] Tried to do it with for cycle, but by iterating it and saving it to a variable didn't work as it saved only the last value. How can I find a min value of a class atribute in list?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48443807

http://stackoverflow.com/comment/83875252
has text: "Questions on professional server- or networking-related infrastructure administration are off-topic for Stack Overflow unless they directly involve programming or programming tools. You may be able to get help on Server Fault."
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48441343
type: AnswerComment

http://stackoverflow.com/q/48362085
has answer: http://stackoverflow.com/a/48362169
answer count: 4
has answer: http://stackoverflow.com/a/48362158
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83711614
downvote count: 2
has answer: http://stackoverflow.com/a/48362338
favorite count: 0
has answer: http://stackoverflow.com/a/48362102
type: Question
has title: Python3: How do I save a text file with a name from an input?
upvote count: 3
has body: This is the line of code: with open('directory/filename.txt', 'w') as output: How do I make filename = input("Write the output file's name :") Work for the code above ?
tagged with: python
has comment: http://stackoverflow.com/comment/83711201

http://stackoverflow.com/q/48425556
favorite count: 0
has answer: http://stackoverflow.com/a/48425637
type: Question
has title: python pandas: count no of users falls in the both categories
has body: I have a data frame of the following format user category 1 A 1 B 1 A 2 B 3 B 2 B Now I am trying to count how many unique users are in each category and in both categories. So for above table I have A=1, B= 3 and A&amp;B = 1 The following code gives me no of users in each category: df.groupby(['category',]).count() But this is not what exactly I am looking for. Any help or clue will be appreciated.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83841073
has comment: http://stackoverflow.com/comment/83851349
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83840959
answer count: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48425769
has answer: http://stackoverflow.com/a/48426019

http://stackoverflow.com/q/48484333
tagged with: python
linked to: http://stackoverflow.com/q/48197234
score: 0
has comment: http://stackoverflow.com/comment/83961342
tagged with: pandas
has title: Pandas: Add rows to a dataframe using one of the columns
tagged with: dataframe
has body: My dataframe looks like following: col1 col2 1 [1,2,3] 2 [1,2] 3 [1] I want to exapnd the dataframe on the basis of col2 such that the values of other columns gets copied in the new rows as following. col1 col2 1 1 1 2 1 3 2 1 2 2 3 1 I've scoured prior questions for something to get me started, but no luck. Any help is appreciated.
duplicate of: http://stackoverflow.com/q/48197234
has comment: http://stackoverflow.com/comment/83961402
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48483979
upvote count: 1
has title: Cannot find/create new file in Docker
has comment: http://stackoverflow.com/comment/83985779
favorite count: 0
has body: I couldn't find any information or a way to do this, and as I am new to Docker, I thought here would be a good place to ask. I have python code, where I take a .jpg image file, convert it to base64, then decode the base64 and create a .png image file with that data. It's been working outside of Docker. Here's the basics of the code: import base64 from PIL import Image with open("testImg.jpg", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) decoded_string = base64.b64decode(encoded_string) newImg = open("newImg.png", "w+") newImg.write(str(decoded_string)) image_file.close() newImg.close() Image.open('newImg.png').show() this creates a new png image and even opens it for me. When I run it in Docker, everything works great, but the file won't open, nor does it seem to be created, because it's not located in the project folder. The Image.open() part is the least of my worries, I assume it's not opening because its being run inside of Docker or something of the sort. My real question is, where is the newImg.png file? if you'd like to see my Dockerfile or code $ docker pull chriscrutt/heyyo
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83976181
tagged with: python
tagged with: type-conversion
tagged with: docker
has comment: http://stackoverflow.com/comment/83962074
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/q/48411251
has answer: http://stackoverflow.com/a/48411363
tagged with: .net
upvote count: 1
tagged with: python
downvote count: 1
has title: Difference between C# and Python UDP Examples
tagged with: udp
has body: You can find this C# UDP example in various forms in many places. UdpClient udpc = new UdpClient(55001); IPEndPoint iep = new System.Net.IPEndPoint(IPAddress.Parse("192.168.1.100"), 55001); byte[] data = udpc.Receive(ref iep); string req = Encoding.ASCII.GetString(data); When I run portqry, I find that it responds to 127.0.0.1, but not 192.168.1.100. PortQry.exe -n 192.168.1.100 -p udp -e 55001 I tried this also using the raw socket interface. I could only get it to work if I bind to 127.0.0.1 and PortQry the same. IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 55001); Socket sock = new Socket(ipe.AddressFamily, SocketType.Dgram, ProtocolType.Udp); byte[] buffer = new byte[1024]; sock.Bind(ipe); sock.Receive(buffer); string req = Encoding.ASCII.GetString(buffer); When I run the Python UDP receiver example using port 192.168.1.100, I find it responds to 192.168.1.100, but not 127.0.0.1. On another machine, I have a route added so that traffic to 192.168.1.100 goes out to the router and then returns. In wireshark, using the Python server, I see a packet go out to the router and one come back when I PortQry 192.168.1.100. Doing the same with the C# example, the packet does not return. What is different? The wireless and VPN adapters are off; so, there should only be one interface being used. I would like to have the behavior I'm seeing in Python in C# so I can see the traffic from WinPcap. I have some additional info. I've tried this with the underlying winsock library using this exact code except to change the IP and port. The problem is the same. I can receive only on the loopback. I've verified the port is being listened to on 192.168.100 using netstat. I've also discovered the python receive example will accept UDP traffic even when I physically disconnect Ethernet and ipconfig shows no IP at all.
answer count: 1
has comment: http://stackoverflow.com/comment/83812396
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83812341
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83840865
comment on: http://stackoverflow.com/q/48424622
type: Comment
score: 0
has text: You completely lack the coordinates of the locations where to plot the data. E.g. spain would be located at 40° North and 4° West. Without that data matplotlib wouldn't know where to plot the points.
type: QuestionComment

http://stackoverflow.com/q/48409042
downvote count: 0
has answer: http://stackoverflow.com/a/48409079
upvote count: 1
tagged with: python
has body: See the program given below: # Store input numbers num1 = input('Enter first number: ') num2 = input('Enter second number: ') # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) Now can't we perform the sum operation inside the print statement? I mean I know I can do this a=2 b=5 print('The sum of', a ,' and ',b,' is',(a+b)) Like I don't need to create another sum named variable in this way. But can we perform the same thing with positional formatting?
has comment: http://stackoverflow.com/comment/83807830
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: formatting
has comment: http://stackoverflow.com/comment/83807808
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83807596
accepted answer: http://stackoverflow.com/a/48409079
has title: Can we perform arithmetic operation in positional formatting?

http://stackoverflow.com/q/48393431
has body: Let say we have a 2-D array like this: &gt;&gt;&gt; a array([[1, 1, 2], [0, 2, 2], [2, 2, 0], [0, 2, 0]]) For each line I want to replace each element by the maximum of the 2 others in the same line. I've found how to do it for each column separately, using numpy.amax and an identity array, like this: &gt;&gt;&gt; np.amax(a*(1-np.eye(3)[0]), axis=1) array([ 2., 2., 2., 2.]) &gt;&gt;&gt; np.amax(a*(1-np.eye(3)[1]), axis=1) array([ 2., 2., 2., 0.]) &gt;&gt;&gt; np.amax(a*(1-np.eye(3)[2]), axis=1) array([ 1., 2., 2., 2.]) But I would like to know if there is a way to avoid a for loop and get directly the result which in this case should look like this: &gt;&gt;&gt; numpy_magic(a) array([[2, 2, 1], [2, 2, 2], [2, 2, 2], [2, 0, 2]]) Edit: after a few hours playing in the console, I've finally come up with the solution I was looking for. Be ready for some mind blowing one line code: np.amax(a[[range(a.shape[0])]*a.shape[1],:][(np.eye(a.shape[1]) == 0)[:,[range(a.shape[1])*a.shape[0]]].reshape(a.shape[1],a.shape[0],a.shape[1])].reshape((a.shape[1],a.shape[0],a.shape[1]-1)),axis=2).transpose() array([[2, 2, 1], [2, 2, 2], [2, 2, 2], [2, 0, 2]]) Edit2: Paul has suggested a much more readable and faster alternative which is: np.max(a[:, np.where(~np.identity(a.shape[1], dtype=bool))[1].reshape(a.shape[1], -1)], axis=-1) After timing these 3 alternatives, both Paul's solutions are 4 times faster in every contexts (I've benchmarked for 2, 3 and 4 columns with 200 rows). Congratulations for these amazing pieces of code! Last Edit (sorry): after replacing np.identity with np.eye which is faster, we now have the fastest and most concise solution: np.max(a[:, np.where(~np.eye(a.shape[1], dtype=bool))[1].reshape(a.shape[1], -1)], axis=-1)
answer count: 3
accepted answer: http://stackoverflow.com/a/48393850
possible better answer: http://stackoverflow.com/a/48393727
upvote count: 3
has answer: http://stackoverflow.com/a/48393850
downvote count: 0
has answer: http://stackoverflow.com/a/48393727
has answer: http://stackoverflow.com/a/48394000
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83816424
score: 3
has comment: http://stackoverflow.com/comment/83800049
has comment: http://stackoverflow.com/comment/83822398
has title: Numpy: replace each element in a row by the maximum of other elements in the same row
tagged with: python
tagged with: numpy

http://stackoverflow.com/q/48478848
has title: Conflicting default and custom paths for nltk_data
favorite count: 0
has body: I understand that there should be two different directories for nltk_data: one for the default download and another one for the user's custom files. In my macOS setup I have manually checked that all the default data packages are in /usr/local/share/nltk_data, and that is the outcome of next(p for p in nltk.data.path if os.path.exists(p)). However, when I try to download another default package it doesn't go to that directory, but to /Users/macbook/nltk_data, where I understant that only my custom files should be. And testing the instalation for the default nltk.corpus.brown.words() fails because it looks for it in my custom path: 'No such file or directory: '/Users/macbook/nltk_data/corpora/brown/ca01' I am using Python 3.6.3, conda 4.4.8, and the outcome of print(nltk.data.path)is ['/Users/macbook/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data', '/Users/macbook/anaconda3/nltk_data', '/Users/macbook/anaconda3/lib/nltk_data', '/usr/local/share/nltk_data']
type: Question
has answer: http://stackoverflow.com/a/48480194
tagged with: python
type: UnansweredQuestion
tagged with: macos
score: 2
upvote count: 2
tagged with: nltk
downvote count: 0
answer count: 1

group-by
tags question: http://stackoverflow.com/q/48335265
tags question: http://stackoverflow.com/q/48366962
tags question: http://stackoverflow.com/q/48373962
tags question: http://stackoverflow.com/q/48347497
tags question: http://stackoverflow.com/q/48351274
tag name: group-by
tags question: http://stackoverflow.com/q/48373984
tags question: http://stackoverflow.com/q/48388616
tags question: http://stackoverflow.com/q/48387268
tags question: http://stackoverflow.com/q/48426455
tags question: http://stackoverflow.com/q/48471648
tags question: http://stackoverflow.com/q/48345415
type: Tag
tags question: http://stackoverflow.com/q/48351811

http://stackoverflow.com/q/48436337
favorite count: 0
type: Question
tagged with: split
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83864309
tagged with: python
has answer: http://stackoverflow.com/a/48436938
tagged with: row
downvote count: 0
tagged with: pandas
has title: separating a row python pandas
score: 1
upvote count: 1
answer count: 1
has body: I have a table looks like this : username email name phone1 phone2 1920 abc@gmail.com TSteve/Nancy a b I want this to be : username email first_name last_name phone1 phone2 1920 abc@gmail.com Steve T a 1920-2 Nancy T b this table is in csv format. For summary: 1) split "name" column to "first_name" and "last_name" and takeout and move the very first letter "T" in this case to "last_name" and separate the row with two names "Steve" and "Nancy". Steve/Nancy will be splitted based on "/" and remove the slash. 2) phone 1 stays but phone 2 will be moved to the next row. (I will merge phone1 and 2 later) 3) A new username one the second row will be the same number with "-2" at the end. I spent 3 days trying several things but failed. It will be very helpful for me to study and learn if you guys can guide me through this steps. Thank you

http://stackoverflow.com/a/48422852
type: Answer
answers question: http://stackoverflow.com/q/48409750
score: 0
has body: Your code may be not correct. For each output you test all inputs: for i in range(4): if GPIO.input(ROW[i]) == 0: Check if for sure exactly one proper input is active. If not, you have to rewrite it. Moreover, the number of * should depend on external counter j, not i (my mistake in the comment, sorry): mylcd.lcd_display_string((j+1) * "*", 2, 0)

http://stackoverflow.com/comment/83701925
score: 1
comment on: http://stackoverflow.com/a/48353182
has text: You're right, I meant to say ``a[1:, 1:]``. My larger point is that solving a specific simplified example in a way that doesn't answer the more general question being asked is not particularly helpful.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48345810
answers question: http://stackoverflow.com/q/48345740
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83677338
has body: Since you have to return something anyway, why not just return the evaluated Boolean result. &gt;&gt;&gt; f=lambda x: x % 2 == 0 &gt;&gt;&gt; f(2) True &gt;&gt;&gt; f(3) False &gt;&gt;&gt; If you are adamant about not returing anything for False case, you can do it in such a way: &gt;&gt;&gt; f=lambda x: x % 2 == 0 or None &gt;&gt;&gt; f(2) True &gt;&gt;&gt; f(3) &gt;&gt;&gt;
type: Answer
has comment: http://stackoverflow.com/comment/83677376

http://stackoverflow.com/comment/83747531
comment on: http://stackoverflow.com/q/48380508
type: Comment
type: QuestionComment
score: 1
has text: Try `WorkingDirectory=/home/muiruri_samuel/webapp/revamp`

http://stackoverflow.com/comment/83677791
type: AnswerComment
has text: @Hippolippo Much better!
type: Comment
comment on: http://stackoverflow.com/a/48345836
score: 0

http://stackoverflow.com/comment/83794365
comment on: http://stackoverflow.com/a/48381421
type: AnswerComment
has text: You were right server was not installed, we need to install rethinkdb server prior to the driver installation. I followed the instruction using following link and installed server and it resolved the issue. https://www.rethinkdb.com/docs/install/ubuntu/
type: Comment
score: 0

http://stackoverflow.com/q/48376664
tagged with: python
tagged with: bottle
has body: I use bottle and uwsgi. uwsgi config: [uwsgi] http-socket = :8087 processes = 4 workers=4 master = true file=app.py app.py: import bottle import os application = bottle.app() @bottle.route('/test') def test(): os.system('./restart_ssdb.sh') if __name__=='__main__': bottle.run() restart_ssdb.sh(just restart a service and do not care about what the service is): ./ssdb-server -d ssdb.conf -s restart Then I start the uwsgi and it works well. Then I access url:127.0.0.1/test The image shows that one of uwsgi processes becomes ssdb server. Then I stop uwsgi: The port 8087 belongs to ssdb. It causes uwsgi server to be unable to restart because the port is used. What causes the problem in Figure 2 to appear? I just want to execute shell(restart ssdb server), But it must be guaranteed not to affect the uwsgi server, what can I do?
tagged with: uwsgi
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48456899
answer count: 1
type: Question
score: 0
has title: uwsgi subprocess create a new process,the socket close wait

http://stackoverflow.com/a/48404663
type: Answer
has body: Or, use reindex In [594]: df1.reindex(columns=df2.columns) Out[594]: b c 0 2 3 1 6 7 Also as In [595]: df1.reindex(df2.columns, axis=1) Out[595]: b c 0 2 3 1 6 7
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48404453
score: 2

http://stackoverflow.com/a/48442400
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48442260
downvote count: 0
has body: You can this: [f.split(".")[0] for f in os.listdir(path) if f.endswith('.txt')]
upvote count: 1

http://stackoverflow.com/q/48374024
tagged with: raspberry-pi
tagged with: automation
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83735795
has body: so, i've been trying to make an automated program that do everything i need to open yowsup(a whatapp robot). i need a programe that will open terminal and start yowsup(it is a code that when its open in terminal it start a consle(PHOTO1). what i've done so far is a very very basci code in python to put a command in terminal to start yowsup,but when yousup is started (after "os.system("yowsup-cli demos....")) the resp of my code does not do what i was expecting(i was expecting to write "/L" in yowsup console) but it doeen't. what happen is: it starts normally yowsup console and it stays there, waiting for me to write manually a command(the same as 1.PHOTO1/2), and when i press "CTRL"+ c to close yowsups's console it turns back in to linux terminal, and in that linux terminal it asks for an input(SEE PHOTHO 3 PIC3)because what realy is happening is it runs the command to open yowsup console and it runs the command input in terminal BUT since the terminal is ocupped with yowsup's console it waits untill i close it to run the rest of my code, i want a solution that will permit me to write in yowsup's console, not to wait until the console is gone and then write the code in terminal. I hope everything is clear now import os import subprocess as sub os.system ("cd yowsup") os.system ("yowsup-cli demos -y -c /home/pi/yowsup/d.conf") a = raw_input('numero: ') m = raw_imput('mensagem: ') os.system("/L") os.system("/message send", a ,"m") PS. I'm running python 2.7.6 in a raspberry pi3(raspian, linux)
score: 2
answer count: 0
favorite count: 0
type: Question
has title: how to control a console oppened in terminal using python
has comment: http://stackoverflow.com/comment/83735280

http://stackoverflow.com/comment/83935349
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48468945
type: AnswerComment
has text: It does not work. Spyder is not in in drop down menu in step 4. I even did: right clicked Python file > open with > other , and then, enable > All applications. Spyder is still in light gray. Does not work!

http://stackoverflow.com/comment/83962216
comment on: http://stackoverflow.com/a/48484782
has text: You can set the `step` value of range to `6`, and then the code will become much neater. Also, your `lambda` function is unnecessary, it *literally* carries out `str()` so just do: `map(str, ...)`!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48440837
downvote count: 0
has body: To clear the content of a frame, the idea is to destroy all its children. All the children of the frame are stored in the dictionnary frame.children (under the form {name: widget}) children = list(frame.children.values()) for child in children: child.destroy() You can use this to clear the content of separator 2,3 &amp; 6 at the start of get(). separator2 is only defined locally inside get() which is inconsistent with the definition of the other frames and means that you create a new separator2 each time you run get(). So I have moved it outside the function, with the other frames. Here is the modified code: from tkinter import * import matplotlib import pandas as pd from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt from wordcloud import WordCloud from matplotlib.figure import Figure master = Tk() separator3 = Frame(master, height=618,width=180, bd=4, bg='dodgerblue') separator6 = Frame(master, height=250,width=240, bd=4, bg='dodgerblue') separator1 = Frame(master, height=100,width=100, bd=1,bg='dodgerblue') separator2 = Frame(master, height=150, width=280, bd=4, bg='dodgerblue') # define separator2 outside get() def get(): # start by clearing frames children = list(separator6.children.values()) + list(separator3.children.values()) + list(separator2.children.values()) for child in children: child.destroy() Disp_pos =10 Disp_neg =-12 w = Scale(separator6, from_=10, to=0,orient=VERTICAL) w.set(Disp_pos) w.pack(anchor=CENTER,side=TOP,ipady=10,ipadx=10) Label1 = Label(separator6, text="") Label1.pack(anchor=CENTER, side=TOP) f3 = Figure(figsize=(2, 3), dpi=100) canvas2 = FigureCanvasTkAgg(f3, master=separator3) Label1 = Label(separator3,text=" WORD CLOUD ") Label1.pack(anchor=CENTER, side=TOP) ax3 = f3.add_subplot(111) text = 'sample' print(type(text)) ax3.set_wordcloud = WordCloud().generate(text) ax3.imshow(ax3.set_wordcloud, interpolation='bilinear') ax3.axis("off") canvas2.show() canvas2.get_tk_widget().pack( side=BOTTOM…
answers question: http://stackoverflow.com/q/48437710
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/48437710
type: AcceptedAnswer

http://stackoverflow.com/comment/83672881
type: AnswerComment
comment on: http://stackoverflow.com/a/48337718
has text: This can help you as well. (https://stackoverflow.com/questions/7391945/how-do-i-read-image-data-from-a-url-in-python)
type: Comment
score: 0

http://stackoverflow.com/comment/83744600
comment on: http://stackoverflow.com/q/48377010
score: 0
type: Comment
type: QuestionComment
has text: @Thank you very much for your reply.I used pandas and numpy to deal with data, i found that pandas need more time than numpy. I don't know if it's normal. I will read what you suggest. Thank you.

http://stackoverflow.com/q/48411341
has comment: http://stackoverflow.com/comment/83812478
favorite count: 0
has answer: http://stackoverflow.com/a/48411798
type: Question
has comment: http://stackoverflow.com/comment/83812581
accepted answer: http://stackoverflow.com/a/48411798
has comment: http://stackoverflow.com/comment/83813298
has title: How to un-categoricalize a column in pandas
upvote count: 1
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
has body: I have a Dataframe in Pandas. For sorting purposes, one of the columns is created with: df['segVar'] = df['segVar'].astype('category', categories=segVars, ordered=True) in normal operation, it's saved to a csv with to_csv and then read in in a later stage. In this mode, once it's read in, segVar is not a category. this is fine, and the functionality I want. For unit testing purposes, however, I'm doing all of this without saving it to a file, and so the segVar column is still a category. This breaks the code, because I do things like df['segVar'].unique() which doesn't work on categoricals. Basically, I want to not change the column, except that instead of being a categorical, I want it to be the original values.
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48409266
score: 0
has title: Detecting Windows System sounds with Python
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/83808227
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48447737
tagged with: python
has comment: http://stackoverflow.com/comment/83807963
has body: I have a python script that pulls the cell values from a spreadsheet and inputs it into a program. Problem is that if there is an error that occurs when the information is being input (duplicate value, navigational error, sql error, etc) the script will not recognize that there is an error and just keep running. I'd like to find a way to have the script recognize when these errors occur and hold the script or take another action. All of the errors vary between each other, but all of them produce a prompt window specifying the error code, the description, and they it plays the default "Windows Background.wav" sound in C:\Windows\media when it. The only thing that remains consistent through all possible errors is that sound so I thought I could have Python store that sound as a variable and constantly check to see if it has been triggered. I saw modules like pyaudio, audioread, and winsound, but none of them seemed to have any way to read the wav file, store it as a variable, and then monitor the output of the system sounds on the volume mixer to check for it. Hoping there is a solution for this or possibly another way of going about checking for any errors that might occur with the program the script interacts with.
tagged with: audio

http://stackoverflow.com/a/48480133
accepted answer of: http://stackoverflow.com/q/48480053
type: Answer
answers question: http://stackoverflow.com/q/48480053
has body: As pointed out by @sascha , I just need to apply the function to the whole array: import numpy as np import time # Some random data x = np.random.rand(5,32,32,3)*255 x = x.astype(int) # Defining some function def normalize(x, a=0, b=1, x_min=0, x_max=255): return a + (x - x_min)*(b - a)/(x_max-x_min) ## Start timer start_time = time.time() # ---------------------IMPLEMENTATION--------------------- # Apply Normalize function to each element in the array x = normalize(x) #_________________________________________________________ # Stop timer and show time in milliseconds elapsed_time = time.time() - start_time print("Time [ms] = " + str(elapsed_time*1000))
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/83843909
score: 0
has text: The code you are calling should be part of the question, not just in the comments.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48424813

http://stackoverflow.com/comment/83888499
type: Comment
has text: What is the question?
type: AnswerComment
comment on: http://stackoverflow.com/a/48407456
score: 0

http://stackoverflow.com/comment/83951781
score: 0
comment on: http://stackoverflow.com/q/48479353
type: Comment
has text: No, because the `if` is a *filter*. Include this item or don't include it, a boolean choice.
type: QuestionComment

http://stackoverflow.com/comment/83955001
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48480875
has text: I didn't debug your source. I just showed you the correct way to use the class.

http://stackoverflow.com/q/48368901
has comment: http://stackoverflow.com/comment/83725286
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83724529
has comment: http://stackoverflow.com/comment/83726222
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83728782
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/83725226
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83732875
has answer: http://stackoverflow.com/a/48391815
has body: I'm writing a program in python 2.7 with PyQt4 and i'm having the following problem with the scrollArea widget. As seen in the images below, the scrollbar is not working correctly. Its not moving the graph at all. The scrollbar in the middle is showing the same thing as in the original position. scroll bar at original position scroll bar almost in the middle I've already try the program in others computers with differents SO and got the same result, which means the problem is the code. The program is too long so i'll just show where the scroll area widget is being called. class graphWidget(QtGui.QWidget): def __init__(self): super(graphWidget, self).__init__() self.graph=CreateGraphFromInputs.createGraph() self.slider=QtGui.QSlider(QtCore.Qt.Vertical) self.setup() def setup(self): #slider setup# self.slider.setMinimum(1) self.slider.setMaximum(20) self.slider.setValue(1) self.slider.setTickPosition(QtGui.QSlider.TicksBelow) self.slider.setTickInterval(1) self.slider.valueChanged.connect(self.sliderValueChange) self.zoomLabel=QtGui.QLabel(str(self.slider.value())+"x") grid=QtGui.QGridLayout() grid.addWidget(QtGui.QLabel(""),0,0) grid.addWidget(QtGui.QLabel("Zoom"),1,1) grid.addWidget(self.slider,2,1) grid.addWidget(self.zoomLabel,3,1) grid.addWidget(QtGui.QLabel(""),4,0) grid.setRowMinimumHeight(0,55) grid.setRowMinimumHeight(4,55) grid.setSpacing(0) #slider setup# #scrollArea setup# scrollArea=QtGui.QScrollArea() scrollArea.setWidgetResizable(False) scrollArea.setWidget(self.graph) scrollArea.setMaximumHeight(270) scrollArea.setMinimumWidth(600) #scrollarea setup# #layout setup hbox = QtGui.QHBoxLayout() hbox.addStretch(0) hbox.setSpacing(5) hbox.addWidget(scrollArea) hbox.addLayout(grid) self.setLayout(hbox) #layout setup# def sliderValueChange(self): if self.graph.lista!=[]: self.graph.setSize(50+(len(self.graph.lista)/float(self.slider.value()))) self.graph.setSizeDivision(1/float(self.slider.value())) self.graph.setZoom(50*self.slider.value()) self.zoomLabel.set…
has comment: http://stackoverflow.com/comment/83725240
tagged with: python-2.7
tagged with: pyqt
has title: PyQt4 ScrollArea widget issues: Scrollbar not working correctly
upvote count: 0

http://stackoverflow.com/comment/83836113
comment on: http://stackoverflow.com/q/48417561
score: 0
type: Comment
type: QuestionComment
has text: There is a `split_on_silence` function, did you try it with that? Use some little silence length like 100ms.

http://stackoverflow.com/comment/83974838
type: AnswerComment
score: 0
has text: @user8423460 I just downloaded the code and it worked for me. The only place an indent is required is line 21 inside the `for` loop. Which line gave you the error?
type: Comment
comment on: http://stackoverflow.com/a/48484816

http://stackoverflow.com/q/48443999
tagged with: word2vec
has answer: http://stackoverflow.com/a/49185832
has body: I am trying to continue training on an existing model, model = gensim.models.Word2Vec.load('model/corpus.zhwiki.word.model') more_sentences = 'Advanced', 'users', 'can', 'load', 'a', 'model', 'and', 'continue', 'training', 'it', 'with', 'more', 'sentences' model.build_vocab(more_sentences, update=True) model.train(more_sentences, total_examples=model.corpus_count, epochs=model.iter) but I got an error with the last line: AttributeError: 'Word2Vec' object has no attribute 'compute_loss' Some posts said it's caused by using a earlier version of gensim, and I have tried to add this after loading the existing model and before train(). model.compute_loss = False After that, it didn't give me the AttributeError, but the output of model.train() is 0, and model didn't trained with new sentences. How to solve this problem?
favorite count: 0
type: Question
has title: gensim - Word2vec continue training on existing model - AttributeError: 'Word2Vec' object has no attribute 'compute_loss'
tagged with: python
has answer: http://stackoverflow.com/a/48472166
tagged with: gensim
upvote count: 6
tagged with: nlp
answer count: 2
type: UnansweredQuestion
score: 6
downvote count: 0

http://stackoverflow.com/comment/83650439
has text: Don't use `exec`. Use a real data structure, like a list or a dict.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48332230

http://stackoverflow.com/q/48370708
upvote count: 13
has title: Best way to subset a pandas dataframe
type: Question
answer count: 2
downvote count: 2
score: 11
possible better answer: http://stackoverflow.com/a/48372370
tagged with: data-science
has comment: http://stackoverflow.com/comment/83728360
favorite count: 0
has answer: http://stackoverflow.com/a/48372370
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83728144
accepted answer: http://stackoverflow.com/a/48371587
has body: Hey I'm new to Pandas and I just came across df.query(). Why people would use df.query() when you can directly filter your Dataframes using brackets notation ? The official pandas tutorial also seems to prefer the latter approach. With brackets notation : df[df['age'] &lt;= 21] With pandas query method : df.query('age &lt;= 21') Besides some of the stylistic or flexibility differences that have been mentioned, is one canonically preferred - namely for performance of operations on large dataframes?
tagged with: pandas
has comment: http://stackoverflow.com/comment/83728284
has answer: http://stackoverflow.com/a/48371587
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48402107
favorite count: 0
has comment: http://stackoverflow.com/comment/83797794
score: 2
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/83792706
has body: my idea is that i want to make car with sensors for obstacle avoidance using raspberry pi and Python as programming language. Thus i want to make a separate thread for sensor in way to keep monitoring the sensor and when it detect obstacle it should directly interrupt the main program( which give the movement command to the motor), and let the car stop İf you can give me code example or just simulation with virtual sensor. Or if there is a better practice please advice.
tagged with: python
has title: How to program the sensor to interrupt the main thread or program in python
type: Question
upvote count: 2
tagged with: raspberry-pi
tagged with: robotics
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83795020
tagged with: multithreading
downvote count: 0
has comment: http://stackoverflow.com/comment/83797254
answer count: 1
has answer: http://stackoverflow.com/a/48598605

http://stackoverflow.com/q/48482899
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48483600
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has title: Dropbox API with Django - Authentication
tagged with: dropbox-api
has body: I'm trying to learn Dropbox API and want to use OAuth 2 for authorization. I'm getting following error: dropbox_auth_start() missing 1 required positional argument: 'request' Here is my code: Views.py from dropbox import DropboxOAuth2Flow from django.shortcuts import redirect def get_dropbox_auth_flow(web_app_session): redirect_uri = "https://www.my-dummy-url.com" APP_KEY = 'my-app-key' APP_SECRET = 'my-app-secret' return DropboxOAuth2Flow( APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") def dropbox_auth_start(web_app_session, request): if request.method == 'GET': authorize_url = get_dropbox_auth_flow(web_app_session).start() return redirect(authorize_url) urls.py urlpatterns = [ path('dropbox/', views.dropbox_auth_start, name='dropbox') ]
has comment: http://stackoverflow.com/comment/84003134
score: 1
has answer: http://stackoverflow.com/a/51469359
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/83976422
comment on: http://stackoverflow.com/a/48467516
type: Comment
type: AnswerComment
has text: "hides a loop": hides a python loop, or hides a machine language loop? AFAIK, a map operation essentially must boil down to "1) operator, memory increment, check for end, if not, goto 1)"
score: 1

scikit-learn
tags question: http://stackoverflow.com/q/48429743
tags question: http://stackoverflow.com/q/48474442
tags question: http://stackoverflow.com/q/48425201
tags question: http://stackoverflow.com/q/48401148
tags question: http://stackoverflow.com/q/48439793
tags question: http://stackoverflow.com/q/48335367
tags question: http://stackoverflow.com/q/48413264
tags question: http://stackoverflow.com/q/48377296
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48426683
tags question: http://stackoverflow.com/q/48402337
tags question: http://stackoverflow.com/q/48403239
tags question: http://stackoverflow.com/q/48434391
tags question: http://stackoverflow.com/q/48482774
tags question: http://stackoverflow.com/q/48377317
tags question: http://stackoverflow.com/q/48348350
tags question: http://stackoverflow.com/q/48390268
tags question: http://stackoverflow.com/q/48459269
type: Tag
tags question: http://stackoverflow.com/q/48375243
tags question: http://stackoverflow.com/q/48373710
tags question: http://stackoverflow.com/q/48417867
tags question: http://stackoverflow.com/q/48382289
tags question: http://stackoverflow.com/q/48427922
tags question: http://stackoverflow.com/q/48424084
tags question: http://stackoverflow.com/q/48450932
tags question: http://stackoverflow.com/q/48461297
tags question: http://stackoverflow.com/q/48437889
tags question: http://stackoverflow.com/q/48333900
tags question: http://stackoverflow.com/q/48447686
tags question: http://stackoverflow.com/q/48447841
tags question: http://stackoverflow.com/q/48470539
tags question: http://stackoverflow.com/q/48468115
tags question: http://stackoverflow.com/q/48390601
tags question: http://stackoverflow.com/q/48360972
tags question: http://stackoverflow.com/q/48419119
tags question: http://stackoverflow.com/q/48389166
tags question: http://stackoverflow.com/q/48478653
tags question: http://stackoverflow.com/q/48434960
tags question: http://stackoverflow.com/q/48450566
tags question: http://stackoverflow.com/q/48332964
tags question: http://stackoverflow.com/q/48473574
tags question: http://stackoverflow.com/q/48480570
tags question: http://stackoverflow.com/q/48370150
tags question: http://stackoverflow.com/q/48413907
tags question: http://stackoverflow.com/q/48467522
tags question: http://stackoverflow.com/q/48333819
tags question: http://stackoverflow.com/q/48461443
tags question: http://stackoverflow.com/q/48406251
tags question: http://stackoverflow.com/q/48460455
tags question: http://stackoverflow.com/q/48481134
tags question: http://stackoverflow.com/q/48425128
tags question: http://stackoverflow.com/q/48462925
tags question: http://stackoverflow.com/q/48431173
tags question: http://stackoverflow.com/q/48487323
tags question: http://stackoverflow.com/q/48463883
tags question: http://stackoverflow.com/q/48459971
tags question: http://stackoverflow.com/q/48477809
tags question: http://stackoverflow.com/q/48454455
tags question: http://stackoverflow.com/q/48445012
tags question: http://stackoverflow.com/q/48422569
tags question: http://stackoverflow.com/q/48403486

http://stackoverflow.com/comment/83944380
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48473706
has text: Sure I will, I was out for a while.

http://stackoverflow.com/comment/83679602
type: QuestionComment
has text: Why are you definining the throw-away variable `w` instead of just supplying that as arguments directly? Also `"""` is for multi-line strings and just clutters this query up for no reason.
comment on: http://stackoverflow.com/q/48346877
score: 1
type: Comment

http://stackoverflow.com/a/67147321
type: Answer
upvote count: 6
downvote count: 0
score: 6
has body: I simply went to the directory of my project and manually deleted the dbsqlite file. After, i rerun... python manage.py makemigrations python manage.py migrate And everything worked well
answers question: http://stackoverflow.com/q/48438100

http://stackoverflow.com/comment/83956198
score: 0
has text: Python uses 0-based indexing, so you want `i=0` and `i<len(x)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48480400

http://stackoverflow.com/comment/83821678
type: Comment
type: QuestionComment
has text: @cdarke Ah You are correct. I had tried it the first time, but apparently I forgot another slash at the end of the path name. If you make it an answer I can accept and close.
score: 1
comment on: http://stackoverflow.com/q/48415928

http://stackoverflow.com/q/48419922
tagged with: cookiecutter
has answer: http://stackoverflow.com/a/48421812
type: Question
has body: I have a cookiecutter template that I want to render a YAML file based on some options. As a simple example, suppose a rendered YAML file could look like this: supported_databases: - mysql - postgres And my cookiecutter JSON looked like this: { "mysql": ["yes", "no"], "postgres": ["yes", "no"] } My YAML file is going to be horribly peppered with ifs to support all 4 valid combinations: {%- if cookiecutter.mysql == 'yes' or cookiecutter.postgres == 'yes' %} supported_databases: {%- if cookiecutter.mysql == 'yes' %} - mysql {%- endif %} {%- if cookiecutter.mysql == 'yes' %} - postgres {%- endif %} {%- endif %} The outer if is required to prevent invalid YAML being rendered in the case when both options are 'no'. Is there a neater way to accomplish this? Thanks for any help.
tagged with: yaml
answer count: 1
accepted answer: http://stackoverflow.com/a/48421812
tagged with: jinja2
has title: How should I render YAML arrays neatly with cookiecutter?
type: AnsweredQuestion
score: 0
tagged with: templating-engine
tagged with: python

http://stackoverflow.com/comment/83899798
has text: This code is not a minimal standalone example. For instance, what is `m`?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48453231

http://stackoverflow.com/comment/83764780
has text: Just remove the try.. except block. If you had done this earlier the real issue would have been more obvious.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48386536

http://stackoverflow.com/q/48357988
answer count: 1
score: -7
favorite count: 0
type: Question
has title: How to extract string using RE in python?
has answer: http://stackoverflow.com/a/48358193
has comment: http://stackoverflow.com/comment/83702818
has body: this is a string: 'ObjectId("5a60a394ac73c233ba1acc55")' I want to get "5a60a394ac73c233ba1acc55",How do I use the regex?
downvote count: 7
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83702726
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/48358193
has comment: http://stackoverflow.com/comment/83702673

http://stackoverflow.com/q/48366379
favorite count: 0
type: Question
has body: I'm trying to train models in batches to improve memory usage. Here's my example of incremental training for gradient boosting in xgboost: https://gist.github.com/antontarasenko/1e7dd3226a3fdcd24396280c8a27a73f It uses xgb_model to train in batches. But this training creates models that perform only as well as the models trained on a single batch. How can I reduce the errors induced by incremental training? Details My incremental training: def xgb_native_batch(batch_size=100): """Train in batches that update the same model""" batches = int(np.ceil(len(y_train) / batch_size)) dtrain = xgb.DMatrix(data=X_train, label=y_train) if XGB_MODEL_FILE: # Save the model bst = xgb.train( params=xgb_train_params, dtrain=dtrain, num_boost_round=0 ) # type: Booster bst.save_model(XGB_MODEL_FILE) else: # OR just use an empty Booster class bst = None for i in range(batches): start = i * batch_size end = start + batch_size dtrain = xgb.DMatrix(X_train[start:end, :], y_train[start:end]) bst = xgb.train( dtrain=dtrain, params=xgb_train_params, xgb_model=XGB_MODEL_FILE or bst ) # type: Booster if XGB_MODEL_FILE: bst.save_model(XGB_MODEL_FILE) dtest = xgb.DMatrix(data=X_test, label=y_test) pr_y_test_hat = bst.predict(dtest) return pr_y_test_hat Tests The tests based on four datasets. I created these models: xgb_native_bulk is the reference model trained on all data at once. xgb_native_bulk_&lt;N&gt; is the model trained on a subsample of size N. xgb_native_batch_&lt;N&gt; is the model trained continuously on all the data divided into small batches of size N (continuous learning through model updates): Metrics: make_classification: binary, N=3750 ======================================== accuracy_score aurocc algorithm xgb_native_bulk 0.8624 0.933398 xgb_native_bulk_100 0.6192 0.669542 xgb_native_batch_100 0.6368 0.689123 xgb_native_bulk_500 0.7440 0.837590 xgb_native_batch_500 0.7528 0.829661 xgb_native_bulk_1000 0.7944 0.880586 xgb_native_batch_1000 0.8048 0.886607 load_breast_cancer: bi…
has title: Reduce error rates from incremental training in xgboost in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/109021584
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/48366380
upvote count: 3
linked to: http://stackoverflow.com/q/38079853
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: memory
tagged with: xgboost

http://stackoverflow.com/a/48459624
accepted answer of: http://stackoverflow.com/q/48459574
answers question: http://stackoverflow.com/q/48459574
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can use the ensure_ascii keyword argument as shown here: json.dumps({'a': 'йцукен'}, ensure_ascii=False)
score: 1
type: Answer

http://stackoverflow.com/q/48425128
tagged with: python
has title: Converting CLI LibSVM to Python: how to use svm-scale
tagged with: svm
type: Question
linked to: http://stackoverflow.com/q/13332268
has answer: http://stackoverflow.com/a/48549819
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48526540
has answer: http://stackoverflow.com/a/48469292
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/13324071
has comment: http://stackoverflow.com/comment/83844742
score: 0
tagged with: libsvm
answer count: 3
has body: I am moving over some command line tool commands to a reusable Python script. However, I can't seem to get my head around the Python implementation of LibSVM. This is the CLI command (Linux) with the LibSVM library installed: svm-scale -l 0 -u 1 -r models/feats.range input.feats &gt; feats.scaled svm-predict feats.scaled models/feats.model feats.pred An example input file (input.feats) where UNK is the label to predict is as below. (Side note that I have found that when testing this on Windows, 'UNK' as an arbitrary value was not allowed and an integer needed to be passed, so libsvm/tools/checkdata.py tells me. I don't understand why though. On Linux there is no issue at all.) UNK 1:4.458333333333333 2:24.0 3:0.20833333333333334 4:8.333333333333334 5:29.166666666666668 6:87.5 7:0.5 8:0.5 9:0.16666666666666666 10:0.16666666666666666 11:4.0 12:4.0 13:0.19047619047619047 14:0.041666666666666664 15:0.041666666666666664 16:1.0 17:1.0 18:0.047619047619047616 19:0.2916666666666667 20:0.25 21:7.0 22:6.0 23:0.2857142857142857 29:0.125 30:0.041666666666666664 31:3.0 32:1.0 33:0.047619047619047616 The first problem is that I cannot seem to find a way to implement svm-scale with a lower (-l) and upper (-u) bound, a given parameter model (-r), and an input file. The Python branch of the official LibSVM implementation is meager. I am not the only one with this question. This answer suggests to use sklearn.preprocessing and even though that'd work for simple -1,1 or 0,1 scaling, I want to scale based on previous parameters - as is possible with the -r (restore) argument in the CLI interface of svm-scale. I have not yet found a solution to this. How can I scale my data with previously saved parameters? An example of such a parameters file feats.range, looks like this: x 0 1 1 3.88936170212766 6.346938775510204 2 7.34375 32.625 3 0.1188118811881188 0.4538461538461538 4 3.3003300330033 34.61538461538461 5 18.13471502590674 67.34693877551021 6 43.38235294117647 78.46153846153847 7 0.4…
has comment: http://stackoverflow.com/comment/84031995

http://stackoverflow.com/a/48464048
has body: If want not use cumsum for last 0 values in all columns: Compare if row no contains 0, shift mask and use cumulative sum. Last compare with last value and filter: a = df.ne(0).any(1).shift().cumsum() m = a != a.max() df[m] = df[m].cumsum() print (df) A B 1 1 2 2 6 2 3 16 2 4 26 3 5 26 4 6 31 6 7 0 0 8 0 0 9 0 0 Similar solution if want processes each column separately - only omit any: print (df) A B 1 1 2 2 5 0 3 10 0 4 10 1 5 0 1 6 5 0 7 0 0 8 0 0 9 0 0 a = df.ne(0).shift().cumsum() m = a != a.max() df[m] = df[m].cumsum() print (df) A B 1 1 2 2 6 2 3 16 2 4 26 3 5 26 4 6 31 0 7 0 0 8 0 0 9 0 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48463989
answers question: http://stackoverflow.com/q/48463989
downvote count: 0
score: 1
upvote count: 1

namespaces
tags question: http://stackoverflow.com/q/48406389
tag name: namespaces
type: Tag

http://stackoverflow.com/comment/83965979
score: 2
has text: Possible duplicate of [ImportError: cannot import name 'ensure\_dir\_exists'](https://stackoverflow.com/questions/48372019/importerror-cannot-import-name-ensure-dir-exists)
comment on: http://stackoverflow.com/q/48486240
type: Comment
type: QuestionComment

storage
tag name: storage
tags question: http://stackoverflow.com/q/48422765
tags question: http://stackoverflow.com/q/48344706
type: Tag
tags question: http://stackoverflow.com/q/48380854

http://stackoverflow.com/a/48349687
score: 2
answers question: http://stackoverflow.com/q/48349548
type: Answer
has body: Assuming by "array" you mean a list or a tuple: In [22]: data = ("1", ...: "---", ...: "some text", ...: "---", ...: "more text", ...: "---", ...: "2", ...: "---", ...: "even more text", ...: "---", ...: "3", ...: "---", ...: "you guessed it", ...: "---") Then your logic should be quite straightforward: In [23]: final = [] In [24]: for x in data: ...: if x.isdigit(): ...: sub = [x] ...: final.append(sub) ...: else: ...: sub.append(x) ...: In [25]: final Out[25]: [['1', '---', 'some text', '---', 'more text', '---'], ['2', '---', 'even more text', '---'], ['3', '---', 'you guessed it', '---']] In [26]:
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48349548

http://stackoverflow.com/comment/83746930
comment on: http://stackoverflow.com/q/48379852
has text: This is my S3 cors config. <?xml version="1.0" encoding="UTF-8"?> * GET POST 3000 Authorization
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83670814
type: Comment
score: 0
type: QuestionComment
has text: @rahnema1 getting a TypeError when I do this: prices1[ii + np.arange(0,2)] (adding reshape(1,-1) results in the same array) >> prices1 = [2,3,6,7,10,11,14,15,18,19,22,23,26,27,30] priceDiff = np.array(pd.DataFrame(data=prices1).diff()) prices1[ii + np.arange(0,2)]
comment on: http://stackoverflow.com/q/48338687

http://stackoverflow.com/a/48382307
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48380953
has body: Matplotlib categorical support is a rather new feature in matplotlib 2.1. There are some issues which are still being worked on. Matplotlib >= 2.1.1 The code from the question runs fine in matplotlib 2.1.1 or higher. import matplotlib.pyplot as plt import numpy as np x1 = ["apple", "banana", "apple", "cherry"] x2 = ["cherry", "date"] y1 = [1,2,2,2] y2 = [3,4] fig = plt.figure() ax1 = fig.add_subplot(111) ax1.scatter(x1, y1, color='black', label='Initial Fruits') ax1.scatter(x2, y2, color='green', label='Further Fruits') plt.legend() plt.show() Matplotlib &lt;= 2.1.0 While matplotlib 2.1.0 allows in principle to plot categories, it is not possible to add further categories to an existing categorical axes. Hence a solution which would also work for even lower versions would need to be used, plotting the values as numerical data. import matplotlib.pyplot as plt import numpy as np x1 = ["apple", "banana", "apple", "cherry"] x2 = ["cherry", "date"] y1 = [1,2,2,2] y2 = [3,4] c = ["black"]*len(x1) + ["green"]*len(x2) u, inv = np.unique(x1+x2, return_inverse=True) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.scatter(inv, y1+y2, c=c, ) f = lambda c : plt.plot([],color=c, ls="", marker="o")[0] ax1.legend(handles = [f("black"), f("green")], labels=['Initial Fruits', 'Further Fruits']) ax1.set_xticks(range(len(u))) ax1.set_xticklabels(u) plt.show() Resulting plot in both cases:
answers question: http://stackoverflow.com/q/48380953
type: AcceptedAnswer
score: 4
downvote count: 0

http://stackoverflow.com/a/48384477
has body: No, as of now it's not possible. You have to specify the primary key to delete an item, although you can optionally pass ConditionExpression to prevent it from being deleted if some condition is not met. Only this much flexibility api is providing us.
answers question: http://stackoverflow.com/q/48384337
upvote count: 2
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83656949
type: QuestionComment
has text: @Adelin That's not true, if an object contains only `__repr__`, `print` will use `__repr__`. But if an object contains `__str__`, `print` will choose `__str__` first.
comment on: http://stackoverflow.com/q/48335791
score: 0
type: Comment

http://stackoverflow.com/a/48565686
upvote count: 1
has comment: http://stackoverflow.com/comment/84134626
type: Answer
answers question: http://stackoverflow.com/q/48408230
score: 1
has body: You have to use a client secret to identify who is calling your api. You will have to generate api keys for your clients. The clients will send these api keys as query params to prove they are your approved clients. for example you generated a token abcd for your ios app. Your ios app will send the request as: https://your-endpoint.com/api/method/?token=abcd To check if the token is correct you can create a custom permission class. class IsApprovedClientPermission(permissions.BasePermission): def has_permission(self, request, view): token = request.query_params.get('token', None) if request.method not in permissions.SAFE_METHODS: # custom checks return token in approved_tokens_list: return True You can apply this permission class to any view you want to verify before letting the request modify your data.
downvote count: 0

http://stackoverflow.com/q/48481671
upvote count: 2
type: UnansweredQuestion
downvote count: 0
score: 2
tagged with: android
tagged with: python
tagged with: kivy
has title: Kivy crashes on resume after screen lock
has body: I'm writing my first app with Kivy and am using Buildozer to deploy the app to Android. Although my app resumes when I switch between applications, if ever I lock my screen, the app does not resume at all. Is there anything that I'm missing? The documentation seems to refer to this problem as a "bug" from previous versions. I'm using Kivy 1.10.0. Here is what I did to handle pause/resume: class MyApp(App): def build(self): return sm def on_pause(self): return True def on_resume(self): return sm
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49181590
answer count: 2
has answer: http://stackoverflow.com/a/48481715

http://stackoverflow.com/q/48355825
accepted answer: http://stackoverflow.com/a/48355853
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48355866
tagged with: python-2.7
answer count: 2
has body: This morning i wanted to host my Discord Bot, written on Python on my VPS on Ubuntu 14.04 After couple of minutes f#@$ing with Python repos i realized, that i got several Python versions installed on my VPS. The main one is Python 2.7.12, that is absolutely old and can't launch Discord Bot, cause it needs pip install Discord, that is supported only with Python 3 and upper. After couple of minutes I installed Python 3.6.3, that i needed. But when I tried to install Discord for Python it didn't install, because it needs, as I've said, Python 3 and upper version. I saw in cmd, that while installing this Discord Plugin for Python cmd tried to execute command python setup.py egg_info, that failed because python runs Python 2.7.12 and to run Python 3.6.3 I've installed i need to write python3.6. So, how can i switch the default (main) version of Python in order to run Python 3.6.3, while executing python. Thank you for your answers. (My apologize, if I've exploded your brain)
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83698226
has answer: http://stackoverflow.com/a/48355853
has title: How can i switch python version, that runs by command "python" in UBUNTU 14.04
linked to: http://stackoverflow.com/q/19256127
has answer: http://stackoverflow.com/a/48355866
score: -2
tagged with: python
tagged with: ubuntu

http://stackoverflow.com/comment/83752386
score: 0
type: Comment
type: QuestionComment
has text: Python is a garbage-collected language. You need to understand this model before you attempt to do much anything at all related to memory management.
comment on: http://stackoverflow.com/q/48382644

http://stackoverflow.com/comment/83800024
comment on: http://stackoverflow.com/q/48393242
score: 0
type: QuestionComment
type: Comment
has text: I literally tried to get the syntax right but my emails would only show up with one attachment.

http://stackoverflow.com/comment/83892366
score: 0
type: Comment
type: QuestionComment
has text: I had followed you given url and also tried your Dec2017 solution. My `from_key` is still remaining in the `errors`
comment on: http://stackoverflow.com/q/48441193

http://stackoverflow.com/comment/83929453
has text: Note, `for key, value in score_dict.items():` should make you pause and think, "Am I using this `dict` correctly"? Do you *really* want to iterate over all the items in the dictionary? Pretty sure you need to use your dictionary as a *map*
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48467887

http://stackoverflow.com/comment/83990163
has text: Thanks - could you update the links? It may be worth submitting a bug report if this is right.
comment on: http://stackoverflow.com/a/48474991
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83723970
comment on: http://stackoverflow.com/a/48360790
score: 0
type: AnswerComment
has text: If I take the column of the column of the 10000 conditional_means, I get the same result as without conditioning. That's why I am confused
type: Comment

http://stackoverflow.com/comment/83892368
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48449653
has text: Calling p.wait() inside the except block still does not solve the issue.

http://stackoverflow.com/comment/83728811
comment on: http://stackoverflow.com/a/48368773
score: 0
type: AnswerComment
has text: @BryanOakley Well, I find it easier with `lambda` as I can connect the dots easier for callbacks to be used with options such as `bind`, `trace_add`, `command`. Then again I'm a beginner as well.
type: Comment

http://stackoverflow.com/comment/83976559
comment on: http://stackoverflow.com/q/48349548
has text: Since the question has been corrected and become clear, reopen it.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83693773
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48353603
has text: Are you saying to exclude the `migrations` folders aswell? (not just the contents of the folders)?
type: Comment

http://stackoverflow.com/comment/83803617
has text: The result is ok also with "deu" in the second case as I pointed above. And I have to stay to "deu" for the German cases. The question is how can I trace any reason for this since I need the same behavior everywhere. Let me update the question a bit.
score: 0
comment on: http://stackoverflow.com/q/48390446
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83689838
has text: Could you try `q.put(x[int(numpy.random.uniform(0,len(x)-1))])` instead of `q.put(x[-1])`? This is still nothing for the CPU, but python will never predict it ;)
comment on: http://stackoverflow.com/q/48351338
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48403872
has comment: http://stackoverflow.com/comment/83796214
has body: You don't need a list comprehension and ord just encode to ascii and ignore the errors: In [106]: {key:value.encode('ascii',errors='ignore') for key, value in a.items()} Out[106]: {'age': b'12', 'name': b'pks'} If you want to replace with space here is an efficient way: In [117]: def replace_nonascii(mydict): for key, value in a.items(): new = value.encode('ascii',errors='ignore') yield key, new + b' ' * (len(value) - len(new)) .....: In [118]: dict(replace_nonascii(a)) Out[118]: {'age': b'12 ', 'name': b'pks '}
downvote count: 0
has comment: http://stackoverflow.com/comment/83796623
has comment: http://stackoverflow.com/comment/83796673
answers question: http://stackoverflow.com/q/48403793
type: Answer
has comment: http://stackoverflow.com/comment/83796475
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/83796302

http://stackoverflow.com/comment/83668741
comment on: http://stackoverflow.com/q/48333550
has text: if frame is smaller then canvas then you have to see red canvas below frame - or use `canvas.itemconfig(self.canvas_frame, height=event.height)` to change frame's height automatically (similar to `width`).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48358856
score: 5
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48358800
has body: use any conditions to check all the elements in a list with the same condition: lst = ['hello','p=15' ,'stack', 'overflow', 'friends'] return any(l.startswith("p=") for l in lst)

http://stackoverflow.com/q/48390664
has answer: http://stackoverflow.com/a/48400221
has body: My main doubt if I can easly convert this script to run in a Jupyter notebook whithout have this error. The function tf.app.run() provide a wrapper that handles flag parsing. But looks like the tensorflow code forcefully exits the process in which it's running after main completes. This is my main function: def main(_): input_fn = make_input_fn hparams = tf.contrib.training.HParams( learning_rate=.1, ) config = tf.ConfigProto( # allow_soft_placement=True, # log_device_placement=True ) trainingConfig = tf.contrib.learn.RunConfig( save_summary_steps=500, save_checkpoints_steps=500, model_dir=("/tmp/tf-logs/bucketized-01"), session_config=config ) estimator = tf.estimator.Estimator( model_fn=make_model, params=hparams, config=trainingConfig ) estimator.train( input_fn=input_fn, steps=TRAIN_EPOCHS, ) When I call in Jupyter notebook: if __name__ == '__main__': tf.app.run(main) I had this error: INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Restoring parameters from /tmp/tf-logs/bucketized-01/model.ckpt-2001 INFO:tensorflow:Saving checkpoints for 2002 into /tmp/tf-logs/bucketized-01/model.ckpt. INFO:tensorflow:loss = 11.734686, step = 2002 INFO:tensorflow:global_step/sec: 4.84241 INFO:tensorflow:loss = 11.320501, step = 2102 (20.653 sec) INFO:tensorflow:global_step/sec: 5.54159 INFO:tensorflow:loss = 9.874545, step = 2202 (18.044 sec) INFO:tensorflow:global_step/sec: 5.20988 INFO:tensorflow:loss = 11.533301, step = 2302 (19.196 sec) INFO:tensorflow:Saving checkpoints for 2401 into /tmp/tf-logs/bucketized-01/model.ckpt. INFO:tensorflow:Loss for final step: 10.57784. An exception has occurred, use %tb to see the full traceback. SystemExit
answer count: 1
tagged with: tensorflow
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/83772665
tagged with: gflags
type: Question
linked to: http://stackoverflow.com/q/46742441
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83769546
tagged with: python
has title: Can I change the script bellow(tf.app.run()) to work in Jupyter notebook without error?
score: 0

http://stackoverflow.com/comment/83862918
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48435358
score: 0
has text: The `finally` block is run, a `ZeroDivisionError` is raised, gets caught and printed. What are you trying to do? There's probably a better way.

http://stackoverflow.com/comment/83865186
score: 1
comment on: http://stackoverflow.com/a/48436888
has text: I don't think any of this matters, though. I think Python will always evaluate and byte-compile `main` no matter where it's located. And if the code is a module, `main` can be easily hidden from the outside.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48477688
has comment: http://stackoverflow.com/comment/83948913
has comment: http://stackoverflow.com/comment/83951532
linked to: http://stackoverflow.com/q/24027589
has comment: http://stackoverflow.com/comment/83950775
has comment: http://stackoverflow.com/comment/83948755
tagged with: python
has answer: http://stackoverflow.com/a/48479474
has comment: http://stackoverflow.com/comment/83951401
type: AnsweredQuestion
downvote count: 0
has body: I am trying to scrape the following page with requests and BeautifulSoup/Lxml https://www.reuters.com/search/news?blob=soybean&amp;sortBy=date&amp;dateRange=all This is the kind of pages that have a load more results button. I have found few pages explaining how to do so, but not within the frame of requests. I understand that I should spend few more hours researching that problem before resorting to asking here, as to show proof that I ve tried. I've tried to look into the inspect pane, into the network tab etc. but i'm still a bit too fresh with requests to understand how to interact with javascript. I don't need a fully blown script/solution as an answer, just some pointers as to how to do this very typical task with requests, as to save me few precious hours of research. Thanks in advance.
has comment: http://stackoverflow.com/comment/83951081
has title: Scrape page with "load more results" button
answer count: 1
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/48479474
favorite count: 0
type: Question
score: 5
upvote count: 5

http://stackoverflow.com/q/48414538
answer count: 1
has answer: http://stackoverflow.com/a/48453711
type: Question
tagged with: python
tagged with: kivy
has body: I tried to run buildozer in docker virtual machine to generate andorid app package(.apk). After tried and filed sometimes, his Dockerfile(https://github.com/jedie/kivy-buildozer-docker) was determined to use to make my environment for my purpose. However, in almost finished building, the error occured. .apk was generated in success, but (I guessed) the error was caused the process that the .apk file copy from a working dir in generation into project_dir as below. [INFO]: &lt;- directory context /home/buildozer/kivy_hello_world/.buildozer/android/platform/python-for-android-new-toolchain [INFO]: # Copying APK to current directory [INFO]: # Found APK file: /home/buildozer/kivy_hello_world/.buildozer/android/platform/build/dists/kivy_hello_world/bin/HelloWorld-0.1-debug.apk [DEBUG]: -&gt; running cp /home/buildozer/kivy_hello_world/.buildozer/android/platform/build/dists/kivy_hello_world/bin/HelloWorld-0.1-debug.apk ./ Traceback (most recent call last): File "/usr/local/bin/buildozer", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/buildozer/scripts/client.py", line 13, in main Buildozer().run_command(sys.argv[1:]) File "/usr/local/lib/python2.7/dist-packages/buildozer/__init__.py", line 1058, in run_command self.target.run_commands(args) File "/usr/local/lib/python2.7/dist-packages/buildozer/target.py", line 92, in run_commands func(args) File "/usr/local/lib/python2.7/dist-packages/buildozer/target.py", line 104, in cmd_debug self.buildozer.build() File "/usr/local/lib/python2.7/dist-packages/buildozer/__init__.py", line 212, in build self.target.build_package() File "/usr/local/lib/python2.7/dist-packages/buildozer/targets/android.py", line 817, in build_package copyfile(join(apk_dir, apk), join(self.buildozer.bin_dir, apk_dest)) File "/usr/lib/python2.7/shutil.py", line 96, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory: u'/home/buildozer/kivy_hello_world/.buildozer/android/platform/b…
tagged with: buildozer
score: 0
type: UnansweredQuestion
has title: buildozer(kivy,python) failed in copying generated apk to the home dir on docker virtual machine

http://stackoverflow.com/a/48361515
has comment: http://stackoverflow.com/comment/89601362
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89605257
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89605180
accepted answer of: http://stackoverflow.com/q/48347728
has comment: http://stackoverflow.com/comment/110110847
upvote count: 2
has body: I found the reason for the NaN's error. In retrospect, I have to say, it's been in front of my nose the whole time. The short version: I used the tf.train.GradientDescentOptimizer() with tf.train.exponential_decay() for the optimization. Changing it to tf.train.AdamOptimizer() solve my problem. The long version: So it wasn't the GPU cluster, but the optimization algorithm. But I didn't immediately notice that, because if I used only one GPU on the GPU cluster, the total loss values were not infinite but if I used several GPUs, the loss value added up and then went into the infinite range. Only when I ran the script on my local machine for a very long time (using a NVIDIA GTX 770) did I get a NaN error. That's when I knew it had nothing to do with the NVIDIA Tesla P100. This GitHub issue caused me to get more involved with the tf.train.GradientDescentOptimizer(). Now it looks like that solved my problem. The TensorFlow tutorial Convolutional Neural Networks use tf.train.GradientDescentOptimizer() and i change now the code from: lr = tf.train.exponential_decay(get_initial_learning_rate(), global_step, decay_steps, get_learning_rate_decay_factor(), staircase=True) opt = tf.train.GradientDescentOptimizer(lr) to: opt = tf.train.AdamOptimizer( get_initial_learning_rate(), # 0.001 beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False)
answers question: http://stackoverflow.com/q/48347728
type: Answer

http://stackoverflow.com/comment/83718407
score: 0
type: AnswerComment
type: Comment
has text: Good to know it helped! I think the key here is that the `member` instance is already created by the time `__init__` is called.. So that assigning to `self` is assigning to the already created object. This is what i found difficult at the start.
comment on: http://stackoverflow.com/a/48365546

http://stackoverflow.com/comment/83843580
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48426629
type: Comment
has text: He may receive the list as output. And using `i` and `i+1` is something which can be very difficult to consider ... *juggling*

http://stackoverflow.com/comment/83947191
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48471792
has text: Reading your question again, I realized it has two parts. First, the difference in log-loss values despite the similar accuracy. Log-loss penalizes more labels that are confident and wrong, so it seems plausible to have different values for the log-loss despite the similar accuracy. The second part is to find the log-loss for every grid-search point. After you have called grid.predict(), can you identify the log-loss in the columns of pd.DataFrame(grid.cv_results_)?

http://stackoverflow.com/comment/83982790
type: Comment
comment on: http://stackoverflow.com/a/48482257
type: AnswerComment
has text: No, I was only saving the User model. I didn't even use UserProfile. Once I made a UserProfile in the register and saved it, it worked as intended
score: 0

http://stackoverflow.com/comment/83739716
type: Comment
type: QuestionComment
has text: Did you read the docs for [`re.search`](https://docs.python.org/3/library/re.html#re.search)? It returns a match object if it found something and `None` otherwise. This is exactly what you're seeing. `re.search(r'\babc\b', 'abc123') is None` and `re.search(r'\babc\b', 'abc 123') is not None` should both be true.
comment on: http://stackoverflow.com/q/48376460
score: 0

http://stackoverflow.com/comment/83783234
has text: Isn't this the same as not providing the `format` argument to `pd.to_datetime()` and letting Pandas figure out the format? The whole point of providing a format is to speed up the parsing.
type: Comment
comment on: http://stackoverflow.com/a/48397656
type: AnswerComment
score: 1

http://stackoverflow.com/q/48378280
type: Question
has comment: http://stackoverflow.com/comment/83743278
has comment: http://stackoverflow.com/comment/83743288
answer count: 2
has comment: http://stackoverflow.com/comment/83743484
tagged with: function
possible better answer: http://stackoverflow.com/a/48379427
tagged with: python
score: -1
downvote count: 1
has answer: http://stackoverflow.com/a/48385510
has body: I'm having problems with stopping a function whilst inside a for loop. def character(char_type,word,number): for i in range(len(word)): for e in range(len(char_type)): if word[i]==char_type[e]: if char_type==vowels: number[0]=number[0]+1 elif char_type==consonants: number[1]=number[1]+1 elif char_type==valid_symbols: number=number else: number=[-1,-1] I need the function to terminate if number=[-1,-1] but can't figure out how to do it. I have tried using return at every level of indentation but it still doesn't work.
accepted answer: http://stackoverflow.com/a/48385510
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48379427
has title: Stopping a function in a for loop python
has comment: http://stackoverflow.com/comment/83743454
favorite count: 0

http://stackoverflow.com/comment/83692204
score: 0
comment on: http://stackoverflow.com/q/48352745
has text: so what is the common format of the strings? otherwise you cannot come up with a generic way to deal with all of it
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48417802
score: 0
has answer: http://stackoverflow.com/a/48418025
has title: How to convert a downloaded string to datetime format?
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48418181
possible better answer: http://stackoverflow.com/a/48417969
answer count: 4
has answer: http://stackoverflow.com/a/48418181
has answer: http://stackoverflow.com/a/48418143
has answer: http://stackoverflow.com/a/48417969
has body: I am trying to check if today's date &lt; date downloaded from text file online. Here is my code : import datetime import requests URL = "http://directlinktotextfile.com/text.txt" result = requests.get(URL) today = datetime.datetime.now().date() Url_date = result.text Url_date.strip() Url_date = datetime.date(Url_date) if today &lt; Url_date : print "Today is less than future date" raw_input() else: print "Today is greater than or = to future date" raw_input() The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today &lt; Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/83834582
has text: Does that still work if the list elements have text instead of just numbers? For instance, does the element [buses] get converted to set(b, e, s, u)?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48419706
type: Comment

http://stackoverflow.com/q/48428508
has comment: http://stackoverflow.com/comment/83848863
has comment: http://stackoverflow.com/comment/83847888
has body: I am trying to import TouchRippleBehavior in Kivy using this: from kivy.uix.behaviors.touchripple import TouchRippleBehavior However, it throws: ModuleNotFoundError: No module named 'kivy.uix.behaviors.touchripple' Currently I am using Python 2.7, 3.5.2, and 3.6.4(pyenv). I tried on all versions but got same error.
type: Question
has title: Kivy Import Error: No module named 'kivy.uix.behaviors.touchripple'
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/83848050
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83860557
has comment: http://stackoverflow.com/comment/83850550

http://stackoverflow.com/q/48392267
has title: Why is this Popen call returning a "io.UnsupportedOperation: fileno" error in Django 2.0?
has answer: http://stackoverflow.com/a/48392466
answer count: 1
downvote count: 0
tagged with: django
tagged with: gulp
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: python
linked to: http://stackoverflow.com/q/42790693
has body: I recently upgraded my project to Django 2.0, and an error started cropping up. First off, I use django_gulp to start a gulp process whenever I start the django runserver. I'm using the runserver_plus branch of the django_gulp project. Here's the relevant code snippet from the django_gulp project, where it makes the subprocess.Popen call. This call was functioning correctly in Django 1.11.x. from __future__ import print_function import atexit import os import psutil import subprocess import sys import traceback from signal import SIGTERM from concurrent.futures import ThreadPoolExecutor from django.core.management.base import CommandError from django.conf import settings from django_extensions.management.commands.runserver_plus import Command \ as DjangoExtensionsRunserverCommand from env_tools import load_env class Command(DjangoExtensionsRunserverCommand): """ Subclass the RunserverCommand from Staticfiles to set up our gulp environment. """ def __init__(self, *args, **kwargs): self.cleanup_closing = False self.gulp_process = None super(Command, self).__init__(*args, **kwargs) @staticmethod def gulp_exited_cb(future): if future.exception(): print(traceback.format_exc()) children = psutil.Process().children(recursive=True) for child in children: print('&gt;&gt;&gt; Killing pid {}'.format(child.pid)) child.send_signal(SIGTERM) print('&gt;&gt;&gt; Exiting') # It would be nice to be able to raise a CommandError or use # sys.kill here but neither of those stop the runserver instance # since we're in a thread. This method is used in django as well. os._exit(1) def handle(self, *args, **options): try: env = load_env() except IOError: env = {} # XXX: In Django 1.8 this changes to: # if 'PORT' in env and not options.get('addrport'): # options['addrport'] = env['PORT'] if 'PORT' in env and not args: args = (env['PORT'],) # We're subclassing runserver, which spawns threads for its # autoreloader with RUN_MAIN set to true, we have to check for # this to avoid running gulp twi…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48392466
tagged with: subprocess

http://stackoverflow.com/comment/83994552
type: QuestionComment
score: 0
has text: @MarkDickinson yes, i am sure. But it is not about user front, but it is about UI front. In the JSON response, they want to see all decimal values. But anyway thanks for your responses.
comment on: http://stackoverflow.com/q/48440007
type: Comment

http://stackoverflow.com/a/48410073
score: 0
has body: Below code produces a label that gets updated randomly, and plays the sound files located in "C:\Windows\Media\" based on the change: import tkinter as tk import random from playsound import playsound def sound(is_positive=True): if is_positive: playsound(r"C:\Windows\Media\chimes.wav", False) else: playsound(r"C:\Windows\Media\chord.wav", False) def random_update(): _old = label['text'] _new = random.randint(1, 100) if _new &gt; _old: # use (_new - _old) == 1 for checking sound() # increment of 1 exclusively elif _new &lt; _old: # use (_new - _old) == -1 for checking sound(False) # decrement of 1 exclusively label['text'] = _new label.after(2000, random_update) if __name__ == '__main__': root = tk.Tk() label = tk.Label(root, text=1) label.after(2000, random_update) label.pack() root.mainloop() playsound is not a built-in package so it needs to be installed separately. You can install using: pip install playsound or: python -m pip install playsound in the command prompt on windows.
answers question: http://stackoverflow.com/q/48400158
type: Answer

http://stackoverflow.com/comment/83879172
score: 0
has text: Díky, co když mi to ale najde nekonečno jako minimum?
type: Comment
comment on: http://stackoverflow.com/a/48443807
type: AnswerComment

http://stackoverflow.com/a/48471979
score: 1
has body: the d dict should be set in the compiled code,and, the data should be splitted to set the dict. def config2dict(fname): d = {} codeobj = compile("txt=open(fname).read()\nd.update(dict([tuple([y.strip() for y in x.split(\"=\")]) for x in txt.split(\"\\n\") if x!=\"\"]))", 'myconfig', 'exec') exec(codeobj) return d dd = config2dict("myconfig.cfg") print(dd)
type: Answer
has comment: http://stackoverflow.com/comment/83938455
has comment: http://stackoverflow.com/comment/83986709
has comment: http://stackoverflow.com/comment/83987497
has comment: http://stackoverflow.com/comment/83941285
has comment: http://stackoverflow.com/comment/83938489
upvote count: 1
has comment: http://stackoverflow.com/comment/83991249
has comment: http://stackoverflow.com/comment/83981114
has comment: http://stackoverflow.com/comment/83938299
has comment: http://stackoverflow.com/comment/83982888
answers question: http://stackoverflow.com/q/48471900
downvote count: 0

http://stackoverflow.com/comment/83729091
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48369959
has text: @DavidParks Here is the error log on line 50 https://gist.github.com/SamKirkiles/d17a3db437247d7b08869f254b9c938d

http://stackoverflow.com/a/48357090
has comment: http://stackoverflow.com/comment/83703151
has body: I think you need first reshape to rows by cumcount + set_index + unstack and then if need change ordering of columns use reindex: df1 = pd.read_csv('df1.csv', names=['a','b']) print (df1) a b 0 Time 07:03:52 1 EmployeeID 98766 2 EmployeeName Joao 3 Time 08:03:52 4 EmployeeID 98765 5 EmployeeName Mary #for columns names created from file2 df2 = pd.read_csv('df2.csv') c = df2.columns.str.strip().tolist() print (c) ['EmployeeID', 'EmployeeName', 'Time'] #or defined in list #c = ['Time', 'EmployeeID', 'EmployeeName'] g = df1.groupby('a').cumcount() df1 = df1.set_index([g,'a'])['b'].unstack().reindex(columns=c) print (df1) a EmployeeID EmployeeName Time 0 98766 Joao 07:03:52 1 98765 Mary 08:03:52
has comment: http://stackoverflow.com/comment/83706604
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83702599
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83703250
has comment: http://stackoverflow.com/comment/83706651
has comment: http://stackoverflow.com/comment/83703263
accepted answer of: http://stackoverflow.com/q/48357044
score: 1
has comment: http://stackoverflow.com/comment/83701058
type: Answer
answers question: http://stackoverflow.com/q/48357044
has comment: http://stackoverflow.com/comment/83700999
has comment: http://stackoverflow.com/comment/83703360
has comment: http://stackoverflow.com/comment/83703602

http://stackoverflow.com/q/48333346
type: Question
has comment: http://stackoverflow.com/comment/83652439
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83652417
linked to: http://stackoverflow.com/q/132318
accepted answer: http://stackoverflow.com/a/48333568
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83652334
tagged with: unidecoder
has answer: http://stackoverflow.com/a/48333568
has title: How to fix an accented string [python]
upvote count: 4
has body: I'm using a webapp to retrieve data from results of a game I play. As I'm brazilian and my language has some latin accented characters, most of the data I retrieve comes in a bad shape for use. Like: Carlos Lopez = Carlos Lã³Pez I searched internet and found ftfy as a good fixer for broken text. Anyway, I'm not really aware about unicode, ascii and stuff, so I used ftfy, and received as output the same errors I already have. In[15]: ftfy.fix_text('Carlos Lã³Pez') Out[15]: 'Carlos Lã³Pez' ftfy.fix_encoding('Carlos Lã³Pez') Out[16]: 'Carlos Lã³Pez' ftfy.fix_text('Carlos Lã³Pez') Out[17]: 'Carlos Lã³Pez' print(ftfy.fix_text('Carlos Lã³Pez')) Carlos Lã³Pez print(ftfy.fix_encoding('Carlos Lã³Pez')) Carlos Lã³Pez ftfy.explain_unicode('Carlos Lã³Pez') U+0043 C [Lu] LATIN CAPITAL LETTER C U+0061 a [Ll] LATIN SMALL LETTER A U+0072 r [Ll] LATIN SMALL LETTER R U+006C l [Ll] LATIN SMALL LETTER L U+006F o [Ll] LATIN SMALL LETTER O U+0073 s [Ll] LATIN SMALL LETTER S U+0020 [Zs] SPACE U+004C L [Lu] LATIN CAPITAL LETTER L U+00E3 ã [Ll] LATIN SMALL LETTER A WITH TILDE U+00B3 ³ [No] SUPERSCRIPT THREE U+0050 P [Lu] LATIN CAPITAL LETTER P U+0065 e [Ll] LATIN SMALL LETTER E U+007A z [Ll] LATIN SMALL LETTER Z ftfy.explain_unicode(unidecode('Carlos Lã³Pez')) U+0043 C [Lu] LATIN CAPITAL LETTER C U+0061 a [Ll] LATIN SMALL LETTER A U+0072 r [Ll] LATIN SMALL LETTER R U+006C l [Ll] LATIN SMALL LETTER L U+006F o [Ll] LATIN SMALL LETTER O U+0073 s [Ll] LATIN SMALL LETTER S U+0020 [Zs] SPACE U+004C L [Lu] LATIN CAPITAL LETTER L U+0061 a [Ll] LATIN SMALL LETTER A U+0033 3 [Nd] DIGIT THREE U+0050 P [Lu] LATIN CAPITAL LETTER P U+0065 e [Ll] LATIN SMALL LETTER E U+007A z [Ll] LATIN SMALL LETTER Z print(ftfy.fix_encoding(unidecode('Carlos Lã³Pez'))) Carlos La3Pez print(ftfy.fix_text(unidecode('Carlos Lã³Pez'))) Carlos La3Pez I'd like to know if there's any package to fix this kind of error, or if you could give me any lead why Carlos López turned into Carlos Lã³Pez. I'd apreciatte.
has comment: http://stackoverflow.com/comment/83652274
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83652643
tagged with: string
tagged with: unicode
favorite count: 0

http://stackoverflow.com/q/48388232
has body: I'm a python new-comer, so there is probably a simple answer to this question, but I have looked and found nothing. I want to define a function that when this is entered: "function(abcdefg123, fg1, " ")" the return is this: "abcde 23". I think it would look like this: def function(something, what_to_deleat, what_to_substitute): if str(what_to_deleat) in str(something): return ## Code that replaces "what_to_deleat" with "what_to_substitute" within "something" else: return something A practical application (and the one I'm wanting to use this for) would convert 25.0 into 25 if 'function("25.0", ".0", "")' was entered.
accepted answer: http://stackoverflow.com/a/48388306
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/10037742
has answer: http://stackoverflow.com/a/48388306
upvote count: 0
answer count: 1
has title: How do you search for and delete a phrase from a string in Python?
has comment: http://stackoverflow.com/comment/83764193
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10037742

http://stackoverflow.com/q/48332632
tagged with: pandas
has comment: http://stackoverflow.com/comment/83651011
answer count: 1
has comment: http://stackoverflow.com/comment/83651173
has comment: http://stackoverflow.com/comment/83651072
tagged with: excel
has comment: http://stackoverflow.com/comment/83651003
type: Question
has body: so I have this data frame with about 5 columns. 2 of them are longitude and lattitude pairs in form of tuples. so I have another user defined function that calculates the distance between two given tuples of lon/lat. data_all['gc_distance'] = "" ### let's start calculate the great circle distance for idx, row in data_all.iterrows(): row['gc_distance'] = gcd.dist(row['ping_location'], row['destination']) print(row) so basically, i created an empty column named gc_distance, then i iterate through each row to calculate the distance. when i print each row, the data looks great; sample print of a row: created_at_des 2018-01-17 18:55:55.154000 location_missing 0 ping_location (-121.9419444444, 37.4897222222) destination (-122.15057, 37.39465) gc_distance 23.85 km Name: 393529, dtype: object as you can see, the gc_distance DOES have value. Here's the sample output from the print statement after the loop: location_missing ping_location \ 0 (-152.859052, 51.218273) 0 (120.585289, 31.298974) 0 (120.585289, 31.298974) 0 (120.585289, 31.298974) 0 (121.4737021, 31.2303904) destination gc_distance 0 (-122.057005, 37.606922) 1 (-122.057005, 37.606922) 2 (-122.057005, 37.606922) 3 (-122.057005, 37.606922) 4 (-122.057005, 37.606922) However, when I print it again outside of the for loop, gc_distance column has only blank vlaues! :( Why is this??? There's no compile or run time error... And all other outputs look good, why is this calculated field not there, even though when I print it during the for loop it does have value? (but outside for loop it doesn't anymore)
has comment: http://stackoverflow.com/comment/83651276
has comment: http://stackoverflow.com/comment/83650961
has title: data populated in the dataframe during for loop but not there anymore after for loop
has comment: http://stackoverflow.com/comment/83651383
has comment: http://stackoverflow.com/comment/83651408
has comment: http://stackoverflow.com/comment/83651416
has comment: http://stackoverflow.com/comment/83651387
tagged with: python
has comment: http://stackoverflow.com/comment/83651019
has comment: http://stackoverflow.com/comment/83651156
has comment: http://stackoverflow.com/comment/83651106
has comment: http://stackoverflow.com/comment/83651313
has comment: http://stackoverflow.com/comment/83651397
has answer: http://stackoverflow.com/a/48333341
accepted answer: http://stackoverflow.com/a/48333341
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83651141

http://stackoverflow.com/a/48589464
type: Answer
upvote count: 6
has body: I'm posing a final solution to this question for posterity sake. The code below is a copy/paste example that works under the most complex conditions this question addresses (note that the other two answers aren't copy/pastable code samples): The goal of the code is: Take a list of (big) files and split it into chunks (filename/index pairs) Process each chunk using a map operation (generators aren't a workable solution here, see: https://github.com/tensorflow/tensorflow/issues/16343) Output multiple samples from a map operation that takes only 1 file/chunk as input. Maintain element naming throughout the process Copy/pastable working sample for Tensorflow 1.5 / Python 3.x import tensorflow as tf import numpy as np files = [b'testA', b'testB', b'testC'] def mymap1(x): result_tensors = tf.py_func(func=mymap2, inp=[x], Tout=[tf.string, tf.int64]) return {'filename': result_tensors[0], 'value': result_tensors[1]} def mymap2(x): return np.array([x, x, x]), np.array([10, 20, 30]) def myflatmap(named_elements): return tf.data.Dataset.zip({ 'filename': tf.data.Dataset.from_tensor_slices(named_elements['filename']), 'value': tf.data.Dataset.from_tensor_slices(named_elements['value']) }) ds = tf.data.Dataset.from_tensor_slices(files) ds = ds.map(map_func=mymap1) ds = ds.flat_map(map_func=myflatmap) element = ds.make_one_shot_iterator().get_next() with tf.Session() as sess: for _ in range(9): print(sess.run(element)) Output: {'filename': b'testA', 'value': 10} {'filename': b'testA', 'value': 20} {'filename': b'testA', 'value': 30} {'filename': b'testB', 'value': 10} {'filename': b'testB', 'value': 20} {'filename': b'testB', 'value': 30} {'filename': b'testC', 'value': 10} {'filename': b'testC', 'value': 20} {'filename': b'testC', 'value': 30}
answers question: http://stackoverflow.com/q/48471688
downvote count: 0
score: 6

http://stackoverflow.com/q/48473977
type: AnsweredQuestion
score: 0
tagged with: nmap
answer count: 1
accepted answer: http://stackoverflow.com/a/48474881
has body: I am wanting to have a script which scans my local network for anybody who has opened an SSH login. I have a script which randomly generates a local IP and sees if the IP is "up". However, I keep getting a dictionary "builtins.KeyError" no matter how I change and fiddle with my code. This error only arises when I use my ipGenerator which returns an ip address as a string. If I manually enter in the IP address into the variable ip it runs fine. I am using WingIDE and I have even stopped the code at the offending line and manually entered the ip variable which was generated and the code ran fine. Yet whenever the variable is referencing the random IP generator function, the code fails with builtins.KeyError: [generated ip address]. The line of code which fails is port22 = nm[ip]['tcp'][22]['state']. Here is the code thus far: import nmap from generate_ip import ipPick nm = nmap.PortScanner() ip = ipPick() nm.scan(ip, '22') port22 = nm[ip]['tcp'][22]['state'] Interestingly enough the line nm.scan(ip, '22') works completely find. But it seems to fail when the dictionary entry is accessed by the problem line of code. Any ideas as to why it fails with the function and not with the manual entry? Thanks.
has title: Python-map: builtins.KeyError in line 568 of nmap.py
type: Question
has answer: http://stackoverflow.com/a/48474881
tagged with: python

http://stackoverflow.com/comment/83884791
type: QuestionComment
has text: I would like iterate I do not want to argue about my matrix size or the memory it uses or how sparse it is. I would like advice on how to use Dask and what is the appropriate block size on my short and fat matrix to be as efficient as possible. I only described my workflow in detail so that the Dask peeps would have as much info as possible to give their advice.
comment on: http://stackoverflow.com/q/48403315
score: 0
type: Comment

http://stackoverflow.com/comment/83733256
type: Comment
type: QuestionComment
has text: So have you tried evaluating the length of your result list? You could, for instance, wrap that function in a loop that goes through a list of integers and only prints them out if `len(result)=3`
score: 0
comment on: http://stackoverflow.com/q/48371778

http://stackoverflow.com/q/48389764
has title: Some sensitive filenames cause failure of loading data
downvote count: 1
has body: In using keras.model.load_weights, by the way, the weight file is saved in a hdf5 format, I come across some situations where the folder names that have initial r or t, cause the error: errno = 22, error message = 'invalid argument', flags = 0, o_flags = 0. I want to know if there are some specified rules on the filenames which should be avoided and otherwise would lead to such reading error in python, or the situation I encountered is only specific to keras.
has comment: http://stackoverflow.com/comment/83767474
favorite count: 0
has comment: http://stackoverflow.com/comment/83767335
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83771497
has comment: http://stackoverflow.com/comment/83771443
tagged with: python
has comment: http://stackoverflow.com/comment/83767707
linked to: http://stackoverflow.com/q/19095796
has answer: http://stackoverflow.com/a/48391700
upvote count: 2
has comment: http://stackoverflow.com/comment/83770769
has comment: http://stackoverflow.com/comment/83767685
answer count: 1
score: 1
tagged with: keras

http://stackoverflow.com/q/48385686
has answer: http://stackoverflow.com/a/48670746
has answer: http://stackoverflow.com/a/55388127
tagged with: gpu
tagged with: numba
has comment: http://stackoverflow.com/comment/83759151
has answer: http://stackoverflow.com/a/73352922
has comment: http://stackoverflow.com/comment/83759055
tagged with: python
score: 27
tagged with: cuda
has answer: http://stackoverflow.com/a/62874302
has comment: http://stackoverflow.com/comment/83761119
has answer: http://stackoverflow.com/a/55778411
has comment: http://stackoverflow.com/comment/83816014
upvote count: 27
has body: I am trying to run the code below but an error is reported: NvvmSupportError: libNVVM cannot be found. Do conda install cudatoolkit: library nvvm not found My development environment is: Ubuntu 17.04, Spyder/Python3.5 and I have installed via conda (numba and cudatoolkit). Nvidia GPUs (GTX 1070 and GTX 1060). import numpy as np from timeit import default_timer as timer from numba import vectorize @vectorize(["float32(float32, float32)"], target='cuda') def VecADD(a,b): return a+b n = 32000000 a = np.ones (n, dtype=np.float32) b = np.ones (n, dtype=np.float32) c = np.zeros(n, dtype=np.float32) start = timer() C = VecADD(a,b) print (timer() - start) Does anyone know how to solve this problem?
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/56226390
tagged with: ubuntu
has answer: http://stackoverflow.com/a/56779154
has comment: http://stackoverflow.com/comment/83761230
favorite count: 0
has answer: http://stackoverflow.com/a/61101626
type: Question
has title: Cuda: library nvvm not found
has comment: http://stackoverflow.com/comment/113200310
answer count: 9
has answer: http://stackoverflow.com/a/56246447

http://stackoverflow.com/comment/83749172
type: QuestionComment
comment on: http://stackoverflow.com/q/48380906
score: 0
type: Comment
has text: @AshwiniChaudhary Thanks for your great help.

http://stackoverflow.com/comment/83967096
type: AnswerComment
has text: @vildhjarta: the ABCs are implemented in Python and have base implementations for the methods. `list` and `tuple` are implemented in C code, their implementations are materially different and would be way too slow if they actually inherited from the base ABC implementations.
score: 0
comment on: http://stackoverflow.com/a/48431082
type: Comment

http://stackoverflow.com/comment/83844486
type: Comment
type: QuestionComment
has text: I doubt that this is the [mcve]. Please narrow it down better.
comment on: http://stackoverflow.com/q/48426950
score: 0

http://stackoverflow.com/q/48481223
has comment: http://stackoverflow.com/comment/83955651
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83955503
has title: ValueError: The truth value of a DataFrame is ambiguous
answer count: 2
accepted answer: http://stackoverflow.com/a/48481632
has comment: http://stackoverflow.com/comment/83956032
tagged with: pandas
has answer: http://stackoverflow.com/a/48481632
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/64445754
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83955994
has answer: http://stackoverflow.com/a/64445754
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/83955485
tagged with: valueerror
upvote count: 6
has body: I have a dataframe that looks like this: total downloaded avg_rating id 1 2 2 5.0 2 12 12 4.5 3 1 1 5.0 4 1 1 4.0 5 0 0 0.0 I'm trying to add a new column with the percent difference of two of these columns, but only for columns that do not have a 0 in 'downloaded'. I'm trying to use a function for this that looks like: def diff(ratings): if ratings[ratings.downloaded &gt; 0]: val = (ratings['total'] - ratings['downloaded']) / ratings['downloaded'] else: val = 0 return val ratings['Pct Diff'] = diff(ratings) I'm getting an error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-129-729c09bf14e8&gt; in &lt;module&gt;() 6 return val 7 ----&gt; 8 ratings['Pct Diff'] = diff(ratings) &lt;ipython-input-129-729c09bf14e8&gt; in diff(ratings) 1 def diff(ratings): ----&gt; 2 if ratings[ratings.downloaded &gt; 0]: 3 val = (ratings['total'] - ratings['downloaded']) / ratings['downloaded'] 4 else: 5 val = 0 ~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self) 953 raise ValueError("The truth value of a {0} is ambiguous. " 954 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." --&gt; 955 .format(self.__class__.__name__)) 956 957 __bool__ = __nonzero__ ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Can someone please help me understand what this error means? Also, would this be a good application for an apply function? Can I use conditions in an apply? How would I use it in this case?

http://stackoverflow.com/a/48424280
answers question: http://stackoverflow.com/q/48423858
type: AcceptedAnswer
downvote count: 0
score: 3
has body: TL;DR: Overwriting var1 with a new object will decrease the reference counter of the original object referenced by var1. If the reference count of an object is zero, the object is destroyed (according to this answer). The actual answer is a lot more complex than this, and I don't think I feel comfortable delving too much in depth with the explanation (hopefully someone will step in or point you to another question, I'm fairly certain this is a duplicate). The problem is, Python's garbage collector is implementation-dependent and even in one implementation it can adopt different policies.
type: Answer
accepted answer of: http://stackoverflow.com/q/48423858
upvote count: 3

http://stackoverflow.com/q/48462646
score: 0
has comment: http://stackoverflow.com/comment/83918194
answer count: 1
has answer: http://stackoverflow.com/a/48462949
has comment: http://stackoverflow.com/comment/83918162
has title: Write a list of different types to a binary file
type: Question
has comment: http://stackoverflow.com/comment/83918174
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48462949
has body: I have a variable of list, airMod, consisting of different types of data: char, uint32, and float. Here is how it looks like in my visual studio code debug mode: Now I'd like to save it in a binary file(raw buffer. I will use C++ to process it byte by byte). I am wondering how I should do it. I searched how it should be done, but mostly the solution of save a list containing same data type (ex. bytearray, to_byte.....). I would like to save the data, then process it in C++ ((fseek, tellg, ifstream, etc. ).Thanks a lot.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83915946
type: AnswerComment
score: 0
has text: @Nullman - Thank you for the recommendation. I have done what you suggested and it has worked on the fields within 'variants', though I cannot pass through the data from the top line in my file. Is there a way to combine this to get the data from the nested and top level data on the same row?
comment on: http://stackoverflow.com/a/48445528
type: Comment

http://stackoverflow.com/comment/83809451
type: AnswerComment
has text: My error -- When I added ... well, I retyped the entire list and used the wrong bookends.
comment on: http://stackoverflow.com/a/48409688
type: Comment
score: 0

http://stackoverflow.com/q/48415038
has answer: http://stackoverflow.com/a/48415061
has comment: http://stackoverflow.com/comment/83819830
answer count: 4
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/48415067
has answer: http://stackoverflow.com/a/48415636
has answer: http://stackoverflow.com/a/48415067
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48415556
score: 4
has comment: http://stackoverflow.com/comment/83819851
has title: Python: Better way to take every letter/number/etc. from a string and convert it into a list?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48415061
has body: I actually know how to do this using loop, but the code looks too ugly :-(. So I would like to ask some better methods. E.g. I have a string: a = "123 456 7sr" I want to convert every number/letter/empty space/etc into a list. The desired result should be like: ["1", "2", "3", " ", "4", "5", "6", " ", "7", "s", "r"] Is there some other methods? (Please not the methods using the for/while loop) Thanks for the help!

http://stackoverflow.com/q/48344087
accepted answer: http://stackoverflow.com/a/48344206
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33346591
has body: I have a DataFrame with two columns "A" and "B". A B 0 foo one 1 bar one 2 foo two 3 bar one 4 foo two 5 bar two 6 foo one 7 foo one 8 xyz one For each group in "A", I'm trying to get the count of each value of "B", i.e. each sub-group of B, but aggregated on the grouping of "A". The result should look like this: A B countOne countTwo 0 foo one 3 2 1 bar one 2 1 2 foo two 3 2 3 bar one 2 1 4 foo two 3 2 5 bar two 2 1 6 foo one 3 2 7 foo one 3 2 8 xyz one 1 0 I have tried several approaches to no avail, so far I'm using this approach: A_grouped = df.groupby(['A', 'B'])['A'].count() A_grouped_ones = A_grouped[:,'one'] A_grouped_twos = A_grouped[:,'two'] df['countOne'] = df['A'].map(lambda a: A_grouped_ones[a] if a in A_grouped_ones else 0) df['countTwo'] = df['A'].map(lambda a: A_grouped_twos[a] if a in A_grouped_twos else 0) However, this seems horribly inefficient two me. Is there a better solution?
tagged with: python
has title: Get the count for each subgroup in a multiple grouped pandas.DateFrame aggregated on one group
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48344206

http://stackoverflow.com/q/48396047
type: Question
upvote count: 0
downvote count: 2
tagged with: random
type: UnansweredQuestion
has title: Check if 2 strings in a wordlist are identical python
has comment: http://stackoverflow.com/comment/83779641
has comment: http://stackoverflow.com/comment/83779605
has answer: http://stackoverflow.com/a/48396286
favorite count: 0
has comment: http://stackoverflow.com/comment/83779696
answer count: 3
has answer: http://stackoverflow.com/a/48396130
has comment: http://stackoverflow.com/comment/83779656
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/48396128
has body: Right now I'm making a slot-machine kind of code and I've hit a roadblock. In this piece you get a wordlist containing the outcome. (SlotOption is a different wordlist) slots = [random.choice(slotOption), random.choice(slotOption), random.choice(slotOption)] And I'm trying to make a piece that compare all the strings in the wordlist to check if any of them are the same. Can someone help?

http://stackoverflow.com/q/48398211
linked to: http://stackoverflow.com/q/13332268
has title: CalledProcessError: Command '('grep', 'route')' returned non-zero exit status 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48398288
tagged with: linux
linked to: http://stackoverflow.com/q/32942207
tagged with: bash
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: Python3 OSX 10.13.2 I am trying to make FACEBOOK_WHITELIST in order to prevent malicious attack from the internet when listening to webhook I am in the process of getting the IP addresses. The command is very simple just whois, pipe, and grep. Problem: def test(): import subprocess ps = subprocess.Popen( ["whois", "-h", "whois.radb.net", "--", "'-i origin AS32934'"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = subprocess.check_output(('grep', 'route'), stdin=ps.stdout) ps.wait() Trackback: --------------------------------------------------------------------------- CalledProcessError Traceback (most recent call last) &lt;ipython-input-28-8d5c434d09bd&gt; in &lt;module&gt;() 5 stderr=subprocess.STDOUT 6 ) ----&gt; 7 output = subprocess.check_output(('grep', 'route'), stdin=ps.stdout) 8 ps.wait() ~/.pyenv/versions/3.6.4/lib/python3.6/subprocess.py in check_output(timeout, *popenargs, **kwargs) 334 335 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, --&gt; 336 **kwargs).stdout 337 338 ~/.pyenv/versions/3.6.4/lib/python3.6/subprocess.py in run(input, timeout, check, *popenargs, **kwargs) 416 if check and retcode: 417 raise CalledProcessError(retcode, process.args, --&gt; 418 output=stdout, stderr=stderr) 419 return CompletedProcess(process.args, retcode, stdout, stderr) 420 CalledProcessError: Command '('grep', 'route')' returned non-zero exit status 1. Then I tried smaller function call. Neither of them are work. First one is single string in single quote In [46]: ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "'-i origin AS32934'"]) ...: ...: In [47]: % No entries found for the selected source(s). Second one is split string into multiple double quoted string In [48]: ps = subprocess.Popen(["whois", "-h", "whois.radb.net", "--", "'-i", "origin", "AS32934'"]) In [49]: % No entries found for the selected source(s). % No entries found for the selected source(s). % No entries found for the selected source(s). Where am I wrong?…
has answer: http://stackoverflow.com/a/48398288
tagged with: python

http://stackoverflow.com/q/48422762
accepted answer: http://stackoverflow.com/a/49160705
linked to: http://stackoverflow.com/q/13208286
has answer: http://stackoverflow.com/a/49160705
has body: I was writing a very simple script to count ellipsoid area and volume and some other things. I was presenting my output printing it out like this: print('Dims: {}x{}m\nArea: {}m^2\nVolume: {}m^3'.format(a, round(b,2), P, V)) What, of course, gave this output (with sample data): Dims: 13.49x2.25m Area: 302.99m^2 Volume: 90.92m^3 As I wrote earlier, I am using jupyter notebook, so I can use $ operators in markdown cells to create LaTeX formulas. My question is, is it possible to generate output using Python code in a way that it will be understood as LaTeX formula and printed in such a way, that: Thanks for all replies.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/75826429
type: Question
tagged with: latex
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83846102
possible better answer: http://stackoverflow.com/a/57312893
score: 48
has title: Is it possible to show `print` output as LaTeX in jupyter notebook?
upvote count: 48
has answer: http://stackoverflow.com/a/57312893
tagged with: python
tagged with: ipython
answer count: 4
has answer: http://stackoverflow.com/a/77709002
tagged with: jupyter-notebook

http://stackoverflow.com/a/48503474
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48479215
score: 1
has body: For business reasons, Connect webhooks can only associated with all envelopes (or all envelopes from a template/powerform) if the Account-level Connect option is purchased. It is available as an add-on for many account types. In that case, as you mention, your webhook listener will receive notifications of envelope events that it is not interested in. For those notification messages, respond 200 (received) and then discard the information.
answers question: http://stackoverflow.com/q/48479215

http://stackoverflow.com/a/48350689
score: 0
has body: To tell if a number is a multiple of three, it should be if counter3 % 3 == 0: counter3 % 3 computes the remainder of counter3 / 3, and this remainder is 0 for exact multiples. Then you need to indent the statements that should be executed when this condition is true. So the loop should be: while counter3 &lt;= 1000: if counter3 % 3 == 0: theList.append(counter3) counter3 = counter3+1 Instead of a while loop, you can use for: for counter3 in range(1, 1001): if counter3 % 3 == 0: theList.append(counter3)
answers question: http://stackoverflow.com/q/48350299
type: Answer

http://stackoverflow.com/comment/83746648
type: QuestionComment
comment on: http://stackoverflow.com/q/48379852
score: 0
has text: It is basically a domain restriction, https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html. You need to remove domain restriction.
type: Comment

http://stackoverflow.com/q/48355543
has comment: http://stackoverflow.com/comment/83697690
has comment: http://stackoverflow.com/comment/83699337
type: Question
has body: I am reading a csv file in python and extracting the column containing json data and extracting the required key-value pairs. So I have given the list of good columns(say good_columns =[]) that I want on my list and I am appending the values for that key in new list(say data=[]) but in json some keys are there that I don't want according to my good column list for that I want to add zero to my data list. Thanks in advance. good_columns = [ "outboundrtp_roundTripTime", "outboundrtp_targetBitrate", "outboundrtp_bytesSent", "outboundrtp_packetsSent", "outboundrtp_packetsLost", "inboundrtp_inboundJitter" , "inboundrtp_bytesReceived" , "inboundrtp_packetsLost" ] json content: { "endpoint_AudioE2ELatency": 0, "endpoint_VideoE2ELatency": 165, "outboundrtp_roundTripTime": 0.340, "outboundrtp_targetBitrate": 17586, "outboundrtp_bytesSent": 8880, "outboundrtp_packetsSent": 78, "outboundrtp_packetsLost": 1, "outboundrtp_remb": 0, "inboundrtp_inboundJitter": 0.024, "inboundrtp_bytesReceived": 24835, "inboundrtp_packetsLost": 0, "inboundrtp_remb": 0 } { "endpoint_AudioE2ELatency": 0, "endpoint_VideoE2ELatency": 149, "outboundrtp_roundTripTime": 0, "outboundrtp_targetBitrate": 5616, "outboundrtp_bytesSent": 37366, "outboundrtp_packetsSent": 654, "outboundrtp_packetsLost": 0, "outboundrtp_remb": 0 } I want my list to contain with value 0 for the keys, not in good columns. So it should give result like: for the first one: Desired output: [0.340,17586,8880,78,1,0.024,24835,0] Current output: [0,0,0.340,17586,8880,78,1,0] for the second one: Desired output: [0,5616,37366,654,0,0,0] Current output: [0,0,0,5616,37366,654,0] What I have tried: for key, value in record.items(): if key in good_columns: data.append(value) elif key not in good_columns: data.append(0) But this is not giving the desired output.
answer count: 2
upvote count: 2
has title: Extract only values from json that matches with good columns list
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83697773
score: 2
has answer: http://stackoverflow.com/a/48358813
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48355627

http://stackoverflow.com/q/48342556
tagged with: server
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48349031
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83678667
answer count: 1
has comment: http://stackoverflow.com/comment/83674219
tagged with: python-requests
has body: I want to be able to call a python script by making a request on a Python server I created from this tutorial I want that when the server receive a particular request, it launch the Python script. I tried this simple code without success. I thought that on GET request it will launch the externalFunc.py script. But it does not. #!/usr/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import os #Create custom HTTPRequestHandler class class KodeFunHTTPRequestHandler(BaseHTTPRequestHandler): #handle GET command def do_GET(self): execfile("root\externalFunc.py") def run(): print('http server is starting...') #ip and port of servr #by default http server port is 80 server_address = ('127.0.0.1', 80) httpd = HTTPServer(server_address, KodeFunHTTPRequestHandler) print('http server is running...') httpd.serve_forever() if __name__ == '__main__': run() I dont have any error, just nothing happens. What am I doing wrong ? EDIT : Here is the GET request made by the client : import sys #get http server ip http_server = '127.0.0.1' #create a connection conn = httplib.HTTPConnection(http_server) #request command to server conn.request('GET', '','') #get response from server rsp = conn.getresponse() #print server response and data print(rsp.status, rsp.reason) data_received = rsp.read() print(data_received) conn.close() And I got a 501 error from the server : 127.0.0.1 - - [20/Jan/2018 15:46:46] code 501, message Unsupported method ('GET') 127.0.0.1 - - [20/Jan/2018 15:46:46] "GET / HTTP/1.1" 501 -
type: Question
has comment: http://stackoverflow.com/comment/83683063
has title: Call Python script on request - Python server

http://stackoverflow.com/q/48366704
type: Question
has body: I have come across fitter package in python which fits the continuous distributions to the given data and identifies the most closest distribution which fits the data Now if I want to check for the discreet distribution , as in which discreet distributions fits the data best for and example If my data contains just array of values A = [0.1, 0.2, 0.5, 0.6, 0.7, 0.8] I want to check if my data fits with binomial/Poisson/or any other discrete distributions. I have gone through few statistical approaches: Ks test is being used but it is only for continuous data. On exploring I got to know python has chisquare test which takes actual value and expected values and degree of freedom as input. If I just have actual values and not expected values then is it a correct way to validate of my data fits to discrete distributions. Can someone help me understand which statistical test would be ideal for this scenario?
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83722508
has title: Fitting discreet distribution to data
has comment: http://stackoverflow.com/comment/85238268

http://stackoverflow.com/q/48382937
linked to: http://stackoverflow.com/q/15988782
has comment: http://stackoverflow.com/comment/83752696
has comment: http://stackoverflow.com/comment/83758086
type: Question
linked to: http://stackoverflow.com/q/63561028
has comment: http://stackoverflow.com/comment/83752855
has comment: http://stackoverflow.com/comment/83758008
has comment: http://stackoverflow.com/comment/83758603
tagged with: python
has comment: http://stackoverflow.com/comment/83752598
tagged with: pygame
has title: Collision detection variable always output "True"?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83759368
has comment: http://stackoverflow.com/comment/83758398
has comment: http://stackoverflow.com/comment/83757270
tagged with: collision
has comment: http://stackoverflow.com/comment/83758697
duplicate of: http://stackoverflow.com/q/63561028
upvote count: 2
has comment: http://stackoverflow.com/comment/83752912
has body: I apologise if you have seen a post of mine regarding this issue already, I am desperate to solve this. I am creating a 2-player top down racing game and need to create a way for the program to know when the users have completed a lap. I have chosen to do this by placing sprites on the track, with the same texture as the track, so that they blend in. The idea is to create a list for each player's vehicle, containing boolean variables, one variable for each checkpoint. Every boolean variable in the list has to equal "True" in order for a lap to be counted. Before I attempt this, I want to figure out how it can be done by detecting when the player's vehicles collide with each other. I have attempted, with help from a previous post, to do this. My vehicle class can be seen, with my checkCollision function, below. class Vehicle(pygame.sprite.Sprite): 'Base class for all vehicles (Cars and Motorbikes) in the game' vehicleCount = 0 def __init__(self, max_speed, acceleration, turning_radius, image): #pygame.sprite.Sprite.__init__(self) self.max_speed = max_speed self.acceleration = acceleration self.turning_radius = turning_radius self.image = image self.rect = self.image.get_rect() Vehicle.vehicleCount = Vehicle.vehicleCount + 1 def displayAmount(): print ("Total number of Vehicle enteries: ", Vehicle.vehicleCount) def displayVehicle(self): print ("max speed: ", self.max_speed, "acceleration: ", self.acceleration, "turning radius: ", self.turning_radius) def checkCollision(self, sprite2): col = pygame.sprite.collide_rect(self, sprite2) if col == True: print ("True") Here is an example of one of my vehicle objects being defined: sportscar = Vehicle(4.5, 0.2, 2.01, sportsimage) I am checking if the vehicles have intersecting by running the following line in the main game loop: choice1.checkCollision(choice2) However, when I run the program, the console outputs "True" constantly, even when the vehicles aren't touching. Does anyone know where I have gone wrong with this? Than…
has comment: http://stackoverflow.com/comment/83758495
has comment: http://stackoverflow.com/comment/83758323
answer count: 0
score: 1
tagged with: sprite
downvote count: 1
favorite count: 0
tagged with: rect
duplicate of: http://stackoverflow.com/q/57730329
has comment: http://stackoverflow.com/comment/83752801
duplicate of: http://stackoverflow.com/q/29640685
linked to: http://stackoverflow.com/q/39324985
has comment: http://stackoverflow.com/comment/83758771
has comment: http://stackoverflow.com/comment/83758162

http://stackoverflow.com/comment/83793909
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48402738
has text: Ev.Konis => your solution worked. how do i close the ticket and mark your answer as solution?
type: Comment

http://stackoverflow.com/q/48341068
answer count: 1
has comment: http://stackoverflow.com/comment/83667446
has comment: http://stackoverflow.com/comment/83667396
linked to: http://stackoverflow.com/q/2050961
linked to: http://stackoverflow.com/q/5222408
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/2050961
tagged with: python
has answer: http://stackoverflow.com/a/48341122
score: 0
has body: So I've been trying out some things in Python to refresh my mind. I've been following 'Learn Python the Hard Way' book and they introduced me to argv. However, for whatever reason, argv seems to be taking the filename as an argument as well, which I don't think should be happening. My code looks like this: from sys import argv value1, value2 = argv print("Hi") print("you seem bored") print(value1) print(value2) And this is what I'm getting on the terminal: userblahblah:Python nut$ python3 another_test.py hi po Traceback (most recent call last): File "another_test.py", line 3, in &lt;module&gt; value1, value2 = argv ValueError: too many values to unpack (expected 2) When I feed in one argument, this is the output: notrealname:Python nut$ python3 another_test.py hi Hi you seem bored another_test.py hi
duplicate of: http://stackoverflow.com/q/5222408
has title: Why is argv taking filename as an argument?

http://stackoverflow.com/comment/83805287
type: QuestionComment
has text: What do you want to compute? `bool1`?
comment on: http://stackoverflow.com/q/48408062
score: 0
type: Comment

http://stackoverflow.com/comment/83859050
comment on: http://stackoverflow.com/a/48433723
score: 0
type: Comment
type: AnswerComment
has text: @roganjosh The other answer uses `.format()`, so I'll leave mine with string concatenation. But I've moved the joining out to another variable.

matrix
tags question: http://stackoverflow.com/q/48464480
tags question: http://stackoverflow.com/q/48359053
tags question: http://stackoverflow.com/q/48373550
tag name: matrix
tags question: http://stackoverflow.com/q/48447841
tags question: http://stackoverflow.com/q/48458326
tags question: http://stackoverflow.com/q/48348828
tags question: http://stackoverflow.com/q/48380129
tags question: http://stackoverflow.com/q/48474308
tags question: http://stackoverflow.com/q/48386479
tags question: http://stackoverflow.com/q/48358002
tags question: http://stackoverflow.com/q/48447005
tags question: http://stackoverflow.com/q/48368179
tags question: http://stackoverflow.com/q/48344065
tags question: http://stackoverflow.com/q/48451231
tags question: http://stackoverflow.com/q/48336165
tags question: http://stackoverflow.com/q/48344706
tags question: http://stackoverflow.com/q/48356593
tags question: http://stackoverflow.com/q/48454627
tags question: http://stackoverflow.com/q/48404268
tags question: http://stackoverflow.com/q/48364447
tags question: http://stackoverflow.com/q/48399707
tags question: http://stackoverflow.com/q/48448288
type: Tag

http://stackoverflow.com/q/48386339
tagged with: string
has comment: http://stackoverflow.com/comment/83760154
has comment: http://stackoverflow.com/comment/83760575
tagged with: parsing
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83760281
has comment: http://stackoverflow.com/comment/83760880
type: UnansweredQuestion
tagged with: python
tagged with: regex
score: 0
has comment: http://stackoverflow.com/comment/83761385
answer count: 0
has body: 1) I have a list of string that contains url link like this: url = "https://www.hostname.com/p/aaa/category/1kuwuz-abcd" 2) and list of strings containing so many string regex like this: ls = [cat. , jumping.dog, ...] ## . (any characters can be inserted) 1) How could i extracting the category? 2) I want to categorizing each element on the list. (ex: if cat. return "cat", or if jumping.dog return "dog") What i have done were by searching string manually one by one : re.search(category1, url) re.search(category2, url) re.search(category3, url) and so for the 2nd problems, manually i make the list become: ls = ['cat', 'cats', 'jumping-dog', 'jumping dog', ...] Can anybody help me in writing for efficient commands? I am new to regex and any help would be appreciated. Thanks!
has title: Python REGEX get category from link url and list of strings
has comment: http://stackoverflow.com/comment/83760503

python-3.6
tags question: http://stackoverflow.com/q/48394344
tags question: http://stackoverflow.com/q/48484885
tags question: http://stackoverflow.com/q/48369297
tags question: http://stackoverflow.com/q/48470529
tags question: http://stackoverflow.com/q/48432611
tags question: http://stackoverflow.com/q/48471086
tags question: http://stackoverflow.com/q/48477949
tags question: http://stackoverflow.com/q/48362950
tags question: http://stackoverflow.com/q/48456900
tags question: http://stackoverflow.com/q/48386253
tags question: http://stackoverflow.com/q/48476180
tags question: http://stackoverflow.com/q/48439854
tags question: http://stackoverflow.com/q/48351165
tags question: http://stackoverflow.com/q/48480193
tags question: http://stackoverflow.com/q/48427127
type: Tag
tag name: python-3.6
tags question: http://stackoverflow.com/q/48388849
tags question: http://stackoverflow.com/q/48355995
tags question: http://stackoverflow.com/q/48362904
tags question: http://stackoverflow.com/q/48468141
tags question: http://stackoverflow.com/q/48392761
tags question: http://stackoverflow.com/q/48424438
tags question: http://stackoverflow.com/q/48444603
tags question: http://stackoverflow.com/q/48480446
tags question: http://stackoverflow.com/q/48471702
tags question: http://stackoverflow.com/q/48431187

http://stackoverflow.com/a/48456235
answers question: http://stackoverflow.com/q/48455204
type: Answer
has comment: http://stackoverflow.com/comment/83939789
has body: I think you use Python 2.x. You can use 3.x instead, your code will work fine without encode required. For 2.x, refer to Unicode HOWTO. For short, you can replace every 'your string' with u'your string'.
score: 0

http://stackoverflow.com/comment/83912824
has text: @quamrana: So that means doing: `import script2, script3, script4` and then `scriptN.myfunc()`?
comment on: http://stackoverflow.com/q/48459455
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/61182045
downvote count: 1
answers question: http://stackoverflow.com/q/48373131
type: Answer
has body: TFRecord is a detail here, which means you can still get it working with TextIO. The trick here is Coder, which is used for encoding and decoding a type during pipeline runs. Generally you should use them unless the type is builtin / trivial. In the protobuf class, using ProtoCoder is simply the right thing to do. from google.protobuf.timestamp_pb2 import Timestamp import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions class ToProtoFn(beam.DoFn): def process(self, element): timestamp = Timestamp() timestamp.seconds, timestamp.nanos = [int(x) for x in element.strip().split(',')] print(timestamp) yield timestamp with beam.Pipeline(options=PipelineOptions()) as p: lines = (p | beam.Create(["1586753000,222333000", "1586754000,222333000"]) | beam.ParDo(ToProtoFn()) | beam.io.WriteToText('time-pb', coder=beam.coders.ProtoCoder(Timestamp().__class__))) class ToCsvFn(beam.DoFn): def process(self, element): print(element) yield ",".join([str(element.seconds), str(element.nanos)]) with beam.Pipeline(options=PipelineOptions()) as p: lines = (p | beam.io.ReadFromText('time-pb-00000-of-00001', coder=beam.coders.ProtoCoder(Timestamp().__class__)) | beam.ParDo(ToCsvFn()) | beam.io.WriteToText('time-csv'), )
score: -1
has comment: http://stackoverflow.com/comment/133455177
upvote count: 0

http://stackoverflow.com/q/48429661
has title: How to decrease the constructor overhead by automatic acquisition and release from an object pool?
tagged with: object-pooling
accepted answer: http://stackoverflow.com/a/48429982
has comment: http://stackoverflow.com/comment/83850104
type: AnsweredQuestion
has body: I have created an immutable data type in Python where millions of objects are created and released every second. After profiling the code thoroughly, it looks like the constructor is where most of the time is spent. The solution I thought of was to use an object pool so that reference counting and memory allocation is done all at once. I have looked at solutions like this, where acquire and release methods need to be called explicitly. However, the class I have implemented is similar to Decimal class in Python where objects are created and released automatically by numpy. For example, a short piece of code that uses my class will look like this (I use Decimal instead of my own class): import numpy as np from decimal import Decimal x = np.array([[Decimal(1), Decimal(2)], [Decimal(3), Decimal(4)]] y = np.array([[Decimal(5), Decimal(6)], [Decimal(7), Decimal(8)]] z = (x * y) + (2 * x) - (y ** 2) + (x ** 3) Because the class is immutable, numpy needs to create a new object for each operation and this slows down the whole code. Additionally, because numpy is the code that is creating these objects, I do not think that I can explicitly call methods such as acquire or release. Is there a better implementation of an object pool or some other method where a lot of objects are created all at once and later, the released objects are automatically placed back in the pool? In other words, is there another solution that avoids frequent object creation and destruction? P.S. I understand that this is not a good way of using numpy. This is one of the first steps in my design and hopefully, numpy will be used more efficiently in next steps.
score: 0
tagged with: oop
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83850077
type: Question
tagged with: numpy
tagged with: python
has answer: http://stackoverflow.com/a/48429982

http://stackoverflow.com/comment/83804828
comment on: http://stackoverflow.com/q/48407384
type: Comment
type: QuestionComment
score: 0
has text: @cdarke, I am not familiar with Pyomo, but it seems it works with Barron.

http://stackoverflow.com/comment/83876054
has text: @brunodesthuilliers Good call, i'll edit the post, thanks
type: Comment
comment on: http://stackoverflow.com/a/48441925
score: 0
type: AnswerComment

http://stackoverflow.com/comment/113699743
comment on: http://stackoverflow.com/a/48347543
type: Comment
type: AnswerComment
has text: No. This did not work.
score: 0

http://stackoverflow.com/a/48373612
has body: Unlike Evan Rose's (now-deleted) answer claims, this is not due to an epsilon value in the sqrt algorithm. Most math module functions cast their inputs to float, and math.sqrt is one of them. 99999999999999975425 cannot be represented as a float. For this input, the cast produces a float with exact numeric value 99999999999999983616, which repr shows as 9.999999999999998e+19: &gt;&gt;&gt; float(99999999999999975425) 9.999999999999998e+19 &gt;&gt;&gt; int(_) 99999999999999983616L The closest float to the square root of this number is 10000000000.0, and that's what math.sqrt returns.
score: 7
type: Answer
answers question: http://stackoverflow.com/q/48373532
downvote count: 1
upvote count: 8

http://stackoverflow.com/q/48384054
has body: I cythonize *.pyx files manually using cython -3 -Wextra mymodule.pyx I use the -Wextra option to generate additional warnings, useful for cleaning up redundant code pieces. However, many warnings of the form warning: mymodule.pyx:123:45: local variable 'x' might be referenced before assignment are printed, which I do not care for. I understand why it is not obvious from the perspective of the compiler, but under no circumstance is it ever possible for x to not be assigned before referencing, in my particular situation. I would therefore like to keep using -Wextra but filter out this type of warning, similar to the -Wno option of gcc. I have however not been able to track down such a feature.
upvote count: 3
answer count: 1
tagged with: warnings
accepted answer: http://stackoverflow.com/a/48388424
downvote count: 0
tagged with: cython
has answer: http://stackoverflow.com/a/48388424
favorite count: 0
type: Question
tagged with: python-3.x
has title: Suppress warnings from Cython
tagged with: suppress-warnings
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/48447114
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48446691
score: 3
type: Answer
has body: If the frontend will run on a browser executed on a laptop o desktop it will run fine, but if the interface will run on a browser executed on the Pi maybe it will be too expensive in terms of GPU/CPU usage and it will require fine tuning in order to avoid unnecessary re-renders. So if the browser is on a remote machine ok, if not think about a something like TkInter for UI.
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48446691

http://stackoverflow.com/q/48385336
has title: Seaborn swarmplot: Get point coordinates
type: Question
has comment: http://stackoverflow.com/comment/83760553
has body: I'm plotting data using seaborn's swarm method. After the plot is drawn, I'd like to retrieve the (x,y)-coordinates of the drawn points. My application for this is: I want to add a legend to the plot, and automatically (I have a large number of plots…) decide whether to display the legend inside or outside the plot. For this, I'd first draw the legend inside, get its bounding box, and check whether any of the drawn points overlap that bounding box. If that is the case, redraw the whole plot with the legend outside. Is it possible to retrieve the coordinates of the drawn points? I tried iterating over the axes's get_children(), but there seem to be other artists in there, which are not points and which cause my legend to go outside even if it would not overlap with any data points. Looking at the code, I don't see any obvious way of doing this, since the coordinates from the beeswarm() method don't seem to be stored anywhere, but perhaps I missed something? Thanks in any case, Lukas Edit: Here's a minimal example: test_data = pd.DataFrame([ {'x': 1, 'y': 1.0, 'color': 1.0}, {'x': 1, 'y': 2.0, 'color': 0.5}, {'x': 1, 'y': 2.8, 'color': 0.25}, {'x': 1, 'y': 4.0, 'color': 0.125}, {'x': 2, 'y': 1.0, 'color': 1.0}, {'x': 2, 'y': 2.0, 'color': 0.5}, {'x': 2, 'y': 2.7, 'color': 0.25}, {'x': 2, 'y': 4.0, 'color': 0.125}, {'x': 3, 'y': 1.0, 'color': 1.0}, {'x': 3, 'y': 2.0, 'color': 0.5}, {'x': 3, 'y': 2.7, 'color': 0.25}, {'x': 3, 'y': 4.0, 'color': 0.125}, ]) p = sns.swarmplot(data=test_data, x='x', y='y', hue='color') legend = p.legend(frameon=True) legend.get_frame().set_fc('gray') This produces this image: I'd like to detect that the legend overlaps the top-rightmost point and draw it outside the plot.
has comment: http://stackoverflow.com/comment/83758611
duplicate of: http://stackoverflow.com/q/36615354
answer count: 0
type: UnansweredQuestion
tagged with: seaborn
downvote count: 0
linked to: http://stackoverflow.com/q/36615354
has comment: http://stackoverflow.com/comment/83759278
has comment: http://stackoverflow.com/comment/83759454
favorite count: 0
has comment: http://stackoverflow.com/comment/83759508
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83759328
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/a/48384995
type: AcceptedAnswer
downvote count: 0
score: 4
has body: You can get the available magics via: from IPython import get_ipython line_magics = list(get_ipython().magics_manager.magics.get('line')) cell_magics = list(get_ipython().magics_manager.magics.get('cell'))
answers question: http://stackoverflow.com/q/48384416
type: Answer
accepted answer of: http://stackoverflow.com/q/48384416
upvote count: 4

http://stackoverflow.com/q/48465788
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: inheritance
has title: In a nested class in Python what's the best way to access the outer classes parent class?
has comment: http://stackoverflow.com/comment/83926210
has answer: http://stackoverflow.com/a/48466396
score: 1
tagged with: nested
tagged with: python
has body: I have a non trivial Django system and there's a lot of Meta class inheritance going on. Boiled down to it's essence that looks like this: class Base: class Meta: pass class Child(Base): class Meta(Base.Meta): # this pass class GrandChild(Child): class Meta(Child.Meta): # this pass The problem with this is it's easy to overlook the lines marked "this" when making changes to the inheritance structure. This is fundamentally the same problem as with Python2's super requiring the name of the parent class. And like with that what I'd like is a way of writing those lines in a way that doesn't explicitly reference the outer classes base. Something like: class Base: class Meta: pass class Child(Base): class Meta(super.Meta): # this pass class GrandChild(Child): class Meta(super.Meta): # this pass Is there anyway of doing this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83926286
tagged with: inner-classes

http://stackoverflow.com/q/48467759
score: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48467866
has answer: http://stackoverflow.com/a/48467922
has answer: http://stackoverflow.com/a/48467943
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48467916
tagged with: dataframe
tagged with: python
has title: Removing strings from df column in Python
answer count: 4
has answer: http://stackoverflow.com/a/48467916
accepted answer: http://stackoverflow.com/a/48467866
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83929162
has comment: http://stackoverflow.com/comment/83929057
has body: I'm working in a python3 jupyter notebook. I'm trying to do some numerical calculations on a column in my dataframe which is made up of dollar amounts. Some of the lines have "$- " instead of numbers. How do I tell python to ignore those rows so I can look at the valid data? movie is my dataframe revenue is the column I'm looking at set(movie['revenue']) I get this type of output: {' $- ', '1', '10', '100', '10000', '97250400', '98000000', '99000000'} I've tried a few ways so far: movie['revenue'] = pd.to_numeric(movie['revenue']) movie['revenue'] = movie['revenue'].astype(np.float64) Nothing seems to work. Please help!
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83964579
type: QuestionComment
comment on: http://stackoverflow.com/q/48483765
has text: It looks like you’re asking several questions here: 1) how do I launch a program without the full path or knowing if it ends with “exe”? 2) how do I get a list of installed programs? The problem here is that combined this is too broad of a question. You’ll see naive attempts at scanning the file system for the latter, but you shouldn’t use that as a solution. You could use subprocess.call() but pass shell=True to have it look at the PATH and COMSPEC. You should really narrow the question down. What is it that you are trying to implement?
score: 1
type: Comment

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48368219
tag name: pygobject

http://stackoverflow.com/a/48411362
has comment: http://stackoverflow.com/comment/83813305
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: You can use np.random.choice, generate random indices, and index df. idx = np.random.choice(len(df), int(15e6)) df = df.iloc[idx, :]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48411339
answers question: http://stackoverflow.com/q/48411339

http://stackoverflow.com/comment/83838746
score: 0
has text: How is `User` defined within `groups/models.py`? Is it a separate class within that file, or is it imported from somewhere else?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48415015

http://stackoverflow.com/q/48344706
type: Question
tagged with: storage
has comment: http://stackoverflow.com/comment/83675612
tagged with: numpy
has comment: http://stackoverflow.com/comment/83776382
has comment: http://stackoverflow.com/comment/83676797
has comment: http://stackoverflow.com/comment/83675495
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48351203
has comment: http://stackoverflow.com/comment/83688331
has answer: http://stackoverflow.com/a/48360686
has comment: http://stackoverflow.com/comment/83675123
upvote count: 6
tagged with: arrays
has comment: http://stackoverflow.com/comment/83675521
score: 6
has comment: http://stackoverflow.com/comment/83675379
tagged with: python
has comment: http://stackoverflow.com/comment/83675416
has title: Python/Numpy: Efficiently store non-sparse large symmetric arrays?
has comment: http://stackoverflow.com/comment/83979909
answer count: 2
has comment: http://stackoverflow.com/comment/83675120
has body: I am trying to store data on my hard drive that comes in the form of 2 million symmetric 100x100 matrices. Almost all elements of these matrices are non-zero. I am currently saving this data in 200 npy files; each of which has size 5.1GB and contains 100000x100x100 numpy array. This takes up more than 1TB of hard drive space. Is there anyway that I can use the fact that the matrices are symmetric to save space on my hard drive?
tagged with: matrix
has comment: http://stackoverflow.com/comment/83979888
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48383082
has title: How to get a list of all methods decorated with `@property`?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48383157
accepted answer: http://stackoverflow.com/a/48383157
answer count: 2
has comment: http://stackoverflow.com/comment/83753749
has body: How to get a list of all methods of a class which have been decorated with the @property decorator? Having the following example, the answer should get a list with only x and y included, but not z, since it hasn't been decorated with @property: class C(object): def __init__(self): self._x = None self._y = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x @property def y(self): return self._y def z(self): pass
tagged with: python
has comment: http://stackoverflow.com/comment/83753328
has answer: http://stackoverflow.com/a/48383196
has comment: http://stackoverflow.com/comment/83753435
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83753793
has comment: http://stackoverflow.com/comment/83753388
downvote count: 2
has comment: http://stackoverflow.com/comment/83752917
score: 1
possible better answer: http://stackoverflow.com/a/48383196
has comment: http://stackoverflow.com/comment/83753308

http://stackoverflow.com/q/48412422
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83815105
possible better answer: http://stackoverflow.com/a/48412672
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48412672
downvote count: 1
has answer: http://stackoverflow.com/a/48412664
has comment: http://stackoverflow.com/comment/83815244
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83814994
has title: How can I determine which variable to use for a defined function in python
accepted answer: http://stackoverflow.com/a/48412664
score: 1
has body: I have defined this function : def xintegral(x,k,z,xdot): f=np.exp((x-xdot)**2*k/(2*z)*1j) return f And I want to insert this function in the place of func to this process: def simpson(func,mini,maxi,N): sum=0 h=(maxi-mini)/N even=mini+2*h odd=mini+h for i in range(N//2-1): sum+=func(even)*2 even+=2*h for i in range(N//2): sum+=func(odd)*4 odd+=2*h sum=(sum+(func(mini)+func(maxi)))*h/3 return sum I want to use as a func the xintegral with variable the xdot. So I tried to write it like that : simpson(xintegral(x,k,z,xdot),mini,maxi,N) but I want the variable to be the xdot. The variables odd,mini,maxi can replace xdot? How can I do that?
has comment: http://stackoverflow.com/comment/83815150
favorite count: 0
has comment: http://stackoverflow.com/comment/83815180

http://stackoverflow.com/comment/83864913
has text: @Alex Nice of you [holder of selected answer] to say this! Thank you for appreciating this approach.
score: 0
comment on: http://stackoverflow.com/a/48435149
type: AnswerComment
type: Comment

angular
tags question: http://stackoverflow.com/q/48457416
tags question: http://stackoverflow.com/q/48475006
tag name: angular
type: Tag
tags question: http://stackoverflow.com/q/48479269

http://stackoverflow.com/comment/121555681
comment on: http://stackoverflow.com/a/48336358
has text: Probably you also need to understand the concept of current working directory. See also [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory/66860904)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84437589
type: Comment
type: AnswerComment
has text: Sorry I unknowingly removed it. Marked again
comment on: http://stackoverflow.com/a/48409315
score: 0

http://stackoverflow.com/q/48474878
answer count: 2
has title: Panda dataframe re-sample timeseries index with multiindex
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48480825
type: Question
has answer: http://stackoverflow.com/a/48476687
tagged with: time-series
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have a set of data, how can I resample its time stamp to 1 second interval, and fill in the data column (other than 'UUT') with 0. UUT Sent Received Latency(ms) Sum DateTime 2018-01-25 15:03:05 uut-1 1 1 427 2 2018-01-25 15:03:05 uut-2 1 1 664 2 2018-01-25 15:03:17 uut-1 1 1 637 2 2018-01-25 15:03:17 uut-2 1 1 1229 2 2018-01-25 15:03:29 uut-1 1 1 1154 2 2018-01-25 15:03:29 uut-2 1 1 1148 2 2018-01-25 15:04:00 uut-1 1 1 279 2 Output something like this: UUT Sent Received Latency(ms) Sum DateTime 2018-01-25 15:03:05 uut-1 1 1 427 2 2018-01-25 15:03:05 uut-2 1 1 664 2 2018-01-25 15:03:06 uut-1 0 0 0 0 2018-01-25 15:03:06 uut-2 0 0 0 0 2018-01-25 15:03:07 uut-1 0 0 0 0 2018-01-25 15:03:07 uut-2 0 0 0 0 2018-01-25 15:03:08 uut-1 0 0 0 0 2018-01-25 15:03:08 uut-2 0 0 0 0 .... 2018-01-25 15:03:17 uut-1 1 1 637 2 2018-01-25 15:03:17 uut-2 1 1 1229 2 2018-01-25 15:03:18 uut-1 0 0 0 0 2018-01-25 15:03:18 uut-2 0 0 0 0 ..... The ultimate goal is to use groupby('UUT') to plot each UUT's time vs any other remaining columns (e.g. 'Sent', Received', 'Latency(ms)')
score: 0

http://stackoverflow.com/q/48368466
has body: Hi I have deployed a simple flask python web in the AWS ubuntu server, followed this guys' e-book(https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling). But I found there is issue, when I want to access the web by the browser. When I accessed the site in the chrome browser, there is security warning as shown in the figure. Although I can click the 'processed to...' to access successfully the site. But I don't want the warning image is shown when accessing the site. I found that this issued is caused by the self-signed SSL certificate in AWS ubuntu server. The command for creating SSL certificate is following: ￼￼￼$ mkdir certs $ openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 \ -keyout certs/key.pem -out certs/cert.pem And the Nginx configuration is following, I want to delete or comment out the ssl_certificate part, and reload it. But I found that I can't access the site. After I added ssl_certificate part, and it works. But there is still warning pages. How to deal with this issue. server { # listen on port 443 (https) listen 443 ssl; server_name _; # location of the self-signed SSL certificate ssl_certificate /home/ubuntu/microblog2/certs/cert.pem; ssl_certificate_key /home/ubuntu/microblog2/certs/key.pem; location / { # forward application requests to the gunicorn server proxy_pass http://127.0.0.1:8000; proxy_redirect off; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; } location /static { # handle static files directly, without forwarding to the application alias /home/ubuntu/microblog2/static; expires 30d; } }
type: Question
tagged with: nginx
tagged with: ssl
has answer: http://stackoverflow.com/a/48368583
tagged with: python
tagged with: amazon-web-services
tagged with: ubuntu
score: 0
has title: How to remove the self-signed SSL certificate created in AWS ubuntu server
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/48374323
score: 1
type: Answer
has body: Alternatively, you can use after_cancel to cancel the queue for the animation. Not sure if there is an advantage to this though: from math import sqrt, cos, sin, radians from tkinter import * class SimplePendulum: def __init__(self): # Create a window win = Tk() win.title('Pendulum') # Create a canvas self.w, self.h = 250, 300 self.canvas = Canvas(win, width=self.w, height=self.h, bg='white') self.canvas.pack() # Bind keys to the window win.bind('s', self.stop) win.bind('S', self.stop) win.bind('r', self.resume) win.bind('R', self.resume) # Pendulum constants self.g = 1 self.L = 4*self.h/5 self.theta_i = radians(20) # Initialize time t to 0 self.t = 0 self._queue = False # Start animation self.isStopped = False self.speed = 1/50 # initial frequency of oscillation self.animate() # Start the event loop win.mainloop() def drawPendulum(self): # Angle of the pendulum (from the vertial) at time t theta = self.theta_i * cos(sqrt(self.g/self.L) * self.t) # The two ends of the cord x_i, y_i = self.w/2, self.h/10 x_f, y_f = x_i + self.L*sin(theta), y_i + self.L*cos(theta) # Draw the cord and bob of the pendulum self.canvas.create_line(x_i, y_i, x_f, y_f, tags='cord') rad = min(self.w, self.h)/20 self.canvas.create_oval(x_f - rad, y_f - rad, x_f + rad, y_f + rad, fill='red', tags='bob') def animate(self): self.canvas.delete(ALL) self.drawPendulum() self.t += 2 self._queue = self.canvas.after(int(1/self.speed), self.animate) def stop(self, event): if self._queue: self.canvas.after_cancel(self._queue) self._queue = False def resume(self, event): if not self._queue: self.animate() SimplePendulum()
answers question: http://stackoverflow.com/q/48373872
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83752560
has text: I only mention it because, OP made the same comment about my answer. Easy fix though, `zip_longest`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48382467
type: Comment

http://stackoverflow.com/a/48387270
type: Answer
answers question: http://stackoverflow.com/q/48382750
has body: Rather than scraping the site, you might consider examining the URLs that the webpage uses to query the data, then use the Python 'requests' package to simply make API requests directly from the server. I'm not a registered user on the site, so I can't provide you with any examples, but the paper that describes the shapenet.org site specifically mentions: "To provide convenient access to all of the model and an- notation data contained within ShapeNet, we construct an index over all the 3D models and their associated annota- tions using the Apache Solr framework. Each stored an- notation for a given 3D model is contained within the index as a separate attribute that can be easily queried and filtered through a simple web-based UI. In addition, to make the dataset conveniently accessible to researchers, we provide a batched download capability." This suggests that it might be easier to do what you want via API, as long as you can learn what their query language provides. A search in their QA/Forum may be productive too.
has comment: http://stackoverflow.com/comment/83770519
downvote count: 0
upvote count: 1
score: 1

virtualenv
tags question: http://stackoverflow.com/q/48423013
tags question: http://stackoverflow.com/q/48382330
tags question: http://stackoverflow.com/q/48402245
tags question: http://stackoverflow.com/q/48427903
tag name: virtualenv
tags question: http://stackoverflow.com/q/48424438
tags question: http://stackoverflow.com/q/48337324
tags question: http://stackoverflow.com/q/48464270
tags question: http://stackoverflow.com/q/48467146
tags question: http://stackoverflow.com/q/48386418
tags question: http://stackoverflow.com/q/48470540
tags question: http://stackoverflow.com/q/48352027
tags question: http://stackoverflow.com/q/48391132
type: Tag
tags question: http://stackoverflow.com/q/48436434

http://stackoverflow.com/q/48358800
tagged with: loops
has comment: http://stackoverflow.com/comment/83704338
score: 4
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
tagged with: list
has answer: http://stackoverflow.com/a/48358856
possible better answer: http://stackoverflow.com/a/48358856
has answer: http://stackoverflow.com/a/48358918
downvote count: 1
has answer: http://stackoverflow.com/a/48358832
tagged with: python
answer count: 6
has title: python: return False if there is not an element in a list starting with 'p='
tagged with: any
has body: having a list like lst = ['hello', 'stack', 'overflow', 'friends'] how can i do something like: if there is not an element in lst starting with 'p=' return False else return True ? i was thinking something like: for i in lst: if i.startswith('p=') return True but i can't add the return False inside the loop or it goes out at the first element.
has answer: http://stackoverflow.com/a/48358855
has comment: http://stackoverflow.com/comment/83704417
has answer: http://stackoverflow.com/a/48358854
accepted answer: http://stackoverflow.com/a/48358854
has comment: http://stackoverflow.com/comment/83704412
has answer: http://stackoverflow.com/a/48358867

http://stackoverflow.com/a/51388010
type: Answer
has comment: http://stackoverflow.com/comment/125400515
score: 2
upvote count: 2
downvote count: 0
has body: If you got openpyxl version 2.5.4 or later, try typing below to set active cell ws.cell(row=4, column=1) wb.save("spreadsheet.xlsx") assume ws is the worksheet you use, and you want to set cell A4 active. Make sure you save the spreadsheet in your code.
has comment: http://stackoverflow.com/comment/137221027
answers question: http://stackoverflow.com/q/48428250

http://stackoverflow.com/comment/83891171
type: Comment
type: QuestionComment
has text: Python integers are "infinite precision" too, so I'm not sure you need mpz
comment on: http://stackoverflow.com/q/48447427
score: 0

http://stackoverflow.com/q/48468827
has comment: http://stackoverflow.com/comment/83931929
has title: Getting value error while performing numpy.dot()
upvote count: 3
has comment: http://stackoverflow.com/comment/83931551
answer count: 1
has comment: http://stackoverflow.com/comment/83932574
downvote count: 1
has comment: http://stackoverflow.com/comment/83931861
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83932177
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/83932551
has comment: http://stackoverflow.com/comment/83931428
has comment: http://stackoverflow.com/comment/83931579
has answer: http://stackoverflow.com/a/48468906
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83931845
has comment: http://stackoverflow.com/comment/83931481
tagged with: python
has comment: http://stackoverflow.com/comment/98421585
has comment: http://stackoverflow.com/comment/83931694
has comment: http://stackoverflow.com/comment/83931977
tagged with: valueerror
has comment: http://stackoverflow.com/comment/83932167
has comment: http://stackoverflow.com/comment/83936498
has comment: http://stackoverflow.com/comment/83931958
has comment: http://stackoverflow.com/comment/83931450
has comment: http://stackoverflow.com/comment/83931512
tagged with: dot-product
has comment: http://stackoverflow.com/comment/83931627
has comment: http://stackoverflow.com/comment/83931517
score: 2
linked to: http://stackoverflow.com/q/24560298
has body: I created two arrays using numpy: import numpy as np a = np.array([[1, 5, 7], [6, 8, 9]]) b = np.array([[1, 8, 8], [5, 8, 0], [8, 9, 0]]) np.dot(a, b) Now, while performing np.dot(a, b) I am getting the error : ValueError: operands could not be broadcast together with shapes (2,3) (3,3) . Normally, value error is raised if the last dimension of a is not the same size as the second-to-last dimension of b. What is wrong with my code?
has comment: http://stackoverflow.com/comment/83931615

http://stackoverflow.com/a/48380988
type: Answer
has comment: http://stackoverflow.com/comment/83748753
has comment: http://stackoverflow.com/comment/83749750
score: 2
has body: You can use a for loop in the django template. EX: {% for key, value in ltp.items %} {{ key }} - {{ value.last_price }} {% endfor %}
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48380538

http://stackoverflow.com/comment/84192172
type: Comment
comment on: http://stackoverflow.com/a/48359205
score: 0
type: AnswerComment
has text: Thanks, there is no date in my post parameters,the five are __VIEWSTATE,__VIEWSTATEGENERATOR,__EVENTVALIDATION,and the remaining2 are the x&y coordinates of login button. I still don't know how to fix this issue,the workaround right now I used is selenium, but I really don't like it

http://stackoverflow.com/comment/83854256
score: 0
comment on: http://stackoverflow.com/a/48431448
type: Comment
has text: No Sir, while signing up!
type: AnswerComment

http://stackoverflow.com/a/48389260
accepted answer of: http://stackoverflow.com/q/48389084
has comment: http://stackoverflow.com/comment/83766268
score: 0
answers question: http://stackoverflow.com/q/48389084
type: AcceptedAnswer
has body: The condition you use to separate records is not quite right, try this: def read_records(iterable): record = {} for line in iterable: if line.startswith('Device'): if record: yield record record = {} key, value = line.strip().split(":",1) record[key.strip()] = value.strip() if record: yield record
type: Answer

http://stackoverflow.com/a/48465605
has body: The idea is to mimic nested for loops. [x for y in z for x in y] is organized in the same order as for y in z: for x in y: yield x This is mentioned in PEP 202 - List Comprehensions The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48465508
downvote count: 0
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48465508

http://stackoverflow.com/comment/83927766
type: Comment
comment on: http://stackoverflow.com/a/48453929
type: AnswerComment
has text: Yes that's version 3.6, it works with Unicode. You can use `os.path.abspath` directly in `SHFileOperation`
score: 0

http://stackoverflow.com/q/48347157
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48347260
has answer: http://stackoverflow.com/a/48347260
tagged with: django
tagged with: python
tagged with: django-rest-framework
has body: As a Django newbie, I am trying to return JSON Objects from two models with each object containing the username, id, ticketID. Right now the code is simply putting the lists together without indexing. I should point out that there is a relationship between user and ticket so that can be traversed also. {"username":"Paul","id":2}, {"username":"Paul","id":2}, {"username":"Ron","id":19}, {"id":"1c6f039c"}, {"id":"6480e439"}, {"id":"a97cf1s"} class UsersforEvent(APIView): def post(self, request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) value = body['event'] queryset = Ticket.objects.filter(event = value) referenced_users = User.objects.filter(ticket_owner__in=queryset.values('id')) result_list = list(itertools.chain(referenced_users.values('username', 'id'), queryset.values('id'))) return Response((result_list))
type: AnsweredQuestion
score: 0
has title: Django concatenate list queries from two models

http://stackoverflow.com/q/48389166
has comment: http://stackoverflow.com/comment/83766432
has body: I have the simple fitting model like this: lm = linear_model.LinearRegression() model = lm.fit(X_train, y_train) predictions = lm.predict(X_test) print accuracy_score(y_test, predictions) and with using cross validation I have this: from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = model, X = X_train, y = y_train, cv = 7) from cross validation how can I take the accuracy in order to have the same measure print accuracy_score(y_test, predictions)? Is it accuracies.mean()?
answer count: 1
score: -1
favorite count: 0
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48389493
has title: Take accuracy for simple fit and cross val
accepted answer: http://stackoverflow.com/a/48389493
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/83766479
downvote count: 1
type: AnsweredQuestion

lstm
tags question: http://stackoverflow.com/q/48382859
tags question: http://stackoverflow.com/q/48417764
tags question: http://stackoverflow.com/q/48416439
tags question: http://stackoverflow.com/q/48422892
tags question: http://stackoverflow.com/q/48484985
tags question: http://stackoverflow.com/q/48483489
type: Tag
tags question: http://stackoverflow.com/q/48420005
tags question: http://stackoverflow.com/q/48375634
tags question: http://stackoverflow.com/q/48333633
tag name: lstm
tags question: http://stackoverflow.com/q/48372994

docker
tags question: http://stackoverflow.com/q/48351418
tag name: docker
type: Tag
tags question: http://stackoverflow.com/q/48423567
tags question: http://stackoverflow.com/q/48475138
tags question: http://stackoverflow.com/q/48406339
tags question: http://stackoverflow.com/q/48483979
tags question: http://stackoverflow.com/q/48347997
tags question: http://stackoverflow.com/q/48439684
tags question: http://stackoverflow.com/q/48388554
tags question: http://stackoverflow.com/q/48381143

http://stackoverflow.com/comment/86160995
comment on: http://stackoverflow.com/a/48411293
score: 1
type: Comment
has text: The second solution requires `from bokeh.models.arrow_heads import TeeHead ` and (at least for my example) resets the line_width to its default value which is about a factor two to large. The first one works like a charm.
type: AnswerComment

http://stackoverflow.com/a/48372641
type: Answer
has body: Under Python 2.7.10, I get very different results between print('\n'.join(difflib.unified_diff(a, b))) and print('\n'.join(difflib.unified_diff(b, a))) (a and b swapped around): &gt;&gt;&gt; a = """kydropqfp ... tpssubdbw tzibqyqvp llmpwtekn xmubmrjch vcojgxxil ... vdrsqhzag xlcldqabb ujccweoha dsooqyyve khilgzjue ... jignrbela glvvueqqb qlfehmlkm brkleswiq vvsplffjf ... yjuoivyjr wtfueypmo pkvlmbcnh tesuistya zbfn""" &gt;&gt;&gt; print('\n'.join(difflib.unified_diff(a, b))) --- +++ @@ -21,7 +21,7 @@ t z i -b +a q y q @@ -201,4 +201,3 @@ z b f -n &gt;&gt;&gt; print('\n'.join(difflib.unified_diff(b, a))) --- +++ @@ -21,183 +21,184 @@ t z i -a -q -y -q -v -p - -l -l -m -p -w -t -e -k -n - -x -m -u -b -m -r -j -c -h - -v -c -o -j -g -x -x -i -l - -v -d -r -s -q -h -z -a -g - -x -l -c -l -d -q -a -b -b - -u -j -c -c -w -e -o -h -a - -d -s -o -o -q -y -y -v -e - -k -h -i -l -g -z -j -u -e - -j -i -g -n -r -b -e -l -a - -g -l -v -v -u -e -q -q -b - -q -l -f -e -h -m -l -k -m - -b -r -k -l -e -s -w -i -q - -v -v -s -p -l -f -f -j -f - -y -j -u -o -i -v -y -j -r - -w -t -f -u -e -y -p -m -o - -p -k -v -l -m -b -c -n -h - -t -e -s -u -i -s -t -y -a - -z -b -f +b +q +y +q +v +p + +l +l +m +p +w +t +e +k +n + +x +m +u +b +m +r +j +c +h + +v +c +o +j +g +x +x +i +l + +v +d +r +s +q +h +z +a +g + +x +l +c +l +d +q +a +b +b + +u +j +c +c +w +e +o +h +a + +d +s +o +o +q +y +y +v +e + +k +h +i +l +g +z +j +u +e + +j +i +g +n +r +b +e +l +a + +g +l +v +v +u +e +q +q +b + +q +l +f +e +h +m +l +k +m + +b +r +k +l +e +s +w +i +q + +v +v +s +p +l +f +f +j +f + +y +j +u +o +i +v +y +j +r + +w +t +f +u +e +y +p +m +o + +p +k +v +l +m +b +c +n +h + +t +e +s +u +i +s +t +y +a + +z +b +f +n &gt;&gt;&gt; difflib has strange parts. The algorithm used is an old one that attempts to 'look good', but obviously there are some cases where it doesn't work. I haven't looked into the code to tell you why it behaves like this, but I hope this shows you that the built-in difflib is good, but not the bes…
answers question: http://stackoverflow.com/q/48372210
score: 0

http://stackoverflow.com/q/48424598
has comment: http://stackoverflow.com/comment/83990457
has title: Parallel plane retrieval from chessboard with pose in OpenCV
downvote count: 0
has comment: http://stackoverflow.com/comment/83842499
upvote count: 1
has comment: http://stackoverflow.com/comment/83989085
favorite count: 0
type: Question
tagged with: opencv
has body: I'm using OpenCV on Python3, and I'd like to get the positions of the corners of a chessboard with dimensions pattern_size on a plane parallel to the one of a chessboard that I have at disposition, vertically displaced by a certain value fdz (in chessboard side units). In order to achieve that, I modified the pose algorithm that can be found in https://docs.opencv.org/3.1.0/d7/d53/tutorial_py_pose.html in this way: function vertical(img,pattern_size, corners, camera_matrix, dist_coefs,fdz): objp = np.zeros((pattern_size[1]*pattern_size[0],3), np.float32) objp[:,:2] = np.mgrid[0:pattern_size[0],0:pattern_size[1]].T.reshape(-1,2) a = [] for j in range(pattern_size[1]): for i in range(pattern_size[0]): axis = np.float32([[0,0,0], [0,0,0], [i,j,-fdz]]).reshape(-1,3) # Find the rotation and translation vectors. _, rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners, camera_matrix, dist_coefs) # project 3D points to image plane imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, camera_matrix, dist_coefs) imgpts = np.array(imgpts) a.append(imgpts[2].ravel()) # draw circles on points found cv2.circle(pose, (imgpts[2].ravel()[0], imgpts[2].ravel()[1]), 5, (0,255,0), -1) cv2.imwrite('./pose.jpg', pose) return(a) This works for some images (original image), while for some others it does this trick: output image. Do you have any suggestions on the problem? My best guess is that I didn't still completely understood how cv2.solvePnPRansac and cv2.projectPoints work. EDIT I did find out that the problems are due to the RANSAC algorithm: here you can see the results of applying cv2.solvePnP instead of cv2.solvePnPRansac to the same image as before; however, this appears to happen only with angles between the chessboard and the camera normals bigger than a certain threshold, below which the script works fine. However, the results with and without the RANSAC step are slightly different, so it would be probably useful to try and include it. Do you have an idea on why this happen…
has comment: http://stackoverflow.com/comment/83841568
tagged with: camera
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83989655
tagged with: homography
tagged with: ransac
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/83839419

http://stackoverflow.com/comment/83884743
score: 0
has text: I continue with the same problem. It did not work for me.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48446327

http://stackoverflow.com/q/48369104
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48369126
score: 5
upvote count: 5
tagged with: arrays
has body: I have an array e.g. a = [5,1,3,0,2] I apply the where function: np.where(a == 2) The output is an empty array (array([], dtype=int64),) I found kind of the same problem here, but in my case it really dosen't make any sense or dose it? Btw. i'm on a Mac using Python 2.7.10
tagged with: python
tagged with: where-clause
has comment: http://stackoverflow.com/comment/83724857
linked to: http://stackoverflow.com/q/9002749
accepted answer: http://stackoverflow.com/a/48369126
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83726191
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83725742
favorite count: 0
has title: Numpy where returns empty array

http://stackoverflow.com/comment/83867420
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48438158
type: Comment
has text: Code does not simply get asynchronous by putting `async` before `def`.

http://stackoverflow.com/a/48396098
answers question: http://stackoverflow.com/q/48395849
score: 1
accepted answer of: http://stackoverflow.com/q/48395849
type: Answer
has body: ungolfed version -)) def list_to_str(lst): return " ".join(lst) def handle_multi_lists (*lsts): return "\n".join(list_to_str(l) for l in lsts) a = ['1','2','3'] b = ['4','5','6'] c = ['7','8','9'] print(handle_multi_lists(a,b,c))
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48420163
answers question: http://stackoverflow.com/q/48419403
type: Answer
score: 2
downvote count: 0
has body: You should use select_related for the forward foreign keys. prefetch_related prefetches reverse foreign key and many-to-many relations: # ... queryset=Circuits.objects\ .select_related('site_data', 'service_contacts', 'circuit_type', 'provider'), # ... .select_related('site_data', 'device_data', 'subnet_type') Displaying all this fk info in the __str__ can be troublesome as the __str__is used by default in several places in the admin, like the change list but also in form input dropdowns. You could display the pk of the related objects instead (if that is informative enough), as it is stored in the local table and won't create extra queries: def __str__(self): return '%s | %s | %s | %s ' % (self.site_data_id, \ self.provider_id, self.circuit_type_id, self.ref_no)
upvote count: 2

http://stackoverflow.com/q/48426505
tagged with: dictionary
tagged with: iteration
accepted answer: http://stackoverflow.com/a/48427047
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48427047
tagged with: pandas
answer count: 1
has body: I have a dictionary with 2 keys for every 1 value like so: Initial Dict Key : ('106338', '2006-12-27') , Value : [] Dict after populating Key : ('106338', '2006-12-27') , Value : [8, 7, 9, 8, 7] The value for each key pair is an array holding some amount of information which I need the length of. I created this dictionary by first itertupling across a dataframe and generating key pairs and empty arrays for each unique record. I then iterated across it again and populated the arrays with the information I need by appending values to the end of each key pair. Key pairs were generated from row values. The first item in the key is the Identification number for the asset and the second item is the date for the asset. Here is code for dict creation: perm_dict = {} for row in df_perm.itertuples(): perm_dict[str(row[1]),str(row[3])] = [] for row in df_perm.itertuples(): if row[6].to_datetime().date() &lt; row[9].to_datetime().date() and row[9].to_datetime().date() &lt; row[5].to_datetime().date(): perm_dict[str(row[1]), str(row[3])].append(row[10]) My problem is that I now need to call those values back via the key pairs by iterating through the original dataframe so I can take my array lengths and make a new column out of them. Screenshot of DataFrame: I am having trouble working out a solution in my head for applying these counts back to the original dataframe as a new column for only the rows with key matches. I can't iterate back through to add them because then I'd be modifying my original DF and I've read that's a big no-no. Any help that you all may be able to provide would be greatly appreciated! Also please lmk if I need to include more information as I can provide more. Edit1 Here are the outputs after running the dictionary comprehension code provided.
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83843792
type: Question
has comment: http://stackoverflow.com/comment/83844976
has title: Can't work out how to apply multi-keyed dictionary vals back to dataframe column
tagged with: python

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/48348910
tags question: http://stackoverflow.com/q/48353732
tags question: http://stackoverflow.com/q/48410401
tags question: http://stackoverflow.com/q/48359761
tags question: http://stackoverflow.com/q/48463933
type: Tag
tags question: http://stackoverflow.com/q/48427484

http://stackoverflow.com/comment/83862110
type: AnswerComment
has text: Thanks for the answer ... it works. If I was using axes to plot (i.e like ax.bar(x,y)) do you know the equalent of your first solution ?
comment on: http://stackoverflow.com/a/48435235
type: Comment
score: 0

http://stackoverflow.com/comment/84323773
comment on: http://stackoverflow.com/a/48544185
type: Comment
type: AnswerComment
has text: when i do the same action again then a new error comes ctypes.ArgumentError: argument 5: <class 'OverflowError'>: int too long to convert
score: 0

http://stackoverflow.com/a/48483427
score: 1
answers question: http://stackoverflow.com/q/48483398
has comment: http://stackoverflow.com/comment/83959708
has body: Original answer sort -k4n myfile.txt &gt; newfile.txt Expanded answer. Perhaps irrelevant with other answer but... I spent a minute writing it, so why not share it? with open('source') as fin, with open('destination', 'w') as fout: unsorted_lines = [line.split(" ") for line in fin.readlines()] sorted_lines = sorted(unsorted_lines, key=lambda coord: coord[2]) joined_lines = [' '.join(line) for line in sorted_lines] for line in joined_lines: fout.writelines(line)
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84118760
comment on: http://stackoverflow.com/a/48553015
has text: Thank you. I'm always again amazed about what is possible with matplotlib.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48429793
has comment: http://stackoverflow.com/comment/84101281
answer count: 1
tagged with: wxpython
type: Question
has comment: http://stackoverflow.com/comment/83851945
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48431767
tagged with: python
has comment: http://stackoverflow.com/comment/83853734
has body: I'm trying to create a gui with the following layout: Where the top panel is going to contain three figures, the three middle panels are going to contain textboxes and the bottom panel some buttons Here is what I have so far: import wx from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure from mpl_toolkits.mplot3d import Axes3D import gui_functions as gf class MainWindow(wx.Frame): def __init__(self, parent, id, title = "Test GUI"): wx.Frame.__init__(self, parent, wx.ID_ANY, title = "MyTitle", size=(1200,1000)) self.graphicsPanel = wx.Panel(self,-1,style=wx.CLIP_CHILDREN) self.textPanel = wx.Panel(self) self.buttonsPanel = wx.Panel(self) self.graphicsPanel.figure = Figure() self.graphicsPanel.canvas = FigureCanvas(self.graphicsPanel, -1, self.graphicsPanel.figure) self.axeshandleA = self.graphicsPanel.figure.add_subplot(131, projection='3d',facecolor='#f3f3f3') self.axeshandleB = self.graphicsPanel.figure.add_subplot(132, projection='3d',facecolor='#f3f3f3') self.axeshandleC = self.graphicsPanel.figure.add_subplot(133, projection='3d',facecolor='#f3f3f3') if __name__ == '__main__': app = wx.App(False) app.frame = MainWindow(None, wx.ID_ANY) app.frame.Show() app.MainLoop() I've assumed that I need to start with three panels, that I somehow have to align vertically. I'm thinking in the middle panel I will then need to add three additional panels and align them horizontally My brain is thinking along the lines of how to structure div boxes in HTML and CSS. My first problem is that I can't work out how to get the panels to a) fill the parent and b) align vertically. Secondly, I'm working Spyder. Why do I have to start a new console after every call to the gui? If I don't then I get the error The wx.App object must be created first! I would really appreciate any help, because I'm stuck! Many thanks I'm running wxPython 4.0.0rc1.dev3617+346e3b7 and Python 3.5.4
has comment: http://stackoverflow.com/comment/83850331
has title: wxPython layout of gui panels
score: 0

http://stackoverflow.com/a/48383730
type: Answer
answers question: http://stackoverflow.com/q/48382823
downvote count: 0
score: 1
upvote count: 1
has body: I want to ensure that all random values lie between 0 and k, but should not be equal to 0 If you have numbers in the range low &lt;= u &lt; high you can easily convert them to low &lt; r &lt;= high: r = high - np.random.uniform(0, high - low) Of course this is only useful if r is allowed to include high but not low.

http://stackoverflow.com/comment/83670323
comment on: http://stackoverflow.com/q/48342441
score: 0
has text: It may be helpful to determine whether there are any inputs that cause a crash, and which have fewer than 37 elements, as this will make debugging easier. For instance, I notice that `randomnumbers = [1,0,1]` will also cause a RecursionError.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83880987
has text: Are you able to run the python file (*CreateBuildNumber.py*) directly from console (when Python.File is set)? In *Jenkins* are they executed (or at least attempted)?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48399497

http://stackoverflow.com/comment/83676522
has text: I have updated my answer to account for printable characters. I am still not sure if this fits the bill
comment on: http://stackoverflow.com/a/48344493
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83709309
comment on: http://stackoverflow.com/q/48361249
has text: Are you sure you're saving after you train? I don't tensorflow, but it looks like the only thing related to saving is at the beginning of your train.py
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/59352668
type: Answer
has body: The array st is the same length as p1 in the first dimension, so it can be used as a "mask" of sorts for how to select the values in p1 This example should assist with how st==1 actually works: &gt;&gt;&gt; st = np.asarray([1,0,0,1,0,1]) &gt;&gt;&gt; p1 = np.reshape(np.arange(len(a)*2), [len(a), 2]) &gt;&gt;&gt; p1 array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]]) &gt;&gt;&gt; st==1 array([ True, False, False, True, False, True]) &gt;&gt;&gt; p1[st==1] array([[ 0, 1], [ 6, 7], [10, 11]]) &gt;&gt;&gt; p1True, False, True, False, True, False array([[0, 1], [4, 5], [8, 9]])
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48385926

http://stackoverflow.com/q/48453186
has answer: http://stackoverflow.com/a/48453250
tagged with: nan
score: 8
type: AnsweredQuestion
tagged with: python-2.7
has body: pandas.DataFrame.to_dict converts nan to nan and null to None. As explained in Python comparison ignoring nan this is sometimes suboptimal. Is there a way to convert all nans to None? (either in pandas or later on in Python) E.g., &gt;&gt;&gt; df = pd.DataFrame({"a":[1,None],"b":[None,"foo"]}) &gt;&gt;&gt; df a b 0 1.0 None 1 NaN foo &gt;&gt;&gt; df.to_dict() {'a': {0: 1.0, 1: nan}, 'b': {0: None, 1: 'foo'}} I want {'a': {0: 1.0, 1: None}, 'b': {0: None, 1: 'foo'}} instead.
answer count: 3
has answer: http://stackoverflow.com/a/48453225
downvote count: 0
linked to: http://stackoverflow.com/q/14162723
has title: Pandas: nan->None
favorite count: 0
type: Question
upvote count: 8
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48453225
accepted answer: http://stackoverflow.com/a/48453250
tagged with: python
linked to: http://stackoverflow.com/q/48452933
has answer: http://stackoverflow.com/a/78642004

http://stackoverflow.com/comment/83844067
type: Comment
type: QuestionComment
has text: @EmilVikström: How did you install Python? I tried again with Python 2.7.14 installed through Homebrew, and the resulting file is also 16M large. Looks like it's something specific about the Homebrew version!
score: 0
comment on: http://stackoverflow.com/q/48422744

http://stackoverflow.com/comment/83879953
type: Comment
type: QuestionComment
has text: Shared memory IPC should be faster in this scenario, and is "true" as far as I can tell. If you need things to be distributed you are obviously looking for mechanisms with higher latency at the expense of the convenience offered by local direct-memory access, so it really depends on what sort of scalability you are looking for. In a way, local pipes seems to be the worst of both worlds ... but the flexibility could be worth it if you *might* want to choose between a local and a remote socket.
comment on: http://stackoverflow.com/q/48437429
score: 1

http://stackoverflow.com/q/48367110
possible better answer: http://stackoverflow.com/a/49330132
tagged with: python
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/49332976
has title: "ImportError: No module named pyRserve" when running AWS Glue job
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: apache-spark
score: 1
upvote count: 1
has body: When I run my Glue job in which I try to import the pyRserve python module (pure Python), I'm getting this error: LogType:stdout Log Upload Time:Sun Jan 21 12:27:32 +0000 2018 LogLength:206 Log Contents: Traceback (most recent call last): File "script_2018-01-21-12-27-05.py", line 8, in &lt;module&gt; import pyRserve ImportError: No module named pyRserve End of LogType:stdout Here are details about my job: $ aws glue get-job --job-name test_trunc { "Job": { "Name": "test_trunc", "Role": "arn:aws:iam::#CLIPPED#:role/AWSGlueServiceRoleDefault", "CreatedOn": 1516192543.117, "LastModifiedOn": 1516537317.889, "ExecutionProperty": { "MaxConcurrentRuns": 1 }, "Command": { "Name": "glueetl", "ScriptLocation": "s3://#CLIPPED#/gluescripts/test_trunc" }, "DefaultArguments": { "--TempDir": "s3://#CLIPPED#/jobs/test_trunc/scripts", "--extra-py-files": "s3://#CLIPPED#/jobs/test_trunc/python-libs/pyRserve.zip", "--job-bookmark-option": "job-bookmark-disable", "--job-language": "python" }, "Connections": { "Connections": [ "redshift" ] }, "MaxRetries": 0, "AllocatedCapacity": 10 } } Here is the script I'm running: import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job import pprint import pyRserve Here is the complete log: https://gist.github.com/mattazend/b611d0232d94ade4bc4c16bcb79f73a8
has answer: http://stackoverflow.com/a/49330132
accepted answer: http://stackoverflow.com/a/49332976
favorite count: 0
type: Question
tagged with: aws-glue

http://stackoverflow.com/comment/84024966
type: Comment
comment on: http://stackoverflow.com/a/48485808
score: 0
type: AnswerComment
has text: Hi John. this is not relevant for my case, I have many properties and all of them are optional, there is no logical grouping for them. I disagree that this is a design smell, a class represents an entity, and an entity may have many attributes, so allowing to initialize any number of them from the constructor to allow the user to initialize my class in a single line makes sense. In C# such a class can easily be initialized using the initialization list syntax, and what I'm searching here is something similar in Python.

http://stackoverflow.com/q/48352048
has comment: http://stackoverflow.com/comment/83726519
favorite count: 0
type: Question
has title: cannot import name defaultdict error for nltk
tagged with: nltk
answer count: 1
accepted answer: http://stackoverflow.com/a/48374726
tagged with: python
has comment: http://stackoverflow.com/comment/83734283
has answer: http://stackoverflow.com/a/48374726
has comment: http://stackoverflow.com/comment/83726378
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83692800
has body: I successfully installed the Natural Language Toolkit nltk. Then I ran Python in the console and typed "import nltk" and I get the following error. I have no idea why and I can't find anything online. Any suggestions on why this is the case? This is the error I get: &gt;&gt;&gt; import nltk Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/__init__.py", line 114, in &lt;module&gt; from nltk.collocations import * File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/collocations.py", line 37, in &lt;module&gt; from nltk.probability import FreqDist File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/probability.py", line 47, in &lt;module&gt; from collections import defaultdict, Counter File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/collections.py", line 13, in &lt;module&gt; import pydoc File "/Users/myusername/anaconda/lib/python2.7/pydoc.py", line 56, in &lt;module&gt; import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings File "/Users/myusername/anaconda/lib/python2.7/inspect.py", line 39, in &lt;module&gt; import tokenize File "tokenize.py", line 2, in &lt;module&gt; from nltk.corpus import stopwords File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/corpus/__init__.py", line 64, in &lt;module&gt; from nltk.tokenize import RegexpTokenizer File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/tokenize/__init__.py", line 67, in &lt;module&gt; from nltk.tokenize.mwe import MWETokenizer File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/tokenize/mwe.py", line 31, in &lt;module&gt; from nltk.util import Trie File "/Users/myusername/anaconda/lib/python2.7/site-packages/nltk/util.py", line 21, in &lt;module&gt; from collections import defaultdict, deque ImportError: cannot import name defaultdict Could there some conflicts or am I missing a prerequisite? When i do pip fr…
has comment: http://stackoverflow.com/comment/85532375
has comment: http://stackoverflow.com/comment/83692511
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83734548
has comment: http://stackoverflow.com/comment/83726373

cx-freeze
tags question: http://stackoverflow.com/q/48384551
tags question: http://stackoverflow.com/q/48470529
tag name: cx-freeze
type: Tag
tags question: http://stackoverflow.com/q/48354778
tags question: http://stackoverflow.com/q/48336713
tags question: http://stackoverflow.com/q/48451224

sqlite
tags question: http://stackoverflow.com/q/48412922
tags question: http://stackoverflow.com/q/48477795
tags question: http://stackoverflow.com/q/48431679
tags question: http://stackoverflow.com/q/48349205
tags question: http://stackoverflow.com/q/48467144
tags question: http://stackoverflow.com/q/48388624
tags question: http://stackoverflow.com/q/48462859
tags question: http://stackoverflow.com/q/48348952
tags question: http://stackoverflow.com/q/48456626
tags question: http://stackoverflow.com/q/48487401
tags question: http://stackoverflow.com/q/48344470
type: Tag
tags question: http://stackoverflow.com/q/48362010
tags question: http://stackoverflow.com/q/48483484
tags question: http://stackoverflow.com/q/48360694
tags question: http://stackoverflow.com/q/48409699
tags question: http://stackoverflow.com/q/48336242
tags question: http://stackoverflow.com/q/48338901
tags question: http://stackoverflow.com/q/48350091
tags question: http://stackoverflow.com/q/48392761
tags question: http://stackoverflow.com/q/48409610
tags question: http://stackoverflow.com/q/48424970
tags question: http://stackoverflow.com/q/48401951
tags question: http://stackoverflow.com/q/48411571
tags question: http://stackoverflow.com/q/48459493
tag name: sqlite
tags question: http://stackoverflow.com/q/48406018
tags question: http://stackoverflow.com/q/48392261
tags question: http://stackoverflow.com/q/48337211

http://stackoverflow.com/comment/83960478
has text: Didn't notice this involved the python-keystoneclient. Andrew Hare's solution is better.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48483861
type: AnswerComment

http://stackoverflow.com/q/48467779
has comment: http://stackoverflow.com/comment/83929562
has title: Python with Visual Studio Code on Mac
has comment: http://stackoverflow.com/comment/83929758
has body: Trying to figure out Python with Visual Studio on Mac. Dependencies and Libraries don't seem to install/launch correctly. For example, I have pandas on my system, installed via pip, and if I do import pandas as pd from a Python prompt, it works fine. With Visual Studio Code, if I create a file with the above code, autocomplete recognizes that pandas is installed When I try to run, I get an ImportError: No module named pandas Any ideas? Update: It works in VSCode's terminal, just not when I run the code in the debugger.
tagged with: visual-studio-code
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48471679
has comment: http://stackoverflow.com/comment/83934862
has answer: http://stackoverflow.com/a/48471679
has comment: http://stackoverflow.com/comment/83933955
has comment: http://stackoverflow.com/comment/83929159
has comment: http://stackoverflow.com/comment/83929304
type: Question
has comment: http://stackoverflow.com/comment/83929259
has comment: http://stackoverflow.com/comment/83929209
tagged with: python
has comment: http://stackoverflow.com/comment/83929198

http://stackoverflow.com/q/48344243
has body: Most terminal emulators allow you to configure it to make Option+Left/Right Arrow jump forward or backward a word. Is it possible to do this in the PyCharm Terminal?
tagged with: python
tagged with: pycharm
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48344507
type: UnansweredQuestion
has title: PyCharm Terminal: Make Option + Arrow Keys go backwards/forwards a word

http://stackoverflow.com/q/48484007
tagged with: api
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48484816
tagged with: twitter
has answer: http://stackoverflow.com/a/48484816
downvote count: 1
favorite count: 0
type: Question
tagged with: python
answer count: 1
has body: I'm working on project where I stream tweets from Twitter API then apply sentiment analysis and visualize the results on an interactive colorful map. I've tried the 'tweepy' library in python but the problem is it only retrieves few tweets (10 or less). Also, I'm going to specify the language and the location which means I might get even less tweets! I need a real time streaming of hundred/thousands of tweets. This is the code I tried (just in case): import os import tweepy from textblob import TextBlob port = os.getenv('PORT', '8080') host = os.getenv('IP', '0.0.0.0') # Step 1 - Authenticate consumer_key= 'xx' consumer_secret= 'xx' access_token='xx' access_token_secret='xx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #Step 3 - Retrieve Tweets public_tweets = api.search('school') for tweet in public_tweets: print(tweet.text) analysis = TextBlob(tweet.text) print(analysis) Is there any better alternatives? I found "PubNub" which is a JavaScript API but for now I want something in python since it is easier for me. Thank you
has title: Alternative to Twitter API
upvote count: 4
tagged with: sentiment-analysis

http://stackoverflow.com/q/48350505
has answer: http://stackoverflow.com/a/48350640
has body: I recently uninstalled Anaconda3 and reinstalled Anaconda on Python 2. Following this, it seems that I cannot get a kernel running when I work with jupyter notebooks. I get this kernel error on any notebook that I tried to open: Failed to start kernel Traceback (most recent call last): File "C:\Users\Ejer\Anaconda2\lib\site-packages\notebook\base\handlers.py", line 516, in wrapper result = yield gen.maybe_future(method(self, *args, **kwargs)) File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\Ejer\Anaconda2\lib\site-packages\notebook\services\sessions\handlers.py", line 75, in post type=mtype)) File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\Ejer\Anaconda2\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\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1055, in run value = future.result() File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "C:\Users\Ejer\Anaconda2\lib\site-packages\tornado\gen.py", line 1063, in run yielded = self.gen.throw(*exc_info) File "C:\Users\Ejer\Anaconda2\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 92, in start_kernel_for_session self.kernel_manager.start_kernel(path=kern…
has comment: http://stackoverflow.com/comment/83688092
tagged with: python
tagged with: jupyter-notebook
score: 0
answer count: 2
has title: Failed to start kernel on jupyter notebook
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56631232
type: Question
tagged with: anaconda

http://stackoverflow.com/a/48743385
answers question: http://stackoverflow.com/q/48415208
has body: I have not tested it, but my comment seems to be the answer. https://github.com/lmas/opensimplex#status It says: stable but slow. If you want something fast you would need to use something in C via a lib like numpy or scipy ... So either contribute to the project by providing faster code or wait for an enhancement. Or write your own implementation.
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84328747
score: 1
has text: @MartijnPieters Well... with at least 99.999999997829302352% probability they actually do produce 40k keys: https://eval.in/951632
type: Comment
comment on: http://stackoverflow.com/q/48421142
type: QuestionComment

http://stackoverflow.com/q/48370348
has comment: http://stackoverflow.com/comment/83729534
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83727505
has answer: http://stackoverflow.com/a/48390934
has body: Is there a way to retrieve the webpage contents from a URL (not hostname) using sockets in Python? socket.connect() only works with a host name. I can get the contents from www.python.org but not www.python.org/about. Thanks!
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83769637
tagged with: python
has comment: http://stackoverflow.com/comment/83727671
favorite count: 0
type: Question
has title: Get HTML contents from URL using Python sockets
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/83920129
comment on: http://stackoverflow.com/q/48458438
type: QuestionComment
type: Comment
has text: @hpaulj Which `item` are you referring to? I'm afraid I can't follow your comment.
score: 0

http://stackoverflow.com/comment/83936934
type: Comment
has text: @DYZ ROTFL your last comment though ;)
comment on: http://stackoverflow.com/q/48471329
type: QuestionComment
score: 1

http://stackoverflow.com/q/48483484
has answer: http://stackoverflow.com/a/48483502
upvote count: 0
tagged with: sqlite
answer count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/1253561
type: Question
has body: Eg. In the Table1 there is a column ColName, some of the items in ColName are "Mike". The code to search one of the them: searchString = " SELECT * FROM Table1 WHERE ColName = 'Mike' " cur.execute(searchString).fetchone() The Problem: The code above allways gives me the first row, where "Mike" in ColName appears. I actually want, by everytime running the sqlite code, to get a random search result from the column ColName, whose value is "Mike". How could I change the code? Thanks for the help!
has title: sqlite3: How to use SELECT + WHERE to search a random row?
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/1253561
tagged with: python
score: -1

http://stackoverflow.com/comment/83851409
type: QuestionComment
has text: So it's not an issue on your side from what I can tell, @AnthonyTuininga. Code posted above
score: 0
comment on: http://stackoverflow.com/q/48406354
type: Comment

http://stackoverflow.com/comment/84020103
comment on: http://stackoverflow.com/q/48483627
type: QuestionComment
has text: how about `with self.assertRaises(models.MyObject.DoesNotExist): obj = models.MyObject.objects.get(id=1)` instead of the `try` and `except`, this is just a wild guess.
score: 0
type: Comment

http://stackoverflow.com/q/48443470
linked to: http://stackoverflow.com/q/47563013
tagged with: django
has title: Adding paths in Django to create more views
accepted answer: http://stackoverflow.com/a/48443975
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83878681
has comment: http://stackoverflow.com/comment/83878843
has comment: http://stackoverflow.com/comment/83878822
has comment: http://stackoverflow.com/comment/83878764
tagged with: python
has comment: http://stackoverflow.com/comment/83878354
has comment: http://stackoverflow.com/comment/83878709
has body: I am following the tutorial on the Django website. I try and replicate this: My code is as follows: views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, film_id): return HttpResponse("You're looking at film %s." % film_id) def results(request, film_id): response = "You're looking at the results of film %s." return HttpResponse(response % question_id) def vote(request, film_id): return HttpResponse("You're commenting on film %s." % film_id) films/urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), # ex: /polls/ path('', views.index, name='index'), # ex: /films/5/ path('&lt;int:film_id&gt;/', views.detail, name='detail'), # ex: /films/5/results/ path('&lt;int:film_id&gt;/results/', views.results, name='results'), # ex: /films/5/vote/ path('&lt;int:film_id&gt;/vote/', views.vote, name='vote'), ] With this I am getting ERR_CONNECTION_REFUSED. If I comment out all the paths leaving only the index url, and also comment out from django.urls import path a page displays, but that is where I was at before trying to add more views.
has answer: http://stackoverflow.com/a/48443975
has comment: http://stackoverflow.com/comment/83878686
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83878522
tagged with: django-views
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83878557
has comment: http://stackoverflow.com/comment/83878969
has comment: http://stackoverflow.com/comment/83879002
has comment: http://stackoverflow.com/comment/83878680
answer count: 1

http://stackoverflow.com/comment/83895200
comment on: http://stackoverflow.com/q/48449611
type: QuestionComment
type: Comment
has text: I'm using selenium 3.8.1
score: 0

superclass
tags question: http://stackoverflow.com/q/48483447
type: Tag
tag name: superclass

http://stackoverflow.com/q/48343322
downvote count: 0
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
tagged with: qtnetwork
upvote count: 2
accepted answer: http://stackoverflow.com/a/48343570
has answer: http://stackoverflow.com/a/48343570
tagged with: python
score: 2
type: AnsweredQuestion
has title: Checking internet connectivity using QtNetwork and PyQt5
has body: I'm trying to check network connectivity the hard way using QtNetwork but can't figure out how to do it properly. This is the code I'm working on it seems that neither finished nor error signals are called. What I'm missing here? import sys from PyQt5 import QtCore, QtNetwork, QtWidgets class CheckConnectivity: def __init__(self): url = QtCore.QUrl("https://www.google.com/") req = QtNetwork.QNetworkRequest(url) net_manager = QtNetwork.QNetworkAccessManager() self.res = net_manager.get(req) self.res.finished.connect(self.processRes) self.res.error.connect(self.processErr) self.msg = QtWidgets.QMessageBox() def processRes(self): if self.res.bytesAvailable(): self.msg.information(self, "Info", "You are connected to the Internet.") else: self.msg.critical(self, "Info", "You are not connected to the Internet.") self.msg.show() self.res.close() def processErr(self, *args): print(*args) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) ic = CheckConnectivity() sys.exit(app.exec_())
tagged with: pyqt

http://stackoverflow.com/q/48373841
has title: django - context processor variables are not being updated
tagged with: processor
answer count: 2
tagged with: django
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/48373880
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48373880
accepted answer: http://stackoverflow.com/a/48373867
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48373867
has body: I have several variables within a navbar that are to be displayed on every single template, so I've made a custom context processor to handle the fetching of those variables. Everything is working, except that when the data is changed in the database, the values of the context variables are not refreshed(for example it'll only get updated once I quit runserver and rerun). Here's my basic pseudo code: context_processor.py: foo = db.get('foo') bar = db.get('bar') def default(request): return {'foo': foo, 'bar': bar} base.html: {% block header %} foo value is: {{ foo }}, bar value is {{ bar}} {% endblock %} {% block content %} {% endblock %} some_other_template.html: {% extends "base.html" %} {% block content %} ...blabla {% endblock %} Is there something I am missing or is this normal behavior? Have I used the wrong approach of using a context processor here?
type: Question

http://stackoverflow.com/comment/83750708
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48375903
type: Comment
has text: @FedericoVaccaro I've made some fixes and added the required Import for When and Case - you can also read about them here https://docs.djangoproject.com/en/2.0/ref/models/conditional-expressions/

http://stackoverflow.com/a/60289054
score: 0
type: Answer
has body: The assertion you actually want to check is simply at the mock_project, and not the mock_project __init__. refer to the link: Asserting that __init__ was called with right arguments
answers question: http://stackoverflow.com/q/48398127

http://stackoverflow.com/q/48413677
has comment: http://stackoverflow.com/comment/83817518
tagged with: python
possible better answer: http://stackoverflow.com/a/48422997
accepted answer: http://stackoverflow.com/a/48413802
has body: I have the following function implemented in python: # Calculation of cumulative binomial distribution def PDP(p, N, min): pdp=0 for k in range(min, N+1): pdp += (float(factorial(N))/(factorial(k)*factorial(N-k)))*(p**k)*((1-p)**(N-k)) return pdp However, calculations produce too large values with a high n (up to 255). I have searched for approximations to these values, but to no avail. How would you go about this?
tagged with: normal-distribution
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48422997
has comment: http://stackoverflow.com/comment/83817396
has answer: http://stackoverflow.com/a/48413802
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83817490
upvote count: 2
has title: Cumulative binomial distribution for large numbers
tagged with: binomial-coefficients

http://stackoverflow.com/a/48428037
has comment: http://stackoverflow.com/comment/83851135
has comment: http://stackoverflow.com/comment/83851227
answers question: http://stackoverflow.com/q/48427501
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Replace: toggle_btn = ttk.Checkbutton(frame, width=2, text='+', command=lambda: self.toggle(var, toggle_btn, sub_frame), variable=var, style='Toolbutton') with: toggle_btn = ttk.Checkbutton(frame, width=2, text='+', variable=var, style='Toolbutton') toggle_btn['command'] = lambda a1=var, a2=toggle_btn, a3=sub_frame: self.toggle(a1, a2, a3) See more on why. The Minimal, Complete, and Verifiable example of above issue should at longest be: from tkinter import * class Example: def __init__(self, root): list_1 = ['item_1', 'item_2'] list_2 = ['a', 'b', 'c'] for item in list_1: frame = Frame(root) frame.pack() var = IntVar() sub_frame = Frame(root) for item in list_2: Label(sub_frame, text=item).pack() toggle_btn = Checkbutton(frame, command=lambda: self.toggle(var, toggle_btn, sub_frame), variable=var) toggle_btn.pack() def toggle(self, show, toggle_button, sub_frame): if bool(show.get()): sub_frame.pack() else: sub_frame.forget() def main(): root = Tk() open = Example(root) root.mainloop() if __name__ == '__main__': main() If you don't want to overwrite simply use iterable types, such as list and dict, instead of singular variables for multiple objects such as your frames and labels. Below code generates a dictionary of frames, then a dictionary of labels for each of the frames: import tkinter as tk if __name__ == '__main__': list_1 = ['item_1', 'item_2'] list_2 = ['a', 'b', 'c'] root = tk.Tk() frames = dict() for item in list_1: frames[item] = tk.Frame(root) frames[item].pack() frames[item].labels = dict() for text in list_2: frames[item].labels[text] = tk.Label(frames[item], text=text) frames[item].labels[text].pack() root.mainloop()
has comment: http://stackoverflow.com/comment/83851153

http://stackoverflow.com/comment/83967676
has text: Same behaviour when adding the line manually: `line = lines.Line2D(x,y); line.set_drawstyle('steps'); ax.add_line(line); ax.relim(); ax.autoscale_view()`. If `ax.add_line` is done *before* `set_drawstyle`, the steps are not shown.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48485538

http://stackoverflow.com/a/48411504
has comment: http://stackoverflow.com/comment/83812989
type: Answer
has comment: http://stackoverflow.com/comment/83812972
has body: The following seems to be a straight forward approach using "normal" programming concepts: def getUpperPositions(str): positions = [] currentPosition = 0 for c in str: if c.isupper(): positions.append(currentPosition) currentPosition += 1 return positions print(getUpperPositions("HaH"))
score: 0
has comment: http://stackoverflow.com/comment/83813017
answers question: http://stackoverflow.com/q/48411435

http://stackoverflow.com/comment/83689394
type: Comment
type: QuestionComment
has text: Use [`Client.delete_message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.delete_message): `await client.delete_message(message)`
comment on: http://stackoverflow.com/q/48351265
score: 0

http://stackoverflow.com/comment/83971724
has text: Django views can’t forbid access to `request.GET`. There’s nothing in the question that explains why `request.GET.get()` wouldn’t work.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48485522

http://stackoverflow.com/q/48339406
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48340069
has title: How to entirely disable linting on a specific file on vscode?
upvote count: 6
score: 6
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54138235
tagged with: python
has answer: http://stackoverflow.com/a/48340069
favorite count: 0
has body: Visual studio code, with the python extension, offers code linting. While in the linked page it is documented how to generally enable/disable linting via user preferences, it is not clear if or how can I disable on a per file basis. More specifically, I'm looking for a way to disable linting on a file, preferably via command palette or similar.
tagged with: visual-studio-code
possible better answer: http://stackoverflow.com/a/54138235

http://stackoverflow.com/q/48436033
has body: In several talks about Dask, an animated task graph is shown with nodes coloured red as they are run and blue as they are completed (example: https://youtu.be/RA_2qdipVng?t=23m57s). I couldn't find this functionality in the documentation. Is it easy/possible for a user to produce this visualisation for their tasks?
has title: How do I view a live execution of a dask graph?
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
answer count: 1
tagged with: dask-distributed
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48443204
tagged with: dask
has answer: http://stackoverflow.com/a/48443204
tagged with: python

http://stackoverflow.com/comment/83725866
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48369589
type: Comment
has text: If you have a sum of O(n) terms each of which is a sum from 1 to n, that suggests the overall complexity is O(n^3).

http://stackoverflow.com/q/48446919
tagged with: reader
answer count: 1
has comment: http://stackoverflow.com/comment/83885928
has comment: http://stackoverflow.com/comment/83886080
tagged with: python
type: Question
type: UnansweredQuestion
has title: Read CSV file per column
has answer: http://stackoverflow.com/a/48447290
has comment: http://stackoverflow.com/comment/83887461
has body: I have a dataset containing four columns with the first three columns being positional arguments XYZ and the latter being a certain value at that position. I want to read this file into a np.array in a specific way, namely for every number of points xnodes I want to read a number of values (lets say 10) from the last column. What I have up until now is this: with open(FilePath, 'rt') as f: reader = csv.reader((row for row in f if not row.startswith('#')), skipinitialspace=True, delimiter=' ') for i, row in enumerate(reader): if i % xnodes == 0: Where FilePath is the location of the datafile. Now when the last if condition is met, I want to store the 10 values from the last column, starting from index i into an array. With my limited knowledge in Python, I do not know how to achieve this. Can anyone help me? Thank you!
score: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/48489832
upvote count: 1
answers question: http://stackoverflow.com/q/48460101
downvote count: 0
type: Answer
has body: Make sure you are passing asn1crypto the byte string, not some internal scapy object. May be you need to cast the latter into a byte string. Alternatively, this tool is designed to decode X.509 certs into a tree of Python objects. You also need to feed it either a string (Python2) or bytes (Python 3).
score: 1

http://stackoverflow.com/comment/83706117
score: 1
comment on: http://stackoverflow.com/q/48340631
type: Comment
type: QuestionComment
has text: I am not able to look into this to see the correct way to do it, but knowing the python error message you got could help me point you in the right direction, maybe.

http://stackoverflow.com/q/48363664
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48400960
favorite count: 0
type: Question
tagged with: google-places-api
tagged with: google-maps
has title: Google maps python API error on calling nearby_places function
tagged with: python
tagged with: google-maps-api-3
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48400960
has body: I am geting an API error following error while trying to call places_nearby function in the python api for google maps https://github.com/googlemaps/google-maps-services-python/blob/master/googlemaps/places.py gmaps = googlemaps.Client(key = maps_api_key) places_result=gmaps.places_nearby(location=(40.714224, -73.961452)) Maybe I am calling it the wrong way. Could anyone please show the proper way to do it. Or Something else I need to fix The image of the error is attatched below: Api Error
answer count: 1

http://stackoverflow.com/q/48419151
linked to: http://stackoverflow.com/q/9393425
has comment: http://stackoverflow.com/comment/83829940
accepted answer: http://stackoverflow.com/a/48423190
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83828114
has body: I'm having a problem with my subprocess command, I like to grep out the lines that match with "Online" line. def run_command(command): p = subprocess.Popen(command,shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'') command = 'mosquitto_sub -u example -P example -t ITT/# -v | grep "Online" '.split() for line in run_command(command): print(line) But I will get an error Error: Unknown option '|'. Use 'mosquitto_sub --help' to see usage. But when running with linux shell user@server64:~/Pythoniscriptid$ mosquitto_sub -u example -P example -t ITT/# -v | grep "Online" ITT/C5/link Online ITT/IoT/tester55/link Online ITT/ESP32/TEST/link Online I also tried shell = True, but with no success, because I will get another error, that dosen't recognize the topic ITT/# Error: You must specify a topic to subscribe to. Use 'mosquitto_sub --help' to see usage. The "possible dublicate" didn't help me at all, So I think I'm having a different problem. I tried to change code to this, put in not getting any return def run_command(command,command2): p1 = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) p2 = subprocess.Popen(command2,stdin=p1.stdout,stdout=subprocess.PIPE) return iter(p2.stdout.readline,'') command = 'mosquitto_sub -u example -P example -t ITT/# -v'.split() command2 = 'grep Online'.split() #subprocess.getoutput(command) for line in run_command(command,command2): print(line)
has comment: http://stackoverflow.com/comment/83828423
tagged with: grep
tagged with: python
has comment: http://stackoverflow.com/comment/83830076
has answer: http://stackoverflow.com/a/48423190
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83829816
tagged with: subprocess
has title: Cant use grep in subprocess command
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48445131
upvote count: 2
type: UnansweredQuestion
tagged with: shopify
has answer: http://stackoverflow.com/a/48445679
tagged with: python
linked to: http://stackoverflow.com/q/1871524
has body: Hoping that I may be able to get some assistance in regards to my code. I have spent the last couple of days crawling the site to try and find a response that would fit the requirements and while I found some excellent information, I am still struggling to implement a working version. I have taken my code from this thread. As the title suggests I am trying to take a nested JSON file received from a Shopify Webhook, flatten it and convert it to a CSV. This is my JSON file: {"id":788032119674292922,"title":"Example T-Shirt","body_html":null,"vendor":"Acme","product_type":"Shirts","created_at":null,"handle":"example-t-shirt","updated_at":null,"published_at":"2018-01-23T03:11:38-05:00","template_suffix":null,"published_scope":"global","tags":"mens t-shirt example","variants":[{"id":642667041472713922,"product_id":788032119674292922,"title":"","price":"19.99","sku":"example-shirt-s","position":0,"inventory_policy":"deny","compare_at_price":"24.99","fulfillment_service":"manual","inventory_management":null,"option1":"Small","option2":null,"option3":null,"created_at":null,"updated_at":null,"taxable":true,"barcode":null,"grams":200,"image_id":null,"inventory_quantity":75,"weight":200.0,"weight_unit":"g","inventory_item_id":null,"old_inventory_quantity":75,"requires_shipping":true},{"id":757650484644203962,"product_id":788032119674292922,"title":"","price":"19.99","sku":"example-shirt-m","position":0,"inventory_policy":"deny","compare_at_price":"24.99","fulfillment_service":"manual","inventory_management":"shopify","option1":"Medium","option2":null,"option3":null,"created_at":null,"updated_at":null,"taxable":true,"barcode":null,"grams":200,"image_id":null,"inventory_quantity":50,"weight":200.0,"weight_unit":"g","inventory_item_id":null,"old_inventory_quantity":50,"requires_shipping":true}],"options":[{"id":527050010214937811,"product_id":null,"name":"Title","position":1,"values":["Small","Medium"]}],"images":[{"id":539438707724640965,"product_id":788032119674292922,"position…
downvote count: 1
has answer: http://stackoverflow.com/a/48445528
favorite count: 0
has answer: http://stackoverflow.com/a/48462604
answer count: 3
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/83882647
has title: Converting Shopify API JSON to CSV

http://stackoverflow.com/comment/98434862
comment on: http://stackoverflow.com/a/52300696
type: Comment
has text: Do you have to authenticate each time you connect your google drive?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83947402
type: QuestionComment
has text: Thank you to poke for recognising that memoisation provides a solution to my problem
score: 0
comment on: http://stackoverflow.com/q/48475907
type: Comment

http://stackoverflow.com/a/48480808
answers question: http://stackoverflow.com/q/48480786
downvote count: 0
has body: board() creates a new board instance each time. Create one board instance with brd = board(), and use it to call brd.update_cell() and brd.display().
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/q/48475377
downvote count: 1
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48475416
accepted answer: http://stackoverflow.com/a/48475402
has answer: http://stackoverflow.com/a/48475416
has answer: http://stackoverflow.com/a/48475402
favorite count: 0
type: Question
answer count: 2
has title: How to omit positional argument with string format?
has body: How will I omit last positional argument with string format ? Consider below. Sometime I am not interested in passing the last positional argument. As last argument value is not there. It`s an optional argument. message = """ {name} {age}""" message.format(name='sameer') # This will give me error
score: 0
upvote count: 1
tagged with: python
tagged with: string

http://stackoverflow.com/comment/83764195
comment on: http://stackoverflow.com/q/48388144
score: 0
type: QuestionComment
type: Comment
has text: i wanted them to duplicate as well. I will edit the question - it was not clear enough.

multithreading
tags question: http://stackoverflow.com/q/48360729
tags question: http://stackoverflow.com/q/48402107
tags question: http://stackoverflow.com/q/48347635
tags question: http://stackoverflow.com/q/48475858
tags question: http://stackoverflow.com/q/48342604
type: Tag
tags question: http://stackoverflow.com/q/48349085
tags question: http://stackoverflow.com/q/48425108
tags question: http://stackoverflow.com/q/48404914
tags question: http://stackoverflow.com/q/48431096
tags question: http://stackoverflow.com/q/48374012
tags question: http://stackoverflow.com/q/48360749
tags question: http://stackoverflow.com/q/48399775
tags question: http://stackoverflow.com/q/48435348
tags question: http://stackoverflow.com/q/48392096
tags question: http://stackoverflow.com/q/48456081
tags question: http://stackoverflow.com/q/48391636
tags question: http://stackoverflow.com/q/48360571
tags question: http://stackoverflow.com/q/48447033
tags question: http://stackoverflow.com/q/48433985
tags question: http://stackoverflow.com/q/48375171
tags question: http://stackoverflow.com/q/48358675
tags question: http://stackoverflow.com/q/48370988
tags question: http://stackoverflow.com/q/48423270
tags question: http://stackoverflow.com/q/48387098
tags question: http://stackoverflow.com/q/48368625
tags question: http://stackoverflow.com/q/48412764
tags question: http://stackoverflow.com/q/48404921
tags question: http://stackoverflow.com/q/48337962
tags question: http://stackoverflow.com/q/48418534
tags question: http://stackoverflow.com/q/48389470
tag name: multithreading
tags question: http://stackoverflow.com/q/48361972
tags question: http://stackoverflow.com/q/48434552
tags question: http://stackoverflow.com/q/48455038
tags question: http://stackoverflow.com/q/48487623

http://stackoverflow.com/comment/83893352
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48450244
has text: Use `df.groupby(['starttime', 'hour']).size().reset_index(name='freq')`, probable duplicate.
score: 0

http://stackoverflow.com/a/48373304
has body: Analysis What I believe to be a Minimal, Complete, and Verifiable example for the above-mentioned issue: import tkinter as tk def callback(event): #checkbutton.wait_variable(var) checkbutton['text'] = var.get() if __name__ == '__main__': root = tk.Tk() var = tk.BooleanVar() checkbutton = tk.Checkbutton(root, text="Check", variable=var, onvalue=True, offvalue=False) checkbutton.pack() checkbutton.bind("<ButtonRelease-1>", callback) root.mainloop() This happens simply because the virtual events, for example, the one that sets a Checkbutton's value based on its state (checked / unchecked), are handled after events attached with bind are handled(See the very last MCVE provided). For more info see: https://stackoverflow.com/a/3513906/7032856 For the code you've provided, it means that Checkbutton's value won't change until the bind event handle filter_categ method is finished. But filter_categ won't move on unless Checkbutton's value is changed. Which makes your program to be stuck at a local event loop, waiting for a 'break', a 'break' comes only if the loop is completed. Feels like a paradox. Review the following example: import tkinter as tk import random def modify_var(event): var.set(random.choice((True, False))) def callback(event): checkbutton.wait_variable(var) checkbutton['text'] = var.get() if __name__ == '__main__': root = tk.Tk() var = tk.BooleanVar() checkbutton = tk.Checkbutton(root, text="Check", variable=var, onvalue=True, offvalue=False) checkbutton.pack(fill='both', expand=True) checkbutton.bind("<ButtonRelease-1>", callback) root.bind_all("<Escape>", modify_var) root.mainloop() It has the same paradoxical behavior your code does, but with the only exception, when Escape is hit, the variable wait_variable waits, var, is modified, so the local event loop is broken. Solutions By using command option in Checkbutton Replace: self.filter_checks[i].bind("<ButtonRelease-1>", self.filter_categ) with: self.filter_checks[i]['command'] = self.filter_categ This is …
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83734005
answers question: http://stackoverflow.com/q/48373128
type: Answer

http://stackoverflow.com/comment/83941226
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48473792
has text: Yes, this is it I look hour to code where is mistake and you found it in 1 minute. Thanks you in advance

http://stackoverflow.com/comment/83759401
comment on: http://stackoverflow.com/a/48385899
type: Comment
score: 0
type: AnswerComment
has text: Yes, I'm implementing this as an exercise and there is a way for Power Method to obtain all eigenvalues using Deflation method described here: https://math.stackexchange.com/questions/768882/power-method-for-finding-all-eigenvectors but I don't know, why it gives me wrong values.

http://stackoverflow.com/comment/83830091
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48420099
has text: The problem is in your `entry = get_object_or_404(Purchases)`. You have to specify the primary key to get only 1 record.
score: 0

http://stackoverflow.com/q/48467887
has comment: http://stackoverflow.com/comment/83929528
has comment: http://stackoverflow.com/comment/83929924
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/83929523
has comment: http://stackoverflow.com/comment/83929278
has comment: http://stackoverflow.com/comment/83929309
possible better answer: http://stackoverflow.com/a/48468281
has comment: http://stackoverflow.com/comment/83929417
tagged with: replace
type: Question
has answer: http://stackoverflow.com/a/48468281
answer count: 2
has body: I have two columns of numbers: one column a record of student SAT scores, and another, their corresponding scores on the ACT test in a python pandas dataframe. SAT Score ACT Score 0 2160.0 32.0 1 1890.0 NaN 2 1720.0 27.0 3 2160.0 34.0 4 2150.0 32.0 5 1310.0 31.0 6 2220.0 NaN 7 2250.0 NaN 8 2170.0 NaN 9 2080.0 NaN 10 2310.0 34.0 The dictionary I have created looks like this: score_dict = {"36": 2390, "35":2330, "34": 2260, "33": 2170, "32": 2110, "31": 2040, "30": 1990, "29":1920, "28": 1850, "27": 1810, "26": 1760, "25":1700, "24": 1640, "23": 1570, "22": 1530}"} I'd like to replace dict keys with their respective dict values when either SAT or ACT scores are missing. I'm not sure how to finish the code. M = df['SAT Score'] N = df['ACT Score'] for index in range(len(M)): i = N[index] k = M[index] if k != k *1: for key, value in score_dict.items(): .... This is as far as I got. I have some NaN values in the SAT Column. My logic was to first look at SAT scores with NaNs in them (k != k*1), then for those rows look at the corresponding ACT scores. I would then use dictionary to look replace the missing SAT scores with the corresponding ACT scores by using the dictionary.
has title: How to replace a number with another number using a dictionary of replacements in python?
downvote count: 0
accepted answer: http://stackoverflow.com/a/48468284
has comment: http://stackoverflow.com/comment/83929566
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48468284
has comment: http://stackoverflow.com/comment/83929445
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83929453

http://stackoverflow.com/q/48402051
favorite count: 0
tagged with: combinatorics
type: Question
has body: I want to produce something between a permutation and a combination for a list of tuples. If, for example, I have the list list_of_tuples = [(1,20), (1,21), (2,18), (2,19)] I want to create all possible "combinations" of 3 tuples so that I want the list to include the result [(1,20), (1,20), (1,20)] but I consider [(1,20), (1,20), (1,21)] to be identical to [(1,20), (1,21), (1,20)] and [(1,21), (1,20), (1,20)] and want to keep only one of these (doesn't matter which one). In other words, if the "combination" includes the same tuples as another "combination", I don't want to keep the other one(s). I've tried something like list_of_lists = [list_of_tuples]*3 results = list(itertools.product(*list_of_lists)) results = set(results) But by using set() I lose [(1,20), (1,20), (1,20)] and all the other results that have the same tuple three times.
accepted answer: http://stackoverflow.com/a/48402101
tagged with: python
has answer: http://stackoverflow.com/a/48402861
type: AnsweredQuestion
score: 0
tagged with: nested-lists
answer count: 3
has answer: http://stackoverflow.com/a/48402101
has answer: http://stackoverflow.com/a/48403537
upvote count: 1
possible better answer: http://stackoverflow.com/a/48402861
downvote count: 1
has title: Unique permutations for a list of tuples

http://stackoverflow.com/q/48442786
type: Question
downvote count: 0
upvote count: 1
answer count: 1
has body: I have a scatter 3d plot using matplotlib. What I'm trying to do is to position the legend inside the plot. I have read the documentation and it seems that is only possible to select predefined positions or only specify x and y coordinates. Is there a way to position the legend specifying the 3 coordinates? fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #more code ax.legend(loc=(0.5,0.5,0.5), frameon=0) The last line is what I thought might work but obviously is not working. This is what I've now: I'm trying to position the legend inside the axes, sort of like: I reached that position by trial and error using ax.legend(loc=(0.15,0.65),frameon=0) because the legend doesn't move as the axes are rotated. The issue is that I'll be doing several plots thus I'm trying to avoid the trial and error approach. Thanks.
has comment: http://stackoverflow.com/comment/83877153
has comment: http://stackoverflow.com/comment/83876974
favorite count: 0
has answer: http://stackoverflow.com/a/48454236
has comment: http://stackoverflow.com/comment/83882506
type: AnsweredQuestion
score: 1
tagged with: matplotlib
tagged with: legend
tagged with: python
has title: Legend specifying 3d position in 3D axes matplotlib
accepted answer: http://stackoverflow.com/a/48454236
has comment: http://stackoverflow.com/comment/83877391

http://stackoverflow.com/a/48648690
type: Answer
has body: You could instead try @client.event async def on_message(message): if message.author.id == "author ID": await client.send_message(message.channel, "success") To find the id of a person, first enable developer mode in discord (Settings, Appearance, Advanced). After that, right click on their name in discord and click Copy Id. Then, paste the ID in the author ID. Hope this helps!
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48333694
score: 1

http://stackoverflow.com/q/48442745
has comment: http://stackoverflow.com/comment/83908782
has comment: http://stackoverflow.com/comment/83908762
has comment: http://stackoverflow.com/comment/83908439
has title: sh module: how to use piping with sudo?
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83908141
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: i use the sh module (github.com/amoffat/sh) quite often. now i have come across a problem i do not know how to solve: how can i pipe the output of one command into a second command; both commands need to be run with root privileges (yes, i could start a shell as root first and then run the commands [how would i to that using sh?]). this is all for the current version: 1.12.14. the recipe to run commands as root is: from getpass import getpass, getuser import sh password = getpass('[sudo] password for {}: '.format(getuser())) with sh.contrib.sudo(password=password, _with=True): ls = sh.ls() print(ls) the recipe for piping is: import sh for line in sh.tr(sh.cat("test.log", _piped=True), "[:upper:]", "[:lower:]", _iter=True): print(line) both work just fine. but combining them does not (as pointed out by tripleee this is a silly example; in the real use-case both commands really do need sudo privileges): from getpass import getpass, getuser import sh password = getpass('[sudo] password for {}: '.format(getuser())) with sh.contrib.sudo(password=password, _with=True): for line in sh.tr(sh.cat("test.log", _piped=True), "[:upper:]", "[:lower:]", _iter=True): print(line) this crashes with the error: Exception in thread background thread for pid 5163: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/workdir/sh.py", line 1540, in wrap fn(*args, **kwargs) File "/workdir/sh.py", line 2459, in background_thread handle_exit_code(exit_code) File "/workdir/sh.py", line 2157, in fn return self.command.handle_command_exit_code(exit_code) File "/workdir/sh.py", line 815, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /usr/bin/sudo -S /usr/bin/tr [:upper:] [:lower:] STDOUT: STDERR: [sudo] password for user: Sorry, try again. [sudo] password for user: Sorry, try again. [sudo] password for user: sudo…
tagged with: python

http://stackoverflow.com/comment/84032433
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48480009
has text: use ```gunicorn -c gconfig.py app:app --log-level=debug --threads 2 --error-logfile somewhere.log``` and show us 'somewhere.log' result, then we can help you with the 500 error.

http://stackoverflow.com/q/48335791
tagged with: python
has comment: http://stackoverflow.com/comment/83656598
tagged with: repr
has body: So yesterday I tried to use repr and str in my code for printing objects from list. Here just small example code where I run to same problem. class Something: def __init__(self): pass def __repr__(self): return "I want this out" def __str__(self): return "this comes out" def main(): k = Something() k print(k) main() What is printed: this comes out Process finished with exit code 0 Why can't i get the repr out of my object even though I have given it line to return when object is called?
has title: Problems understanding __repr__, doesn't print anything even I've decleared it
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/83656942
has comment: http://stackoverflow.com/comment/83656949
answer count: 2
has answer: http://stackoverflow.com/a/48336348
has comment: http://stackoverflow.com/comment/83657548
has comment: http://stackoverflow.com/comment/83656817
type: Question
has comment: http://stackoverflow.com/comment/83656764
has comment: http://stackoverflow.com/comment/83656728
tagged with: object
has answer: http://stackoverflow.com/a/48336159
has comment: http://stackoverflow.com/comment/83656716
linked to: http://stackoverflow.com/q/2654113
has comment: http://stackoverflow.com/comment/83656930
linked to: http://stackoverflow.com/q/3764360
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83657037
linked to: http://stackoverflow.com/q/1436703

http://stackoverflow.com/comment/83732826
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48372768
type: AnswerComment
has text: Are you certain these are all the requirements? When I create a folder named `mypackage` with empty `__init__.py` and `spam.py` and with `from . import spam` as the sole line for `foo.py` it raises `ImportError: cannot import name 'spam'`.

http://stackoverflow.com/comment/83906614
has text: Glad it helped! I think you can accept the answer, so as to close it for future reference.
comment on: http://stackoverflow.com/a/48436884
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83749001
score: 0
has text: Do you have `REDIS_URI` env var set in your container? You may want to add `-e REDIS_URI` to your `docker run` call.
comment on: http://stackoverflow.com/q/48381143
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48465998
score: 0
has body: Django looks for template names in a sequential order through all your apps and uses the first match it finds. You might have to rename the templates, to something like posts_modify.html user_modify.html EDIT: Alternative solution, restructure your templates. make it such that you have posts/templates/posts/ and users/templates/users/ change posts view code to def post_modify(request): Postlist=Post.objects.all() return render(request,'posts/modify.html',{'Postlist':Postlist}) change users view code to def modify(request): Userlist=User.objects.all() return render(request,'users/modify.html',{'Ul':Userlist})
answers question: http://stackoverflow.com/q/48465870
accepted answer of: http://stackoverflow.com/q/48465870
has comment: http://stackoverflow.com/comment/83925630
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83925856
type: Answer

http://stackoverflow.com/a/61831367
downvote count: 0
has body: An alternative to BeautifulSoup that you could use is pandas. I have had success scraping free-proxy-list.net using the pandas.read_html function import requests import pandas as pd resp = requests.get('https://free-proxy-list.net/') df = pd.read_html(resp.text)[0] Resulting DataFrame stored in df: IP Address Port Code Country Anonymity Google Https Last Checked 0 2.50.154.155 53281.0 AE United Arab Emirates elite proxy no yes 6 seconds ago 1 134.249.165.49 53281.0 UA Ukraine elite proxy no yes 6 seconds ago 2 158.58.133.106 41258.0 RU Russian Federation elite proxy no yes 6 seconds ago 3 92.52.186.123 32329.0 UA Ukraine elite proxy no yes 6 seconds ago 4 178.213.0.207 35140.0 UA Ukraine elite proxy no yes 6 seconds ago .. ... ... ... ... ... ... ... ... 296 93.185.96.60 41003.0 CZ Czech Republic elite proxy no yes 22 minutes ago 297 1.20.103.248 52574.0 TH Thailand elite proxy no yes 22 minutes ago 298 190.210.8.92 8080.0 AR Argentina elite proxy no yes 22 minutes ago 299 166.150.32.182 56074.0 US United States elite proxy no yes 22 minutes ago 300 NaN NaN NaN NaN NaN NaN NaN NaN [301 rows x 8 columns] This DataFrame can be manipulated any which way now. For example, say I only wanted elite proxy's that are also listed in the United States, I could so something like df[(df['Anonymity'] == 'elite proxy') &amp; (df['Country'] == 'United States')] which would return IP Address Port Code Country Anonymity Google Https Last Checked 32 138.68.53.220 5836.0 US United States elite proxy no yes 6 seconds ago 76 173.217.255.36 33351.0 US United States elite proxy no no 10 seconds ago 86 24.172.34.114 40675.0 US United States elite proxy no no 10 seconds ago 111 209.190.32.28 3128.0 US United States elite proxy no yes 10 seconds ago 150 104.148.76.176 3128.0 US United States elite proxy no no 11 minutes ago 151 104.148.76.185 3128.0 US United States elite proxy no no 11 minutes ago 168 104.148.76.136 3128.0 US United States elite proxy no no 11 minutes ago 169 104.148.76.182 …
type: Answer
answers question: http://stackoverflow.com/q/48426624
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/121796169

http://stackoverflow.com/comment/83936205
comment on: http://stackoverflow.com/q/48471086
has text: @Mad Physicist True, but it also falsely pretends there is an expression.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/83707639
type: Comment
type: QuestionComment
has text: Thanks for that clarification. I did not understand that distinction.
comment on: http://stackoverflow.com/q/48360030
score: 0

http://stackoverflow.com/comment/83752526
has text: @YvesDaoust Indeed. Fixed!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48382792
type: Comment

random
tags question: http://stackoverflow.com/q/48358792
tags question: http://stackoverflow.com/q/48396047
tags question: http://stackoverflow.com/q/48435848
tags question: http://stackoverflow.com/q/48421142
tags question: http://stackoverflow.com/q/48424044
tags question: http://stackoverflow.com/q/48419408
tags question: http://stackoverflow.com/q/48425201
tag name: random
tags question: http://stackoverflow.com/q/48358500
tags question: http://stackoverflow.com/q/48414404
type: Tag
tags question: http://stackoverflow.com/q/48475696
tags question: http://stackoverflow.com/q/48374664
tags question: http://stackoverflow.com/q/48361670
tags question: http://stackoverflow.com/q/48343525
tags question: http://stackoverflow.com/q/48382823
tags question: http://stackoverflow.com/q/48474034
tags question: http://stackoverflow.com/q/48346418
tags question: http://stackoverflow.com/q/48362898

qt
tags question: http://stackoverflow.com/q/48332086
tags question: http://stackoverflow.com/q/48407081
type: Tag
tags question: http://stackoverflow.com/q/48433529
tags question: http://stackoverflow.com/q/48391959
tags question: http://stackoverflow.com/q/48487910
tags question: http://stackoverflow.com/q/48367819
tags question: http://stackoverflow.com/q/48339767
tags question: http://stackoverflow.com/q/48418802
tags question: http://stackoverflow.com/q/48485636
tags question: http://stackoverflow.com/q/48394344
tag name: qt

http://stackoverflow.com/a/48418149
type: Answer
answers question: http://stackoverflow.com/q/48410064
upvote count: 1
has comment: http://stackoverflow.com/comment/83840693
score: 1
has body: Answer: there where multiple problems: Payload: 'form_id': 'voetbal_login_login_form' was missing. Thanks @t.m.adam Cookies: request cookies where missing. They seem to be static, so I tried to add them manually, which worked. Thanks @match and @Patrick Doyle Headers: removed the 'content-type' line; which contained a dynamic part. Login works like a charm now!
downvote count: 0

http://stackoverflow.com/q/48368896
has answer: http://stackoverflow.com/a/48397442
tagged with: pymongo
has body: Put operation causing Type and Attribute errors when using with MongoClient and GridFS. However the same operation passes with mongofiles utility.Appreciate pointers. Version information [xxxx@yyyy ~]$ python Python 3.5.1 (default, Jan 20 2018, 19:04:00) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. [xxxx@yyyy ~]$ mongo MongoDB shell version v3.6.1 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.6.1 &gt;&gt;&gt; pymongo.version '3.6.0' Code &gt;&gt;&gt; from pymongo import MongoClient &gt;&gt;&gt; from gridfs import GridFS &gt;&gt;&gt; from bson import objectid &gt;&gt;&gt; db = MongoClient().test &gt;&gt;&gt; fs = GridFS(db) &gt;&gt;&gt; with open("/tmp/dictionary") as dictionary: ... uid = fs.put(dictionary) Errors Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/local/lib/python3.5/site-packages/gridfs/__init__.py", line 122, in put grid_file.write(data) File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 365, in write self.__flush_data(to_write) File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 257, in __flush_data self._file['md5'].update(data) TypeError: Unicode-objects must be encoded before hashing &gt;&gt;&gt; ob = fs.put("hello world") Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 337, in write read = data.read AttributeError: 'str' object has no attribute 'read' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 344, in write data = data.encode(self.encoding) File "/usr/local/lib/python3.5/site-packages/gridfs/grid_file.py", line 235, in __getattr__ raise AttributeError("GridIn object has no attribute '%s'" % name) AttributeError: GridIn object has no attribute 'encoding' During handling of the ab…
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: gridfs
answer count: 1
has title: Pymongo GridFS put Type/Attribute errors
tagged with: python
score: 2
downvote count: 0

http://stackoverflow.com/q/48394128
accepted answer: http://stackoverflow.com/a/48510016
tagged with: arcpy
upvote count: 2
tagged with: ide
tagged with: python
has title: Arcpy script was fast now slow?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48510016
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83811375
downvote count: 1
favorite count: 0
has body: Question pretty much sums it up. I had the following script running in PyCharm earlier today: rasterfolder = "F:/1_Raster_Processing/Classified/" vectorfolder = "H:/Output/SplitShapes/" tablefolder = "H:/Output/Split_Tables_3/" import arcview import arcpy from arcpy.sa import * arcpy.CheckOutExtension("spatial") arcpy.env.workspace = vectorfolder flist = arcpy.ListFeatureClasses() for f in flist: TabulateArea(f,"FID",rasterfolder + "KNN100_" + f[:-6] + ".tif","Value",tablefolder + f[:-4] + ".dbf",0.25) It was taking ~4 minutes a featureclass and there are a couple hundred to run through. At some point in the middle of the day, the process hung and wasn't generating any more output, so I killed it and started over (thinking this was a pyCharm issue). When I started over, it was suddenly taking ~1hr+ per feature class to do the exact same process. I've tried the same process in WingIDE and I'm still having the issue. I've restarted everything and am running nothing but this one process on this machine. Thoughts? Do I need to sacrifice a barnyard animal here? Pay for winRar? Has any one else had an issue where they run a script; it runs fine the first few times, but then suddenly, and for no apparent reason, it takes a massive slowdown?
type: Question

http://stackoverflow.com/a/48410326
has body: The immediate answer is that a dict's values method returns a non-indexable object, as the error indicates. You can get around that by passing to to list: list(word_centroid_map.values()) But really you'd do better to rewrite your loop like this: for key, value word_centroid_map.items(): if value == cluster: words.append(key) Or even better, use a list comprehension: words = [k for k, v in word_centroid_map.items() if v == cluster]
answers question: http://stackoverflow.com/q/48410254
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48410254

http://stackoverflow.com/comment/83706635
score: 0
has text: Possible duplicate of [A column-vector y was passed when a 1d array was expected](https://stackoverflow.com/questions/34165731/a-column-vector-y-was-passed-when-a-1d-array-was-expected)
type: QuestionComment
comment on: http://stackoverflow.com/q/48359899
type: Comment

http://stackoverflow.com/q/48347002
upvote count: 1
tagged with: python
answer count: 3
tagged with: while-loop
has comment: http://stackoverflow.com/comment/83679901
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48347037
has body: I am wanting to write a loop that stays in the loop until a condition is met. Here's the code so far, and I'm not sure if all is correct, I have little experience in while loops: x = 2885 y = 1440 difference = 0 while True: if x &gt; y: difference = x - y break So what I want is to keep subtracting my constant y from x until y &gt; x and to have the final difference = 5 Any help is much appreciated, thanks in advance!
downvote count: 1
has answer: http://stackoverflow.com/a/48347037
favorite count: 0
has title: Python - Stay in loop Until condition is met
possible better answer: http://stackoverflow.com/a/48347054
type: Question
has answer: http://stackoverflow.com/a/48347054
tagged with: if-statement
has answer: http://stackoverflow.com/a/48347818

http://stackoverflow.com/q/48452399
answer count: 1
has comment: http://stackoverflow.com/comment/83898126
favorite count: 0
has answer: http://stackoverflow.com/a/48453652
accepted answer: http://stackoverflow.com/a/48453652
type: Question
score: 1
has comment: http://stackoverflow.com/comment/83898200
tagged with: python
has comment: http://stackoverflow.com/comment/83899461
has title: Filling 2D numpy array based on True/False value contained in another array in Python
tagged with: numpy
type: AnsweredQuestion
has body: I have a 1D empty numpy array (b) of size 4 into which I want to stack columns. The value contained in the columns are dependent on another 1D numpy array (a) containing True/False bool values. I have manage to fill it in the way I want using for loops but I think it can be done more efficiently using slices. Here is the working code giving me the correct result: import numpy as np import random b = np.empty(4, dtype=object) # The array we are trying to fill for i in range (5): # a contains 4 random True/False values a = np.random.randint(0,2,size=(4), dtype=bool) # If a row is true in a then b should contain data, otherwise nan data = random.random() iteration = 0 for value in a : if b[iteration] is None: # We check if b is empty, if yes we initialize if (value): # If the row in a is true we fill with the value b[iteration]=np.array([data]) else: b[iteration]=np.array([np.nan]) else: # If b is not empty then we just stack if (value): b[iteration]=np.hstack([b[iteration],data]) else: b[iteration]=np.hstack([b[iteration],np.nan]) iteration +=1 print(b) Output: array([array([ nan, 0.04209371, 0.03540539, nan, 0.59604905]), array([0.66677989, nan, 0.03540539, nan, nan]), array([0.66677989, 0.04209371, 0.03540539, nan, 0.59604905]), array([0.66677989, 0.04209371, 0.03540539, nan, nan])], dtype=object) I have tried the following code using slices of numpy arrays but it gives me an error: b = np.empty(4, dtype=object) for i in range (5): a = np.random.randint(0,2,size=(4), dtype=bool) data = random.random() b[a] = np.vstack([b[a],np.zeros(len(b[a]))+data]) print(b) Output: TypeError: NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions I am trying to find the most efficient way of solving this problem, any suggestions ?
has comment: http://stackoverflow.com/comment/83898256
upvote count: 1
has comment: http://stackoverflow.com/comment/83898165
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/83753220
type: AnswerComment
has text: `1 / 4503599627370496` is winning the classic lotto game of 6/49 **twice in a row**.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48382909

http://stackoverflow.com/a/48338069
upvote count: 10
accepted answer of: http://stackoverflow.com/q/48337914
answers question: http://stackoverflow.com/q/48337914
type: AcceptedAnswer
downvote count: 0
has body: you can use builtin method dir(obj) The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information: If the object is a module object, the list contains the names of the module’s attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes. source : https://docs.python.org/2/library/functions.html#dir
score: 10
type: Answer

http://stackoverflow.com/q/48368201
has answer: http://stackoverflow.com/a/48368327
has body: I am a beginner with Python, and I come from MATLAB. What I need to do is create a loop with years from 2000 to 2016. I have a directory with a lot of files, whose filenames contain these years, like "file_2006". How can I create a loop to open the files for specific years? In MATLAB I would do it like: for i=2000:2016 year=num2str(i); filename=['file_' year]; X=cdfread(filename); % and then some operations with X that I read here end But is it possible to do it in Python? Thank you!
type: Question
tagged with: python-3.x
has title: Python: How to iterate over files changing their names in loop?
has comment: http://stackoverflow.com/comment/83723007
accepted answer: http://stackoverflow.com/a/48368298
tagged with: python
has answer: http://stackoverflow.com/a/48368298
type: AnsweredQuestion
tagged with: python-2.7
score: 0
possible better answer: http://stackoverflow.com/a/48368327
answer count: 2

http://stackoverflow.com/comment/83648645
score: 1
has text: There are quite a few more problems in this code, I'm afraid.
type: Comment
comment on: http://stackoverflow.com/q/48331358
type: QuestionComment

http://stackoverflow.com/comment/83660871
type: Comment
score: 2
has text: https://stackoverflow.com/questions/13329617/change-the-volume-of-a-wav-file-in-python
comment on: http://stackoverflow.com/q/48337864
type: QuestionComment

http://stackoverflow.com/a/48338285
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/83787951
has body: One method would be to read the file in chunks and then filter the lines out in the chunks, it's possible this will be faster if you have a large file with a lot of unwanted rows as reading in the entire df and then filtering may be non-performant: In[17]: t="""name timestamp value1 state value2 Cs01 1.514483e+09 19.516 0 9.999954e-01 Cs02 1.514483e+09 20.055 0 9.999363e-01 Cs03 1.514483e+09 20.054 0 9.999970e-01 Cs01 1.514483e+09 20.055 0 9.999949e-01 Cs01 1.514483e+09 10.907 0 9.963121e-01 Cs02 1.514483e+09 10.092 0 1.548312e-02""" d = pd.read_csv(io.StringIO(t), delim_whitespace=True, chunksize=2) dfs = pd.concat([x[x['name'].str.startswith('Cs01')] for x in d]) dfs Out[17]: name timestamp value1 state value2 0 Cs01 1.514483e+09 19.516 0 0.999995 3 Cs01 1.514483e+09 20.055 0 0.999995 4 Cs01 1.514483e+09 10.907 0 0.996312 Here the chunksize param specifies the number of lines to read, you can set this to some arbritrary size, you then do a list comprehension and filter on each chunk and then call concat to produce a single df
answers question: http://stackoverflow.com/q/48338064
has comment: http://stackoverflow.com/comment/83788075
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/83650061
type: Comment
has text: @Valachio TBH, I think wwii's answer is the best solution for this particular question since you only want the indicies from a particular list: `opterator.itemgetter(1, 4, 5, 6, 9)(a) == (a[1], a[4], a[5], a[6], a[9])`.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48331947

http://stackoverflow.com/q/48423643
type: Question
tagged with: breach-attack
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83839442
has comment: http://stackoverflow.com/comment/83837503
has body: I've just got vulnerability report that came from pentesters for my Django project. The report says my Django app is vulnerable to the BREACH ATTACK. SSL is active, cookies are flagged as secure, session cookies are set as secure. HTTP Compressions closed by the sysadmin it is controlled from the Nginx that I have no access. So gzip is closed. Now I want to randomize csrf token for per client-side request for the django admin, especially for the login page. Is there a way to do this in settings.py in a simple way or do I have to write custom admin view? What is the best practice for this issue?
tagged with: csrf
tagged with: django
tagged with: penetration-testing
tagged with: python
has comment: http://stackoverflow.com/comment/83837965
has title: How can I randomize csrf token for django admin
has comment: http://stackoverflow.com/comment/83839709
has comment: http://stackoverflow.com/comment/83837701
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83837980
has comment: http://stackoverflow.com/comment/83837914

http://stackoverflow.com/q/48368625
has comment: http://stackoverflow.com/comment/83724163
answer count: 0
has comment: http://stackoverflow.com/comment/111141670
has comment: http://stackoverflow.com/comment/120259710
score: 1
upvote count: 1
tagged with: multithreading
downvote count: 0
has body: I create this two object Queue and PortScanner class Queue(object): def __init__(self, queue=[]): self.lock = threading.Lock() self.queue = queue self.len = len(queue) def append(self, value): # Append value to the end of the list self.lock.acquire() try: self.queue.append(value) self.len += 1 finally: self.lock.release() def pop(self): # Pop value from the end of the list self.lock.acquire() value = None try: value = self.queue.pop() self.len -= 1 finally: self.lock.release() return value def getall(self): return self.queue class PortScanner(object): def __init__(self, host): self.qinit = Queue([20,21,22,23,24,25]) self.qport = Queue([]) self.host = host def check_port(self): s = socket.socket() port = self.qinit.pop() try: s.connect((self.host,port)) s.close() self.qport.append(port) except: pass def check_multi_port(self, num_threads=2): for i in range(int(self.qinit.len / num_threads)): threads = [ threading.Thread(target=self.check_port) for _ in range(num_threads) ] [t.start() for t in threads] [t.join() for t in threads] return self.qport.getall() But it remains blocked until i press Ctrl+C and then get this error: &gt; ^CTraceback (most recent call last): File "test.py", line 156, in &gt; &lt;module&gt; &gt; ports = scanner.check_multi_port() File "test.py", line 144, in check_multi_port &gt; [t.join() for t in threads] File "test.py", line 144, in &lt;listcomp&gt; &gt; [t.join() for t in threads] File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", &gt; line 1056, in join &gt; self._wait_for_tstate_lock() File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", &gt; line 1072, in _wait_for_tstate_lock &gt; elif lock.acquire(block, timeout): KeyboardInterrupt ^CException ignored in: &lt;module 'threading' from &gt; '/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py'&gt; &gt; Traceback (most recent call la…
has title: Lock error (_wait_for_tstate_lock) in multithreading
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/106757205
has comment: http://stackoverflow.com/comment/83723887
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/83724370

http://stackoverflow.com/comment/83944157
comment on: http://stackoverflow.com/q/48475440
score: 0
type: Comment
type: QuestionComment
has text: Given your example, would the string `block4` be replaced with `block 4`, and so on?

http://stackoverflow.com/a/78061390
answers question: http://stackoverflow.com/q/48462171
type: Answer
has body: Since it is the dependencies that are problematic, there might be yet another remedy: load the dependencies explicitly. Because libLMR_Demodulator.so was not found with RPATH, it might be enough to just load it manually first: import ctypes lib_demodulator = ctypes.cdll.LoadLibrary('./libLMR_Demodulator.so') sh_obj = ctypes.cdll.LoadLibrary('./libDemodulatorJNI_LMR.so') actual_start_frequency = sh_obj.getActualStartFrequency(ctypes.c_long(0)) print('The Current Actual Frequency Is: ' + str(actual_start_frequency))
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/48443426
has comment: http://stackoverflow.com/comment/83888637
tagged with: pandas
has comment: http://stackoverflow.com/comment/83880187
upvote count: 0
has comment: http://stackoverflow.com/comment/83909692
has comment: http://stackoverflow.com/comment/83880539
has comment: http://stackoverflow.com/comment/83880662
downvote count: 2
linked to: http://stackoverflow.com/q/17573814
answer count: 1
has body: I am quite new to Python, so sorry for my not-knowing. I want to create, for example, a table in which the rows are documents and the columns are labels. A document feature matrix if you will. Every label represents an arbitrary number of words (usually 1, 2 or 3 words). They are stored in a dict: regexDict = {u'item_4278': [u'occupational', u'position', u'job'], u'item_4279': [u'job', u'blue', u'collar'], u'item_4276': [u'job', u'civil', u'service'], ...} Now, I have a number of documents (represented as strings in a df) and I want to find out how often the words from one label appear in a document. For the following: df = doc text doc1 My job is in civil service. I love my job blabla civil bla bla service bla. doc2 My job is in civil service. It is a job that you call blue collar. doc3 This is a document completely unrelated to the items. I would like to count the amount of times the values occur somewhat close to each other in a document, for example with this regex I created: occupational\W+(?:\w+\W+){0,3}?position\W+(?:\w+\W+){0,3}?job\W+(?:\w+\W+){0,3}? Desired output: item_4278 item_4279 item_4276 Doc 1 0 0 2 Doc 2 0 1 1 Doc 3 0 0 0 Edit: If only 1 or 2 words appear in the document, it should get a score of 0. It is important that all words appear in the document! :) By somewhat close to each other, I mean that if it says "This is a text. These sentences don't contain interesting words. My job is in civil service. The previous sentence does contain interesting words", 'job' 'civil' and 'service' appear quite close to each other in the entire document, so the document gets a score of 1 for item_4276. Right now, all I got is this, but it is far from satisfactory: testdic = { 'item_1': r'occupational\W+(?:\w+\W+){0,3}?position\W+(?:\w+\W+){0,3}?job\W+(?:\w+\W+){0,3}?', 'item_2': r'job\W+(?:\w+\W+){0,3}?blue\W+(?:\w+\W+){0,3}?collar\W+(?:\w+\W+){0,3}?', 'item_3': r'job\W+(?:\w+\W+){0,3}?civil\W+(?:\w+\W+){0,3}?service\W+(?:\w+\W+){0,3}?' } total = [] for key, ite…
has answer: http://stackoverflow.com/a/48446186
has comment: http://stackoverflow.com/comment/83879871
has comment: http://stackoverflow.com/comment/83880572
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83883932
has title: Counting occurrence of multiple words Python
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/83880067
tagged with: feature-extraction
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83887651

http://stackoverflow.com/q/48400175
accepted answer: http://stackoverflow.com/a/48400848
type: AnsweredQuestion
has body: I am using standard stream redirection in Python. I have a writer.py file as below. for data in (123, 0, 999, 42): print('%03d' % data) The output of it is being used as input to an addition program. import sys sum = 0 while True: try: line = sys.stdin.readline()[:-1] except EOFError: break else: sum += int(line) print(sum) Giving the first script's output to other as : python writer.py | python adder.py This gives me the error as : File "adder.py", line 9, in &lt;module&gt; sum += int(line) ValueError: invalid literal for int() with base 10: '' What needs to be changed in adder.py script.
possible better answer: http://stackoverflow.com/a/48401613
answer count: 2
has answer: http://stackoverflow.com/a/48400848
has answer: http://stackoverflow.com/a/48401613
score: 0
type: Question
tagged with: stdin
has title: ValueError: invalid literal for int() : while using python stream redirection
has comment: http://stackoverflow.com/comment/83789703
has comment: http://stackoverflow.com/comment/83789522
tagged with: eoferror
has comment: http://stackoverflow.com/comment/83788962
tagged with: python

http://stackoverflow.com/a/48357135
answers question: http://stackoverflow.com/q/48356424
type: AcceptedAnswer
has body: If I understand correctly: In [34]: chk_set = set(['PRP','MD','NN']) In [35]: chk_set.issubset(t.tag_ for t in nlp("I will go to the mall")) Out[35]: True In [36]: chk_set.issubset(t.tag_ for t in nlp("I will go")) Out[36]: False UPDATE: how can I read the word marked as NN and print it out? In [53]: [t.text for t in nlp("I will go to the mall") if t.tag_ in ['NN']] Out[53]: ['mall']
score: 4
accepted answer of: http://stackoverflow.com/q/48356424
has comment: http://stackoverflow.com/comment/83701234
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/83844599
type: AnswerComment
score: 0
has text: @Ev.Kounis The OP said they "don't want to use **kwargs", so I think this is exactly what they want.
comment on: http://stackoverflow.com/a/48427148
type: Comment

http://stackoverflow.com/q/48470644
has body: I am having trouble with a simple Python Lambda Function. The Lambda (called by Zapier) function basically creates a Confluence Page and recalls another Zapier Webhook. I upload a .zip file in my S3, which has all folders of the required packages, and then a src folder with my Python file which has my handler function. .zip --> src/lambda_function.py which then I call a handler function. At the top of my lambda_function.py I have the following: import string import json import pyconfluence as pyco import requests import os import time def create_page(name, content, label): data = {} data["type"] = "page" data["title"] = name data["ancestors"] = [{"id": str(12345678)}] #172949526 is the Parent data["space"] = {"key": "PK"} data["body"] = {"storage": {"value": content, "representation": "storage"}} data["metadata"] = {"labels": [{"name": label}]} return pyco.api.rest("/", "POST", json.dumps(data)) def lambda_handler(event, context): # Page 12345678 that is in fact a representation of the template content = pyco.get_page_content(12345678) page_title = event['issue_key'] + ": " + event['issue_title'] content = string.replace(content, "PK-200", event['issue_key']) create_page(page_title, content, "active-product-requirement") api_url = "https://acmein.atlassian.net/rest/api/2/issue/"+event['issue_key']+"/remotelink/" webhook = 'https://hooks.zapier.com/hooks/catch/123456/8v6fde/' requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (os.environ["PYCONFLUENCE_USER"], os.environ["PYCONFLUENCE_TOKEN"]) result = requests.get(api_url, headers=requisite_headers, auth=auth).json() if len(result) &gt; 0: confluence_url = result[0]["object"]["url"] else: confluence_url = "Error getting the page" callback = requests.post(webhook, data={'issue_key': event['issue_key'], 'confluence_url': confluence_url }) return ["Success"] and then in my CloudWatch logs I have the following errors:
has answer: http://stackoverflow.com/a/48510453
downvote count: 0
tagged with: python
has title: RuntimeWarning: Parent module 'src' not found while handling absolute import - AWS Lambda
tagged with: amazon-web-services
score: 3
upvote count: 3
answer count: 1
tagged with: aws-lambda
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83936632
type: UnansweredQuestion

http://stackoverflow.com/comment/83701515
comment on: http://stackoverflow.com/q/48357372
has text: @MateusBuarque the case of "I have thousands of these ifs" is arguably exactly where you should *avoid* doing that. The indent makes it very readable, a single-line `if` is much harder to notice when looking through the code.
type: Comment
type: QuestionComment
score: 0

user-agent
tags question: http://stackoverflow.com/q/48454949
type: Tag
tag name: user-agent

http://stackoverflow.com/comment/83719342
type: QuestionComment
comment on: http://stackoverflow.com/q/48361145
has text: should've looked like this: result = conn.execute(""" insert into expert(model, price) values(%s, %s) """, (item['model'], item['price']))
score: 0
type: Comment

http://stackoverflow.com/comment/83928165
comment on: http://stackoverflow.com/a/48467205
score: 0
has text: Thank you! Matlabfuture.py also gives an AttributeError when trying to pythonengine.createMATLABAsync(tokens). Changing this to matlab.engine instead of pythonengine gives the same AttributeError. Do you have an idea of which module I should be using?
type: Comment
type: AnswerComment

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/48440907
tag name: deconvolution

http://stackoverflow.com/a/48353323
answers question: http://stackoverflow.com/q/48353281
has comment: http://stackoverflow.com/comment/83693221
has comment: http://stackoverflow.com/comment/83693286
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48353281
has body: One quick solution would be to try to cast the items to an int and keep those that succeed. List of any type: result = [] for i in x: try: result.append(int(i)) except Exception: pass print(result) &gt;&gt;[2, 42, 69] List Of Strings As Mateen Ulhaq mentioned, if your input is always string type, it would be more appropriate to use: [int(s) for s in my_list if s.isdigit()] Note: This solution won't work if your string has negative numbers such as '-12'
score: 1
type: Answer

http://stackoverflow.com/comment/83953108
score: 2
has text: Someone eventually will. But to be honest: did you spend 5 mins with the docs? Your function is very suitable to exploit numpy's vectorized operations. No loops needed. The docs also warn about np.vectorize (somewhat a hidden loop)! The solution is more or less the same code, just doing the operations on the array x itself. No wrapping.
comment on: http://stackoverflow.com/q/48480053
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83782986
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48397615
has text: Mentioning `newest Anaconda` is dependent on the current date. Actual version would be more useful.
score: 0

http://stackoverflow.com/comment/83754939
score: 0
type: Comment
type: QuestionComment
has text: Wow, that's a nice unexpected result
comment on: http://stackoverflow.com/q/48381870

http://stackoverflow.com/comment/83889274
type: QuestionComment
comment on: http://stackoverflow.com/q/48448206
has text: @John Gordon See video and the time it is executing
type: Comment
score: 0

http://stackoverflow.com/comment/130635456
type: AnswerComment
comment on: http://stackoverflow.com/a/61478547
score: 1
type: Comment
has text: I think "task" was confusing so I've renamed everything to "coro". When you create a task it gets started right away so it's actually a future. I don't believe you want to use this function for futures.

selenium-webdriver
tags question: http://stackoverflow.com/q/48402242
tags question: http://stackoverflow.com/q/48448850
tags question: http://stackoverflow.com/q/48351231
tags question: http://stackoverflow.com/q/48389938
tags question: http://stackoverflow.com/q/48430329
tags question: http://stackoverflow.com/q/48438000
tags question: http://stackoverflow.com/q/48411823
type: Tag
tags question: http://stackoverflow.com/q/48395485
tags question: http://stackoverflow.com/q/48414801
tags question: http://stackoverflow.com/q/48469706
tags question: http://stackoverflow.com/q/48334346
tags question: http://stackoverflow.com/q/48365252
tags question: http://stackoverflow.com/q/48374960
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/48423414
tags question: http://stackoverflow.com/q/48373198
tags question: http://stackoverflow.com/q/48461493
tags question: http://stackoverflow.com/q/48393941

http://stackoverflow.com/comment/83872921
type: Comment
has text: [SimpleHTTPServer](https://docs.python.org/2/library/simplehttpserver.html)
comment on: http://stackoverflow.com/q/48440816
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83876305
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48440816
type: QuestionComment
has text: @user9148619 this is __still__ unrelated (and OT here). Your question is not about programming, it's about system configuration, and the fact that you need this system configuration for a program you're writing doesn't change anything to it.

http://stackoverflow.com/comment/83929198
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48467779
score: 0
has text: I woudl suggest to test what version is running in VSCode, in my case by default it was 2.7.

http://stackoverflow.com/comment/83903066
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48449757
has text: First, thank you so much for the answer. So, I guess the surface creation is unnecessary. And about the Bullet calculation, I was intending to make it possible for the bullets go diagonally by calculating x and y axis separately. But I just solved it. I was mistaking it as getting the angle.

http://stackoverflow.com/comment/83955386
type: QuestionComment
comment on: http://stackoverflow.com/q/48480667
score: 0
has text: You don't need to "install" modules to use them in python.
type: Comment

http://stackoverflow.com/comment/83752010
type: Comment
score: 2
has text: Perhaps this http://turbodbc.readthedocs.io/en/latest/ could be a better solution. If you're curious you could watch this https://www.youtube.com/watch?v=B-uj8EDcjLY
type: QuestionComment
comment on: http://stackoverflow.com/q/48382380

http://stackoverflow.com/q/48407367
has comment: http://stackoverflow.com/comment/83803732
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: I run cURL command using API key and extract data in test1.json file and then I use python 2.7 using json module to parse
tagged with: curl
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48407681
has comment: http://stackoverflow.com/comment/83803694
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: shell
upvote count: 1
has comment: http://stackoverflow.com/comment/83804074
has body: I execute curl command using API and get data in test1.json file then I use below python script to parse that data so that data using json module I get in 1 line with slash n starting and ending the all key and value import os import json # test.sh is a curl command for getting customer id and then extract all data for all child customer and save the result to test1.json os.system('sh test1.sh') # Open test1.json file and read them with open('test1.json', 'r') as f: data = f.read() d = json.dumps(data, indent=6) print(d)
favorite count: 0
has comment: http://stackoverflow.com/comment/83804252
type: Question

http://stackoverflow.com/comment/83811742
type: AnswerComment
comment on: http://stackoverflow.com/a/48410820
score: 1
type: Comment
has text: man you asked about `uint` types... if you have a better way I will be happy to hear.

http://stackoverflow.com/comment/83853507
type: Comment
comment on: http://stackoverflow.com/q/48431125
score: 1
type: QuestionComment
has text: SO isn't a code-writing or tutorial service; if you have a problem with your implementation then please ask about that, otherwise you will need to do some research and write some code.

django-admin
tags question: http://stackoverflow.com/q/48337814
tags question: http://stackoverflow.com/q/48369286
tags question: http://stackoverflow.com/q/48488077
tags question: http://stackoverflow.com/q/48404736
type: Tag
tags question: http://stackoverflow.com/q/48363069
tag name: django-admin
tags question: http://stackoverflow.com/q/48361494

http://stackoverflow.com/q/48373395
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48373445
type: AnsweredQuestion
tagged with: pandas-groupby
score: 1
possible better answer: http://stackoverflow.com/a/48373719
has answer: http://stackoverflow.com/a/48373719
favorite count: 0
type: Question
has title: Pandas dataframe output
answer count: 2
has comment: http://stackoverflow.com/comment/83733904
accepted answer: http://stackoverflow.com/a/48373445
has body: I have the following Pandas data frame created. #usr/bin/python import pandas as pd vals = [ 1 , 2 , 3 ] ctry_grp = ['USA', 'USA', 'USA'] state_grp = ['MA' , 'MA' , 'CT' ] country_mean = pd.DataFrame( {'values': vals,'country': ctry_grp,'state': state_grp }).groupby(['country']).mean() print(country_mean) state_mean = pd.DataFrame( {'values': vals,'country': ctry_grp,'state': state_grp }).groupby(['country','state']).mean() print(state_mean) The output for country_mean in the above code is in the format of values country USA 2 I want to get the output in the format of [2 , 2 , 2] The output for state_mean for above code is in the format of values country state USA CT 3.0 MA 1.5 I want to get the output in the format of [1.5, 1.5, 3] Please help to modify the above code. Thanks in advance.
downvote count: 0

robotics
tags question: http://stackoverflow.com/q/48402107
tag name: robotics
type: Tag

http://stackoverflow.com/a/48382177
type: Answer
answers question: http://stackoverflow.com/q/48382122
score: 5
downvote count: 0
upvote count: 5
has body: Use Index.isin: df = df.index.isin([('007','5000')]) print (df) [ True False False]

http://stackoverflow.com/a/48412109
type: Answer
score: 0
has body: I would use a pub/sub websocket-framework, like Autobahn/Python, with one script as a "server" and it handles all the file communication but it depends on scale maybe this could be Overkill.
answers question: http://stackoverflow.com/q/48409610

http://stackoverflow.com/a/48357711
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48357030
upvote count: 5
type: Answer
has body: The problem is you have installed original pytesseract package (downloaded using pip) and referring documentation of madmaze GitHub version, actually both are different. I suggest uninstalling the present version and cloning the GitHub repo and installing the same, by following this steps: Uninstall present version: pip uninstall pytesseract Clone madmaze/pytesseract GitHub repo by either using git: git clone https://github.com/madmaze/pytesseract.git or download it directly by clicking here Get to the root directory of the cloned repo and run: pip install .
score: 5
answers question: http://stackoverflow.com/q/48357030
type: AcceptedAnswer

http://stackoverflow.com/comment/83886162
type: QuestionComment
has text: The upstream Python documentation **explicitly** tells you how to set up pipelines with `subprocess`. See https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline
comment on: http://stackoverflow.com/q/48446461
type: Comment
score: 0

http://stackoverflow.com/a/48394321
upvote count: 2
downvote count: 0
has body: sys.getsizeof(posList) is not giving you what I think you think it is: it's telling you the size of the list object containing the lines; this does not include the size of the lines themselves. Below are some outputs from reading a roughly 3.5Gb file into a list on my system: In [2]: lines = [] In [3]: with open('bigfile') as inf: ...: for line in inf: ...: lines.append(line) ...: In [4]: len(lines) Out[4]: 68318734 In [5]: sys.getsizeof(lines) Out[5]: 603811872 In [6]: sum(len(l) for l in lines) Out[6]: 3473926127 In [7]: sum(sys.getsizeof(l) for l in lines) Out[7]: 6001719285 That's a bit over six billion bytes, there; in top my interpreter was using about 7.5Gb at this point. Strings have considerable overhead: 37 bytes each, it looks like: In [2]: sys.getsizeof('0'*10) Out[2]: 47 In [3]: sys.getsizeof('0'*100) Out[3]: 137 In [4]: sys.getsizeof('0'*1000) Out[4]: 1037 So if your lines are relatively short, a large part of the memory use will be overhead.
answers question: http://stackoverflow.com/q/48385340
type: Answer
score: 2

http://stackoverflow.com/q/48474731
score: 0
has title: ImportError: cannot import name connection : Mongoengine
has answer: http://stackoverflow.com/a/48474875
linked to: http://stackoverflow.com/q/29489883
tagged with: flask-mongoengine
has answer: http://stackoverflow.com/a/48497348
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: python
tagged with: flask
has body: I'm trying to get a Flask app running with Apache via WSGI but am getting the following error flagged in the Apache logs when I try to connect to the server. At a bit of a loss. Appreciate any pointers. Thanks! mod_wsgi (pid=7884): Target WSGI script '/var/www/tracker/tracker/tracker.wsgi' cannot be loaded as Python module. mod_wsgi (pid=7884): Exception occurred processing WSGI script '/var/www/tracker/tracker/tracker.wsgi'. Traceback (most recent call last): File "/var/www/tracker/tracker/tracker.wsgi", line 3, in &lt;module&gt; from tracker import app as application File "/var/www/tracker/tracker/tracker.py", line 3, in &lt;module&gt; from flask_mongoengine import MongoEngine File "/var/www/tracker/lib/python3.5/site-packages/flask_mongoengine/__init__.py", line 6, in &lt;module&gt; import mongoengine File "/var/www/tracker/lib/python3.5/site-packages/mongoengine/__init__.py", line 2, in &lt;module&gt; from mongoengine import connection ImportError: cannot import name connection

http://stackoverflow.com/q/48445240
type: Question
has body: For the first time I've decided to play about with some classes in Python, and I think this is an example of a task that would actually benefit from their use. I'm trying to parse the ouput text file from a bioinformatics tool, but I'm not sure what the best way to proceed will be. The file contains several distinct 'sections' of data, all of which I'd like to collect. The section I'm most interested in is somewhat delimited by >> strings (i.e. the file contains >> Result 1 >> Result 2 >> etc...) I'm at a bit of a loss for the best way to start separating out the chunks I want without opening and reading the file over and over again (especially since the files have the possibility of being large). ClusterBlast scores for /home/wms_joe/PVCs/other_genomes/multigene/operon_genbank/PVCcif_ATCC43949.gbk Table of genes, locations, strands and annotations of query cluster: PAU_01961 8 457 + T4-like_virus_tail_tube_protein_gp19 no_locus_tag PAU_01962 521 1618 + major_tail_sheath_protein no_locus_tag PAU_01963 1799 3280 + tail_sheath_protein no_locus_tag PAU_01964 3334 4533 + tail_sheath_protein no_locus_tag PAU_01965 4547 5005 + T4-like_virus_tail_tube_protein_gp19 no_locus_tag PAU_01966 5002 5181 + hypothetical_protein no_locus_tag PAU_01967 5168 5851 + hypothetical_protein no_locus_tag PAU_01968 5848 7449 + Rhs_element_Vgr_protein no_locus_tag PAU_01969 7462 7905 + baseplate_wedge_subunit no_locus_tag PAU_01970 7902 8318 + hypothetical_protein no_locus_tag PAU_01971 8527 11253 + hypothetical_protein no_locus_tag PAU_01972 11246 14197 + hypothetical_protein no_locus_tag PAU_01973 14333 15184 + hypothetical_protein no_locus_tag PAU_01974 15247 17145 + hypothetical_protein no_locus_tag PAU_01975 17155 19227 + ATP-dependent_zinc_metalloprotease_FtsH no_locus_tag PAU_01976 19252 20166 + hypothetical_protein no_locus_tag PAU_01977 20327 21223 + hypothetical_protein no_locus_tag PAU_01978 21308 22291 + hypothetical_protein no_locus_tag PAU_01979 22788 23684 + hypothetical_protei…
tagged with: text-parsing
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83882579
score: 0
has title: Breaking a repetitive file in to instances of classes in python
answer count: 0
has comment: http://stackoverflow.com/comment/83882397
has comment: http://stackoverflow.com/comment/83882785

http://stackoverflow.com/a/48491595
type: Answer
accepted answer of: http://stackoverflow.com/q/48482355
answers question: http://stackoverflow.com/q/48482355
has body: Here is solution: class Product(models.Model): name = models.CharField("product", max_length=200) price = models.DecimalField("price", max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="products", verbose_name="category") def discount_value(self): return self.category.discount
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/83693046
type: QuestionComment
has text: Did you add any custom middleware ?
score: 0
comment on: http://stackoverflow.com/q/48352586
type: Comment

http://stackoverflow.com/a/48473784
has body: In pandas is the best avoid loops because slow, so better is use numpy.select: #first replace all numeric to NaN and then to 0 dd.RT = m1 = dd.Type=='NR' m2 = dd.Type=='RP' s = dd.QPA *dd.MT * dd.WH s1 = dd.MTBR * 1000 s2 = s * 24 / s1 s3 = s * dd.RT / s1 dd['mean_v'] = np.select([m1, m2], [s2, s3], default=np.nan) But if only NR and RP values in Type column use numpy.where: dd['mean_v'] = np.where(m1, s2, s3) Loop version (very slow): dd.RT = pd.to_numeric(dd.RT, errors='coerce').fillna(0) for i, x in dd.iterrows(): if x['Type'] =='NR': dd.loc[i, 'mean_v'] = x.QPA*x.MT*x.WH*24 / (x.MTBR*1000) elif x.Type=='RP': dd.loc[i, 'mean_v'] = x.QPA*x.MT*x.WH*x.RT / (x.MTBR*1000) else: dd.loc[i, 'mean_v'] = np.nan If always RT is 24 for TYPE==NR: s = pd.to_numeric(dd.RT, errors='coerce').fillna(24) dd['mean_v'] = (dd.QPA * dd.MT * dd.WH * s) / (dd.MTBR * 1000) print (dd) MT MTBR Prd QPA RT Type WH mean_v 0 3 539 24Months 1 0.0 NR 188 0.025113 1 3 51 24Months 4 0.0 NR 188 1.061647 2 3 112 24Months 10 6.0 RP 188 0.302143 3 3 385 24Months 2 7.0 RP 188 0.020509 4 3 206 24Months 1 8.0 RP 188 0.021903 5 3 349 24Months 19 0.0 NR 188 0.736917 6 3 569 24Months 18 0.0 NR 188 0.428204 7 3 66 24Months 20 8.0 RP 188 1.367273 8 3 181 24Months 9 0.0 NR 188 0.673061 9 3 149 24Months 2 0.0 NR 188 0.181691 10 3 131 24Months 8 7.0 RP 188 0.241099 11 3 289 24Months 11 3.0 RP 188 0.064401 12 3 392 24Months 13 2.0 RP 188 0.037408 13 3 303 24Months 9 0.0 NR 188 0.402059 14 3 318 24Months 5 5.0 RP 188 0.044340 15 3 103 24Months 9 6.0 RP 188 0.295689 16 3 447 24Months 8 6.0 RP 188 0.060564 17 3 600 24Months 19 0.0 NR 188 0.428640 18 3 258 24Months 12 0.0 NR 188 0.629581 19 3 164 24Months 13 0.0 NR 188 1.072976 20 3 589 24Months 11 0.0 NR 188 0.252795 Timings: In [1]: %timeit jez1(dd) 14.1 ms ± 82 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [2]: %timeit jez2(dd) 8.97 ms ± 32 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [3]: %timeit jez3(dd) 25.1 s ± 769 ms per loop (mean…
has comment: http://stackoverflow.com/comment/83942991
has comment: http://stackoverflow.com/comment/83943553
score: 3
has comment: http://stackoverflow.com/comment/83962431
type: Answer
answers question: http://stackoverflow.com/q/48473706
has comment: http://stackoverflow.com/comment/83963482
has comment: http://stackoverflow.com/comment/83961128
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48369286
type: Question
has title: django-ckeditor applying changes to content correctly but not applying change in admin
has body: I have replaced default django admin with django-ckeditor GoogleWebFonts installed, loading and applying font to content correctly. Problem is changes not being applied in django admin. Specifically,the source is correct (pressing the source button on ckeditor interface), showing the font applied correctly and therefore my content is changed to the font i want. But when i reload the page in admin it defaults back to a normal text, but still with the correct source code. I have ran python manage.py collectstatic and have my static url, static root, media url and media root assigned and working correctly. I am using the editor by replacing my TextField models.py from ckeditor.fields import RichTextField ... body = RichTextField() ... And urls.py : url(r'^ckeditor/', include('ckeditor_uploader.urls')), config.js: CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.extraPlugins = 'ckeditor-gwf-plugin'; config.font_names = 'GoogleWebFonts;' + config.font_names; }; settings.py : CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 900, }, }
tagged with: django-admin
tagged with: wysiwyg
tagged with: python
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48479583
answer count: 1
tagged with: django
tagged with: ckeditor

http://stackoverflow.com/comment/83888881
score: 0
comment on: http://stackoverflow.com/q/48448240
has text: Welcome to StackOverflow! Please read about [how to ask a question](https://stackoverflow.com/help/how-to-ask) (particularly [how to create a good example](https://stackoverflow.com/help/mcve)) in order to get good responses.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48404881
has answer: http://stackoverflow.com/a/48405017
has comment: http://stackoverflow.com/comment/83798422
tagged with: python
type: AnsweredQuestion
upvote count: 19
tagged with: identifier
answer count: 2
has comment: http://stackoverflow.com/comment/111247161
tagged with: syntax
downvote count: 0
has comment: http://stackoverflow.com/comment/83798633
score: 19
tagged with: unicode
has title: Unicode subscripts and superscripts in identifiers, why does Python consider XU == Xᵘ == Xᵤ?
favorite count: 0
type: Question
has body: Python allows unicode identifiers. I defined Xᵘ = 42, expecting XU and Xᵤ to result in a NameError. But in reality, when I define Xᵘ, Python (silently?) turns Xᵘ into Xu, which strikes me as somewhat of an unpythonic thing to do. Why is this happening? &gt;&gt;&gt; Xᵘ = 42 &gt;&gt;&gt; print((Xu, Xᵘ, Xᵤ)) (42, 42, 42)
possible better answer: http://stackoverflow.com/a/48405016
accepted answer: http://stackoverflow.com/a/48405017
has answer: http://stackoverflow.com/a/48405016

http://stackoverflow.com/q/48454373
has title: How would one find the median of a set of three integers without sorting or if statements in python?
answer count: 2
has answer: http://stackoverflow.com/a/48455430
has comment: http://stackoverflow.com/comment/83901908
has comment: http://stackoverflow.com/comment/83902401
has body: I figured I could obtain the middle integer by finding the Max and Min from the set leaving the remaining integer to be the median. How can I say that the Median is an integer that is not equal to the Maximum and Minimum without obtaining just True and False statements? def median3(num1,num2,num3): Maximum = max(num1,num2,num3) Minimum = min(num1,num2,num3) Median = int != (Maximum and Minimum) print(Median)
tagged with: python
has comment: http://stackoverflow.com/comment/83901802
possible better answer: http://stackoverflow.com/a/48454463
has comment: http://stackoverflow.com/comment/83902058
has answer: http://stackoverflow.com/a/48454463
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48455430
has comment: http://stackoverflow.com/comment/83901825
has comment: http://stackoverflow.com/comment/83901935
has comment: http://stackoverflow.com/comment/83902282
type: Question

http://stackoverflow.com/comment/83725608
has text: How to force a specific version to start?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48369356
type: Comment

http://stackoverflow.com/q/48417302
answer count: 0
has comment: http://stackoverflow.com/comment/83824366
type: UnansweredQuestion
tagged with: python
has title: Folium: Rendering Issues
score: 0
tagged with: visualization
has body: Has anyone attempts to visualize data on Folium map and ended up with Grey Blocks as seen in the picture below? The codes I used is shown below m = folium.Map([41.8781, -87.6298], zoom_start=11) for i, row in df_1.iterrows(): if(row['counts'] &lt; 300): for i in range(0, 5): folium.CircleMarker(location=[row['start_latitude'], row['start_longitude']], radius=10, color='#00000000',fill = True, fill_color='blue').add_to(m) elif(row['counts'] &lt; 1000): for i in range(0, 5): folium.CircleMarker(location=[row['start_latitude'], row['start_longitude']], radius=10, color='#00000000',fill = True, fill_color='green').add_to(m) elif(row['counts'] &lt; 2000): for i in range(0, 5): folium.CircleMarker(location=[row['start_latitude'], row['start_longitude']], radius=10, color='#00000000',fill = True, fill_color='yellow').add_to(m) else: for i in range(0, 5): folium.CircleMarker(location=[row['start_latitude'], row['start_longitude']], radius=10, color='#00000000',fill = True, fill_color='crimson').add_to(m) m.save('mapPlot.html') In general I am trying to plot the color of each dot based on it's count. I looped to plot the same area 5 times in order to solidify the color as the circlemarker in folium is slightly transparent. Everything works fine but when I attempt to zoom in for more information certain places do not render resulting in the grey boxes. Therefore, is there a way to fix and remove these grey blocks?
has comment: http://stackoverflow.com/comment/83832002
tagged with: folium
type: Question

http://stackoverflow.com/comment/83771580
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48391568
has text: How about this one? https://stackoverflow.com/questions/43000500/change-pyplot-axes-text-color-to-white
score: 0

http://stackoverflow.com/q/48463451
has body: I have a list with 240 figures all starting with the fig and the number of the fig. Here is an example : fig1-24-24-32 fig3-45-32-12 fig2-24-24-31 fig5-24-24-31 fig6-24-24-31 fig4-24-24-31 I would like to order that list by fig name: fig1-24-24-32 fig2-24-24-31 fig3-45-32-12 fig4-24-24-31 fig5-24-24-31 fig6-24-24-31 I have tried : print(glob.glob('fig*[1-241]*')) However this does not work This is what I get UPDATE Found the answer to my question here: https://stackoverflow.com/a/2669120/6235069 Answer is given by @Mark Byers
has comment: http://stackoverflow.com/comment/83919951
score: 0
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/2669059
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48463565
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48464957
upvote count: 1
has title: Ordering file in list by pattern python
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/84006506
type: Comment
score: 0
type: AnswerComment
has text: Just add the geckodriver in your [**PATH**](https://stackoverflow.com/questions/40388503/how-to-put-geckodriver-into-path). Check the link.
comment on: http://stackoverflow.com/a/48490870

http://stackoverflow.com/comment/83813048
has text: check out the [documentation](https://docs.python.org/3.6/library/multiprocessing.html#sharing-state-between-processes)
comment on: http://stackoverflow.com/q/48411582
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83733320
type: Comment
comment on: http://stackoverflow.com/a/48363024
score: 0
type: AnswerComment
has text: Liquibase is not a database. The short answer is 'yes'. It can be embedded in your application such that on startup it will check to see if any schema changes/data migrations need to be applied, applies them automatically, and then continues with your application startup. I'd encourage you to peruse the liquibase website via the link I provided.

http://stackoverflow.com/comment/90187762
type: Comment
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/48377388
has text: Did you maybe got `object has no attribute 'feature_importance'` error?

http://stackoverflow.com/comment/83677368
type: AnswerComment
comment on: http://stackoverflow.com/a/48345591
score: 0
has text: Now it is giving all values as nan.
type: Comment

http://stackoverflow.com/comment/83804236
comment on: http://stackoverflow.com/q/48407551
score: 1
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/855191/how-big-can-a-python-array-get

http://stackoverflow.com/q/48440816
has title: How can I make php and py in a certain directory display as text or download?
linked to: http://stackoverflow.com/q/4236951
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83872921
has comment: http://stackoverflow.com/comment/83875439
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83873802
tagged with: php
tagged with: .htaccess
has body: How can I make php and py in a certain directory display as text? I am working on a file hosting program, but I need to make php files either download, or display as text. I haven't been able to find any information on this.
score: 0
has comment: http://stackoverflow.com/comment/83876305
has answer: http://stackoverflow.com/a/48441343
has comment: http://stackoverflow.com/comment/83875170

http://stackoverflow.com/q/48487521
tagged with: terminal
type: UnansweredQuestion
tagged with: python
downvote count: 0
upvote count: 1
score: 1
has title: Change terminal tab name with ncurses in python
has answer: http://stackoverflow.com/a/48487898
answer count: 1
tagged with: unix
has body: I use to change terminal tab names in python using: sys.stdout.write('\x1b]2;' + name + '\x07') Can this can be achieved while using ncurses? If not, is there any workaround?
favorite count: 0
tagged with: ncurses
type: Question

http://stackoverflow.com/q/48347409
answer count: 2
tagged with: pyqt
tagged with: pyqt5
has body: This should be a stupid question. I am just curious and could not find the answer on my own. E.g. I define in PyQt5 some widgets: self.lbl = QLabel("label") self.btn = QPushButton("click") self.txt = QLineEdit("text") Is there any method to detect what kind of widget the self.lbl, self.btn, or self.txt are? I could imagine: by detecting the widget type, the input is self.lbl, the output should be QLabel... Or something like this. I have only found the isWidgetType() method. But it is not what I want to have.
favorite count: 0
accepted answer: http://stackoverflow.com/a/48347524
type: Question
has answer: http://stackoverflow.com/a/48347561
has answer: http://stackoverflow.com/a/48347524
score: 9
linked to: http://stackoverflow.com/q/1549801
upvote count: 9
tagged with: pyqt4
downvote count: 0
tagged with: python
has title: How to detect the type of widget?
possible better answer: http://stackoverflow.com/a/48347561
type: AnsweredQuestion

http://stackoverflow.com/comment/83852320
score: 0
has text: You might need to ask a new question as this strays from SUMIFs with *Jurisdiction* and *Product* criteria. And look into [`merge_asof`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html#pandas.merge_asof).
comment on: http://stackoverflow.com/a/48410398
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83656706
comment on: http://stackoverflow.com/a/48335834
score: 0
type: Comment
has text: The `exit` is somewhat redundant, as `conti()` seems to be the last statement in `main` anyways (assuming wrong indentation), but `return` is even more redundant, as it would be the last statement in the function. Also, don't just copy code from other answers!
type: AnswerComment

http://stackoverflow.com/comment/83730487
type: Comment
score: 0
type: AnswerComment
has text: @Webair, because in the latter case you have 2 captured groups: one with the whole match `r'(....)'` and another one with sequence `(ha)`. Visually you observe one group nested in another, but they are all considered separately when generating the results of matching
comment on: http://stackoverflow.com/a/48371595

http://stackoverflow.com/q/48429257
tagged with: python-logging
downvote count: 0
has answer: http://stackoverflow.com/a/48581323
has body: I'm using python and requests module==2.18.4 While crawling some data with requests, I used the logging module for debugging. I want the log to look something like this: [DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290 [DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290 [DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290 But I get this: [DEBUG] 2018-01-25 03:15:36,940 http://localhost:8888 "GET /aaa" 200 2290 [DEBUG] 2018-01-25 03:15:36,974 EUC-JP Japanese prober hit error at byte 1765 [DEBUG] 2018-01-25 03:15:36,990 EUC-KR Korean prober hit error at byte 1765 [DEBUG] 2018-01-25 03:15:36,994 CP949 Korean prober hit error at byte 1765 [DEBUG] 2018-01-25 03:15:37,009 EUC-TW Taiwan prober hit error at byte 1765 [DEBUG] 2018-01-25 03:15:37,036 utf-8 not active [DEBUG] 2018-01-25 03:15:37,036 SHIFT_JIS Japanese confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,036 EUC-JP not active [DEBUG] 2018-01-25 03:15:37,036 GB2312 Chinese confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,036 EUC-KR not active [DEBUG] 2018-01-25 03:15:37,036 CP949 not active [DEBUG] 2018-01-25 03:15:37,036 Big5 Chinese confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,036 EUC-TW not active [DEBUG] 2018-01-25 03:15:37,036 windows-1251 Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 KOI8-R Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 ISO-8859-5 Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 MacCyrillic Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 IBM866 Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 IBM855 Russian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 ISO-8859-7 Greek confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 windows-1253 Greek confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 ISO-8859-5 Bulgairan confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 windows-1251 Bulgarian confidence = 0.01 [DEBUG] 2018-01-25 03:15:37,038 TIS-620 Thai confidence = 0.01 [DEBUG] 2018-01-25 0…
has title: python requests module logging of encoding
has answer: http://stackoverflow.com/a/48657052
has answer: http://stackoverflow.com/a/48581391
score: 17
upvote count: 17
tagged with: python-requests
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50919396
has answer: http://stackoverflow.com/a/49400143
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/65319585
tagged with: logging

http://stackoverflow.com/a/48548567
has body: The following approach should help to get you started: import requests from bs4 import BeautifulSoup r = requests.get('https://pastebin.com/hGeHMBQf') soup = BeautifulSoup(r.text, "html.parser") raw = soup.find('textarea', id='paste_code').text print raw Which for this example should display: hello world
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48480345

http://stackoverflow.com/comment/83876832
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48440957
has text: the chunksize solved the problem!! Thank you so much!!! @GerardH.Pille. you are a legend

http://stackoverflow.com/comment/83668396
score: 0
type: Comment
has text: edit question and use button `{}` to correctly format code - currently you have wrong indentions.
type: QuestionComment
comment on: http://stackoverflow.com/q/48333550

http://stackoverflow.com/comment/83713854
comment on: http://stackoverflow.com/a/48363498
type: Comment
has text: Then I suppose you will want to use regex's after all. I tried. :D
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83871650
comment on: http://stackoverflow.com/q/48439807
type: QuestionComment
score: 0
has text: Raspberry got an monitor ? How to connect X-server ?
type: Comment

http://stackoverflow.com/q/48367665
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/48367889
has answer: http://stackoverflow.com/a/48367889
type: Question
tagged with: pyqt
tagged with: qt-signals
downvote count: 0
tagged with: pyqt5
upvote count: 1
score: 1
answer count: 1
tagged with: qt-slot
has title: Slot as method of a locally instantiated class is never called
type: AnsweredQuestion
has body: I have a list of mp3 files that I'm trying to play through pygame whenever different buttons are pressed (one file per button). Since there is a variable number of those files, I'm simply implementing a for loop, and I have an AudioPlayer class that I instantiate each time as follows: import sys, pygame from PyQt5.QtWidgets import * from PyQt5.QtCore import * class AudioPlayer(QObject): def __init__(self, filename): super().__init__() self.filename = filename print("Created " + filename) def play(self): print("Playing " + self.filename) pygame.mixer.music.load(self.filename) pygame.mixer.music.play() class Session(QMainWindow): def __init__(self): super().__init__() self.mainWid = QWidget(self) self.vbox = QVBoxLayout() self.mainWid.setLayout(self.vbox) self.setCentralWidget(self.mainWid) self.show() pygame.mixer.init() filenames = [r'C:\...\file1.mp3', r'C:\...\file2.mp3'] for filename in filenames: playButton = QPushButton('Play', self) localPlay = AudioPlayer(filename) playButton.clicked.connect(localPlay.play) self.vbox.addWidget(playButton) if __name__ == '__main__': app = QApplication(sys.argv) Session() sys.exit(app.exec_()) My problem is simply that the files do not play when I press the button, neither does the message get printed at all; it's like the slot never gets called: admin@home&gt; python main2.py Created C:\...\file1.mp3 Created C:\...\file2.mp3 admin@home&gt; If I play the files manually outside of the loop, like this, it works: class Session(QMainWindow): def __init__(self): # ... filenames = [r'C:\...\file1.mp3', r'C:\...\file2.mp3'] pygame.mixer.music.load(filenames[0]) pygame.mixer.music.play() As you can see, I made sure AudioPlayer inherited QObject and called __init__, so I believe it should be able to receive signals. So what is going on here? Is it a local variable issue?

http://stackoverflow.com/comment/83911619
type: Comment
score: 2
has text: `wsize - (vector.shape[0] - 1) % (wsize - overlap) - 1`
type: QuestionComment
comment on: http://stackoverflow.com/q/48458787

http://stackoverflow.com/a/48464918
type: AcceptedAnswer
has body: Long XPaths like those are very prone to breaking when there are minor changes in the page's code. Try these XPaths instead: '//input[@type="text"]' // username or phone number '//input[@type="password"]' // password '//button[contains(text(), "Log in")]' // log in button
type: Answer
accepted answer of: http://stackoverflow.com/q/48459978
score: 0
answers question: http://stackoverflow.com/q/48459978

http://stackoverflow.com/comment/84138859
type: QuestionComment
comment on: http://stackoverflow.com/q/48441336
score: 0
has text: Yes, correct. Still having the option to override the connection header will be helpful when dealing with these type of servers.
type: Comment

http://stackoverflow.com/q/48476348
has body: Is there a way to print letter by letter (redraw between frame update) in Python 3.4.1 using Tkinter? This is doable in the normal IDLE window using this piece of code: import time string = "hello world" for char in string: print(char, end='') time.sleep(.25) But I can't do this in GUI Tkinter window. In my opinion, I could display a label on to the tkinter window, add a letter from a string into it, and wait for a period of time before adding another letter (about 0.25 secs), with the same idea as the code above. Any solutions? For example: String To Display = 'abc' First frame : 'a' Second frame : 'ab' Third Frame : 'abc' Thanks in advance!
has answer: http://stackoverflow.com/a/48478389
possible better answer: http://stackoverflow.com/a/48478389
has comment: http://stackoverflow.com/comment/83946054
has title: Print letter by letter using Tkinter
has comment: http://stackoverflow.com/comment/83947769
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83945848
upvote count: 0
tagged with: tkinter
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/83946138
score: -4
has answer: http://stackoverflow.com/a/48476943
accepted answer: http://stackoverflow.com/a/48476943
tagged with: python
has comment: http://stackoverflow.com/comment/83949283
has comment: http://stackoverflow.com/comment/83946028
has comment: http://stackoverflow.com/comment/83946595
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83947726

http://stackoverflow.com/q/48472028
tagged with: python
has comment: http://stackoverflow.com/comment/83938405
has answer: http://stackoverflow.com/a/48473217
has comment: http://stackoverflow.com/comment/83938392
score: 0
tagged with: sql
answer count: 1
tagged with: mysql
has title: Error when storing values into mySQL table
tagged with: mariadb
type: Question
type: UnansweredQuestion
has body: I am trying to store my data into the database. In my script, this worked for me where I have 6 variables including timestamp: mariadb_connection = mariadb.connect(user='user', password='pw', database='mydb') cursor = mariadb_connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS mytable (ts TIMESTAMP, Day0 decimal (5,2), Day1 decimal (5,2), Day2 decimal (5,2), Day3 decimal (5,2), Day4 decimal (5,2), Day5 decimal (5,2))") sql ="INSERT INTO mytable (ts, Day0, Day1, Day2, Day3, Day4, Day5)" sql += "VALUES (NULL, %s, %s, %s, %s, %s, %s)" cursor.execute(sql,(day0, day1, day2, day3, day4, day5)) print("Storing values into SQL database") mariadb_connection.commit() mariadb_connection.close() However, if I wanted to store a single value (float) (value=7.4995244) along with a timestamp, I get a syntax error. Why is this so? mariadb_connection = mariadb.connect(user='user', password='pw', database='mydb') cursor = mariadb_connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS mytable2 (ts TIMESTAMP, Day0 float(10,8))") sql ="INSERT INTO mytable2 (ts, Day0)" sql += "VALUES (NULL, %s)" cursor.execute(sql,(day0)) #the error happens here print("Storing values into SQL database") mariadb_connection.commit() mariadb_connection.close() The error I get is: mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s)' at line 1
has comment: http://stackoverflow.com/comment/83938510
has comment: http://stackoverflow.com/comment/83942647

http://stackoverflow.com/comment/83704217
score: 0
comment on: http://stackoverflow.com/q/48358442
type: Comment
type: QuestionComment
has text: See especially [this answer](https://stackoverflow.com/a/45925049/4124317) to the duplicate.

http://stackoverflow.com/q/48347290
has comment: http://stackoverflow.com/comment/83680971
tagged with: python
has answer: http://stackoverflow.com/a/48347347
has comment: http://stackoverflow.com/comment/83680521
has comment: http://stackoverflow.com/comment/83680661
has comment: http://stackoverflow.com/comment/83680881
has comment: http://stackoverflow.com/comment/83681525
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83680805
has comment: http://stackoverflow.com/comment/83680537
has comment: http://stackoverflow.com/comment/83680556
answer count: 1
has body: According to the source of the Requests module, the __bool__ function is used solely to check if the status code of a response is between 200 and 400. Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. This use of the __bool__ function made the below code work not as intended: def request_url(url): error_message = None try: r = requests.get(url) except: # Do some other error handling... error_message = "Bad request." r = None return r, error_message r, error_message = request_url(url) if r: # Do some stuff to the response operate_on_response(r) else: # Skip this response object and move to the next. The statement if r: returns False when the status code of the url I request is a 500. Even though the exception is NOT triggered, if r: returns False every time there's a server error. My intention is to test if the response object exists, though. I'm not asking for a workaround: I know I can just check if the error_message is not None. The code above is just an example, not the actual code I'm using. But, to me, it doesn't seem natural or logical to use the __bool__ function to check if a status code is between two values. Like I said, I can find a workaround myself, but I'm mainly asking why? Why use the __bool__ method this way? Is there some logic I'm not seeing?
downvote count: 0
has comment: http://stackoverflow.com/comment/83680825
has comment: http://stackoverflow.com/comment/83681002
has title: Why does requests response object __bool__ check for 200 <= status < 400?
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83681585
has comment: http://stackoverflow.com/comment/83680498
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83680820
score: 5
has comment: http://stackoverflow.com/comment/83680756
upvote count: 5
accepted answer: http://stackoverflow.com/a/48347347
has comment: http://stackoverflow.com/comment/83681478

http://stackoverflow.com/comment/139494385
type: AnswerComment
has text: it is now called as `model = load_model(model_file, custom_objects={ 'custom_weighted_loss': custom_weighted_loss_func })`
comment on: http://stackoverflow.com/a/48373959
type: Comment
score: 0

http://stackoverflow.com/comment/83668816
type: Comment
type: QuestionComment
score: 0
has text: (remember that Python is case-sensitive)
comment on: http://stackoverflow.com/q/48340560

http://stackoverflow.com/q/48395434
has comment: http://stackoverflow.com/comment/83779106
has comment: http://stackoverflow.com/comment/83779853
has comment: http://stackoverflow.com/comment/83779084
has comment: http://stackoverflow.com/comment/83779922
downvote count: 0
has body: I am trying to compare images using OpenCV and Python. Consider these images: Both feature an identical pair of shoes, set to a white background. The only difference being that the first has a taller background than the second. I want to know how to programmatically crop the white backgrounds of both so that I'm left with only the pair of shoes. I must add that it won't be possible for me to manually crop the backgrounds.
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/83783928
has comment: http://stackoverflow.com/comment/83778516
has answer: http://stackoverflow.com/a/48396815
possible better answer: http://stackoverflow.com/a/70843981
has comment: http://stackoverflow.com/comment/83779170
has comment: http://stackoverflow.com/comment/83778667
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83784859
has answer: http://stackoverflow.com/a/61592780
has comment: http://stackoverflow.com/comment/83784467
has answer: http://stackoverflow.com/a/70843981
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/83780063
has comment: http://stackoverflow.com/comment/83788927
accepted answer: http://stackoverflow.com/a/48399309
has title: How to crop or remove white background from an image
has comment: http://stackoverflow.com/comment/83780312
linked to: http://stackoverflow.com/q/14134892
has answer: http://stackoverflow.com/a/69772465
tagged with: scikit-image
has answer: http://stackoverflow.com/a/48399309
has comment: http://stackoverflow.com/comment/83778646
has comment: http://stackoverflow.com/comment/83778911
upvote count: 24
favorite count: 0
score: 24
type: Question
has comment: http://stackoverflow.com/comment/83778446
has answer: http://stackoverflow.com/a/55730231
has comment: http://stackoverflow.com/comment/83784885
has comment: http://stackoverflow.com/comment/83778832

http://stackoverflow.com/comment/83741937
type: Comment
type: QuestionComment
has text: Can you indent your code properly?
score: 0
comment on: http://stackoverflow.com/q/48377577

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/48450396
type: Tag
tags question: http://stackoverflow.com/q/48431070

http://stackoverflow.com/comment/83717748
score: 2
comment on: http://stackoverflow.com/q/48363425
type: Comment
type: QuestionComment
has text: Why do you need this? You only really need to release the GIL to do multithreading. Using `print` from multiple threads can end easily just end up giving jumbled output.

http://stackoverflow.com/comment/83763466
comment on: http://stackoverflow.com/a/48387472
score: 0
type: Comment
type: AnswerComment
has text: Also thanks for the help, your code looks more efficient, I have used multiple lines because that’s how I learnt it, going forward I will go with your version

http://stackoverflow.com/q/48452021
tagged with: pandas
has title: change bar chart to match specific colors I set in color variable
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/83898562
score: 0
tagged with: seaborn
has comment: http://stackoverflow.com/comment/83901074
tagged with: bar-chart
answer count: 0
has comment: http://stackoverflow.com/comment/83898475
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83901239
has comment: http://stackoverflow.com/comment/83897176
has body: I want to plot in a chart and pie chart the number of male and female users. I want the colors to match. You'll notice female in the pie chart is coral and male is light blue. It does not show up this way in the bar chart. Here is the code: colors = ["lightskyblue", "lightcoral"] f,ax=plt.subplots(1,2,figsize=(18,8)) df1['sex'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],colors=colors,shadow=True) df1['sex'].value_counts().plot(kind='bar', ax=ax[1],color=colors)
type: Question

numpy-ndarray
tag name: numpy-ndarray
type: Tag
tags question: http://stackoverflow.com/q/48406763
tags question: http://stackoverflow.com/q/48474274
tags question: http://stackoverflow.com/q/48471852

http://stackoverflow.com/q/48345715
has comment: http://stackoverflow.com/comment/83678043
has answer: http://stackoverflow.com/a/48346288
has comment: http://stackoverflow.com/comment/83678437
has comment: http://stackoverflow.com/comment/83678189
tagged with: python
tagged with: diacritics
has comment: http://stackoverflow.com/comment/83677377
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48346288
has body: I am trying to render some basic umlauts with jinja2. test.html Umlauts: ä ü ö Result.html Umlauts: Ã¤ Ã¼ Ã¶ My code from jinja2 import Template file = open("test.html") data = file.read() Template(data).stream().dump("index.html") Now I don't understand how to get jinja to process the umlauts correctly. How can I do this? I am using stream, because in my actual usecase I am providing some data to fill in, then dumping it to an html to be displayed. EDIT: Is what I want even possible? As I understand this from here it is not? It is not possible to use Jinja2 to process non-Unicode data. The reason for this is that Jinja2 uses Unicode already on the language level. For example Jinja2 treats the non-breaking space as valid whitespace inside expressions which requires knowledge of the encoding or operating on an Unicode string.
upvote count: 3
has comment: http://stackoverflow.com/comment/83677885
has title: How to render umlauts with jinja2?
answer count: 1
tagged with: jinja2
downvote count: 1
favorite count: 0
type: Question

scrapy
tags question: http://stackoverflow.com/q/48435966
tags question: http://stackoverflow.com/q/48421714
tags question: http://stackoverflow.com/q/48469817
tags question: http://stackoverflow.com/q/48342727
tags question: http://stackoverflow.com/q/48358516
tags question: http://stackoverflow.com/q/48436679
tags question: http://stackoverflow.com/q/48462644
tags question: http://stackoverflow.com/q/48433812
tags question: http://stackoverflow.com/q/48378106
tags question: http://stackoverflow.com/q/48393809
tags question: http://stackoverflow.com/q/48428095
tags question: http://stackoverflow.com/q/48357610
tag name: scrapy
tags question: http://stackoverflow.com/q/48400391
tags question: http://stackoverflow.com/q/48473691
tags question: http://stackoverflow.com/q/48350712
tags question: http://stackoverflow.com/q/48375056
tags question: http://stackoverflow.com/q/48425792
tags question: http://stackoverflow.com/q/48348598
tags question: http://stackoverflow.com/q/48390005
tags question: http://stackoverflow.com/q/48367292
tags question: http://stackoverflow.com/q/48333148
tags question: http://stackoverflow.com/q/48343098
tags question: http://stackoverflow.com/q/48448900
tags question: http://stackoverflow.com/q/48441336
tags question: http://stackoverflow.com/q/48391494
tags question: http://stackoverflow.com/q/48340114
tags question: http://stackoverflow.com/q/48428689
tags question: http://stackoverflow.com/q/48454632
tags question: http://stackoverflow.com/q/48484962
tags question: http://stackoverflow.com/q/48361145
tags question: http://stackoverflow.com/q/48480345
tags question: http://stackoverflow.com/q/48443236
type: Tag
tags question: http://stackoverflow.com/q/48371683
tags question: http://stackoverflow.com/q/48363419
tags question: http://stackoverflow.com/q/48406852
tags question: http://stackoverflow.com/q/48374455
tags question: http://stackoverflow.com/q/48480009
tags question: http://stackoverflow.com/q/48473110
tags question: http://stackoverflow.com/q/48425276
tags question: http://stackoverflow.com/q/48478337
tags question: http://stackoverflow.com/q/48482933

http://stackoverflow.com/comment/83827543
type: Comment
comment on: http://stackoverflow.com/a/48408399
type: AnswerComment
score: 0
has text: Thanks, that's a nice way of grouping by a condition

http://stackoverflow.com/comment/83972295
score: 0
comment on: http://stackoverflow.com/q/48483560
type: Comment
type: QuestionComment
has text: OK, so check edited answer bellow - I add 3 possible solutions.

http://stackoverflow.com/q/48458706
possible better answer: http://stackoverflow.com/a/48459055
has answer: http://stackoverflow.com/a/48459210
has answer: http://stackoverflow.com/a/48459055
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48470096
type: AnsweredQuestion
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has body: I have a DataFrame such as this: df = pd.DataFrame([['Col1Val', 'Col2Val', '[3, 31.1, -341.4, 54.13]']], columns=['col1', 'col2','values']) The only differences are I have a few million rows and column values is a string of exactly 200 floats in each row, instead of 4 in my example. The csv file containing this data is ~5 GB. However, this reduces when I load into pandas after converting the first 2 string columns into categories. Hence I am able to perform most manipulations (filtering, slicing, indexing) with no performance issues. I need to expand the values column of strings into separate columns of floats. So there will be 200 columns each containing a float. I made an attempt at performing this, but I consistently run out of memory. Theoretically, I think this should be possible line by line in a memory efficient way, since columns of floats should take less memory than many numbers in a string. What's a good algorithm for this? My existing code is below for splitting values column. df['values'] = df['values'].str.replace('[','').str.replace(']','') # code runs out of memory in next line! df_values = pd.DataFrame([x.split(',') for x in df['values'].values.tolist()]) df_values[df_values.columns] = df_values[df_values.columns].apply(pd.to_numeric, errors='coerce') df_values[df_values.columns] = df_values[df_values.columns].fillna(0.0) df= df.drop('values', 1).join(df_values) Expected result for my sample, which above code generates correctly for small number of rows: df = pd.DataFrame('Col1Val', 'Col2Val', 3.0, 31.1, -341.4, 54.13, columns=['col1', 'col2', 0, 1, 2, 3]) To labour my reasoning for why I'm hoping (wishing!) for a "memory decreasing" solution, floats should normally take less space than string: from sys import getsizeof getsizeof('334.34') #55 getsizeof(334.34) #24 getsizeof('-452.35614') #59 getsizeof(-452.35614) #24
has title: Expanding pandas string column of floats memory-efficiently
favorite count: 0
tagged with: performance
type: Question
has answer: http://stackoverflow.com/a/48470096
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48437722
has comment: http://stackoverflow.com/comment/83939183
has title: Shape [-1, 1] has negative dimensions
has comment: http://stackoverflow.com/comment/83938690
type: Question
has comment: http://stackoverflow.com/comment/83921341
answer count: 0
tagged with: tensorflow-serving
has comment: http://stackoverflow.com/comment/83903133
tagged with: python
type: UnansweredQuestion
has body: I'm working on a single class classification problem on tensorflow. The training has finished and I saved my model. When I try to call for prediction using google cloud, I get this error: { "error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"Shape [-1,1] has negative dimensions\n\t [[ Node: outputs = Placeholder[_output_shapes=[[-1,1]], dtype=DT_FLOAT, shape=[?,1], _device=\"/job:localhost/replica:0/task:0/cpu:0\"]()]]\")" } I defined my prediction signature for outputs as the build_tensor_info of the output variable I defined as following: Y = tf.placeholder("float", [None, n_classes], name = 'outputs') Training and testing work fine on my laptop and on google cloud. It's only when I call for predictions that I get this error. I use this code to call for predictions: gcloud ml-engine predict --model ${MODEL_NAME} --json-instances request.json I believe this is a simple issue that I'm missing about how shape works in python/tensorflow. Has anyone else had this issue before?
tagged with: google-cloud-platform
score: 0

http://stackoverflow.com/comment/83917683
type: Comment
comment on: http://stackoverflow.com/q/48462171
score: 1
type: QuestionComment
has text: @Rawing, eh? The current working directory is *not* in the default library search path. The OP named that directory for the library they're ultimately trying to load, but it's not the library they're trying to load that wasn't found, but rather one of its dependencies. (If `.` *were* part of the default library path, you'd have much the same security bugs you have when it's in the `PATH` for executables).

http://stackoverflow.com/a/48427803
answers question: http://stackoverflow.com/q/48426696
accepted answer of: http://stackoverflow.com/q/48426696
upvote count: 3
has comment: http://stackoverflow.com/comment/83848421
type: AcceptedAnswer
downvote count: 0
score: 3
has body: You can use ast.parse to create a syntax tree of your string. Then you can iterate over the tree and validate whatever parse-time qualities you like. As internet_user says, this will not tell you about the run-time qualities of your code; if modules are imported through a mechanism other than the usual import statement, those won't be validated. If your classes are dynamically changed to add or remove methods, you won't know that just from looking at the defs in their class definition. Provided that you're not worried about any of that, here's a sample implementation: import ast import sys import os import imp s = """ import math, gzip from os import system import numpy import obviouslyFakeModuleName class A(int): def troz(self): return 23 class B(str): def zort(self): return 42 """ def can_be_imported(name): try: imp.find_module(name) return True except ImportError: return False def iter_nodes_by_type(code, type_or_types): for node in ast.walk(code): if isinstance(node, type_or_types): yield node def iter_imported_module_names(code): for node in iter_nodes_by_type(code, ast.Import): for alias in node.names: yield alias.name for node in iter_nodes_by_type(code, ast.ImportFrom): yield node.module def iter_globally_defined_classes(code): for child in ast.iter_child_nodes(code): if isinstance(child, ast.ClassDef): yield child def iter_methods(class_): for node in ast.iter_child_nodes(class_): if isinstance(node, ast.FunctionDef): yield node try: code = ast.parse(s) except SyntaxError: print("That string is not valid Python.") sys.exit(0) #inspection of imports for name in iter_imported_module_names(code): if can_be_imported(name): print("module {} is available for import.".format(name)) else: print("module {} is not available for import.".format(name)) #inspection of classes for class_ in iter_globally_defined_classes(code): class_name = class_.name base_class_names = [name.id for name in class_.bases] function_names = [func.name for func in iter_methods(class_)] print…
type: Answer

http://stackoverflow.com/comment/83756610
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48384422
score: 0
has text: This is a question for reshape https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe/47152692#47152692

http://stackoverflow.com/q/48410876
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83812072
tagged with: python-2.7
has title: Extract content from folder inside of zip archive
score: 0
has comment: http://stackoverflow.com/comment/83812395
tagged with: gitlab
answer count: 1
has answer: http://stackoverflow.com/a/48411187
has body: I'm trying to get a zip file from a GitLab repo, access the only folder that is inside of it (folder name always starts with the same string), and copy the contents of the folder in another zip file. Example gitlab_repo.zip: gitlab_repo.zip --------------------- gitlab_repo_folder ├── subfolder | ├── subfolder_file_1 | └── subfolder_file_2 ├── file_1 └── file_2 Example final.zip: (expected output) final.zip --------------------- ┌── subfolder | ├── subfolder_file_1 | └── subfolder_file_2 ├── file_1 └── file_2 The code snippet I have currently, which writes everything(including the folder) to a new archive: final = '/tmp/final.zip' gitlab_repo='https://gitlab.com/...' r = requests.get(gitlab_repo, auth=('user', 'pass')) open(final, 'wb').write(r.content) Aditional Info: This code will be triggered every time there is a push to the repository, so i need to automate the process My Python skill level: I watched some youtube videos and I'm following a Python class on Udemy Any help or hints for what library should I use to achieve this as efficiently as possible is much appriciated!

http://stackoverflow.com/q/48359255
has comment: http://stackoverflow.com/comment/83705852
has comment: http://stackoverflow.com/comment/83705364
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48359689
tagged with: currency
has answer: http://stackoverflow.com/a/48361130
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83706792
has body: Say I have the following strings (inputs) in python: 1) "$ 1,350,000" 2) "1.35 MM $" 3) "$ 1.35 M" 4) 1350000 (now it is a numeric value) Obviously the number is the same although the string representation is different. How can I achieve a string matching or in other words classify them as equal strings? One way would be to model -using regular expressions- the possible patterns. However there might be a case that I haven't thought of. Does someone see a NLP solution to this problem? Thanks
has title: Python - match and parse strings containing numeric/currency amounts
has comment: http://stackoverflow.com/comment/83705719
downvote count: 3
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83705910
tagged with: parsing
has comment: http://stackoverflow.com/comment/83705445
answer count: 3
accepted answer: http://stackoverflow.com/a/48359614
has answer: http://stackoverflow.com/a/48359614
upvote count: 7
tagged with: text-mining
score: 4
possible better answer: http://stackoverflow.com/a/48361130

http://stackoverflow.com/comment/83745133
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48379224
score: 0
has text: Do you mean you want to compute the mean for ask1 and the sum for tradeVolume per group, where each group contain all trades within one second?

http://stackoverflow.com/q/48331358
type: Question
tagged with: oop
has body: I have an error that I can not get my head around. The code is as follows: def saveData(): filename = input("Filename to save: ") print("Saving Data...") outFile = open(filename, "wt") for x in team.keys(): name = team[x].getname() phone = team[x].getphone() jersey = team[x].getjersey() outFile.write (name+", "+phone+", "+jersey+"\n") print("Data saved.") outFile.close() def loadData(): self = {} filename = input("Filename to load: ") inFile = open(filename, "rt") print("Loading data...") while True: inLine = inFile.readline() if not inLine: break inLine = inLine[:-1] name, phone, jersey = inLine.split(", ") team[name] = self(name, phone, jersey) print("Data Loaded Successfully.") inFile.close() return self class teamClass: name = "" phone = 0 jersey = 0 def __init__(self, name, phone, jersey): self.name = name self.phone = phone self.jersey = jersey def setName(self, name): self.name = name def setPhone(self, phone): self.phone = phone def setJersey(self, jersey): self.jersey = jersey def getName(self, name): return name def getPhone(self, phone): return phone def getJersey(self, jersey): return jersey def displayData(team): print("\n") print("Welcome to the Team Manager") print("---------------------------") print("Name: ", team.name) print("Phone #: ", team.phone) print("Jersey #: ", team.jersey) print("\n") def displayMenu(): print("--------Main Menu--------") print("\n1. Display Team") print("2. Add Member") print("3. Remove Member") print("4. Edit Member") print("9. Exit Program") print("\n") return int(input("Selection: ")) def printTeam(team): if len(team) == 0: print("No team members in memory.") else: for x in team.keys(): team.displayData() def addTeam(team): newName = input("Enter the new player name: ") newPhone = input("Enter the phone #: ") newJersey = input("Enter the jersey #: ") team[newName] = teamClass(newName, newPhone, newJersey) return team def removeTeam(team): removeName = input("Enter the member to be removed: ") if removeName in team: del …
tagged with: python
has comment: http://stackoverflow.com/comment/83648598
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83648605
type: AnsweredQuestion
has title: Python Dictionary As Object Error
accepted answer: http://stackoverflow.com/a/48331395
has comment: http://stackoverflow.com/comment/83648645
score: 0
has comment: http://stackoverflow.com/comment/83652898
has answer: http://stackoverflow.com/a/48331395
has comment: http://stackoverflow.com/comment/83652527
answer count: 1
has comment: http://stackoverflow.com/comment/83652782

http://stackoverflow.com/comment/83858683
comment on: http://stackoverflow.com/a/48433480
type: AnswerComment
score: 0
has text: @delrocco No, in my initial solution the memory was not duplicated since it replaced the previous memory space. On the other hand I understood you with your initial comment that you did not want to lose the initial image.
type: Comment

http://stackoverflow.com/a/48374342
downvote count: 0
answers question: http://stackoverflow.com/q/48374124
type: Answer
score: 4
upvote count: 4
has body: TensorFlow 1.0.0 for Windows is only compiled for Python 3.5. If you have a recent install of Anaconda (4.3.0 or higher), you are likely on Python 3.6. To get specifically 1.0.0 you need to the following Conda commands to create a Python 3.5 environment named "tensorflow" with Jupyter Notebooks, and then install TensorFlow 1.0.0 conda create --name tensorflow python=3.5 jupyter -y conda install --name tensorflow tensorflow=1.0.0 --channel conda-forge -y This is going to take a good amount of time to install. After it finishes, you can swap to the environment and fire up a Jupyter Notebook using: activate tensorflow jupyter notebook

http://stackoverflow.com/q/48482317
answer count: 1
has answer: http://stackoverflow.com/a/48483743
tagged with: image
favorite count: 0
has comment: http://stackoverflow.com/comment/83957764
has comment: http://stackoverflow.com/comment/83957679
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83957704
downvote count: 1
has title: Slice an Image into "Tiles" Using Numpy
score: 2
has body: I have an image that I want to tile into smaller chunks for some deep learning purposes. I want to use numpy arrays to better understand using np. Currently my image is loaded into a numpy array and its shape is: (448, 528, 3) I want to have a list of smaller, 8x8 chunks, I believe the representation would be (n, 8, 8, 3). Currently when I take the following action: smaller_image.reshape(3696, 8, 8, 3) the image gets distorted. Thank you for your time.
has comment: http://stackoverflow.com/comment/83957786
upvote count: 3

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/48482641
tags question: http://stackoverflow.com/q/48340747
type: Tag

http://stackoverflow.com/comment/83769541
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48389178
has text: On my PC it's about 3MB (the Python executable is actually only about 10kb - almost all the detail is actually in `libpython`). You also need some (but probably not all) of the Python standard library. That's around 30MB in total (but you might be able to select the parts you need).

http://stackoverflow.com/a/48420423
answers question: http://stackoverflow.com/q/48420022
has comment: http://stackoverflow.com/comment/91432406
has comment: http://stackoverflow.com/comment/83832840
downvote count: 0
upvote count: 1
has body: The nearest thing to an id for a file (some unique number identifying the file in the filesystem) is called an inode, that's indeed the number returned by stat in the field st_ino. This number may change in some circumstances even if the name of the file does not, for instance when the file is replaced by another one (copy), or deleted and recreated. This number won't change if you merely open the file and perform reads and writes over it. CHeck here for more detailed explanation about inodes https://github.com/angrave/SystemProgramming/wiki/File-System,-Part-2:-Files-are-inodes-(everything-else-is-just-data...) Also notice that not all filesystems have inodes, this is a concept that originated on Unix. There is no such thing with vfat. If you are only interested about the filename, another way to get a unique number is expanding the filename to it's full path up to the filesystem root (or drive on windows), then calling hash() on the string. What you are losing doing that is that on some filesystems a given file on disk may be reached using several names (hardlinks or softlinks, I won't expand here on the differences). Depending on you use case it may or may not be a problem. If you are looking for files with the same content, that's yet another story. Filesystems don't care for the content of the file. To know if two files are identical you'll have to open them and compare them. Using python you should have a look at filecmp module. A common way to compare many files is relying on a hash signature of the file content. For instance have a look at that answer to see how to do that for MD5 (a bit outdated, but easily adapted to more modern signatures) Generating a MD5 signature of a file
has comment: http://stackoverflow.com/comment/91455818
score: 1
has comment: http://stackoverflow.com/comment/83870677
type: Answer
has comment: http://stackoverflow.com/comment/91455907

http://stackoverflow.com/comment/83864181
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48436380
has text: Are you sure that `a*b` in the Python code actually computes it instead of being lazy? (lazy as in Python3 `range`) / There is a missing `}` at the end of the C++ code. / Your `fill` command in C++ is filling each row with one value, which is different from the Python behavior. Should not be a problem however.
score: 1

http://stackoverflow.com/comment/83893374
comment on: http://stackoverflow.com/q/48434919
type: QuestionComment
has text: The other question answers the same thing, but it didn't turn up in my extensive search for an anwer. I believe the way this question is framed provides few value additions - 1 very simple/basic example , (2) calling out -ve values which really confused , which might help others to find out the answer. Would providing a link to the other question address your concern
type: Comment
score: 0

sockets
tags question: http://stackoverflow.com/q/48392891
tags question: http://stackoverflow.com/q/48373670
tags question: http://stackoverflow.com/q/48370411
tags question: http://stackoverflow.com/q/48359761
tags question: http://stackoverflow.com/q/48369356
tags question: http://stackoverflow.com/q/48427484
tags question: http://stackoverflow.com/q/48435567
tags question: http://stackoverflow.com/q/48357989
tags question: http://stackoverflow.com/q/48481668
tags question: http://stackoverflow.com/q/48370348
tags question: http://stackoverflow.com/q/48406991
tags question: http://stackoverflow.com/q/48438463
tags question: http://stackoverflow.com/q/48414559
tags question: http://stackoverflow.com/q/48338714
tags question: http://stackoverflow.com/q/48433543
tags question: http://stackoverflow.com/q/48344907
tags question: http://stackoverflow.com/q/48401056
tag name: sockets
tags question: http://stackoverflow.com/q/48397845
tags question: http://stackoverflow.com/q/48424465
tags question: http://stackoverflow.com/q/48367819
tags question: http://stackoverflow.com/q/48394741
tags question: http://stackoverflow.com/q/48468365
tags question: http://stackoverflow.com/q/48450053
tags question: http://stackoverflow.com/q/48479182
tags question: http://stackoverflow.com/q/48433985
tags question: http://stackoverflow.com/q/48485672
tags question: http://stackoverflow.com/q/48370988
tags question: http://stackoverflow.com/q/48390709
type: Tag
tags question: http://stackoverflow.com/q/48368625

http://stackoverflow.com/a/48465562
accepted answer of: http://stackoverflow.com/q/48465536
type: Answer
answers question: http://stackoverflow.com/q/48465536
upvote count: 31
type: AcceptedAnswer
downvote count: 0
score: 31
has body: You can't use it like that. Because of operator precedence, what you have written is parsed as (weather == "Good") or ("Great") The left part may be false, but right part is true (python has "truth-y" and "fals-y" values), so the check always succeeds. The way to write what you meant to would be if weather == "Good!" or weather == "Great!": or (in more common python style) if weather in ("Good!", "Great!"):

http://stackoverflow.com/comment/83797027
has text: Thank you for this, changing X_train to a pandas dataframe then gives me a new error at the final Logistic_regression line: TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe' However, I will search is see what I can do to fix this, thank for your help!
score: 0
comment on: http://stackoverflow.com/a/48404158
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48408878
answers question: http://stackoverflow.com/q/48408751
type: Answer
has body: def fun(item): return [item[item1]+' '+k for k in item[item2]] res = [] [res.append(fun(i)) for i in some_list if(fun(i)) not in res] print res this should work
has comment: http://stackoverflow.com/comment/83807050
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83807368

http://stackoverflow.com/q/48430392
score: 0
accepted answer: http://stackoverflow.com/a/48431776
has body: When I upload and try to open the file using the below code, I am getting this error: IOError: [Errno 2] No such file or directory My code is as follows: from google.colab import files #upload file uploaded = files.upload() # Open file f = open(uploaded['small.txt'], 'r') # Feed the file text into findall(); it returns a list of all the found strings strings = re.findall(r'ne\w', f.read())
answer count: 1
has answer: http://stackoverflow.com/a/48431776
upvote count: 1
has comment: http://stackoverflow.com/comment/83851703
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83851481
tagged with: python
tagged with: google-colaboratory
has title: Opening uploaded file in google colaboratory
type: AnsweredQuestion

http://stackoverflow.com/q/48459455
has comment: http://stackoverflow.com/comment/83911749
accepted answer: http://stackoverflow.com/a/48459673
linked to: http://stackoverflow.com/q/3207219
has comment: http://stackoverflow.com/comment/83911722
tagged with: function
has comment: http://stackoverflow.com/comment/83913153
has answer: http://stackoverflow.com/a/48459673
answer count: 1
has title: Import and call identical function from all modules in the same directory
downvote count: 0
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83912824
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83912060
has comment: http://stackoverflow.com/comment/83913120
tagged with: import
favorite count: 0
type: Question
has body: I have def myfunc() in script2.py, script3.py, script4.py. In script1.py, I want to call myfunc from script2, script3 and script 4. In script1.py, rather than tediously listing out: from script2.py import myfunc myfunc() from script3.py import myfunc myfunc() from script4.py import myfunc myfunc() Is there a way that I can import myfunc from all scripts present in that same directory?
tagged with: python-import

http://stackoverflow.com/a/48351156
answers question: http://stackoverflow.com/q/48349998
accepted answer of: http://stackoverflow.com/q/48349998
type: Answer
has comment: http://stackoverflow.com/comment/83753908
score: 0
type: AcceptedAnswer
has body: The line conn = pyodbc.connect(r'DSN=my_dsn;UID=User;PWD=Password') seems to be using the literal string values of my_dsn, User and Password. You can try using keywords like the documentation here, or do a similar string formatting as you did for your hard coded solution but replace it with the loaded config data. From the documentation it seems you should be able to load the DSN info directly from the ini, but I haven't had much success on my own either. The caveat is the document only said you can possibly use the login credential, so maybe it depends on the driver? Either way, below is a version using configparser that should work. It might be considered a hack for some. import pyodbc from configparser import ConfigParser config = ConfigParser() config.read(configfile) # your odbc.ini file path and name dsn = config['my_dsn'] #If you want to use Keywords: conn = connect(driver=dsn['driver'], server=dsn['server'], database=dsn['database'], uid=dsn['user'], pwd=dsn['password']) #If you want to use string formatting with list comprehension instead: conn = pyodbc.connect(''.join(['{0}={1}; '.format(k, l) for k, l in d.items()])

http://stackoverflow.com/comment/83903725
type: AnswerComment
has text: could you give us the error from that error callback?
comment on: http://stackoverflow.com/a/48454574
type: Comment
score: 0

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/48397280

http://stackoverflow.com/comment/83830164
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48418140
has text: Why using RTS pin (Using RTS pins causes low performance)? another question `why don't use Device addressing?` If you need an additional pine, the IC 74hc14 and a 100nf capacitor provide you with automatic direction determination(max 115.2kbps).

http://stackoverflow.com/a/48361806
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48361738
has body: Just use a try/except based on the exception that you know should be raised for the particular action you are performing. I'm pretty sure the exception you are most likely getting is UnicodeDecodeError. Alternatively, you could also open the file using "read-bytes" -> rb: f = open('filename', 'rb') More directly in your problem for using the try/except: for item in direct: print("Checking " + item) try: if 'userType' in open(os.path.join(path ,item)).read(): print("FOUND USERTYPE IN " + item) except WhateverTheExceptionIsYouWantToCatch: pass Doing the above will raise when something unexpected happens so you can then determine how you want to proceed, otherwise, continue. I would also suggest as an added bonus, to either explicitly call .close on your open, or even better and strongly recommended, use a context to handle the opening/closing for you, so you don't end up with a bunch of open files. for item in direct: print("Checking " + item) try: with open(os.path.join(path, item)) as f: if 'userType' in f.read(): print("FOUND USERTYPE IN " + item) except WhateverTheExceptionIsYouWantToCatch: pass Finally, to the point of this comment, you should probably ensure you even want to open certain files that you might not care about. Using the glob as suggested in that respective answer, you will probably filter down to files you actually care about. Use pathlib It would be a good opportunity to also start making use of pathlib, as it provides great tools.
type: Answer
has comment: http://stackoverflow.com/comment/83710558
has comment: http://stackoverflow.com/comment/83710690
accepted answer of: http://stackoverflow.com/q/48361738
has comment: http://stackoverflow.com/comment/83710609

neural-network
tags question: http://stackoverflow.com/q/48458509
tags question: http://stackoverflow.com/q/48400655
tags question: http://stackoverflow.com/q/48388641
tags question: http://stackoverflow.com/q/48345006
type: Tag
tags question: http://stackoverflow.com/q/48342068
tags question: http://stackoverflow.com/q/48423769
tags question: http://stackoverflow.com/q/48445942
tags question: http://stackoverflow.com/q/48453143
tags question: http://stackoverflow.com/q/48382597
tags question: http://stackoverflow.com/q/48355700
tags question: http://stackoverflow.com/q/48430916
tags question: http://stackoverflow.com/q/48336738
tags question: http://stackoverflow.com/q/48486598
tags question: http://stackoverflow.com/q/48484985
tags question: http://stackoverflow.com/q/48343536
tags question: http://stackoverflow.com/q/48384434
tags question: http://stackoverflow.com/q/48345755
tags question: http://stackoverflow.com/q/48347530
tags question: http://stackoverflow.com/q/48431507
tags question: http://stackoverflow.com/q/48481873
tags question: http://stackoverflow.com/q/48470591
tags question: http://stackoverflow.com/q/48463442
tags question: http://stackoverflow.com/q/48402009
tags question: http://stackoverflow.com/q/48429611
tags question: http://stackoverflow.com/q/48372575
tags question: http://stackoverflow.com/q/48483489
tags question: http://stackoverflow.com/q/48345857
tags question: http://stackoverflow.com/q/48414717
tags question: http://stackoverflow.com/q/48363823
tags question: http://stackoverflow.com/q/48460913
tag name: neural-network
tags question: http://stackoverflow.com/q/48470539
tags question: http://stackoverflow.com/q/48415957
tags question: http://stackoverflow.com/q/48407730
tags question: http://stackoverflow.com/q/48487570
tags question: http://stackoverflow.com/q/48471255
tags question: http://stackoverflow.com/q/48480751
tags question: http://stackoverflow.com/q/48405386
tags question: http://stackoverflow.com/q/48385830
tags question: http://stackoverflow.com/q/48458635

http://stackoverflow.com/q/48342068
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/48342868
answer count: 1
tagged with: neural-network
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48342868
tagged with: keras
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83670973
has comment: http://stackoverflow.com/comment/83671046
has body: for iteration in range(NUM_ITERATIONS): print() print("="*50) print("Iteration:",iteration) model.fit(X,y,batch_size=BATCH_SIZE,epochs=NUM_EPOCH_ITERATION) rand=np.random.randint(len(x_labels)) test="vikas n s " print(test,end="") for i in range(NUM_PREDICTION_PER_EPOCH): Xtest=np.zeros((1,sqlen,nb_chars),dtype=np.bool) for i,ch in enumerate(test): Xtest[0,i,char2index[ch]]=1 pred=model.predict(Xtest) temp=pred pred=pred[0] ypredict=index2char[np.argmax(pred)] print(ypredict,end="") test=test[1:]+ypredict In this code,at every iteration I'm fitting the model. My assumption is that as I'm fitting the model again the loss should be reset to original loss or something close to that.But what I'm finding is that the loss continues. ie: if the initial loss is 4 and after all the epoch in 1st iteration loss drops to 2. Now when i once again fit the model in the next iteration i expect the loss to start from 4.Instead it continues from 2. Why is this happening?
tagged with: python
score: -1
has title: Will the loss decrease if i fit the model once again or will it reset to initial loss?

http://stackoverflow.com/comment/83911659
comment on: http://stackoverflow.com/q/48458787
has text: Note that casting to float happens also in the first case (see the dot after the numbers) because integer data types cannot represent NaN. The "random" numbers are uninitialized memory.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48372808
has comment: http://stackoverflow.com/comment/83732881
linked to: http://stackoverflow.com/q/5036700
has comment: http://stackoverflow.com/comment/83732924
has comment: http://stackoverflow.com/comment/83732993
type: Question
upvote count: 2
tagged with: sympy
has comment: http://stackoverflow.com/comment/83732835
answer count: 1
has answer: http://stackoverflow.com/a/48373109
accepted answer: http://stackoverflow.com/a/48373109
tagged with: variables
has comment: http://stackoverflow.com/comment/83732864
favorite count: 0
tagged with: recursion
has comment: http://stackoverflow.com/comment/83732744
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/522563
has body: I have a recursive function that can produce a difficult-to-know number of expressions, each needing a new variable multiplied to it. These variables will later be removed out by calculations involving integration or residue. How can I develop these unknown number of variables? Maybe indexed? All examples I've seen on the internet are working with an a priori known object of a definite size, e.g. "item" in How can you dynamically create variables via a while loop? or Accessing the index in Python 'for' loops I think I can boil it down to this simple example to use in my real script: import sympy as s p0,p1,p2,p3,p4=s.symbols('p0 p1 p2 p3 p4') l = [p0, p1, p2, p3, p4] def f(n): if n == 0: return l[n] elif n == 1: return l[n] else: return f(n-1)*l[n]+f(n-2) f(3) # works f(6) # doesnt' work - need to define ahead of time the # dummy variables l[6], l[5], .... # even if they are just symbols for (much) later numerical evaluation. I need this above snippet to actually generate the needed unknowns ahead of time. I saw some mentions of pandas, but couldn't find a good example for my need, nor even sure if that was the best route. Also saw things like, "...an unknown number of lines [file]...", or "...unknown number of arguments...", but those are, seemingly, not applicable.
has comment: http://stackoverflow.com/comment/83732969
tagged with: python
has title: Create an unknown number of programmatically defined variables

http://stackoverflow.com/comment/83798156
score: 0
comment on: http://stackoverflow.com/q/48404694
has text: Actually, after reading your question again, it may not, because it does not take those monthly duplicates into account. See my answer for a revised version.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83890971
has text: Possible duplicate of [Hashing (hiding) strings in Python](https://stackoverflow.com/questions/19580412/hashing-hiding-strings-in-python)
type: Comment
comment on: http://stackoverflow.com/q/48448830
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83687088
type: QuestionComment
type: Comment
has text: Can you please provide an example how to use a restored variable from 'pickle' in 'feed_dict' in a restored tensorflow model?
score: 0
comment on: http://stackoverflow.com/q/48346918

http://stackoverflow.com/comment/83727265
comment on: http://stackoverflow.com/a/48370246
has text: Is pip owned by root? You may need to change perms
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83776828
has text: which linux distro are you using? the error is `'lsb_release -a' returned non-zero exit status 3`, you can try this command `lsb_release -a` on you command line and see what happens.
type: Comment
comment on: http://stackoverflow.com/q/48394638
type: QuestionComment
score: 0

module
tags question: http://stackoverflow.com/q/48362486
type: Tag
tags question: http://stackoverflow.com/q/48370990
tags question: http://stackoverflow.com/q/48332507
tags question: http://stackoverflow.com/q/48466943
tags question: http://stackoverflow.com/q/48332649
tags question: http://stackoverflow.com/q/48368388
tag name: module
tags question: http://stackoverflow.com/q/48471252
tags question: http://stackoverflow.com/q/48356809
tags question: http://stackoverflow.com/q/48457887

http://stackoverflow.com/a/48354686
has body: You can set the ticks used for the x axis via ax.set_xticks() and labels via ax.set_xticklabels(). For instance you could just provide that method with a list of dates to use, such as every 20th value of the current pd.DataFrame index (df.index[::20]) and then set the formatting of the date string as below. # Get the current axis ax = plt.gca() # Only label every 20th value ticks_to_use = df.index[::20] # Set format of labels (note year not excluded as requested) labels = [ i.strftime("%-H:%M") for i in ticks_to_use ] # Now set the ticks and labels ax.set_xticks(ticks_to_use) ax.set_xticklabels(labels) Notes If labels still overlap, you could also rotate the them by passing the rotatation argument (e.g. ax.set_xticklabels(labels, rotation=45)). There is a useful reference for time string formats here: http://strftime.org.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48352482
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/48352482
downvote count: 0
type: Answer

http://stackoverflow.com/a/67458185
upvote count: 1
answers question: http://stackoverflow.com/q/48360763
has comment: http://stackoverflow.com/comment/119240068
type: Answer
score: -1
has body: from django.conf.urls.static import static write this line, Instead of from django.conf.urls import static
downvote count: 2

http://stackoverflow.com/q/48366939
score: -1
tagged with: list
tagged with: postgresql-9.5
upvote count: 0
answer count: 1
has title: AttributeError: 'list' object has no attribute 'rowcount'
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48368255
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48368255
tagged with: attributeerror
has body: class code: def rowcount(self): return self._psql_cur.rowcount And the code in the main program: def sql_query(self, sql, *data, **kwdata): """ NOTE: This function returns a generator. So if you use it to do any kind of update to the dbms that doesn't return anything, it won't be executed! """ self.last_select_id += 1 n_retrials = kwdata.get("___n_retrials", 0) if n_retrials &gt; 10: raise OperationalError assert not (len(data) &gt; 0 and len(set(kwdata) - {"___n_retrials"}) &gt; 0), \ "Pass either keyword-based data or comma-separated data." time_start = time.time() n_records_retrieved = 0 status = None toclose = False print "*********************inside db.py******************" if self.logfile is not None: self.logfile.write("&gt;&gt;&gt; {} {} {} START SELECT\n{}\ndata={}\nkwdata={}\n\n".format( self.cursor_id, self.last_select_id, time_start, sql, data, kwdata)) print "\n************* QUERY:\n", sql print "\n***************************" try: if len(data) &gt; 0: print "\n**************printing data***********",data print "\n******************printing sql**************************",sql print "\n*******************************************************" # self._psql_cur.execute(sql, data) cur, toclose = self._execute_query(sql, data) elif len(kwdata) &gt; 0: # self._psql_cur.execute(sql, kwdata) cur, toclose = self._execute_query(sql, kwdata) else: cur, toclose = self._execute_query(sql, None) print "################check###################" n_records_reported = cur.rowcount print "\n*************printing rowcount**********",n_records_reported # Yield records for record in cur: n_records_retrieved += 1 if n_records_retrieved == n_records_reported: status = "Finished" yield record following code conatains _execute_query: def _execute_query(self, sql, args): # sql = sql.lower().strip() # print sql sql_strip = sql.lower().strip() print "-------4",args # print self.dbname, sql_strip if sql_strip.startswith("select ") or \ (sql_strip.startswith("with ") # and "update " no…
has comment: http://stackoverflow.com/comment/83722919
tagged with: python
has comment: http://stackoverflow.com/comment/83720513

http://stackoverflow.com/a/48455043
has comment: http://stackoverflow.com/comment/83903199
score: 0
has comment: http://stackoverflow.com/comment/83903128
has comment: http://stackoverflow.com/comment/83903209
has comment: http://stackoverflow.com/comment/83903248
has comment: http://stackoverflow.com/comment/83903118
has body: I wound up setting the blob as public and doing the following since it is text. Not super ideal but it gets the job done. import urllib.request for line in urllib.request.urlopen(blob_url): &lt;do something with line&gt; EDIT One problem I had to contend with was socket loss because I was working against a live blob. I had to take a snapshot and use a session or I was gettign disconnects after about 5 seconds of processing. snapshotBlob = append_blob_service.snapshot_blob(container, blobName) _params = { 'snapshot': snapshotBlob.snapshot, 'timeout': 20000, } s = requests.Session() r = s.get(target_url, params=_params, stream=True, timeout=20000) for line in in r.iter_lines(): &lt;do something with line&gt;
answers question: http://stackoverflow.com/q/48454906
type: Answer

http://stackoverflow.com/comment/83702004
score: 5
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48357666
has text: this question is a dupe. Either use `df['col'].str.replace("\t"," ")` or `df['col'].replace("\t"," ", regex=True)`

http://stackoverflow.com/a/48430586
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48425626
answers question: http://stackoverflow.com/q/48425626
has body: I found this to work properly thanks to some of the comments. a = int(input()) b = int(input()) if a == 0: if b == 0: print('many solutions') else: print('no solution') elif b % a == 0: print(b // a) else: print('no solution')

http://stackoverflow.com/comment/83962189
score: 0
comment on: http://stackoverflow.com/q/48475138
has text: Don't use celery as a init process, container are not made for it. Instead, try running celery command(`celery -A ProjectA worker --autoscale=6,6 --concurrency=100`) as a foreground process for container using `CMD` or `ENTRYPOINT`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48409575
has body: I'm trying to make a login form. If i add a button to my form, when where appears a big space. I tried grid_columnfigure with weight=1 but it sets the x coordinate only a little bit lower (like self.NewProfilePasswordEntry) My Code: from tkinter import * from tkinter import ttk class App: def CreateProfileDataInput(self): Root = Tk() Root.resizable(width=FALSE, height=FALSE) Root.geometry("450x500") NewProfilePasswordRepeatLabel = Label(Root, text="Passwort wiederholen", font="Tahoma 13").grid(row=3, column=0, padx=(10, 20), pady=(20, 0), sticky=W) self.NewProfilePasswordRepeatEntry = ttk.Entry(Root, width=35, show="*").grid(row=3, column=1, pady=(20, 0)) self.CreateProfileButton = Button(Root, text="Profil erstellen", width=55, height=2, relief="flat", borderwidth=1, bg="#30b1e8", command=lambda:self.CreateProfile()).grid(row=4, column=0, pady=(25, 0)) Root.mainloop() App().CreateProfileDataInput() I want this But it gives me that (beacuse the button)
has comment: http://stackoverflow.com/comment/83810992
has comment: http://stackoverflow.com/comment/83809072
tagged with: grid
type: Question
has comment: http://stackoverflow.com/comment/83809949
accepted answer: http://stackoverflow.com/a/48412719
has title: Python big space between Entry and Button
tagged with: python
has comment: http://stackoverflow.com/comment/83809833
type: AnsweredQuestion
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/83811022
answer count: 1
has answer: http://stackoverflow.com/a/48412719

http://stackoverflow.com/a/48434038
has body: &gt;&gt;&gt; word = "hello" &gt;&gt;&gt; len(word) 5 &gt;&gt;&gt; "*" * len(word) '*****' Why can't you just put len(word)? len(word) gets you 5. Then we multiply '*' by 5 and we get '*****'
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48433872

http://stackoverflow.com/a/48449856
downvote count: 0
has comment: http://stackoverflow.com/comment/83903303
accepted answer of: http://stackoverflow.com/q/48449788
has comment: http://stackoverflow.com/comment/83906065
has comment: http://stackoverflow.com/comment/83901709
score: 3
has comment: http://stackoverflow.com/comment/83908542
answers question: http://stackoverflow.com/q/48449788
has body: No. py2exe and similar tools just create a bundle including the Python interpreter, the bytecode of your Python sources and their dependencies. It's just a deploy convenience, there's no speed advantage (besides skipping the initial parsing of the .py files; in this respect, it's like running your code the second time when the .pyc files are already created). For "out of the box" performance improvement you can try running your script with PyPy instead of CPython - for "all interpreted" (=> no numpy &amp; co.) numerical Python code I saw very often 20x speedups.
type: Answer
has comment: http://stackoverflow.com/comment/83910954
has comment: http://stackoverflow.com/comment/83901784
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/48365154
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/94088074
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/48363259
has comment: http://stackoverflow.com/comment/94088046
answers question: http://stackoverflow.com/q/48363259
type: AcceptedAnswer
has body: If you subtract one of the % symbols it should work. Minimal example: import google.datalab.storage as storage import pandas as pd from io import BytesIO mybucket = storage.Bucket('BUCKET_NAME') data_csv = mybucket.object('data.csv') uri = data_csv.uri %gcs read --object $uri --variable data df = pd.read_csv(BytesIO(data)) df.head()

http://stackoverflow.com/comment/83899920
type: QuestionComment
comment on: http://stackoverflow.com/q/48452882
has text: perhaps [ExcelPython - Write a user-defined function in Python](http://ericremoreynolds.github.io/excelpython/quickstart/), or [Python in Excel with PyXLL](https://www.pyxll.com/) are helpful
score: 0
type: Comment

http://stackoverflow.com/comment/83685126
has text: ok then `the_string.replace('\r\n',' ')`. [mcve] please.
comment on: http://stackoverflow.com/q/48349028
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83760310
comment on: http://stackoverflow.com/q/48385340
score: 0
has text: @GaurangShah Thanks for your comment. I have made some clarifications. In a downstream step, I do what you suggest here which is read in the line, do an operation, and move on. The issue that I'm facing is that the memory required for this seems to be out of sync with my expectations. I believe Python is keeping something in memory that I'm not aware of because as written, I would expect that memory usage would be: 1) Size of growing list 2) Single line being read in Memory usage goes well above the size of the file and list combined (43Gb to read a 17Gb file and make a 5Gb list)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83937483
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48471648
has text: @ayhan, I don't follow his logic either. I don't think it's a difficult programming task to have an argument in `groupby` to specify whether we want to calculate all category combinations.

http://stackoverflow.com/a/48368769
answers question: http://stackoverflow.com/q/48368577
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48368577
type: Answer
has body: Here's a basic approach using the mean to interpolate the value. Of course you can apply a more formal calculation, but this is a start import numpy as np # Interpolate using the mean of each row # Your original data x = np.array([[ 1.31, 1.44, 0, 2.51, 0, 0], [ 0, 1.45, 1.63, 2.48, 0, 2.69], [ 1.31, 1.43, 1.59, 2.48, 2.55, 2.71]]) print(x) print() # for each row in x, set the zero values to the mean of the non zero values for row in x: row[row == 0] = np.mean(row[np.nonzero(row)]) print(x) Output below: [[ 1.31 1.44 0. 2.51 0. 0. ] [ 0. 1.45 1.63 2.48 0. 2.69] [ 1.31 1.43 1.59 2.48 2.55 2.71]] [[ 1.31 1.44 1.75333333 2.51 1.75333333 1.75333333] [ 2.0625 1.45 1.63 2.48 2.0625 2.69 ] [ 1.31 1.43 1.59 2.48 2.55 2.71 ]]

http://stackoverflow.com/a/48472243
score: 0
has body: By using mask data_df["mean radius"]=data_df["mean radius"].mask(data_df["mean radius"] &gt; 12.0,0)
answers question: http://stackoverflow.com/q/48472156
type: Answer

http://stackoverflow.com/comment/83897877
comment on: http://stackoverflow.com/q/48452294
has text: Wouldn't it be easier to directly search for all filenames within your python script using the [glob.glob](https://docs.python.org/3.6/library/glob.html?highlight=glob#module-glob) method?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83901727
type: QuestionComment
has text: I also added the original of the Image.
comment on: http://stackoverflow.com/q/48437262
score: 0
type: Comment

http://stackoverflow.com/comment/83771491
has text: Show the exact error with trace. You're trying to treat a string as a function somewhere.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48391706
type: QuestionComment

http://stackoverflow.com/comment/122919539
type: Comment
has text: @joseville I think the anthropomorphizing does help me and hopefully also the readers, or at the very least it entertains me :-). Though I rarely do it as much as I did here. About my solutions: I'd say both elegance and tricks come from a lot of experience, the elegance also from spending way too much time on *making* it elegant, and the tricks often stem from a desire and extra effort to intentionally do interesting different things rather than boring "standard" ways. At LeetCode partly because the standard ways often had been posted already and try not to repeat.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48476719

http://stackoverflow.com/a/48379940
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48379879
score: 2
accepted answer of: http://stackoverflow.com/q/48379879
has body: Convert the column to datetime using pd.to_datetime: v = pd.to_datetime(df.CreationDate).dt.date Next, find the minimum date and compare to get a mask. Use the mask to filter df. df[v.gt(v.min())] This removes all rows whose date is the same as the minimum date found.

http://stackoverflow.com/q/48449151
has answer: http://stackoverflow.com/a/48449877
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
has body: I have a model Staff which consists simple staff information. And I have another model Schedule with schedule information class Schedule(models.Model): staff = models.ForeignKey(Staff, models.SET_NULL, blank=True, null=True) attendance = models.DateTimeField() I am getting the schedule by date something like schedules = Schedule.objects.filter(attendance__date=today) Now I want to return json of it for the api. Currently I am doing raw_data = serializers.serialize("python", schedules) return JsonResponse(raw_data, safe=False) It is giving me response something like: ` [ { model: "schedule.schedule", pk: 11, fields: { staff: 1, attendance: "some_date", } } ] ` But I want the json to be without model name and instead of ID on foreign key I want user information and id instead of foreign key. ` [ { id: 11, fields: { staff: { id: 6, name: 'Jack' }, attendance: 'some_date', } } ] ` Can I get this from serializer of I have to make a custom dictionary and add all the field in my design and dump it ? Help will be much appriciated :)
tagged with: http://stackoverflow.com/tag/json
has title: django serialize a model in desired way for api
has comment: http://stackoverflow.com/comment/83891308
answer count: 1
has comment: http://stackoverflow.com/comment/83891573

http://stackoverflow.com/a/48425740
score: 0
has body: I have tried it in this way: from datetime import datetime # print("Hello Python") t1 = "31/12/2015 10:33:26" t2 = "01/01/2016 10:33:37" newdate1 = datetime.strptime(t1, "%d/%m/%Y %H:%M:%S") newdate2 = datetime.strptime(t2, "%d/%m/%Y %H:%M:%S") thedifference = newdate2 - newdate1 print(thedifference) # Result: 1 day, 0:00:11 Make sure you import what you need on top
answers question: http://stackoverflow.com/q/48425392
type: Answer

http://stackoverflow.com/comment/83943764
has text: change `class_mode='categorical'` for the arguments to your generator. That should help.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48470788

http://stackoverflow.com/q/48477528
has comment: http://stackoverflow.com/comment/83951118
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84132426
downvote count: 0
answer count: 0
has body: I have this code: which writes some Russian symbols to csv file: def start_csv_writer(self, result_file_name): scriptpath = os.path.dirname(__file__) result_file_name = os.path.join(scriptpath, result_file_name) open(result_file_name, 'w',encoding='utf8').close() result = open(result_file_name, 'ab',encoding='utf8') csv_writer = csv.writer(result, delimiter=';', quotechar='"',lineterminator='\n') csv_writer.writerow(['запрос', '#', 'url', 'заголовок', 'сниппет' , 'brand_rate','snippet_rate', 'url_rate']) csv_writer.writerow([ 'brand_names: ' + str(self.brand_names), 'additional_brand_words: ' + str(self.additional_brand_words), 'urls: ' + str(self.urls), 'keys: '+ str(self.keys)]) return csv_writer it works fine: BUt when I try to upload cpde to pythonanywhere.com and host it there - everything brokes and I see strange symbols:
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python - issuewith encoding when deploying to hosting
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83952511

http://stackoverflow.com/comment/83797405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48404203
has text: i just want more objects.
score: 0

http://stackoverflow.com/q/48487916
type: AnsweredQuestion
has title: How to convert a text file with one column into multiple columns?
has body: I have a text file with repeating inputs all stacked in a column, with two spaces separating the next group of data : ID 1 Na 2 SK 3 ID 2 Na 4 SK 3 ID 3 Na 6 SK 6 I want to create separate columns for each data set like this: ID 1 ID 2 ID 3 Na 2 NA 4 NA 6 SK 3 SK 3 SK 6 I have tried several options but I am getting a nested which I cannot seem to manipulate. Thanks your help in advance.
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/48488471
type: Question
has answer: http://stackoverflow.com/a/48488471
has comment: http://stackoverflow.com/comment/83969269
downvote count: 2
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83975346
score: 1
comment on: http://stackoverflow.com/q/48481620
has text: Using the schema might be tripping it off. Try `ForeignKey('parent.id')`. About "there are no foreign keys in the parent": no, but there are foreign keys between the 2, so that's not the issue.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48378702
type: Question
has body: I am trying to access adb shell of an android device and pass multiple commands such as adb root adb shell cd /data/local/tmp export PATH =/data/local/tmp:$PATH export PATH =/data/local/tmp/testcases:$PATH sh ./runltp -p -l 1213reportipc.log -d /data/local/tmp/LTP13/tmp -f ipc1q exit While I am able to do this manually using adb shell, I am unable to do this via a Python script since as soon script execution encounters 'adb shell' command it spawns a new internal shell and rest of the commands are not executed. Can anyone please help me with this.
score: 1
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/83744251
favorite count: 0
has answer: http://stackoverflow.com/a/63093151
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: adb
upvote count: 1
has comment: http://stackoverflow.com/comment/83750139
has title: How to pass multiple commands through adb shell using python script without exiting the shell

http://stackoverflow.com/comment/83652145
comment on: http://stackoverflow.com/q/48333298
has text: Have you tried reading the documentation?
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48459269
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83912816
tagged with: machine-learning
has title: Interpret predicted probabilities in multiclass logistic regression
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48485164
has answer: http://stackoverflow.com/a/48486027
favorite count: 0
tagged with: logistic-regression
tagged with: multiclass-classification
has body: I have a dataset as given below where A,B,C,D,E are features and 'T' is Target Variable. A B C D E T 32 22 55 76 98 3 12 41 90 56 33 2 31 78 99 67 89 1 51 85 71 21 37 1 ...... ...... Now, I have applied multiclass logistic regression classifier using Scikit Learn and get predict values and matrix of probablities as:- A B C D E T Predicted Probablity 32 22 55 76 98 3 3 0.35 12 41 90 56 33 2 1 0.68 31 78 99 67 89 1 3 0.31 51 85 71 21 37 1 1 0.25 Now just want to ask how to I interpret the outcome probablities, 1) As far I have studied that python by default gives the probablity of event to be 1. So if this is the case, is 0.35 considered to be probablity of being event 1? OR 2) is value 0.35 is possibility of 1st case to be belongs from class "3"? How could I calculate probablities for remaining two classes. Something like:- A B C D E T Predicted P_1 P_2 P_3 32 22 55 76 98 3 3 0.35 0.20 0.45 12 41 90 56 33 2 1 0.68 0.10 0.22 31 78 99 67 89 1 3 0.31 0.40 0.29 51 85 71 21 37 1 1 0.25 0.36 0.39
score: 3
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/a/48467916
score: 0
answers question: http://stackoverflow.com/q/48467759
has body: Two ways I see going about handling this. Given: import pandas as pd df = pd.DataFrame({'A':['12','$10','22','$99','100']}) df A 0 12 1 $10 2 22 3 $99 4 100 1) Coerce the values that pandas.to_numeric(...) can't convert to be Nans. This way most calculations will ignore them. pd.to_numeric(df.A, errors='coerce') 0 12.0 1 NaN 2 22.0 3 NaN 4 100.0 2) Remove the '$' if present and convert to number so you are not loosing data. df.A.apply(lambda i: float(i[1:]) if i[0] == '$' else float(i)) 0 12.0 1 10.0 2 22.0 3 99.0 4 100.0
type: Answer

http://stackoverflow.com/a/48356992
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48351165
answers question: http://stackoverflow.com/q/48351165
has body: Turned out the other person needed to install ActiveTCL 8.5.
type: Answer
score: 0

http://stackoverflow.com/comment/83752480
type: QuestionComment
score: 0
has text: @Ev.Kounis It is not almost 0. It is in fact zero: http://stattrek.com/probability-distributions/discrete-continuous.aspx?Tutorial=Stat
type: Comment
comment on: http://stackoverflow.com/q/48382823

http://stackoverflow.com/a/48405817
accepted answer of: http://stackoverflow.com/q/48405005
upvote count: 1
has body: You can use the following variation of A = A.T.reshape(-1,n): B = A.reshape(n, -1).T A is not overwritten and its grid structure remains preserved. No data is copied - B is a view into A (only works because we reshape before .T) Now you can use A to access the data in a grid structure and B to access the same data in a flat structure. Example: A = np.mgrid[[slice(0,11,1)]*4] B = A.reshape(4, -1).T # modify first point print(B[0]) # [0 0 0 0] B[0] = [1, 3, 3, 7] print(A[:, 0, 0, 0, 0]) # [1 3 3 7]
type: Answer
answers question: http://stackoverflow.com/q/48405005
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48418195
has title: Why is python dictionary attribute shared
has body: I am new to python. When I was playing around with the code, I found this. Source Code: dic = {} mem_dic = {} def set_op(ind, data): global dic, mem_dic key, value = data.split() dic[key] = int(value) mem_dic[ind] = dic print(ind, "====", mem_dic) set_op(0, 'aaa 1') set_op(1, 'bbb 2') Expected Output: 0===={0:{'aaa':1}} 1===={0:{'aaa':1},1:{'aaa':1,'bbb':1}} Actual Output: 0===={0:{'aaa':1,'bbb':1}} 1===={0:{'aaa':1,'bbb':1}} Could anyone please explain the reason for this behavior. And what changes should I incorporate to get the expected output.
has answer: http://stackoverflow.com/a/48418254
has comment: http://stackoverflow.com/comment/83826023
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83826660
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83836307
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/2438938
score: 0
has answer: http://stackoverflow.com/a/48418265
answer count: 2

http://stackoverflow.com/comment/83701317
comment on: http://stackoverflow.com/a/48349031
score: 0
type: AnswerComment
has text: @thib I don't know, I don't use `BaseHTTPRequestHandler`, I usually use tornado. I'll take a closer look later. The error message is probably an exception, at which part of the code did you get that?
type: Comment

http://stackoverflow.com/comment/83754802
comment on: http://stackoverflow.com/q/48383789
type: Comment
score: 0
has text: It's just `and`. Unfortunately though, your syntax would be correct but your code would still throw errors. It isn't sure what you're trying to do though.
type: QuestionComment

http://stackoverflow.com/comment/83987925
comment on: http://stackoverflow.com/a/48460190
score: 0
type: AnswerComment
type: Comment
has text: Declaring it trainable causes an optimizer to see it in `trainable_variables`. I don't know whether this causes problems or not, as I never tried it myself. I suggest you, however, to declare `global_step` via `tf.train.get_or_create_global_step` which automatically declares it non-trainable (or retrieves an existing `global_step` variable in case it was already defined somewhere in your graph)

http://stackoverflow.com/a/48389034
answers question: http://stackoverflow.com/q/48388833
has body: Perl will let you change the input separator ($/) from newline to another character. You could take advantage of this to get some convenient chunking. perl -pe'BEGIN{$/="}"}s/^({"seq_id")/\n$1/' my_giant_json.json That sets the input separator to be "}". Then it looks for chunks that start with {"seq_id" and prefixes them with a newline. Note that it puts an unnecessary empty line at the beginning. You could complicate the program to eliminate that or just delete it manually after.
score: 3
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48388833

http://stackoverflow.com/q/48422892
answer count: 0
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/48049962
upvote count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/83889910
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: lstm
has comment: http://stackoverflow.com/comment/83866142
has body: I am trying to build a model that takes a sentence as input, takes each word and tries to predict the next word. My input and output both are a 3D matrix with (number of sentences, number of words per sentence, dimension of word embedding). Input is e. g. "I like green apples" while the output is "like green apples _", each word embedded as a 300 dimensional vector used from pre-trained GoogleWord2Vec. I only use an Input Layer, an LSTM layer and a TimeDistributed Output layer. _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input (InputLayer) (None, 15, 300) 0 _________________________________________________________________ rnn (LSTM) (None, 15, 300) 721200 _________________________________________________________________ tanh (TimeDistributed) (None, 15, 300) 90300 ================================================================= #building the model words = keras.layers.Input(batch_shape=(None, maxSeqLength, numDimensions), name = "input") #inputs hiddenStates = keras.layers.LSTM(300, input_shape=(batch_size, maxSeqLength, numDimensions), return_sequences = True, name = "rnn")(words) timeOutput = TimeDistributed(keras.layers.Dense(numDimensions, activation='relu'), name = "tanh")(hiddenStates) model = keras.models.Model(input = words, output = timeOutput) model.compile(loss='mse', optimizer = keras.optimizers.RMSprop(lr = 0.0001), metrics=['accuracy']) print(model.summary()) #training the model model.fit(input, output, batch_size=batch_size, epochs = 100, verbose=1) My problem is that when I run the model my accuracy is like 0,05. Trying different learning rates or inputs does not improve it. Can somebody tell me why my model might fail? The goal of the model is that I want to use the last hidden state as a vector representing the input sentence.
has title: Keras LSTM model has very low accuracy

http://stackoverflow.com/q/48405474
tagged with: django
tagged with: python
score: -1
tagged with: css
downvote count: 1
has answer: http://stackoverflow.com/a/48406001
has comment: http://stackoverflow.com/comment/83799607
has body: I have followed my first Django App video series on Youtube. I have created admin, but I am unable to load CSS: What I want is this:
has title: How can't my django admin got no css attached?
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/83812969
has text: When you fork a child process it inherits the original process's `stdout`, so its output should go to the file.
type: Comment
comment on: http://stackoverflow.com/q/48411485
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83699496
comment on: http://stackoverflow.com/q/48347728
has text: oh you right :) i change the question. Thanks!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83759671
type: Comment
comment on: http://stackoverflow.com/q/48386100
type: QuestionComment
score: 0
has text: I don't know what your c++ snippet is trying to do, but I suspect it won't achieve what you want.

http://stackoverflow.com/comment/83957540
type: Comment
comment on: http://stackoverflow.com/a/48482194
type: AnswerComment
has text: The bio field isnt showing, i have been querying it but looks like it didnt even add bio to it
score: 0

http://stackoverflow.com/a/48382904
has body: To create a new column (str_set) with the items in the set column converted to string: df["str_set"] = [[str(item) for item in df.loc[row, "set"]] for row in range(len(df["set"]))]
score: 0
answers question: http://stackoverflow.com/q/48382663
type: Answer

http://stackoverflow.com/a/48475404
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48442419
upvote count: 1
has body: I don't speak python, but I think you're skipping possible matches by doing start=end-1. You probably need to do start=start+1. For example, let's say you have these strings: GATCAA GAGCAATCAA Your algorithm will first find GA as common substring, and then continue looking from the third character. But that way you're missing the real longest common substring, ATCAA. EDIT: Obviously you also need to reinitialize end together with start. Either you set it to start+1 to always start looking from a two-letter string like you're doing, or you can optimize your code by starting from the length of the longest match you've found so far.

http://stackoverflow.com/q/48459710
type: Question
has title: Grab docstrings from scripts in Sphinx
has comment: http://stackoverflow.com/comment/84159276
tagged with: python-sphinx
has body: I have a code repository which is a mix of modules and analytical scripts. I am trying to document it with Sphinx. -MyProject -MyModule -Scripts_using_MyModule -Specific_Analytical_Question_1.py -Specific_Analytical_Question_2.py Using .. automodule:: I can grab the docstrings from the modules in the MyModule folder. But I would also like to take the docstrings that I have written in the scripts. What I mean by scripts are small pieces of code for a very specific purpose, they are not written as functions so that you can see all the variables when they run in Spyder. Is there a way to give Sphinx the folder name and have it list all the files with their docstrings?
has comment: http://stackoverflow.com/comment/84001806
tagged with: python
tagged with: restructuredtext
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83913068
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83821947
score: 0
comment on: http://stackoverflow.com/a/48379664
type: Comment
type: AnswerComment
has text: Thanks, I think it solved my problem. But I still have 2 questions, 1. Since it needs to scroll down a bit by bit, it appears to be a bit slow, I need to build a crawler so is it possible to make it faster? 2. Why do I need to scroll down gradually to get the contents, which web tech does it related to, I am a noob in this field so a little bit of explanation or pointing me somewhere to look for will be of great help. Thanks again!

python-wheel
tags question: http://stackoverflow.com/q/48377637
type: Tag
tag name: python-wheel
tags question: http://stackoverflow.com/q/48379846

http://stackoverflow.com/comment/83690513
type: Comment
type: QuestionComment
has text: I just figured it out. had to put the xs = [] an ys = [] outside of the function
comment on: http://stackoverflow.com/q/48351853
score: 1

http://stackoverflow.com/q/48401389
has title: How can I install BeautifulSoup? I keep getting "No module named bs4"
has answer: http://stackoverflow.com/a/48401572
linked to: http://stackoverflow.com/q/11783875
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83791030
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83790752
tagged with: python
has comment: http://stackoverflow.com/comment/83790822
score: 0
has comment: http://stackoverflow.com/comment/83790740
has comment: http://stackoverflow.com/comment/83790807
answer count: 1
has body: When I try to import bs4 I keep getting the error ImportError: No module named bs4 I have tried to address this by trying all of the following (individually and together) with Python 2 and Python 3 and have had no success. What's going wrong? sudo pip2 install beautifulsoup4 sudo pip3 install beautifulsoup4 sudo apt-get install python-bs4 sudo apt-get install python3-bs4

http://stackoverflow.com/comment/84180550
type: Comment
comment on: http://stackoverflow.com/a/48482101
type: AnswerComment
has text: I did, at least eight or ten times in the course of testing. Always worked. :shrug: Glad you found a solution, though!
score: 0

http://stackoverflow.com/a/48469797
downvote count: 0
upvote count: 1
has body: Here is one solution: birthdays = {"Anne": {"month":"Jan","day":"27"}, "Mike": {"month":"Feb","day":"13"}, "Nicolas": {"month":"Jun","day":14}, "Marta": {"month":"Jan","day":16}} {k: v['day'] for k, v in birthdays.items() if v['month']=='Jan'} # {'Anne': '27', 'Marta': 16}
answers question: http://stackoverflow.com/q/48469155
type: Answer
score: 1

http://stackoverflow.com/a/48709118
has body: Looking at your data, one can expect that medcouple is small, but positive. Medcouple is a measure of skewness. As it is stated by Hubert and Vandervieren: It clearly follows from this definition that the medcouple always lies between −1 and 1. A distribution that is skewed to the right has a positive value for the medcouple, whereas the MC becomes negative at a left skewed distribution. Finally, a symmetric distribution has a zero medcouple. In your data, you have a lot of 10s, plus 9 values to the left (1 to 9) and 11 values to the right (11 to 21). So, it is little skewed to the right. In your calculations, they are returning zero due rounding (I've checked your python code and it is returning 0, not 1.) But if you put not so many 10s in the data, you could see a small positive value: &gt; medcouple([10.0]*3 + [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]) array(0.05263158) Update Actually, my initial interpretation were wrong... Sorry about that! I've checked the R code you provided, and it is returning 1, not zero as you saw. I've also plotted (using R) the medcouple for different samples (adding different amounts of 10s to the initial data). I've used not only mrfDepth library, but also robustbase that also implements medcouple statistic. They've returned the same values. Just to help understanding the behavior of this asymmetry measure, I've added some plots using the skewness statistic. And, at last, to make things more interesting, I've compared all these results with a very similar data sample (only omitting 2 numbers: 20 and 21). See code below: library(robustbase) # mc (also a medcouple implementation) library(mrfDepth) # medcouple library(moments) # skewness symmetric.sample = function(n) { c(c(1:19), rep(10,n)) } skewed.sample = function(n) { c(c(1:21), rep(10,n)) } xlab = "# 10s added" n = 1:150 png("skew.png", width=600, height=1000, pointsize=8, res=160) par(mfrow=c(4,2), pch=20) hist(sapply(30, symmetric.sample), breaks=0:21, xlab="symmet…
answers question: http://stackoverflow.com/q/48448318
type: Answer
has comment: http://stackoverflow.com/comment/113456742
has comment: http://stackoverflow.com/comment/113456539
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/a/48362276
has comment: http://stackoverflow.com/comment/83711537
has comment: http://stackoverflow.com/comment/83711757
has body: Pandas has a clean interface for this kind of task: import pandas as pd df = pd.read_csv(filepath, delimiter='|', header=None, names=['username', 'score']) highest_score = df['score'].max() highest_score_username = df.loc[df['score'] == highest_score, 'username']
has comment: http://stackoverflow.com/comment/83711644
answers question: http://stackoverflow.com/q/48362221
upvote count: 2
has comment: http://stackoverflow.com/comment/83711628
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/72036804
upvote count: 4
has body: Closing launch.json if it is open for editing may solve the issue If launch.json is the latest open file, VSCode may be trying to run launch.json as a Python module (despite the fact that it's clearly not a Python module). See the NameError in the OP's third screenshot - looks like Python interpreter running against launch.json (Note: the contribution of this answer is solely to put the crux of Haru's Solution 1.1 and Nick's own self-diagnosis into simple language in the answer's first line)
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48435774

http://stackoverflow.com/comment/83893563
comment on: http://stackoverflow.com/q/48450050
has text: Not all objects are tracked by the garbage collector, indeed, this is stated in the `gc` [docs](https://docs.python.org/3/library/gc.html#gc.is_tracked). Python only uses the garbage collector to clean up objects that might be missed by reference counting (i.e. caused by cyclic references).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84058364
has text: One should clarify that this is a workaround. `has` not working is a bug, which is fixed in the development version and should work in the next release (1.2).
score: 0
comment on: http://stackoverflow.com/a/48472035
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83679797
type: AnswerComment
comment on: http://stackoverflow.com/a/48346929
score: 0
type: Comment
has text: This is insanely overcomplicated. Even if producing the string of underscores was the actual problem, `'_'*len(word)` alone would do the job.

facebook-graph-api
tags question: http://stackoverflow.com/q/48424180
tag name: facebook-graph-api
type: Tag

http://stackoverflow.com/comment/83873464
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48438913
type: Comment
has text: Since you are using Django, you should do a search for unit testing in Django.

http://stackoverflow.com/a/48410165
type: Answer
has body: For starters, quit doing a prime factorization. Instead, use Euclid's algorithm to check whether the numerator and denominator have a GCD of 1. If you do find a need for primes, search for faster generating algorithms, such as the Sieve of Eratosthenes. Finally, think on this: generate the primes (efficiently); factor each denominator, as you're doing now. However, instead of looping through all possible numerators, how can you generate the valid numerators for your needs?
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83810026
answers question: http://stackoverflow.com/q/48410012

http://stackoverflow.com/a/48456053
type: AcceptedAnswer
downvote count: 0
has body: So there are multiple problems. Change your choices to strings: choices=[('1', 'M'), ('2', "F")] Change your form method to POST, because validate_on_submit() requires it: &lt;form action="" method="POST"&gt; Additionally, to debug other possible errors (like CSRF), add this to your template: {% if form.errors %} {{ form.errors }} {% endif %} That fixed your code for me.
has comment: http://stackoverflow.com/comment/83914004
score: 10
type: Answer
upvote count: 10
answers question: http://stackoverflow.com/q/48455689
accepted answer of: http://stackoverflow.com/q/48455689

http://stackoverflow.com/q/48384551
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83761365
has body: Currently, I'm working on a Tkinter program. This program works fine, but after i convert it to a exe file, i encounter a problem. The code is as follows: import tkinter as tk import numpy as np import scipy import pandas as pd import math import os import numpy.core._methods, numpy.lib.format from tkinter.ttk import Progressbar class Main(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, Calculatepage,Final): frame = F(container, self) self.frames[F] = frame self.geometry("700x400") self.wm_title('Test') self["bg"]="white" frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.update_page() frame.tkraise() def show_frame2(self, cont): frame = self.frames[cont] frame.tkraise() frame.update_page() self.update() page=self.get_page(cont) value = page.value frame = self.frames[Final] frame.update_page(value) frame.tkraise() def get_page(self, page_class): return self.frames[page_class] class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) self["bg"]="white" frame2 = tk.Frame(height=150, bd=10,bg="green") frame2.pack(fill=tk.X) button1 = tk.Button(self, text='Calculate', width=25, height=2, bg="green",fg="white",command=lambda: controller.show_frame2(Calculatepage)) button1.place(x=250,y=100) def update_page(self): # empty method but I need it pass class Calculatepage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self["bg"]="white" self.controller=controller self.label1=tk.Label(self, text="Loading...",bg="white",fg="green",font="verdana 10") self.label1.pack() self.label2 = tk.Label(self, text="",bg="white",fg="green",font="verdana 20") self.label2.pack() def update_page(self): A = 1…
tagged with: scipy
tagged with: cx-freeze
tagged with: python
has title: Tkinter exe is not working as expected
tagged with: exe
favorite count: 0
type: Question
score: 2
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/83954704
has text: More support for it being a theano issue: https://github.com/pymc-devs/pymc3/issues/2266
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48480193
score: 0

http://stackoverflow.com/comment/83739652
type: QuestionComment
type: Comment
has text: I don't windows anymore, but did you right click your cmd prompt and "Run as Administrator"?
comment on: http://stackoverflow.com/q/48376226
score: 1

http://stackoverflow.com/comment/83798866
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48405017
has text: @Ev.Kounis: no, because the identifier has been normalised *before* bytecode is produced, when parsing (a stage that converts tokens into an AST, which the compiler then uses to produce bytecode).

http://stackoverflow.com/q/48484463
has title: How to python Scrape text in span class
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48484567
possible better answer: http://stackoverflow.com/a/48484567
tagged with: python
has body: So I'm making a bitcoin checker practice and I'm having trouble scraping data because the data I want is in a span class and I don't know how to retrieve the data. so here is the line that I got from inspect: 11,511.31 USD I want to scrape the "11,511.31" number. How do I do this? I tried so many different things and I honestly have no clue what to do anymore. here is the URL:link Im scraping the current USD price (right next to "BTC/USD") EDIT: Guys a lot of the examples you gave me is where i input the data. Thats not useful because i want to refresh the page every 30 seconds so I need the program to find the span class and extract the data and print it' EDIT:current code. need to get programm to get "html" part by itself from urllib.request import urlopen as uReq from bs4 import BeautifulSoup url = 'https://www.gdax.com/trade/BTC-USD' #program need to retrieve this by itself html = """11,560.00 USD""" soup = BeautifulSoup(html, "html.parser") spans=soup.find_all('span', {'class': 'MarketInfo_market-num_1lAXs'}) for span in spans: print(span.text.replace('USD','').strip())
accepted answer: http://stackoverflow.com/a/48484534
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83961621
has answer: http://stackoverflow.com/a/48485318
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48484534
type: Question

http://stackoverflow.com/comment/83730549
comment on: http://stackoverflow.com/q/48371615
has text: Sounds like he structured his question incorrectly. Since you guys are already running the code, care to tell me what the problem is pleeeaaase :)? I'm just curious and couldn't see the issue in a cursory scan.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48470627
has body: I'm currently working with data from a sports related test. I want to visualize the (multidimensional) test-data of one athlete from several tests (different dates), so I made grouped vbar with the dates at the lowest level of grouping. Now I want to tap on one bar to select it and the corresponding ones from the same date should be selected (and highlighted), too. Till now I was searching on stackoverflow with "[python][bokeh]taptool" query, I looked up the whole issues section on git/bokeh with the tag "taptool" and did a google with similar queries, but I can't find a matching thread. To clarify my needs, I modified the grouped_bars_example from the bokeh repository. My goal is to select all bars of one manufacturer by clicking on one bar. (I know it's possible to hold shift-key for multiselections, but it is quiet annoying to select, for example, 6 corresponding bars out of 120 bars. Thatswhy I'm looking for an efficient way to do so with one click) #### basic example code from ~/latest/docs/user_guide/categorical.html#grouped from bokeh.io import show, output_file from bokeh.models import ColumnDataSource, HoverTool, TapTool from bokeh.plotting import figure from bokeh.palettes import Spectral5 from bokeh.sampledata.autompg import autompg_clean as df from bokeh.transform import factor_cmap # output_file('bars.html') # preparing data for figure df.cyl = df.cyl.astype(str) df.yr = df.yr.astype(str) group = df.groupby(('cyl', 'mfr')) source = ColumnDataSource(group) index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1) # setting up figure p = figure(plot_width=800, plot_height=300, title="Mean MPG by # Cylinders and Manufacturer", x_range=group, toolbar_location=None, tools="") # adding grouped vbar p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=source, line_color="white", fill_color=index_cmap, ) # figurestyling p.y_range.start = 0 p.x_range.range_padding = 0.05 p.xgrid.grid_line_color = None p.xaxis.axis_label = "Man…
downvote count: 0
tagged with: bokeh
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Select corresponding/multiple bars on bokeh vbar with taptool
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/q/48449057
has answer: http://stackoverflow.com/a/48564700
has body: I have to ask the user for a query and then get print the number of matches, and the Title, First Author Name, Last Author Name for the first 5 returned results. What I have so far: from Bio import Entrez from Bio import Medline pmquery = str(input("Enter the Pubmed query:")) Entrez.email = "myemailadress@bdm.com" handle = Entrez.esearch(db="pubmed", term=pmquery,retmax=5) record = Entrez.read(handle) handle.close() print(record)
score: 0
tagged with: pubmed
tagged with: python
tagged with: biopython
has title: BioPython to write a program for a PubMed query
has comment: http://stackoverflow.com/comment/83890933
type: Question
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/48366412
has body: The problem is with alpha, which tensorflow interprets as an int. Change it to alpha=0.3 to avoid conversion.
score: 3
accepted answer of: http://stackoverflow.com/q/48366249
upvote count: 3
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48366249

http://stackoverflow.com/q/48363237
tagged with: python
has body: I'm having trouble understanding how to implement queue into a multiprocessing example below. Basically, I want the code to: 1) spawn 2 processes (done) 2) split up my id_list into two portions (done) 3) have each process iterate over the list printing out each item, and only close when its done with the list. I know I have to implement some type of Queueing system, and pass that to each worker, but I'm not sure how to do that. Any help would be much appreciated. from multiprocessing import Pool,Queue id_list = [1,2,3,4,5,6,7,8,9,10] def mp_worker(record): try: print record sleep(1) except: pass print "worker closed" def mp_handler(): p = Pool(processes = 2) #number of processes p.map(mp_worker, id_list) #devides id_list between 2 processes, defined above p.close() p.join() mp_handler() Note - the code prints out "worker closed" 10 times. Id like for this statement to be printed only twice (once for each worker, after each worker prints out the 5 numbers from id_list)
answer count: 4
accepted answer: http://stackoverflow.com/a/48363352
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83728275
downvote count: 0
has answer: http://stackoverflow.com/a/48363414
possible better answer: http://stackoverflow.com/a/48363414
has title: python multiprocessing queue implementation
has comment: http://stackoverflow.com/comment/83727395
tagged with: queue
favorite count: 0
tagged with: multiprocessing
has answer: http://stackoverflow.com/a/48363352
type: Question
has comment: http://stackoverflow.com/comment/83728829
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83727802
has comment: http://stackoverflow.com/comment/83728181
has answer: http://stackoverflow.com/a/59305416
has answer: http://stackoverflow.com/a/71993736

http://stackoverflow.com/q/48471630
possible better answer: http://stackoverflow.com/a/48471817
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48471817
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48471994
has body: I am running a python script to scan for a fakeAP in an area. Currently, the script has been configured to send an email notification to admin through the following code. I would like to create a new .csv file and save the result (message) to a csv file instead and get rid off all code for sending message notification. I have tried to write a simple script to help solve this problem but nothing seem to work. Any help solve this problem will be greatly appreciated. Thank you in advance # sending an alert to the admin email def AlertAdmin(message): try: cmd = "select opt_val from options where opt_key = 'admin_email'" cursor.execute(cmd) if cursor.rowcount &gt; 0: row = cursor.fetchone() admin_email = row[0] cmd = "select opt_val from options where opt_key = 'admin_smtp'" cursor.execute(cmd) if cursor.rowcount &gt; 0: row = cursor.fetchone() admin_smtp = row[0] cmd = "select opt_val from options where opt_key = 'admin_smtp_username'" cursor.execute(cmd) if cursor.rowcount &gt; 0: row = cursor.fetchone() admin_smtp_username = row[0] cmd = "select opt_val from options where opt_key = 'admin_smtp_password'" cursor.execute(cmd) if cursor.rowcount &gt; 0: row = cursor.fetchone() admin_smtp_password = row[0] message = "From: EvilAP_Defender &lt;{}&gt;\nTo: Admin &lt;{}&gt;\nSubject: EvilAP_Defender Alert!\n\n"\ .format(admin_smtp_username, admin_email) + message try: print bcolors.OKBLUE + "\nConnecting to SMTP server\n" + bcolors.ENDC mailsrv = smtplib.SMTP(admin_smtp,587) print bcolors.OKBLUE + "\nSending ehlo message to SMTP server\n" + bcolors.ENDC mailsrv.ehlo() print bcolors.OKBLUE + "\nStarting TLS with SMTP server\n" + bcolors.ENDC mailsrv.starttls() print bcolors.OKBLUE + "\nSending ehlo message to SMTP server\n" + bcolors.ENDC mailsrv.ehlo() print bcolors.OKBLUE + "\nLogin to SMTP server\n" + bcolors.ENDC mailsrv.login(admin_smtp_username,admin_smtp_password) print bcolors.OKBLUE + "\nSending the message ...\n" + bcolors.ENDC mailsrv.sendmail(admin_smtp_username, …
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48471994
tagged with: python
has title: Creating a new csv and writing a variable result to the file

http://stackoverflow.com/comment/83947506
score: 2
has text: the compression level isn't the issue here. this level just tells how hard the compressor must look for similar strings/try various approaches to gain size. It's transparent for the decompressor.
type: Comment
comment on: http://stackoverflow.com/q/48477154
type: QuestionComment

http://stackoverflow.com/a/48487796
has comment: http://stackoverflow.com/comment/84015745
answers question: http://stackoverflow.com/q/48487747
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: IIUC: import pandas as pd ips = pd.read_csv('/Users/kiya/Desktop/webgw logs/check/1st.log', delim_whitespace=True, usecols=[3], squeeze=True) print(ips.unique())

http://stackoverflow.com/a/48446327
answers question: http://stackoverflow.com/q/48446233
has comment: http://stackoverflow.com/comment/83884743
type: Answer
has body: The following line should do the trick: plt.ylim(ymin=0)
score: 0

http://stackoverflow.com/q/48379205
has comment: http://stackoverflow.com/comment/83745027
has comment: http://stackoverflow.com/comment/83746269
has comment: http://stackoverflow.com/comment/83745111
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83746186
has answer: http://stackoverflow.com/a/48379918
has comment: http://stackoverflow.com/comment/83745696
tagged with: arrays
has body: I want to manually convert a RGB image to Grayscale image. What I want to know is how to get the Red/Blue/Green values of a RGB pixel ? img = cv2.imread("images/penguins.jpg",0) grey = img for i in range(0,grey.shape[0]-1): for j in range(0,grey.shape[1]-1): img[i,j]=[ ] I dont know what to do next Thanks, Sorry for my bad english
tagged with: python
has comment: http://stackoverflow.com/comment/83745752
has title: How to manual convert `BGR` image to `grayscale` (Python OpenCV)?
score: -1
has comment: http://stackoverflow.com/comment/83745665
tagged with: image
has comment: http://stackoverflow.com/comment/83746105
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83745074
accepted answer: http://stackoverflow.com/a/48379918
upvote count: 2
has comment: http://stackoverflow.com/comment/83745275
has comment: http://stackoverflow.com/comment/83746034
answer count: 1
downvote count: 3

http://stackoverflow.com/comment/83690111
type: Comment
comment on: http://stackoverflow.com/a/48348399
type: AnswerComment
has text: Yes, my program uses _MEIPASS. I think VLC is installed on all computers involved, but should this matter?
score: 0

http://stackoverflow.com/comment/83802764
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48406107
has text: Thank you for the response. This seems to work when I take a piece of the file but when I include the entire thing I get the following "ParserError: Too many columns specified: expected 7 and found 3". Earlier in the file this method takes blank cells and treats them as "nans". For some reason later it thinks there is just no column there...this is probably a different question but please let me know if you have insight into that. Thanks!
score: 0

http://stackoverflow.com/comment/83852957
comment on: http://stackoverflow.com/q/48430510
score: 0
type: QuestionComment
has text: @HåkenLid No, i know that, but what i need is not to show the value of one field but the entire queryset result in a table, including the field names as headers and all teh values the filter got.
type: Comment

generator
type: Tag
tags question: http://stackoverflow.com/q/48360864
tags question: http://stackoverflow.com/q/48483952
tags question: http://stackoverflow.com/q/48435165
tags question: http://stackoverflow.com/q/48480954
tags question: http://stackoverflow.com/q/48365635
tags question: http://stackoverflow.com/q/48471212
tag name: generator
tags question: http://stackoverflow.com/q/48345294
tags question: http://stackoverflow.com/q/48365275
tags question: http://stackoverflow.com/q/48474295
tags question: http://stackoverflow.com/q/48481870
tags question: http://stackoverflow.com/q/48344129
tags question: http://stackoverflow.com/q/48343828

http://stackoverflow.com/comment/83912605
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48457416
type: Comment
has text: i am using angular 4 template, so the have one line of code to upload data const URL = 'http://localhost:3000/upload'; public uploader: FileUploader = new FileUploader({ url: URL }); this through an error that that header is there, you need to specify header. but i am not passing any header here

http://stackoverflow.com/comment/83862740
type: AnswerComment
has text: @Tai Many Thanks! No need to upvote. "Coold optimization" was good enough for me!
score: 1
comment on: http://stackoverflow.com/a/48435149
type: Comment

http://stackoverflow.com/a/48346401
answers question: http://stackoverflow.com/q/48346156
type: Answer
has comment: http://stackoverflow.com/comment/83678861
has body: Give this ago :) acc = 2 seedStamp = 1506447570 timeStamps = [] for i in range(acc): for k in range(33): timeStamps.append(seedStamp) if k &gt;31: seedStamp += 1 timeStamps.append(seedStamp) print('--') for i in timeStamps: print(i)
score: 0

http://stackoverflow.com/a/48365300
type: AcceptedAnswer
has body: Checkout the docs on finding elements. I find xpaths or css selectors particularly powerful because they are extremely generalizable. xpath upload_field = driver.find_element_by_xpath("//input[@type='file']") css selector upload_field = driver.find_element_by_css_selector("input[name='filePath'][type='file']")
accepted answer of: http://stackoverflow.com/q/48365252
has comment: http://stackoverflow.com/comment/83717473
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83717627
has comment: http://stackoverflow.com/comment/83718055
answers question: http://stackoverflow.com/q/48365252
has comment: http://stackoverflow.com/comment/83718083
has comment: http://stackoverflow.com/comment/83717406
score: 38
upvote count: 38
has comment: http://stackoverflow.com/comment/83717616

http://stackoverflow.com/comment/83788896
comment on: http://stackoverflow.com/q/48399718
score: 0
has text: @DennisSoemers sry, I have corrected my op
type: QuestionComment
type: Comment

http://stackoverflow.com/a/54391213
score: 5
has body: I also had this issue and it turned out to be my region was wrong. Silly but worth a check!
downvote count: 0
has comment: http://stackoverflow.com/comment/110619646
answers question: http://stackoverflow.com/q/48438202
upvote count: 5
type: Answer

http://stackoverflow.com/comment/83796932
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48397717
score: 0
has text: yup FreeTDS indeed, I modify tags

http://stackoverflow.com/a/54764354
score: 12
answers question: http://stackoverflow.com/q/48391777
downvote count: 0
has body: You can use this trick. import click @click.command() @click.option('--users', nargs=0, required=True) @click.argument('users', nargs=-1) @click.option('--bar') def fancy_command(users, bar): users_str = ', '.join(users) print('Users: {}. Bar: {}'.format(users_str, bar)) if __name__ == '__main__': fancy_command() Add fake option with a needed name and none arguments nargs=0, then add 'argument' with the unlimited args nargs=-1. $ python foo --users alice bob charlie --bar baz Users: alice, bob, charlie. Bar: baz But be careful with the further options: $ python foo --users alice bob charlie --bar baz faz Users: alice, bob, charlie, faz. Bar: baz
type: Answer
has comment: http://stackoverflow.com/comment/98285096
has comment: http://stackoverflow.com/comment/132860568
has comment: http://stackoverflow.com/comment/132828052
has comment: http://stackoverflow.com/comment/98851928
upvote count: 12

http://stackoverflow.com/comment/83920720
comment on: http://stackoverflow.com/a/48463565
type: Comment
has text: Thank you the logical explantation seems right however I have this error when running the script over my 240 figures: ValueError: invalid literal for int() with base 10: 'ig144'
score: 0
type: AnswerComment

dictionary
tags question: http://stackoverflow.com/q/48335063
tags question: http://stackoverflow.com/q/48408467
tags question: http://stackoverflow.com/q/48446408
tags question: http://stackoverflow.com/q/48380512
tags question: http://stackoverflow.com/q/48466298
tags question: http://stackoverflow.com/q/48437673
tags question: http://stackoverflow.com/q/48337542
tags question: http://stackoverflow.com/q/48408529
tags question: http://stackoverflow.com/q/48414645
tags question: http://stackoverflow.com/q/48467273
tags question: http://stackoverflow.com/q/48393069
tags question: http://stackoverflow.com/q/48443426
tags question: http://stackoverflow.com/q/48414190
tags question: http://stackoverflow.com/q/48471688
tags question: http://stackoverflow.com/q/48463474
tags question: http://stackoverflow.com/q/48447367
tags question: http://stackoverflow.com/q/48482119
tags question: http://stackoverflow.com/q/48374437
tags question: http://stackoverflow.com/q/48335590
tags question: http://stackoverflow.com/q/48453726
tags question: http://stackoverflow.com/q/48457570
tags question: http://stackoverflow.com/q/48439059
tags question: http://stackoverflow.com/q/48464958
tags question: http://stackoverflow.com/q/48454827
tags question: http://stackoverflow.com/q/48469155
tags question: http://stackoverflow.com/q/48467887
tags question: http://stackoverflow.com/q/48412774
tags question: http://stackoverflow.com/q/48375618
tags question: http://stackoverflow.com/q/48455895
tags question: http://stackoverflow.com/q/48417874
tags question: http://stackoverflow.com/q/48428367
tags question: http://stackoverflow.com/q/48334703
tags question: http://stackoverflow.com/q/48408751
tags question: http://stackoverflow.com/q/48352616
tags question: http://stackoverflow.com/q/48362370
tags question: http://stackoverflow.com/q/48354276
tags question: http://stackoverflow.com/q/48435051
tags question: http://stackoverflow.com/q/48433207
tags question: http://stackoverflow.com/q/48394789
tags question: http://stackoverflow.com/q/48391579
tags question: http://stackoverflow.com/q/48461808
tags question: http://stackoverflow.com/q/48366442
tags question: http://stackoverflow.com/q/48432692
tags question: http://stackoverflow.com/q/48362570
tags question: http://stackoverflow.com/q/48461380
tags question: http://stackoverflow.com/q/48391911
tags question: http://stackoverflow.com/q/48374568
tags question: http://stackoverflow.com/q/48351558
tags question: http://stackoverflow.com/q/48361965
tags question: http://stackoverflow.com/q/48481883
tags question: http://stackoverflow.com/q/48375342
tags question: http://stackoverflow.com/q/48361131
tags question: http://stackoverflow.com/q/48372419
tags question: http://stackoverflow.com/q/48371760
tags question: http://stackoverflow.com/q/48352978
tags question: http://stackoverflow.com/q/48464565
tags question: http://stackoverflow.com/q/48418195
tags question: http://stackoverflow.com/q/48385062
tags question: http://stackoverflow.com/q/48363552
tags question: http://stackoverflow.com/q/48348598
tags question: http://stackoverflow.com/q/48426505
tags question: http://stackoverflow.com/q/48459090
tags question: http://stackoverflow.com/q/48360836
tags question: http://stackoverflow.com/q/48331358
tags question: http://stackoverflow.com/q/48390451
tags question: http://stackoverflow.com/q/48339497
tags question: http://stackoverflow.com/q/48359714
tags question: http://stackoverflow.com/q/48385577
tags question: http://stackoverflow.com/q/48460264
tags question: http://stackoverflow.com/q/48432069
tags question: http://stackoverflow.com/q/48395051
tags question: http://stackoverflow.com/q/48348334
tags question: http://stackoverflow.com/q/48366549
type: Tag
tags question: http://stackoverflow.com/q/48462925
tags question: http://stackoverflow.com/q/48391502
tags question: http://stackoverflow.com/q/48403793
tags question: http://stackoverflow.com/q/48404484
tags question: http://stackoverflow.com/q/48468309
tags question: http://stackoverflow.com/q/48465846

http://stackoverflow.com/comment/83722930
has text: Check out the updated code. It works without any errors now. I guess you should consider sticking to just one language as of now in Jupyter
type: Comment
comment on: http://stackoverflow.com/a/48365103
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83913658
type: QuestionComment
has text: @Coldspeed not exactly a dupe, if they are asking about the implementation details
score: 0
comment on: http://stackoverflow.com/q/48460332
type: Comment

http://stackoverflow.com/q/48352341
duplicate of: http://stackoverflow.com/q/48352058
tagged with: tk-toolkit
has comment: http://stackoverflow.com/comment/83698986
has comment: http://stackoverflow.com/comment/83703778
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83698425
tagged with: python
has title: Why is having identical str(object)s as textvariable option to widgets make their texts synchronized?
linked to: http://stackoverflow.com/q/48352058
has comment: http://stackoverflow.com/comment/83701837
has comment: http://stackoverflow.com/comment/83702218
tagged with: tcl
has body: This question made me wonder, what is exactly going on in the code below? import tkinter as tk class MyDot(): def __str__(self): return "." if __name__ == '__main__': root = tk.Tk() my_dot = MyDot() tk.Entry(root, textvariable=root).pack() tk.Label(root, textvariable=my_dot).pack() tk.Button(root, textvariable=".").pack() root.mainloop() Why is having identical str(object)s, as textvariable option to widgets make their texts synchronized?
score: 0
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/83957118
has text: Since you've been a tad faster than me, I'm going to remove my answer. I would only recommend you to replace those variable names with something more readable and sensible, especially since the OP is a newbie.
score: 0
comment on: http://stackoverflow.com/a/48481991
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48380429
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48374469
accepted answer of: http://stackoverflow.com/q/48374469
type: Answer
has body: If you're trying to put the search string into a regex to then do a match, this should do that: import re test_str = ("account" "jones" "Jan" "150 jones" "Feb" "200 jones" "Mar" "140 jones jones") for search_string in ['jo', 'jones']: regex = r'\b{0}\b'.format(search_string) number_of_matches = len(re.findall(regex, test_str)) print(number_of_matches) Haven't been able to test with panda, but should give you enough to work with.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48337339
has body: I have an excel file with 3 columns: id, url1 and url2. Both url1 and url2 contain the URL of an image. How to get the images and paste to WORD and PDF in a table format? There are 3 columns: id, image from url1 and image from url2. import pandas as pd import urllib from docx import Document from docx.shared import Inches df = pd.read_excel('data.xlsx') document = Document() p = document.add_paragraph() r = p.add_run() r.add_picture('a.jpg')#OK url = r'http://www.example.com/a.jpg' r.add_picture(urllib.request.urlopen(url))#fail, how to do it? document.save('demo.docx') Thank you very much.
has answer: http://stackoverflow.com/a/48337718
tagged with: ms-word
linked to: http://stackoverflow.com/q/7391945
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48373692
score: 0
answer count: 2
tagged with: url
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has title: Get photos from URL and paste to WORD or PDF
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python

http://stackoverflow.com/a/48340927
has comment: http://stackoverflow.com/comment/83667105
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83667106
has body: You can do that by comparing each element with which is closer. Is it closer to 1 or 9: a_1 = [i for i in A if abs(i-1)&lt;=abs(i-9)] a_2 = [i for i in A if abs(i-1)&gt;abs(i-9)] But of course this is not a general solution for clustering. It only work in this case when you know the center of the cluster (1 and 9). If you don't know the center of the cluster, I think you should use a clustering algorithm like K-Means This is a simple K-Means implementation (with k=2 and 100 as limit iteration). You didn't need to know the center of the cluster, it picks randomly at first. from random import randint A = [1.0, 1.1, 9.0, 9.2, 0.9, 9.1, 1.0, 1.0, 1.2, 9.2, 8.9, 1.1] x = A[randint(0,len(A)-1)] y = A[randint(0,len(A)-1)] for _ in range(100): a_1 = [i for i in A if abs(i-x)&lt;=abs(i-y)] a_2 = [i for i in A if abs(i-x)&gt;abs(i-y)] print(x,y) x = sum(a_1)/len(a_1) y = sum(a_2)/len(a_2) print a_1 print a_2
has comment: http://stackoverflow.com/comment/83667461
answers question: http://stackoverflow.com/q/48340841
has comment: http://stackoverflow.com/comment/83667191
has comment: http://stackoverflow.com/comment/83667264
has comment: http://stackoverflow.com/comment/83669745

http://stackoverflow.com/q/48403028
downvote count: 0
has comment: http://stackoverflow.com/comment/83794283
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/47152691
possible better answer: http://stackoverflow.com/a/48403093
has answer: http://stackoverflow.com/a/48403142
upvote count: 5
has answer: http://stackoverflow.com/a/48403093
tagged with: python
has body: I have a dataframe which is a list of organisations (multiple rows per organisation) which has a boolean value associated with it. So organisation A has 3 true rows and 3 false i.e. Organisation Value A True A True A False A False A True A False B True B True C False C False I want to get it into the format where I have each organisation listed only once, and the true and false values under the value column as new column headers like this (and then counted): Organisation True False A 3 3 B 2 0 C 0 2 Currently by code is like this: sqlDf.groupby(['Organisation','Value']).size().reset_index(name='counts') But that doesnt do what I need it to do. Any advice?
has title: Python Pandas - Groupby and make column values headers
accepted answer: http://stackoverflow.com/a/48403142
type: AnsweredQuestion
answer count: 2
score: 5
tagged with: pandas

http://stackoverflow.com/comment/83756706
score: 0
comment on: http://stackoverflow.com/q/48384681
type: Comment
type: QuestionComment
has text: That doesn't really answer either of my questions. Is that the result of *multiple REST calls* (in which case you need to rethink how *you're* storing them) or of a single call (in which case you need to complain to whoever maintains the service that they're returning broken JSON)?

http://stackoverflow.com/q/48413726
answer count: 3
has answer: http://stackoverflow.com/a/48413918
has comment: http://stackoverflow.com/comment/83817596
upvote count: 1
has comment: http://stackoverflow.com/comment/83848594
has body: As per this code: # coding=utf-8 import sys import chardet print(sys.getdefaultencoding()) a = 'abc' print(type(a)) print(chardet.detect(a)) b = a.decode('ascii') print(type(b)) c = '中文' print(type(c)) print(chardet.detect(c)) m = b.encode('utf-8') print(type(m)) print(chardet.detect(m)) n = u'abc' print(type(n)) x = n.encode(encoding='utf-8') print(type(x)) print(chardet.detect(x)) I use utf-8 to encode n but the result still show the result is ascii. So I want to know, what is relation between utf-8, ascii and unicode. i run with python2. ===================result================================= =======================end result =============================
has title: Why encoding in utf-8 still results in ascii?
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83818186
tagged with: encoding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83817556
tagged with: python
has comment: http://stackoverflow.com/comment/83817538
has answer: http://stackoverflow.com/a/48414681
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48413804
score: 0
linked to: http://stackoverflow.com/q/2276200

http://stackoverflow.com/comment/83727492
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48359982
type: Comment
has text: Reply to @jshrimp29 The code updates you helped me with are sweet. I am new to coding and I have a lot to learn still. I learn as I go and I never went school for development. I made the updates to each section of my code as you explained in your response. I did not run an insert yet, that is next. One adjustment I had to make was lining the sql line, the for loop for the excel with the rowidx for loop or it would keep looping.

http://stackoverflow.com/a/48429912
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83852461
type: Answer
has comment: http://stackoverflow.com/comment/83850547
answers question: http://stackoverflow.com/q/48429427
has comment: http://stackoverflow.com/comment/83852497
accepted answer of: http://stackoverflow.com/q/48429427
has body: Jean-Fançois's answer is great, but if you're not understanding the fundamentals behind this, you should look into another example that uses lambdas: def returns_function_example(): return lambda arg1: arg1 + 2 function_returned = returns_function_example() print(function_returned(1)) # Output = 3 Run this in your debugger to see that "function_returned" in indeed a function. You can connect the dots after the "print" function is called.

http://stackoverflow.com/q/48436875
tagged with: pygame
has comment: http://stackoverflow.com/comment/83925758
accepted answer: http://stackoverflow.com/a/48443144
score: 2
has answer: http://stackoverflow.com/a/48443144
upvote count: 2
has comment: http://stackoverflow.com/comment/83905094
has comment: http://stackoverflow.com/comment/83894869
downvote count: 0
answer count: 1
has title: Can't move the image with collidepoint(event.pos)?
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I've just recently become interested in pygame and the thing is my code doesn't work as what I intended: the image that I want to move with my mouse doesn't moving at all. So here's mine (contains code from previous question I saw): import pygame,sys,os WHITE = (255,255,255) BLACK = (0,0,0) GREY = (128,128,128) class SilverGeneral: def __init__(self,rect): self.click = False self.rect = pygame.Rect(rect) def update(self,screen): if self.click: self.rect.center = pygame.mouse.get_pos() pygame.init() screen=pygame.display.set_mode([1000,600]) pygame.display.set_caption("Test") silv = SilverGeneral((5,5,40,20)) silv.rect.center=screen.get_rect().center clock = pygame.time.Clock() image = pygame.image.load("c:\game\silvergeneral.bmp").convert() while 1: screen.fill(WHITE) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: print(silv.rect.collidepoint(event.pos)) if silv.rect.collidepoint(event.pos): print("True") silv.click=True elif event.type == pygame.MOUSEBUTTONDOWN: print("False") silv.click=False elif event.type == pygame.QUIT: pygame.quit() sys.exit() print (pygame.mouse.get_pos()) print (silv.rect.center) silv.update(screen) screen.blit(image,silv.rect) clock.tick(10) pygame.display.update() I have been thinking for a whole hour and don't know why the collidepoint(event.pos) doesn't work. Also even if it's tested, the console never prints True.
tagged with: python

http://stackoverflow.com/comment/83857258
comment on: http://stackoverflow.com/q/48432671
type: Comment
score: 1
type: QuestionComment
has text: From the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) you could try `parse_dates`. As a side note: `from datetime import datetime` does _nothing_ by itself to parse dates, it just gives you access to the `datetime` class should you wish to try create a `datetime` object.

http://stackoverflow.com/q/48362692
tagged with: pandas
score: 1
has title: Sample Dataset into equal positive and negative samples
tagged with: dataframe
tagged with: python
has body: I am trying to get a sample of huge dataset where number of +ve samples = num of -ve sample in a memory efficient way. the ratio of data is 4 : 2 +ve to -ve so i am trying to make a sample where the data would be in the ratio of 2 : 2 A B C class 0 0 1 2 0 1 3 4 5 0 2 6 7 8 1 3 9 10 11 1 4 12 13 14 1 5 15 16 17 1 Desired output : A B C class 0 0 1 2 0 1 3 4 5 0 2 6 7 8 1 3 9 10 11 1 I tried to sample it using python code using pandas value_counts func but it is not memory efficient.
has answer: http://stackoverflow.com/a/48362730
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: machine-learning
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48830550
has comment: http://stackoverflow.com/comment/97292597
answers question: http://stackoverflow.com/q/48355918
has comment: http://stackoverflow.com/comment/90941999
has comment: http://stackoverflow.com/comment/95704746
accepted answer of: http://stackoverflow.com/q/48355918
upvote count: 10
score: 10
type: Answer
has body: You can assign the member names to it: fields.String(description='The object type', enum=EnumGender._member_names_)
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83808097
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48409226
has text: Is the channel represented along first or last axis?

http://stackoverflow.com/comment/83774990
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48393590
has text: Are the lines in the text file already sorted by date and time?

http://stackoverflow.com/comment/96211481
type: AnswerComment
has text: Are you sure the data must be *scaled* only and not *normalised*? The two things are different: scaling produces a distribution with zero expectation value and unit standard deviation, normalisation normalises the vectors to have unit norm (the answer that you link to addresses the latter, not the former).
comment on: http://stackoverflow.com/a/48460486
score: 0
type: Comment

http://stackoverflow.com/q/48440514
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: max
tagged with: arrays
has comment: http://stackoverflow.com/comment/83872261
tagged with: python
has body: The documentation on np.argmax() says that it Returns the indices of the maximum values along an axis. The examples given are straightforward: In[1]: a = np.arange(6).reshape(2,3) In[2]: a Out[2]: array([[0, 1, 2], [3, 4, 5]]) In[3]: np.argmax(a) Out[3]: 5 In[4]: np.argmax(a, axis=0) Out[4]: array([1, 1, 1]) In[5]: np.argmax(a, axis=1) Out[5]: array([2, 2]) Except in the case of In[4]: np.argmax(a, axis=0) Out[4]: array([1, 1, 1]) Since 5 corresponds to a[1][2], why is it returning array([1, 1, 1])? Also, if I assign In[6]: b=np.array([[[2,3,4],[4,5,6]],[[3,7,1],[2,5,9]]]) In[7]: b Out[7]: array([[[2, 3, 4], [4, 5, 6]], [[3, 7, 1], [2, 5, 9]]]) and then ask for the maximum value, why do these two return a different value? In[8]: b.max() Out[8]: 9 In[9]: np.argmax(b) Out[9]: 11 Why does np.argmax() return the integer 11, when that number does not even appear in the array?
tagged with: argmax
type: AnsweredQuestion
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/48440562
has title: Python: how to interpret the outcome of np.argmax()?
answer count: 1
has answer: http://stackoverflow.com/a/48440562

http://stackoverflow.com/q/48467518
answer count: 1
tagged with: django
has body: I have two models like this: class Question(models.Model): ques_id = models.IntegerField() test_id = models.ForeignKey('exam.Test') ques = models.TextField() class UserAnswer(models.Model): user = models.ForeignKey('exam.User') test_id = models.ForeignKey('exam.Test') ques_id=models.ForeignKey('exam.Question') user_ans = models.TextField() I need to execute this query to get the correct 'ques' field values. SELECT A.ques_id, B.ques, A.user_ans FROM useranswer A inner join question B on B.ques_id= A.ques_id and B.test_id =A.test_id WHERE A.user_id=1 and B.test_id='101' So far what I have done: UserAnswer.objects.filter(test_id=test_id, user_id=user_id).values('ques_id', 'ques_id__ques','user_ans') But it doesn't returning the right 'ques' field values because it doesn't considering the B.test_id =A.test_id section. How to retrieve it???
type: Question
has answer: http://stackoverflow.com/a/48467725
has title: How to join tables with multiple foreign keys and get filtered data in Django?
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48461568
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48462097
has comment: http://stackoverflow.com/comment/83915992
tagged with: python
score: 4
has title: Finding row in list - python
upvote count: 4
has answer: http://stackoverflow.com/a/48461630
tagged with: list
tagged with: row
linked to: http://stackoverflow.com/q/3462143
answer count: 3
has answer: http://stackoverflow.com/a/48461714
downvote count: 0
has body: I'm comparing two list of the same structure, one with the full dataset, and one with a subset.list_a ist the full list and list_b ist the subset. The result should be a list_c with the rows which are different or not in list_b. for row_a in file_a: for row_b in file_b: if row_a != row_b: file_c.append(row_a) The if statement seams to be wrong as file_c has multiple times the values of file_a and file_b.
favorite count: 0
type: Question

http://stackoverflow.com/a/48424015
answers question: http://stackoverflow.com/q/48420091
downvote count: 1
type: Answer
score: -1
has body: try this one: @api.depends('stock_quant_ids', 'stock_move_ids') def _compute_quantities(self): packs = self.filtered('pack') no_packs = (self + packs.mapped('pack_line_ids.product_id')) - packs res = super(ProductProduct, no_packs)._compute_quantities() for product in packs: pack_qty_available = [] pack_virtual_available = [] for subproduct in product.pack_line_ids: subproduct_stock = res[subproduct.product_id.id] sub_qty = subproduct.quantity if sub_qty: pack_qty_available.append(math.floor( subproduct_stock['qty_available'] / sub_qty)) pack_virtual_available.append(math.floor( subproduct_stock['virtual_available'] / sub_qty)) # TODO calcular correctamente pack virtual available para negativos res[product.id] = { 'qty_available': ( pack_qty_available and min(pack_qty_available) or False), 'incoming_qty': 0, 'outgoing_qty': 0, 'virtual_available': ( pack_virtual_available and max(min(pack_virtual_available), 0) or False), } return res
upvote count: 0

http://stackoverflow.com/a/48459143
score: 0
has comment: http://stackoverflow.com/comment/83937336
has body: You getting frames every 50 ms + processing time, but writing them to video with delay 50ms, so they will be played with higher speed with ratio=(50+processing time)/ 50ms.
has comment: http://stackoverflow.com/comment/83927600
type: Answer
has comment: http://stackoverflow.com/comment/83937309
answers question: http://stackoverflow.com/q/48457948
has comment: http://stackoverflow.com/comment/83930080

http://stackoverflow.com/q/48386479
has comment: http://stackoverflow.com/comment/83760762
tagged with: python
linked to: http://stackoverflow.com/q/1095265
has comment: http://stackoverflow.com/comment/83760679
tagged with: matlab
has comment: http://stackoverflow.com/comment/83760586
has comment: http://stackoverflow.com/comment/83760821
has title: Convert 3D numpy Array in Python to 3D Matrix in Matlab
score: 0
has comment: http://stackoverflow.com/comment/83760670
answer count: 0
tagged with: matrix
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83760514
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10997254
has comment: http://stackoverflow.com/comment/83761141
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83760949
duplicate of: http://stackoverflow.com/q/10997254
has body: Is there a way to convert a 3D numpy Array in Python to a 3D Matrix in Matlab? I only found a way to convert a 2D matrix by saving it as a dictionary using savemat function in scipy.io. But nothing clear about how to covert a 3D numpy Array in Python to a 3D Matrix in Matlab

http://stackoverflow.com/a/48343410
answers question: http://stackoverflow.com/q/48342039
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: One way to solve this problem without accessing the tree of kivy hierarchies is using global variables, but it is advisable not to abuse this type of variables since the errors generated by its misuse are difficult to trace. [...] class Row(BoxLayout): [...] def on_text(self, text_input, value): print('Calling') popup.calculate() class rv(BoxLayout): [...] def add(self): self.mode = "Add" global popup popup = User() popup.open() [...]
type: Answer
accepted answer of: http://stackoverflow.com/q/48342039

http://stackoverflow.com/comment/83852204
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48430297
has text: ... AND..1. These are my fist lines of python ever written, just newbbie concern. 2. The final project is intended to hold several nested collections and i found the referencing/calls redundant. 3. for the same reason, my original idea was to attach a collection of sub objects to the sup class and be able to use sup attributes as an input in sub methods.

http://stackoverflow.com/a/48474875
type: Answer
has comment: http://stackoverflow.com/comment/83987278
has body: Mongoengine doesn't have a "connection" method or object. If you want to connect to database, please use "connect(%database_name%)". Source: http://docs.mongoengine.org/guide/connecting.html#connecting-to-mongodb
answers question: http://stackoverflow.com/q/48474731
score: 0

http://stackoverflow.com/q/48378910
type: Question
upvote count: 2
tagged with: django
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion
has title: Django view to call api
accepted answer: http://stackoverflow.com/a/48378983
has body: So i'm using django view to call api post method but its giving me 400 error As i encounter csrf forbidden error b4, im using the @csrf_exempt for now. I tried doing post method on both the API itself and also using the view to call the api. However when using the view to call, i got 400 error when both are using the same post value to post. Posting using api: QueryDict: {'book': ['Second '], 'author': ['Ban'], 'date': ['2018-01-10 08:00AM']} [22/Jan/2018 18:56:09] "POST /api/test/ HTTP/1.1" 200 61 Posting using view: QueryDict: {} [22/Jan/2018 18:56:12] "POST /api/test/?book=Second+&amp;author=Ban&amp;date=2018-01-10+08%3A00AM HTTP/1.1" 400 36 [22/Jan/2018 18:56:12] "POST /test/ HTTP/1.1" 200 19 Here is my code models.py class TestPost(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48378983
has comment: http://stackoverflow.com/comment/83745276
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/48562338
score: 1
has body: Applying tf.py_func inside ds.map works. I created a very simple file as example. Where I just write 10 inside. dummy_file.txt: 10 Here for the script: import tensorflow as tf filelist = ['dummy_file.txt', 'dummy_file.txt', 'dummy_file.txt'] def py_func(input): # perform operations outside of tensorflow parsed_txt_file = int(input) return 'test', parsed_txt_file def map_element_counts(fname): # let tensorflow read the text file file_string = tf.read_file(fname['filenames']) # then use python function on the extracted string a, b = tf.py_func( func=py_func, inp=[file_string], Tout=[tf.string, tf.int64] ) return {'elementA': a, 'elementB': b, 'file': fname['filenames']} ds = tf.data.Dataset.from_tensor_slices({'filenames': filelist}) ds = ds.map(map_element_counts) element = ds.make_one_shot_iterator().get_next() with tf.Session() as sess: print(sess.run(element)) print(sess.run(element)) print(sess.run(element)) Output: {'file': b'dummy_file.txt', 'elementA': b'test', 'elementB': 10} {'file': b'dummy_file.txt', 'elementA': b'test', 'elementB': 10} {'file': b'dummy_file.txt', 'elementA': b'test', 'elementB': 10}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48471688
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48471688
type: Answer

http://stackoverflow.com/comment/83715667
type: QuestionComment
has text: Then your list comprehension makes no sense.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48364352

http://stackoverflow.com/q/48432038
has comment: http://stackoverflow.com/comment/83855615
has title: Why would importing pandas use up almost all my ram?
has comment: http://stackoverflow.com/comment/84037305
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83855294
tagged with: python
has comment: http://stackoverflow.com/comment/83855539
has comment: http://stackoverflow.com/comment/83856024
score: 0
tagged with: pandas
has body: I'm fairly new to python but I'm pretty sure I didn't get this behaviour before. A couple of days back I've noticed that if I open a new python console and simply do: import pandas as pd Then python.exe ram usage grows steadily in about 5 seconds to reach about 96% utilisation (ie about 15.5G of my 16G total ram). That's not normal, right? I'm using anaconda3 python 3.5 on windows 10....I've updated my conda and pandas but to no avail... Cheers
tagged with: ram
has answer: http://stackoverflow.com/a/48432486
answer count: 1
tagged with: conda
has comment: http://stackoverflow.com/comment/83856090
type: Question

http://stackoverflow.com/q/48471077
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48471262
accepted answer: http://stackoverflow.com/a/48471268
tagged with: django
has answer: http://stackoverflow.com/a/48471268
has comment: http://stackoverflow.com/comment/83957369
possible better answer: http://stackoverflow.com/a/48471262
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83936381
has title: Django - aggregate and annotate for simple operations
tagged with: python
has body: I see in the docs the aggregate and annotate functions can be used to create a new column in the query, so if I write something like: my_object = ...objects.filter(something).annotate(extra_column=Avg(value)) the inner query will give an extra column , AVG(value) AS "extra_column" ... Now, it seems to me that it can be used only will functions like count, avg, max, and min... can I do something as a simple +/- certain number? I'm trying .annotate(extra_column=another_column+1) or .annotate(extra_column='another_column'+1) but it doesn't work. What am I doing wrong? Sorry for the silly question.

http://stackoverflow.com/q/48472784
score: 0
tagged with: byte
upvote count: 1
has comment: http://stackoverflow.com/comment/83939442
has comment: http://stackoverflow.com/comment/83939371
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48473354
has title: Bytes Operation Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/48473354
type: Question
tagged with: operation
has body: I am trying to solve an bytes operation: 0x25 ^ (0xFFFFFFFF &lt;&lt; 1) = 0x87654321 * x I am trying to find the value of x that would make this statement true.
has comment: http://stackoverflow.com/comment/83940220
answer count: 1
has comment: http://stackoverflow.com/comment/83939409
type: AnsweredQuestion

http://stackoverflow.com/comment/83798693
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48405017
has text: This might be a stupid question but should there not be a step in the `dis` where the name is converted to its NFKC form? In other words, should it not take a *tad* longer to define a value like that?

http://stackoverflow.com/q/48365594
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83722729
has title: Can I use Python's Decimal type with NumPy?
tagged with: python
has comment: http://stackoverflow.com/comment/83717818
tagged with: floating-accuracy
has comment: http://stackoverflow.com/comment/83718106
has comment: http://stackoverflow.com/comment/83717799
answer count: 0
score: 1
tagged with: floating-point
has comment: http://stackoverflow.com/comment/83717794
has comment: http://stackoverflow.com/comment/83728110
has comment: http://stackoverflow.com/comment/125835887
has comment: http://stackoverflow.com/comment/83717831
downvote count: 1
has body: I'm doing some calculations with Python3 and NumPy using float64 and sometimes, when I change my formulas a little (but mathematically equivalent), then I get slightly different results. I know that both formulas must produce the same result because they are actually the same, but floating-point calculations have their deficiencies and it shows. That's why I'd like to use Decimal. As an example, the original formula would have the result 8.412265434e-6 and the changed formula would result in 8.412265425e-6 (last two digits are different). The difference is almost meaningless, but annoying (some equality checks do fail and no, I won't compare ± ε). Since my formulas work with rational numbers only (divisions of integers), could I implement the formulas using NumPy and Decimal? If yes, are there things to be careful about? I didn't find anything on the Internet about Decimal + NumPy. EDIT: Should have been more specific... I'm calculating the mutual information of some variables, which requires logarithms (base 2 in my case).
has comment: http://stackoverflow.com/comment/83718308

http://stackoverflow.com/q/48343339
downvote count: 2
answer count: 1
upvote count: 1
tagged with: machine-learning
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48343449
type: UnansweredQuestion
has title: How can I write a python function wrapper, that loads the result if the hash of the input arguments is known?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83673903
has body: Many functions in my machine learning environment are deterministic. Meaning, for the same input they always have exactly the same output. As I often call those function with the same argument, I'd like to automatically detect if the computation was done before. If yes, reload from a pickle file, else calculate and store to a pickle file with the hash of the arguments. How can I implement that? With a wrapper class? A decorator?
has comment: http://stackoverflow.com/comment/83673325
has comment: http://stackoverflow.com/comment/83673296

http://stackoverflow.com/comment/83696398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48354887
has text: yes, I edited the question.
score: 0

http://stackoverflow.com/a/48372112
answers question: http://stackoverflow.com/q/48367060
type: Answer
score: 0
has body: Kv language rule is evaluated before class is initialized (before the __init__ method is executed), therefore the instance attribute does not exist at that moment. The simplest thing is that you use a StringProperty: from kivy.app import App from kivy.config import Config from kivy.uix.boxlayout import BoxLayout from kivy.uix.popup import Popup from kivy.properties import StringProperty Config.set('graphics', 'width', 800) Config.set('graphics', 'height',500) class CustomPopup(Popup): pass class Seleccionador(Popup): idea_texto = StringProperty() # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; def __init__(self, idea, **kwargs): super(Seleccionador, self).__init__(**kwargs) self.idea_texto = idea class Principal(BoxLayout): def abre_popup(self): the_popup = CustomPopup() the_popup.open() def abre_seleccionador(self): idea = 'idea brillante' popin = Seleccionador(idea) popin.open() class KvpopApp(App): title = 'Pruebas de pop up y filechooser' def build(self): return Principal() if __name__ == '__main__': KvpopApp().run()

http://stackoverflow.com/comment/83903378
score: 0
type: QuestionComment
has text: I assume `Process` is using them internally.
type: Comment
comment on: http://stackoverflow.com/q/48455038

http://stackoverflow.com/q/48338183
has comment: http://stackoverflow.com/comment/83662335
type: UnansweredQuestion
tagged with: range
tagged with: python
has title: Map n different values in range [0, 1] to unique integers in range [0, n-1] (used for 0-indexing)
tagged with: indexing
score: 0
tagged with: mapping
answer count: 0
has comment: http://stackoverflow.com/comment/83662239
has comment: http://stackoverflow.com/comment/83664295
has body: Problem statement: We want to map n different values in range [0, 1] to unique integers in range [0, n-1]. E.g., say we have the values 0, 0.05, 0.1, 0.15, where n=4. Multiplying them by 20 yields: 0, 1, 2, 3. Note: In the above example the result are integers, however they do not need to be, e.g. the result 0.5, 1.3, 2.7, 3.8 is also valid because after this mapping we can simply apply floor() to transform them to integers). Goal: This mapping can be used to create integer indices from values between [0,1].
has comment: http://stackoverflow.com/comment/83661559
has comment: http://stackoverflow.com/comment/83664246
type: Question

http://stackoverflow.com/a/48437860
accepted answer of: http://stackoverflow.com/q/48437770
has comment: http://stackoverflow.com/comment/83867450
has body: You need to connect to example database and then create tables and manipulate data. conn = psycopg2.connect(database='example', user='postgres', host='localhost', password='123456')
answers question: http://stackoverflow.com/q/48437770
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/83867468
score: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48389534
score: 5
accepted answer of: http://stackoverflow.com/q/48389486
has body: You are adding " lbs" to the input which makes the variable weight_input "16 lbs". You can add the "lbs" to the message that you display at the end of the loop: while True: weight_input = raw_input ("Add your weight: ") try: val = int(weight_input) except ValueError: print("Insert numbers only") print("Your weight is " + weight_input + " lbs!")
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83774197
answers question: http://stackoverflow.com/q/48389486
upvote count: 5
has comment: http://stackoverflow.com/comment/83766966
type: Answer
has comment: http://stackoverflow.com/comment/83766953

http://stackoverflow.com/a/48399764
downvote count: 0
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/83787565
upvote count: 2
answers question: http://stackoverflow.com/q/48399637
has body: Yes, Make id as None. dp = SomeModel.objects.filter(type="customer").last() dp.id = None dp.save()

http://stackoverflow.com/a/63955740
score: 2
downvote count: 0
has body: You need first to check if you have Pycharm Community or Pycharm Professional. You can plot in different windows just in case you have a professional version. You can use seeting -&gt; scientific python ( link : https://www.jetbrains.com/help/pycharm/matplotlib-support.html ). Or, use matplotlib backends: Qt5Agg, Qt4Agg and TkAgg. (https://intellij-support.jetbrains.com/hc/en-us/community/posts/360004382380-Matplotlib-doesn-t-show-plots-in-new-window ) However, I can suggest you to download your plot in a file and close the window. So, you can have your plots in different windows. Check out this code: file = '___your path___' ... make your code for visualisation plt.show() plt.savefig(file+'\\fig.png') plt.close('all')
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48334853

http://stackoverflow.com/comment/83652671
type: QuestionComment
has text: I'm not 100% on this, but doesn't it mean "infinity"?
type: Comment
comment on: http://stackoverflow.com/q/48333572
score: 1

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/48357969
tag name: countvectorizer

http://stackoverflow.com/q/48463236
score: 0
has comment: http://stackoverflow.com/comment/83919354
tagged with: shell
has body: I am a beginner to python and I have this date and time code from shell script, and how do I make it into python, also how can I take date from last month till now ToDay=`date "+%Y%m%d"` CheckDATE=`date "+%Y-%m-%d" --date '1 day ago'` NOWDATE=`date "+%Y-%m-%d"` This is the python code from datetime import datetime, date, timedelta progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":1},{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":4}]}]}]},\\"scope\\":\\"global\\",\\"size\\":1,\\"from\\":0,\\"sort\\":{\\"create_date\\":{\\"order\\":\\"desc\\"}}}" &gt; ' + ResultDir + 'srciplist-' + ToDay + '.json' ToDay = datetime.now().strftime('%Y%m%d') CheckDATE = datetime.strptime("2017-12-01", "%Y-%m-%d").date() NOWDATE = datetime.now().date() Error: progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\"…
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48463693
accepted answer: http://stackoverflow.com/a/48463693
tagged with: python
has answer: http://stackoverflow.com/a/48463387
possible better answer: http://stackoverflow.com/a/48463387
type: AnsweredQuestion
has title: Converting date and time from shell script into python

http://stackoverflow.com/comment/83810418
comment on: http://stackoverflow.com/q/48410012
type: Comment
has text: @TypeIA I only use it beacuse it is faster in total! I know exactly that when the denominator x is a prime the number of new unique fractions is x-1, so I add it intantly instead of going through another for-loop
score: 0
type: QuestionComment

http://stackoverflow.com/a/48393385
score: 3
has comment: http://stackoverflow.com/comment/83774588
type: Answer
has comment: http://stackoverflow.com/comment/83774826
has comment: http://stackoverflow.com/comment/83774684
has comment: http://stackoverflow.com/comment/83774575
upvote count: 3
answers question: http://stackoverflow.com/q/48393336
downvote count: 0
has body: This is how you'd do it, using sort_values + groupby + head - dfg.sort_values(('rating', 'mean'), ascending=False)\ .groupby(level=0)\ .head(2)\ .sort_index() rating sales mean sum count store product bar B 4.388521 636.813757 1 C 3.931341 1843.772878 1 baz A 2.501077 23110.162196 4 B 3.339784 10610.257660 2 foo B 2.785306 10315.968161 2 D 2.160556 31084.181719 5 The final sort_index call sorts out the index-out-of-order problem (pun intended).
has comment: http://stackoverflow.com/comment/83775016
has comment: http://stackoverflow.com/comment/83777892

http://stackoverflow.com/a/48408216
downvote count: 0
has comment: http://stackoverflow.com/comment/83806029
type: Answer
answers question: http://stackoverflow.com/q/48408062
score: 1
type: AcceptedAnswer
has body: Use tf.cond, not session: def customPool(x): patches = tf.extract_image_patches(x, [1, 2, 2, 1], [1,2,2,1], [1,1,1,1], 'SAME') pred = tf.greater(tf.reduce_max(patches), tf.contrib.distributions.percentile(patches, q=75.)) return tf.cond(pred, lambda: tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME'), lambda: tf.nn.avg_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')) Update: You've also a copy-paste bug: it's conv1 = customPool(conv1) twice in a row, conv2 isn't downsampled, hence the dimensions error.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48408062
has comment: http://stackoverflow.com/comment/83806143
has comment: http://stackoverflow.com/comment/83806610

http://stackoverflow.com/q/48410433
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83810681
has answer: http://stackoverflow.com/a/48411239
has title: Conflicting libraries error in Python
has answer: http://stackoverflow.com/a/48410817
tagged with: google-search-api
tagged with: python
accepted answer: http://stackoverflow.com/a/48410817
has comment: http://stackoverflow.com/comment/83811171
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48411239
tagged with: pycharm
has comment: http://stackoverflow.com/comment/83810822
has body: I'm trying to install a library and run it on PyCharm. Tried to install it through PyCharm but I wasn't able, some error happened: Collecting Google-Search-API Using cached Google-Search-API-1.1.13.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 "/private/var/folders/5t/y8w_0_2j52l866cgl2p2q0nm0000gn/T/pycharm-packaging0.tmp/Google-Search-API/setup.py", line 15, in &lt;module&gt; with open("test_requirements.txt") as f: FileNotFoundError: [Errno 2] No such file or directory: 'test_requirements.txt' Together with the error message there was a sugestion: "Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at '/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5'." Cool. So I went to terminal, did a export PATH=/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5:$PATH to make sure that pip was sending the lib to the right place. After tried pip install Google-Search-API, all seemed alright: MacBook-Air-2:~ santanna_santanna$ pip install Google-Search-API Requirement already satisfied: Google-Search-API in /anaconda/lib/python2.7/site-packages No errors, all cool. So I went back to PyCharm and, as suggested in the [Google-Search-API GitHub][1] typed: import google And got: ImportError: No module named 'google' I've been burning my brains to install that and use on PyCharm. Note: After doing the export PATH=... on terminal I did a which python and the answer terminal gave me was //anaconda/bin/python EDIT Tried sudo /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 -m pip install Google-Search-API and the error I got was very similar to the one on PyCharm: The directory '/Users/santanna_santanna/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions a…
tagged with: conflicting-libraries
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48471964
has title: 404 on slug in django
type: Question
tagged with: slug
accepted answer: http://stackoverflow.com/a/48472062
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83938032
tagged with: django
has comment: http://stackoverflow.com/comment/83937976
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48472062
tagged with: python
has comment: http://stackoverflow.com/comment/83938008
has body: I am following a tutorial where they do something like this: Leave a comment They use slug. I have not been doing that, but have been referencing an ID. The parts of my code which I think are important to this are: films/urls.py: from django.conf.urls import url from django.urls import path from . import views app_name = 'films' urlpatterns = [ path('', views.index, name='index'), url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'), path('films/<int:film_id>/', views.detail, name='detail'), ] films/views.py def add_comment(request, film_id): film = get_object_or_404(Film, pk=film_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit = False) comment.post = post comment.save() return redirect('film:detail',film) else: form = CommentForm() template = 'films/add_comment.html' context = {'form':form} return render (request,template,context) mysite/urls.py: urlpatterns = [ url(r'^accounts/',include('accounts.urls')), url(r'^', include('films.urls')), url(r'^admin/', admin.site.urls), ] add_comment.html: {% extends 'base_layout.html' %} {% block content %} Add Comment {% endblock %} If I click the link I made which is: Leave a comment I get this: And if I manually alter the url to http://127.0.0.1:8000/films/2/comment/ I get this: But it looks like url 3 in that list matches what I typed?

http://stackoverflow.com/q/48373267
type: Question
tagged with: python-3.x
has title: python matplotlib converter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83749826
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83733654
has body: I wrote a program that takes data and plots it via matplotlib. It works no problem on one computer but on the other I get the error: TypeError: Couldn't find foreign struct converter for 'cairo.Context' Traceback (most recent call last): File "/usr/lib/python3.5/idlelib/run.py", line 125, in main seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "/usr/lib/python3.5/queue.py", line 172, in get raise Empty queue.Empty what can I do to get a cairo.Context converter?
tagged with: raspberry-pi3
linked to: http://stackoverflow.com/q/1252163
has comment: http://stackoverflow.com/comment/83735232
has comment: http://stackoverflow.com/comment/83735250

http://stackoverflow.com/a/48521379
has body: This will hopefully get you started: import csv from collections import Counter from datetime import datetime, timedelta with open('test.csv') as f_input: csv_input = csv.reader(f_input) header = next(csv_input) start_time = None thirty_mins = timedelta(minutes=30) cnt = Counter() for row in csv_input: # Convert the first entry into a datetime object dt = datetime.strptime("{} {:06}".format(row[0], int(row[1]) * 1000), '%Y-%m-%d %H:%M:%S %f') if start_time == None: start_time = dt if dt &gt;= start_time + thirty_mins: for (dept, type), count in cnt.items(): print('{} {:03},{},{},{}'.format(start_time.strftime('%Y-%m-%d %H:%M:%S'), start_time.microsecond//1000, dept, type, count)) start_time += thirty_mins cnt = Counter() if row[4] == "m": cnt[row[2], row[3]] += 1 for (dept, type), count in cnt.items(): print('{} {:03},{},{},{}'.format(start_time.strftime('%Y-%m-%d %H:%M:%S'), start_time.microsecond//1000, dept, type, count)) The idea is to convert the times into a datetime object. With that you can determine if a row falls within the next 30 minutes boundary. Your second column appears to contain milliseconds. The datetime format uses microseconds so this needs to be converted and added. Read each row and convert the time. Next determine if we have gone passed a 30 minute boundary. If so display the counter values for that boundary and reset the counter. Advance the time boundary by 30 minutes. Otherwise if the row is male, add to the counter. At the end, print any remaining entries for the last boundary. For the example you have given, this would give you: 2017-09-07 14:46:14 018,management,b,1 2017-09-07 14:46:14 018,it,a,1 2017-09-07 15:16:14 018,marketing,c,1 2017-09-07 15:46:14 018,it,a,2 2017-09-07 16:16:14 018,marketing,c,1 2017-09-07 16:46:14 018,management,c,1 2017-09-07 17:46:14 018,management,a,1 2017-09-07 18:16:14 018,marketing,b,1 2017-09-07 18:46:14 018,marketing,a,1 Note, some boundaries contain no entries.
score: 0
answers question: http://stackoverflow.com/q/48473602
type: Answer

http://stackoverflow.com/q/48386578
favorite count: 0
has answer: http://stackoverflow.com/a/48387056
has comment: http://stackoverflow.com/comment/83760983
answer count: 1
has body: I'm trying to splice my data from my text-file and instead of returning a specific column it returns all my data. It might possibly be a syntax error but I can't seem to google what I'm doing wrong. For example I have: x y 1 2 2 4 3 6 and after splicing I receive '1 2\n 2 4\n 3 6\n' in the variable I'm storing instead of just '1 2 3' Which is what I want I've been trying to do this: data = open('file').read() x = data[1:][2:]
type: Question
tagged with: python-3.x
downvote count: 4
has title: Splicing Amount of Data From Text File Into Array
upvote count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/83761243

http://stackoverflow.com/a/50297495
answers question: http://stackoverflow.com/q/48433578
type: Answer
accepted answer of: http://stackoverflow.com/q/48433578
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: I've solved it tweaking the blueprint bp = Blueprint(name='myblueprint', import_name=__name__, static_folder='static/myblueprint', template_folder='templates', static_url_path='/static', # this is what myblueprint.static will point to url_prefix='/myblueprint', subdomain=None, url_defaults=None, root_path=None) With this, my static paths inside the blueprint will point to /myblueprint/static, and I will need to modify my create-react-app build folder. replace calls to static in every *.css, *.js and .html in /build to /myblueprint/static rearrange folders inside /build to match my blueprint static folder. Move /build/static to /blueprint/static Set my own jinja template in /blueprint/templates/index.html that calls these files. Make sure this file points to the static assets in /myblueprint/static and not to /build/static. I've created a gulpfile that will automate this process, var gulp = require('gulp'); var replace = require('gulp-replace'); var rename = require('gulp-rename'); // script to deploy react build into flask blueprint directory // it replaces values and folder names // README // how to use this: // in the react app, run npm run build // copy the resulting /build folder in /myblueprint // create a template of a template in /templates/base as index.default.html // install gulp, gulp-replace, gulp-rename // run gulp from /myblueprint // replace routes inside css files gulp.task('othertemplates', function(){ gulp.src(['./build/static/css/main.*.css']) .pipe(replace('url(/static/media/', 'url(/myblueprint/static/media/')) .pipe(gulp.dest('static/myblueprint/css/')); }); // replace routes inside js files gulp.task('jsthingtemplates', function(){ gulp.src(['./build/static/js/main.*.js']) .pipe(replace('static/media/', 'myblueprint/static/media/')) .pipe(gulp.dest('static/myblueprint/js/')); }); // move other files gulp.task('mediastuff', function(){ gulp.src(['./build/static/media/*']) .pipe(gulp.dest('static/myblueprint/media/')); gulp.src(['./build/asset-m…

http://stackoverflow.com/q/48400491
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48400959
favorite count: 0
type: Question
has body: I'm reading an excel sheet from an excel and I need to store that data as json in HDFS. For some sheets I'm facing the exception excel_file = pd.ExcelFile("export_n_moreExportData10846.xls") for sheet_name in excel_file.sheet_names: df = pd.read_excel(excel_file, header=None, squeeze=True, sheet_name=sheet_name) if sheet_name=='Passed': print '**************' + sheet_name + '******************' for i, row in df.iterrows(): data = df.iloc[(i+1):].reset_index(drop=True) data.columns = pd.Series(list(df.iloc[i])).str.replace(' ','_') break for c in data.columns: data[c] = pd.to_numeric(data[c], errors='ignore') print data #I'm able to print the data result1 = sparkSession.createDataFrame(data) #Facing the exception here print "inserting data into HDFS..." result1.write.mode("append").json(hdfsPath) print "inserted data into hdfs" I'm facing the below exception raise TypeError("Can not merge type %s and %s" % (type(a), type(b))) TypeError: Can not merge type &lt;class 'pyspark.sql.types.StringType'&gt; and &lt;class 'pyspark.sql.types.DoubleType'&gt; Image shows the data
has comment: http://stackoverflow.com/comment/83789498
tagged with: pyspark
tagged with: hdfs
has answer: http://stackoverflow.com/a/48400959
tagged with: python
has comment: http://stackoverflow.com/comment/83791785
type: AnsweredQuestion
has title: Exception while reading an excel sheet
tagged with: pandas
upvote count: 1
score: 1

http://stackoverflow.com/comment/83740078
type: Comment
comment on: http://stackoverflow.com/a/48334763
type: AnswerComment
has text: `with open("logs.txt", "a+") as fd: for entry in driver.get_log('browser'): log = entry print entry print "\n" if log['source'] == 'network': fileData["logError"] = log['message'] if log['source'] == 'javascript': fileData["logError"] = log['message'] fd.seek(0) fd.write(json.dumps(fileData)) fd.write("\n")`
score: 0

http://stackoverflow.com/comment/84016933
type: Comment
score: 0
has text: However it seems as a promising solution, after reading more on alembic docs and learning about the Config object and attributes. something may be missing here
type: AnswerComment
comment on: http://stackoverflow.com/a/48501417

http://stackoverflow.com/comment/83790136
has text: yes, you're absolutely right !! but it also works without it.
type: Comment
comment on: http://stackoverflow.com/a/48399584
type: AnswerComment
score: 0

http://stackoverflow.com/q/48455042
has comment: http://stackoverflow.com/comment/83903173
has body: With this test code on python 3.6.3 tkinter.Tcl().eval('info patchlevel') returns '8.6.6' My OS is Mint 18.3 Cinnamon 3.6.7, but I want my code to be crossplatform. I use the console to run the script: from tkinter import * from tkinter import ttk def valid(*args): print("Dans valid", nom.get()) root.quit() root = Tk() rootW = 300 rootH = 200 x = (root.winfo_screenwidth() - rootW)//2 y = (root.winfo_screenheight() - rootH)//2 root.geometry(f'{rootW}x{rootH}+{x}+{y}') mainFrame = ttk.Frame(root, padding="5") mainFrame.grid(column=0, row=0, sticky=(N, W, E, S)) mainFrame.columnconfigure(0, weight=1) mainFrame.rowconfigure(0, weight=1) nom = StringVar() nomEntry = ttk.Entry(mainFrame, width=20, textvariable=nom) nomEntry.grid(column=2, row=2, sticky=(E)) ttk.Label(mainFrame, text="Inscription").grid(column=2, row=1, sticky=W) ttk.Label(mainFrame, text="Votre nom").grid(column=1, row=2) ttk.Button(mainFrame, text="Validation", command=valid).grid(column=2, row=3, sticky=W) for child in mainFrame.winfo_children(): child.grid_configure(padx=5, pady=5) nomEntry.focus() #root.update_idletasks() root.overrideredirect(1) root.mainloop() root.destroy() I want to use a tkinter window that removes all window manager decorations from that window with overrideredirect() method. In this case, I don't have any more decoration, but I am no longer able to access the Entry field, while the "Validation" button is operational and exits the window. If I comment the line root.overrideredirect(1) everything works normally, with decoration. I tried adding the line root.update_idletasks(), but it doesn't change my problem: it's ok but with decorations. How do I get an operational window without decorations?
type: Question
has comment: http://stackoverflow.com/comment/83903940
linked to: http://stackoverflow.com/q/39529600
has comment: http://stackoverflow.com/comment/83916722
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/48478829
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83914354
has comment: http://stackoverflow.com/comment/83916977
has comment: http://stackoverflow.com/comment/83903135
has comment: http://stackoverflow.com/comment/83927633
score: 0
has title: Windows without decorations
has comment: http://stackoverflow.com/comment/83903345
has answer: http://stackoverflow.com/a/48455905

kivy
tags question: http://stackoverflow.com/q/48481671
tags question: http://stackoverflow.com/q/48342039
tags question: http://stackoverflow.com/q/48349812
type: Tag
tags question: http://stackoverflow.com/q/48467917
tags question: http://stackoverflow.com/q/48367060
tags question: http://stackoverflow.com/q/48484885
tag name: kivy
tags question: http://stackoverflow.com/q/48351129
tags question: http://stackoverflow.com/q/48480913
tags question: http://stackoverflow.com/q/48376058
tags question: http://stackoverflow.com/q/48398104
tags question: http://stackoverflow.com/q/48453695
tags question: http://stackoverflow.com/q/48439807
tags question: http://stackoverflow.com/q/48373755
tags question: http://stackoverflow.com/q/48485131
tags question: http://stackoverflow.com/q/48450867
tags question: http://stackoverflow.com/q/48382245
tags question: http://stackoverflow.com/q/48403987
tags question: http://stackoverflow.com/q/48368463
tags question: http://stackoverflow.com/q/48356191
tags question: http://stackoverflow.com/q/48481941
tags question: http://stackoverflow.com/q/48333043
tags question: http://stackoverflow.com/q/48344991
tags question: http://stackoverflow.com/q/48487175
tags question: http://stackoverflow.com/q/48469736
tags question: http://stackoverflow.com/q/48395202
tags question: http://stackoverflow.com/q/48428508
tags question: http://stackoverflow.com/q/48386125
tags question: http://stackoverflow.com/q/48486807
tags question: http://stackoverflow.com/q/48398900
tags question: http://stackoverflow.com/q/48362622
tags question: http://stackoverflow.com/q/48476595
tags question: http://stackoverflow.com/q/48477845
tags question: http://stackoverflow.com/q/48349779
tags question: http://stackoverflow.com/q/48462057
tags question: http://stackoverflow.com/q/48414538
tags question: http://stackoverflow.com/q/48368186
tags question: http://stackoverflow.com/q/48347569
tags question: http://stackoverflow.com/q/48453816
tags question: http://stackoverflow.com/q/48357972
tags question: http://stackoverflow.com/q/48438074
tags question: http://stackoverflow.com/q/48426128
tags question: http://stackoverflow.com/q/48400885
tags question: http://stackoverflow.com/q/48436742

http://stackoverflow.com/comment/83703360
score: 0
has text: Because problem seems in data. so is possible send me your file to my email in my profile?
type: Comment
comment on: http://stackoverflow.com/a/48357090
type: AnswerComment

http://stackoverflow.com/a/48433229
downvote count: 0
has body: When you do: def pictures(): you're redefining the variable pictures. It now names the function, not the class that was defined earlier. Give the function a name that doesn't conflict with the class, e.g. def show_pictures(): Also, in the last function you use pictures.pictures. That should be pictures.picture. After you fix those, this line is wrong: pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1 animal_pics is a list, you can't use it as a dictionary key. I think you meant: pictures.picture[str_animal] += 1
answers question: http://stackoverflow.com/q/48433207
score: 3
has comment: http://stackoverflow.com/comment/83858696
has comment: http://stackoverflow.com/comment/83858746
type: Answer
upvote count: 3

http://stackoverflow.com/q/48362837
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/48367542
has answer: http://stackoverflow.com/a/48367542
tagged with: python
has comment: http://stackoverflow.com/comment/83720341
tagged with: image
tagged with: stereoscopy
score: 2
type: AnsweredQuestion
has body: I recently completed some Python (2.7) code for generating random dot stereograms based on this paper. The output is fairly good, though I have noticed that, even with a smooth gradient in the depth map, the output stereogram lacks these smooth gradients, instead having varying levels of depth. I believe this to be due to the DPI chosen when generating the image. While the detail of the depth can be increased by increasing the DPI, this becomes impractical as the convergence point becomes more difficult to reach. Here are two examples. First at 75 DPI and second at 175 DPI. On the 75 DPI image, distinct "triangles" of depth can be seen. In the 175 DPI image, these are less pronounced but the guidance dots at the bottom of the image are further apart, and therefore viewing the 3D image is more difficult. I'm looking to modify my current code to anti-alias the 3D image in order to smooth out the gradients even with a lower DPI. I have tried using SSAA on the depth map and pattern and generating the stereogram, then reducing the image size again with an antialiasing filter. However this seems to just contain the stereogram to the left of the image. For example, if I make the image 4 times bigger, the stereogram is limited to the left hand quarter of the image. The rest is just random noise and cannot be viewed. How would I go about antialiasing the image hidden in the stereogram? My code is almost the same as the algorithm described in the paper, so an antialiasing algorithm based on that would be perfect.
has comment: http://stackoverflow.com/comment/83722877
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83712683
tagged with: antialiasing
has comment: http://stackoverflow.com/comment/83795567
favorite count: 0
type: Question
has title: Anti-aliasing of random dot stereograms
upvote count: 2

http://stackoverflow.com/comment/83681925
comment on: http://stackoverflow.com/q/48347497
type: Comment
type: QuestionComment
has text: @Alex @ayhan I've edited the expected output. Essentially, `es` and `gb` would appear before `us`.
score: 0

http://stackoverflow.com/a/48359717
has comment: http://stackoverflow.com/comment/83726511
answers question: http://stackoverflow.com/q/48359581
type: Answer
score: 0
has body: you have to use self in the method definition and in calling the methods inside the class. here is the fixed code: import random class Enemy: def __init__(self): self.life = 20 def attack(self,gun): if (self.life &lt;= 0): print("Dead") else: if gun is "AK47": self.life = self.life - 5 self.life_left(self.life) elif gun is "Magnum": self.life = self.life - 4 self.life_left(self.life) else: self.life = self.life - 1 self.life_left(self.life) def life_left(self,life): print ("Life : " , str(life)) def start(players): a = 1 arr = [] while a &lt;= players: arr.append("player" + str(a)) arr[a-1] = Enemy() #print (arr[a-1]) a += 1 enemy = int(input("How many times do you want them to fight ? ")) fight = 1 guns = ["AK47" , "Magnum" , "other"] while fight &lt;= enemy: number = random.randint(0,players-1) guns_number = random.randint(0,len(guns)-1) arr[number].attack(guns[guns_number]) fight += 1 start(7)
has comment: http://stackoverflow.com/comment/83725692

http://stackoverflow.com/comment/83800704
score: 0
has text: i suspect you need to extract the whole array, modify the value, and reset the whole thing.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48402613

c++
tags question: http://stackoverflow.com/q/48473513
tags question: http://stackoverflow.com/q/48444655
tags question: http://stackoverflow.com/q/48455182
tags question: http://stackoverflow.com/q/48384209
tags question: http://stackoverflow.com/q/48436380
tags question: http://stackoverflow.com/q/48391959
tags question: http://stackoverflow.com/q/48357855
tags question: http://stackoverflow.com/q/48390703
tags question: http://stackoverflow.com/q/48487171
tags question: http://stackoverflow.com/q/48353656
tags question: http://stackoverflow.com/q/48367649
tags question: http://stackoverflow.com/q/48391926
tags question: http://stackoverflow.com/q/48459985
tags question: http://stackoverflow.com/q/48482702
tags question: http://stackoverflow.com/q/48436078
tags question: http://stackoverflow.com/q/48372537
tags question: http://stackoverflow.com/q/48333362
type: Tag
tags question: http://stackoverflow.com/q/48367659
tags question: http://stackoverflow.com/q/48411287
tags question: http://stackoverflow.com/q/48367819
tags question: http://stackoverflow.com/q/48442308
tag name: c++
tags question: http://stackoverflow.com/q/48432577
tags question: http://stackoverflow.com/q/48407081

http://stackoverflow.com/comment/83729248
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48370962
score: 0
has text: @cricket_007, Thank you for the advises. The type of the json is <class 'dict'>

http://stackoverflow.com/comment/83773896
type: Comment
type: QuestionComment
has text: The behavior on fork seems reasonable to me. My primary concern is why on import numpy has so much memory allocated to the process by default. I think this feature of numpy would make it so that spawning would have the same effect, no? Your advice to raise ticket is good idea I will do that.
comment on: http://stackoverflow.com/q/48392773
score: 0

http://stackoverflow.com/q/48404263
has body: As much as this may sound like a simple task, I have not encountered a way to do it though the documentation. After running an arbitrary routine (such as one of these examples, I get something like &gt;&gt;&gt; print(est_gp) sqrt(div(add(1.000, sub(div(sqrt(log(0.978)), X0), mul(-0.993, X0))),add(-0.583, 0.592))) How do I (or can I even) convert this to an expression that can be used outside gplearn, like a sympy expression?
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48414315
accepted answer: http://stackoverflow.com/a/48414315
upvote count: 8
favorite count: 0
type: Question
tagged with: gplearn
has answer: http://stackoverflow.com/a/52996766
possible better answer: http://stackoverflow.com/a/52996766
tagged with: python
score: 8
type: AnsweredQuestion
has title: How to export the output of gplearn as a sympy expression or some other readable format?
answer count: 2
tagged with: sympy
tagged with: symbolic-math

http://stackoverflow.com/q/48436742
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/48464915
accepted answer: http://stackoverflow.com/a/48439992
type: AnsweredQuestion
score: 0
has title: How can I put a button to be always in the center and bottom of my App?
type: Question
has body: I'd like to put an 'Update Button' in the center and bottom of my app, but I also need to add some widgets in the screen. I put a BoxLayout to be always in the center and bottom of my app, but I need to put a Button inside it and it has to be always in the BoxLayout center bottom too. What I did: My .kv source code: &lt;WindowMain&gt;: orientation: 'horizontal' BoxLayout: orientation: 'vertical' size_hint: .1, .1 pos_hint: {"x":1., "bottom":1.} padding: 2 Button: size_hint: .2, 1. pos_hint: {'x': .5, 'y': 1.} font_name: 'consola' text: 'Update'
tagged with: android-layout
answer count: 2
has answer: http://stackoverflow.com/a/48439992
tagged with: android
possible better answer: http://stackoverflow.com/a/48464915

http://stackoverflow.com/comment/83900557
has text: I'd recommend looking up an example of `or` before using it, the commas are invalid. Remove them, after that you will won't get respected results because it separates conditions (ex: `"-"` by itself is always true). But you don't need those conditions, just make the other items into `elseif` and change your `elseif` to `else`.
comment on: http://stackoverflow.com/q/48453769
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/71993736
has comment: http://stackoverflow.com/comment/127282574
has body: Since this is the top Google result for Python Multiprocessing Queue implementation I'm going to post a slightly more generalized example. Consider the following script: import time import math import pprint def main(): print('\n' + 'starting . . .' + '\n') startTime = time.time() my_list = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] result_list = [] for num in my_list: result_list.append(squareNum(num)) # end for elapsedTime = time.time() - startTime print('result_list: ') pprint.pprint(result_list) print('\n' + 'program took ' + '{:.2f}'.format(elapsedTime) + ' seconds' + '\n') # end function def squareNum(num: float) -&gt; float: time.sleep(1.0) return math.pow(num, 2) # end function if __name__ == '__main__': main() This script declares 10 floats, squares them (sleeping for 1 second upon each square to simulate some significant process), then collects the results in a new list. This takes about 10 seconds to run. Here is a refactored version using Multiprocessing Process and Queue: from multiprocessing import Process, Queue import time import math from typing import List import pprint def main(): print('\n' + 'starting . . .' + '\n') startTime = time.time() my_list = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] result_list = [] multiProcQueue = Queue() processes: List[Process] = [] for num in my_list: processes.append(Process(target=squareNum, args=(num, multiProcQueue,))) # end for for process in processes: process.start() # end for for process in processes: process.join() # end for while not multiProcQueue.empty(): result_list.append(multiProcQueue.get()) # end for elapsedTime = time.time() - startTime print('result_list: ') pprint.pprint(result_list) print('\n' + 'program took ' + '{:.2f}'.format(elapsedTime) + ' seconds' + '\n') # end function def squareNum(num: float, multiProcQueue: Queue) -&gt; None: time.sleep(1.0) result = math.pow(num, 2) multiProcQueue.put(result) # end function if __name__ == '__main__': main() This script runs in abou…
answers question: http://stackoverflow.com/q/48363237
type: Answer
score: 0

http://stackoverflow.com/q/48421712
has title: My program is giving more than one result when it should only give one?
has answer: http://stackoverflow.com/a/48421805
has comment: http://stackoverflow.com/comment/83832833
type: AnsweredQuestion
score: 0
has body: I have written this scissors paper rock game in python, sometimes it works perfectly but other times it prints more than one result. For example it will say that you tied and then also that you won and sometimes it will also say that you lost. This is not dependent on the actual outcome though and it seems completely random, please help! while True: import time print('Scissors ') time.sleep(1) print(' paper') time.sleep(1) print(' rock!') choice = input() if choice not in ('rock', 'paper', 'scissors'): print('Invalid Input') import random RPS = ['rock', 'paper', 'scissors']#BOT CHOICE #TIE TIE = ['The bot also chose ' + choice, 'It is a tie!', 'TIE!'] #WIN RWIN = ['The bot chose scissors, but you smashed them with your rock!', 'YOU WIN!', 'Your rock beat the bots scissors'] PWIN = ['The bot chose rock, but you smothered it with your paper', 'YOU WIN!', 'Your paper beat the bots rock'] SWIN = ['The bot chose paper but you cut it to bits!', 'YOU WIN', 'Your scissors beat the bots paper!'] #LOSS RLOSS = ['The bot chose paper and smotherd your rock :(', 'You loose...', 'Nice try but you lost...better luck next time'] PLOSS = ['The bot chose scissors and chopped your paper to bits :(', 'You loose...', 'Nice try but you lost...better luck next time'] SLOSS = ['The bot chose rock and smashed your scissors :(', 'You loose...', 'Nice try but you lost...better luck next time'] #TIE if choice ==(random.choice(RPS)): print(random.choice(TIE)) #WIN #ROCK if choice =='rock' and (random.choice(RPS)) =='scissors': print(random.choice(RWIN)) #PAPER if choice =='paper' and (random.choice(RPS)) =='rock': print(random.choice(PWIN)) #SCISSORS if choice =='scissors' and (random.choice(RPS)) =='paper': print(random.choice(SWIN)) #LOSS #ROCK if choice =='rock' and (random.choice(RPS)) =='paper': print(random.choice(RLOSS)) #PAPER if choice =='paper' and (random.choice(RPS)) =='scissors': print(random.choice(PLOSS)) #SCISSORS if choice =='scissors' and (random.choice(RPS)) =='rock': print(r…
has answer: http://stackoverflow.com/a/48421821
possible better answer: http://stackoverflow.com/a/48421805
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/48421831
has answer: http://stackoverflow.com/a/48421794
tagged with: python
accepted answer: http://stackoverflow.com/a/48421794

http://stackoverflow.com/comment/83949235
comment on: http://stackoverflow.com/a/48445249
score: 0
type: Comment
has text: Hi @Thomas Jiang, I implemented as suggested. please check urls.py path('sale/<int:pk>/', views.retrieve_update_delete_sale, name='retrieve_update_delete_sale'), html --> Reverse for 'retrieve_update_delete_sale' with no arguments not found. 1 pattern(s) tried: ['geo_gas\\/sale\\/(?P<pk>[0-9]+)\\/$']
type: AnswerComment

http://stackoverflow.com/q/48460391
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83914068
has answer: http://stackoverflow.com/a/48460732
has answer: http://stackoverflow.com/a/48460651
has body: I have a list of strings with items looking like "{name, 'test1'}" or '{name, "test1"}' (note the single/double quotes around test1). list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}'] How can I filter the list for the "test" strings, that is I want: final_list = ['test1', 'test2', 'test3', 'test4']
score: -3
has title: How to filter a list using a regular expression?
tagged with: python
has comment: http://stackoverflow.com/comment/83913802
has answer: http://stackoverflow.com/a/48460691
accepted answer: http://stackoverflow.com/a/48460691
has comment: http://stackoverflow.com/comment/83913989
downvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48460651
linked to: http://stackoverflow.com/q/1059559
answer count: 3
has comment: http://stackoverflow.com/comment/83913754
upvote count: 1

http://stackoverflow.com/comment/83932563
score: 1
type: Comment
has text: Just a note: `print("")` works in Python2 and Python3. `print ""` only works in Python2
type: AnswerComment
comment on: http://stackoverflow.com/a/48469367

stdin
tags question: http://stackoverflow.com/q/48400175
tag name: stdin
type: Tag
tags question: http://stackoverflow.com/q/48371780

http://stackoverflow.com/comment/83652417
score: 0
comment on: http://stackoverflow.com/q/48333346
type: Comment
has text: Possible duplicate of https://stackoverflow.com/questions/132318/how-do-i-correct-the-character-encoding-of-a-file
type: QuestionComment

http://stackoverflow.com/a/61101626
score: 0
type: Answer
has body: Debian »Buster« with CUDA 10.2 (and pip3 instead conda) numba -s … CUDA libraries: Finding cublas ERROR: can't locate lib Finding cusparse ERROR: can't locate lib Finding cufft ERROR: can't locate lib Finding curand ERROR: can't locate lib Finding nvvm ERROR: can't locate lib finding libdevice for compute_20... ERROR: can't open libdevice for compute_20 finding libdevice for compute_30... ERROR: can't open libdevice for compute_30 finding libdevice for compute_35... ERROR: can't open libdevice for compute_35 finding libdevice for compute_50... ERROR: can't open libdevice for compute_50 … then a manual sudo ln -sv /usr/lib/x86_64-linux-gnu/libcublas.so.10 /usr/local/cuda/lib64/ export NUMBAPRO_CUDALIB=/usr/local/cuda/lib64/ export NUMBAPRO_LIBDEVICE=/usr/local/cuda/nvvm/libdevice/ export NUMBAPRO_NVVM=/usr/local/cuda/nvvm/lib64/libnvvm.so and we get numba -s … CUDA libraries: Finding cublas named libcublas.so.10 trying to open library... ok Finding cusparse named libcusparse.so.10.3.1.89 trying to open library... ok Finding cufft named libcufft.so.10.1.2.89 trying to open library... ok Finding curand named libcurand.so.10.1.2.89 trying to open library... ok Finding nvvm named libnvvm.so trying to open library... ok finding libdevice for compute_20... ok finding libdevice for compute_30... ok finding libdevice for compute_35... ok finding libdevice for compute_50... ok …
answers question: http://stackoverflow.com/q/48385686

http://stackoverflow.com/comment/83847023
type: Comment
type: AnswerComment
has text: True, @Zero that is a nicer way to do it
comment on: http://stackoverflow.com/a/48428194
score: 0

http://stackoverflow.com/comment/83940707
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48473457
has text: Where can I find the exact function that python uses to computer pow(a,b) ?
score: 0

http://stackoverflow.com/comment/83751310
type: QuestionComment
type: Comment
has text: I edited the question
score: 0
comment on: http://stackoverflow.com/q/48382047

multidispatch
tag name: multidispatch
type: Tag
tags question: http://stackoverflow.com/q/48483650

http://stackoverflow.com/q/48452708
has body: I have a process that receives nested dictionaries in Python: Example Nested Dictionary Schema (pseudocode) key1: value1, key2: dict( key3: value2, key4: value3, ), key5: list(value4,value5) # any value is fine, just not empty or null Example Nested Dictionary Data (pseudocode) key1: 'value', key2: dict( key3: '', key4: 12345, ), key5: list() I want to iterate over/scan this dict and check if each key has a value (is not Null or blank - false/0 are ok). I will need to scan a bunch of identical dicts to get an overall "fill rate" for that set of dicts. The process sees sets of dicts with different formats every time it's run, so it needs to automatically generate the fill rate report: Example Fill Rate for the Single Nested Example Above (ideally a flat dict): key1: 1 key2: 1 key2-key3: 0 key2-key4: 1 key5: 0 If we scanned ten dicts of the same structure, for example, we might see a :fill rate" like this: key1: 5 key2: 6 key2-key3: 6 key2-key4: 4 key5: 3 Questions What is the most pythonic way to scan dicts of varying structure to gen a fill rate? Is there a more efficient way if I have to do this millions of times? What is the most pythonic way to create a flat dict to store the counts and how do I update it?
has answer: http://stackoverflow.com/a/48452912
type: Question
has answer: http://stackoverflow.com/a/48457627
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48453025
has comment: http://stackoverflow.com/comment/83898743
has title: Gen Fill Rates on Varying Nested Dictionaries in Python?
tagged with: loops
has answer: http://stackoverflow.com/a/48453348
favorite count: 0
has comment: http://stackoverflow.com/comment/83898607
score: 1
tagged with: python
tagged with: counting
answer count: 4

http://stackoverflow.com/comment/83659269
has text: Probably an issue with the string formatting as here https://stackoverflow.com/a/5082482/4132383 Have you tried to print without formatting as in the softmax tutorial?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48335132
score: 0

http://stackoverflow.com/comment/83734527
type: QuestionComment
comment on: http://stackoverflow.com/q/48373506
has text: So, what you're "complaining" is that python can't find an error unles that part of the code is run. I thought this was a feature rather than a bug.
type: Comment
score: 0

http://stackoverflow.com/a/48471133
upvote count: 1
answers question: http://stackoverflow.com/q/48471093
has body: The SessionAuthenticationMiddleware class has been removed - session authentication was unconditionally enabled in 1.10. (see: https://docs.djangoproject.com/en/2.0/releases/2.0/#miscellaneous) i.e. yes, it should come after AuthenticationMiddleware
type: Answer
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48471093
downvote count: 0

http://stackoverflow.com/comment/83824804
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48416307
has text: What's self.batch_size? are you sure dataA and dataB aren't empty?
score: 0

http://stackoverflow.com/a/48419770
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48419408
has body: You can just sample from a normal distribution with mean 0 and then move the value to the new mean. Cleaning and improving your code slightly, it should look like this. # We create all new (x,y) in one go rand_x = numpy.random.normal(0, std_deviation_x, len(pixels)) rand_y = numpy.random.normal(0, std_deviation_y, len(pixels)) for i in range(len(pixels)): x, y = pixels[i] # using unpacking # now we shift the mean new_x = x + rand_x[i] new_y = y + rand_y[i] # reasignment pixels[i][0] = new_x pixels[i][1] = new_y For sure this can further improved and made more optimal, there are still quite some superfluous assignments.

http://stackoverflow.com/comment/83822157
comment on: http://stackoverflow.com/a/48406150
score: 0
type: Comment
type: AnswerComment
has text: Thanks for your answer. But your previous answer seems more suitable to me as I don't want to use Pandas. I am posting my answer too. Let it be if somebody wants to do the same by using Pandas then your answer can help.

cognos-tm1
type: Tag
tags question: http://stackoverflow.com/q/48383314
tag name: cognos-tm1

http://stackoverflow.com/a/48424787
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48424673
accepted answer of: http://stackoverflow.com/q/48424673
has body: I think you need cumcount for Counter for new indices. Also is possible use parameter names in read_csv, so then is not necessary assign list later: df = pd.read_csv('thing.ical', sep=":", names=['cols', 'vals'], skiprows=6) print (df) df = pd.pivot(index=df.groupby('cols').cumcount(), columns=df['cols'], values=df['vals'])
score: 1

http://stackoverflow.com/comment/83967803
has text: Seems very interesting, I don't have a nVidia GPU on my machine, but I'll test asap. (or is it supposed to work with Radeon? - I have the same performance as numpy with MKL)
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48482089
type: Comment

http://stackoverflow.com/comment/83819035
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48414513
has text: Your function does not return anything. It does not have a `return` statement. `print(converter(10,'in','cm'))` always prints `None`.

http://stackoverflow.com/comment/83882517
has text: I missed the 3 previously
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48444800
score: 0

http://stackoverflow.com/a/48361639
has comment: http://stackoverflow.com/comment/83754704
has body: If you're getting ready to overlay widgets, you could have very custom requirements, or there may be a more suitable widget for your needs. If you're not bent on using the treeview, perhaps the table widget will provide what you want. You can control the individual cell contents, it allows user editing of the cells (by default) and you can control the 'active' cell attributes separately from other cells. Your data is placed in a table using this code. import tkinter as tk import tkinter.ttk as ttk from tkinter.tktable import Table as ttkTable from tkinter.tktable import ArrayVar class App(tk.Frame): def __init__(self, parent, *args, **kwargs): ttk.Frame.__init__(self, parent, *args, **kwargs) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) parent.grid_columnconfigure(0, weight=1) parent.grid_rowconfigure(0, weight=1) self.content = ArrayVar(parent) self.table = ttkTable(rows=4, cols=4, titlerows=1, titlecols=0, roworigin=0, colorigin=0, anchor='w', selecttype='cell', rowstretch='none', colstretch='unset', flashmode='off', ellipsis='...', ipadx=2, colwidth=12, multiline=False, resizeborders='col', selectmode='browse', cursor='arrow', insertwidth=2, variable=self.content, insertbackground='white' ) self.table.tag_configure('title', relief='raised', anchor='center', bg='blue', fg='white', state='disabled' ) self.table.tag_configure('active', bg='gray30', fg='white') c_headers = ["Name", "Date", "Time", "Loc"] for col, word in enumerate(c_headers, start=0): index = '0,' + str(col) self.table.set('col', index, word) self.table.width((0,1,2,3), (30,30,30,40)) self.table.set('row','1,0', "John","2017-02-05","11:30:23","Airport") self.table.set('row','2,0', "Betty","2014-06-25","18:00:00","Orchard Road") self.table.grid(sticky='news')
downvote count: 0
has comment: http://stackoverflow.com/comment/83716875
answers question: http://stackoverflow.com/q/48358084
has comment: http://stackoverflow.com/comment/83719681
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/comment/83968769
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48487936
has text: ___Don't call `eval` on user input.___ Read [this](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) or google "why is eval bad" and read any of the 5 thousand results. Just use `float` instead.

http://stackoverflow.com/a/69283213
type: Answer
answers question: http://stackoverflow.com/q/48388624
score: 0
has body: If connecting via SQLAlchemy, the uri=true flag needs to be set on the URI itself, eg: sqlalchemy.create_engine('sqlite:///:memory:?cache=shared&amp;uri=true') See https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#uri-connections for details

http://stackoverflow.com/q/48421596
tagged with: openpyxl
has body: I am running a python code in Spyder. When i start the code memory is on 22%, but after finishing the code the memory remain on 64%. I must restart kernel or end process from task manager to back to 22%. Why this situation occurs? and how to handle it? I attached the my code for more details. import csv import re import openpyxl import os papers_dir = os.listdir('Persian - Copy') #Journals for y in papers_dir: papers = [] if y.endswith('.xlsx'): wb = openpyxl.load_workbook('Persian - Copy/'+y) sheet = wb.active for z in range(2, sheet.max_row+1): id_ = str(sheet.cell(row=z, column=1).value) field = str(sheet.cell(row=z, column=2).value).replace('ي','ی').replace('ك','ک').split() field1 = str(sheet.cell(row=z, column=4).value).replace('ي','ی').replace('ك','ک').replace('None', '').split('،') field2 = re.sub(re.compile('&lt;.*?&gt;'), '', str(sheet.cell(row=z, column=3).value)) field2 = field2.replace('ي','ی').replace('ك','ک').replace('لطفا برای مشاهده چکیده به متن کامل (PDF) مراجعه فرمایید.','').replace(' لطفا برای مشاهده چکیده به متن کامل (PDF) مراجعه فرمایید.','').replace('None', '').replace('.',' ').split() f = [id_, (field + field1 + field2)] papers.append(f) wb.close() sheet = 0 print(y) #Making Unique Rows uniques = [] x_0 = [] for x in papers: if x[0] not in x_0: x_0.append(x[0]) uniques.append(x) with open('all.csv', 'a+', newline='', encoding='UTF-16') as un: writer = csv.writer(un, delimiter= '\t') for x in uniques: writer.writerow(x) papers = 0 uniques = 0 x_0 = 0 f = 0
type: Question
type: UnansweredQuestion
tagged with: spyder
has title: spyder does not free memory after running code
tagged with: python
tagged with: memory
has answer: http://stackoverflow.com/a/48424815
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51946110

http://stackoverflow.com/a/48453963
type: Answer
has comment: http://stackoverflow.com/comment/83904929
answers question: http://stackoverflow.com/q/48363560
score: 0
has comment: http://stackoverflow.com/comment/83902406
has body: Use crcmod. It will generate efficient code for the specified CRC.

http://stackoverflow.com/comment/83772207
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48392096
has text: The two processes you created have separate memory spaces and do not affect each other. You need some kind of memory sharing and synchronisation to make the variable shared across processes.
type: Comment

http://stackoverflow.com/comment/83840535
has text: could it be that "\u00e9" is actually written in the file (without encoding), indicating that the source of the data has written this as characters into a text file ? --> please post binary input file to check the actual binary content to figure out the encoding of such.
type: Comment
comment on: http://stackoverflow.com/q/48421703
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84116806
has text: ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert parameter 2
comment on: http://stackoverflow.com/a/48544185
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83672376
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48343387
type: QuestionComment
has text: And it's the **value** of the string (`'string'`) that's problematic because it is not convertible to a float.

http://stackoverflow.com/a/59926133
score: 0
answers question: http://stackoverflow.com/q/48459409
type: Answer
has body: In conf.py, after removing spaces before import statements it's working as expected

http://stackoverflow.com/q/48372461
has answer: http://stackoverflow.com/a/48373194
downvote count: 0
has body: I have a DataFrame with various text and numeric columns which I use like a database. Since a column can be of dtype object, I can also store more complex objects inside a single cell, like a numpy array. How could I store another DataFrame inside a cell? df1=pd.DataFrame([1,'a']) df2=pd.DataFrame([2,'b']) This assigment fails: df1.loc[0,0] = df2 ValueError: Incompatible indexer with DataFrame PS. It is not a duplicate question as suggested below since I do not want to concatenate the "sub"-DataFrames
favorite count: 0
type: AnsweredQuestion
has title: How to store a DataFrame inside a DataFrame
accepted answer: http://stackoverflow.com/a/48373194
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48372516
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48372516
has comment: http://stackoverflow.com/comment/83731963
has comment: http://stackoverflow.com/comment/83732009
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83735309
answer count: 2
linked to: http://stackoverflow.com/q/28368598

http://stackoverflow.com/a/48475100
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48475032
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48475032
has body: As @SilverSlash mentions you can group your variables to a tuple on the fly. A way to save re-writing (a,b,c) is to use a loop, and use the variables themselves for the wildcards: def hello (a,b,c): for (match,result) in ( ((1,1,1),1), ((2,2,2),2), ..., ((a,b,3),3), ...): if (a,b,c) == match: return result return "elseValue" This looks kind of like the code you're used to. I couldn't say if it's idiomatic or not, but I think it's equally OK as a standard if-else list. It's a bit of a waste of run-time doing the full list check if you just want to look at the last element, but it may not matter for many applications. Even if you go for an if-else though, I would definitely group to tuples rather than use and between each element. That (I think - maybe a bit of an opinion based question?) is more idiomatic.
type: Answer

http://stackoverflow.com/comment/83959774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48483447
has text: Shouldn't you be passing an argument to `c = C(<class instance here>)` when invoking? Otherwise, what's the point in expecting an argument for either class B or class C?
score: 1

http://stackoverflow.com/comment/83967911
type: AnswerComment
has text: IT WORKED! But is there a way to print the string without the spaces between them?
type: Comment
comment on: http://stackoverflow.com/a/48478389
score: 0

http://stackoverflow.com/comment/83659849
type: QuestionComment
comment on: http://stackoverflow.com/q/48335494
has text: can you print `sys.path` in both cases and edit in your question?
score: 1
type: Comment

http://stackoverflow.com/comment/83707766
comment on: http://stackoverflow.com/q/48360377
type: Comment
type: QuestionComment
score: 0
has text: The tricky part about doing this for mergesort is that it is recursive. You should try to unroll it into a loop so that you can take it one step at a time (and display your graph after each step). You could probably achieve this by employing a deque of slices that need to be processed by mergesort next. Instead of recursing, `append` to the deque.

http://stackoverflow.com/q/48400374
has comment: http://stackoverflow.com/comment/83790647
type: Question
has comment: http://stackoverflow.com/comment/83835570
score: 0
has comment: http://stackoverflow.com/comment/83790544
has comment: http://stackoverflow.com/comment/83790797
has comment: http://stackoverflow.com/comment/83789423
tagged with: python
has title: Python 3 request module: .iter_content not downloading files correctly
has body: I am currently working in a project in the form of a silly gift to my girlfriend: a program that automatically downloads pictures of puppies and kitties, and other animals. (By simply changing some things, it would be capable of downloading .pdf, books, movies or whatever, so that's the serious goal...). The program works correctly: it searches images on a series of web-sites stored on a list, and downloads one randomly and automatically. The problem is that some pictures are not fully downloaded: their size is much smaller than the pictures correctly downloaded, and, when opened, won't show any image. Why are some pictures downloaded fine, and others, though the file is there, are so small in size and show no image when opened? Where am I making a mistake? I really want to correct this. I am really new on Python, so any other advises are more than welcome (mostly if they are related to a way of reducing that messy bunch of code I made on the look_images(x, z) function, with all those try, except and while loops codes and stuff...). Thank you! Here's the script: #! python3 import os, requests, bs4, random, shelve, wget def create_folder(): #Creates the folder 'Puppies' print('Comprobando pelusitas y pulguitas...') os.makedirs('Puppies', exist_ok=True) def download_image(url, request_response): #Saves the image in the folder 'Puppies' image_file = open(os.path.join('Puppies', os.path.basename(url)), 'wb') for chunk in request_response.iter_content(chunk_size=1024): image_file.write(chunk) image_file.flush() image_file.close() def create_saves(saves_list): #Creates a data file, if not yet created, storing the pictures already downloaded. if os.path.isfile('C:\\Users\\usuario\\Documents\\santi\\saves.dat') == False: page_files = shelve.open('saves') page_files['saves'] = saves_list page_files.close() def look_images(pages_list, saves_list): for i in pages_list: #For every item in the pages_list (for every page...) res = requests.get(i) res.raise_for_status() soup = bs4…
has comment: http://stackoverflow.com/comment/83790292
has comment: http://stackoverflow.com/comment/83789504
has comment: http://stackoverflow.com/comment/83789647
has comment: http://stackoverflow.com/comment/83789860
tagged with: download
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83790087
has comment: http://stackoverflow.com/comment/83903948
tagged with: request
tagged with: python-requests
linked to: http://stackoverflow.com/q/16694907

http://stackoverflow.com/a/48432699
has comment: http://stackoverflow.com/comment/83859409
type: Answer
answers question: http://stackoverflow.com/q/48432611
has body: (Edited to match the sample code from the question) This may be a nice place for a partial, if you modify your function to make cx a keyword argument (or, alternatively, the last positional argument) like so: def function1(s1: str, cx: Context = None): print(f'{cx.s} {s1}!') Then you can do: from module1 import Context from module1 import function1 from functools import partial cx = Context('hello') function1 = partial(function1, cx = cx) And when you call function1, you'll be calling the partial, which already has the cx argument set.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83858484
has comment: http://stackoverflow.com/comment/84423431
has comment: http://stackoverflow.com/comment/83859491
upvote count: 2

http://stackoverflow.com/q/48445403
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48445495
possible better answer: http://stackoverflow.com/a/48445495
has title: Populate once static variable from static method Python within a class
favorite count: 0
type: AnsweredQuestion
has body: I have a Class A in Python and I would like to populate the a static variable calling a static method like: Class A: arr = [] @staticmethod def FillArr(): #do more stuff but for semplicity... A.arr = [[2,2,2,]] FillArr.__func__() when I run the code I got 'NameError: name A not defined' so essentially I can't initialize the arr static variable. Essentially once the the class has been instantiated once I would like to populate the static variable
tagged with: python
tagged with: class
type: Question
tagged with: static-methods
answer count: 2
has answer: http://stackoverflow.com/a/48445569
score: 1
accepted answer: http://stackoverflow.com/a/48445569
tagged with: static-variables

http://stackoverflow.com/comment/83893158
comment on: http://stackoverflow.com/a/48435382
score: 0
type: Comment
type: AnswerComment
has text: any thoughts on how I can fix this?

http://stackoverflow.com/a/48477668
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83950021
answers question: http://stackoverflow.com/q/48477441
has body: The only problem with your code was you were always using the same initial amount for all years. While the amount for every year changes and accordingly interest should be calculated. I hope this update solves your problem: def interest_calculator(): i_amount=eval(input('Your initial amount:')) num_yr=eval(input('Number of years:')) anual_rate=eval(input('Annual interest rate as percentage:' )) money=i_amount for i in range(1,num_yr+1): # 1 so that it begins from 1 and not 0 money=money+money*(anual_rate/100) print('Money after ',i,'year is',round(money,2)) print('Money growth after', num_yr,'year is(as percentage',((money-i_amount)/(i_amount))*100)
accepted answer of: http://stackoverflow.com/q/48477441
type: Answer
has comment: http://stackoverflow.com/comment/83950117

http://stackoverflow.com/comment/83761418
score: 0
comment on: http://stackoverflow.com/q/48386928
type: Comment
has text: You should use `is not` which checks the identity and works with numpy arrays as well.
type: QuestionComment

http://stackoverflow.com/a/48443975
downvote count: 0
has body: You are referring to the documentation for newer Django version as path() did not exist in older versions. You can select the documentation version by clicking on the Documentation version button at the bottom right here.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48443470
accepted answer of: http://stackoverflow.com/q/48443470
type: AcceptedAnswer

http://stackoverflow.com/q/48434492
favorite count: 0
has body: Which path is used in os.path.isfile(filename) in python. I have file in /home/debian and I have added that path in PYTHONPATH variable still os.path.isfile(filename) returns FALSE.
has comment: http://stackoverflow.com/comment/83860651
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/48434543
has comment: http://stackoverflow.com/comment/83860556
answer count: 1
has comment: http://stackoverflow.com/comment/83977566
has title: why os.path.isfile returns false if file is other directory?
type: Question
upvote count: 2
tagged with: os.path
type: UnansweredQuestion
tagged with: pythonpath
tagged with: python
has comment: http://stackoverflow.com/comment/83860708

http://stackoverflow.com/q/48475727
has answer: http://stackoverflow.com/a/48477344
accepted answer: http://stackoverflow.com/a/48477344
downvote count: 0
upvote count: 1
score: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83948117
has title: SQLAlchemy: Unnecessary join with joinedload
linked to: http://stackoverflow.com/q/9821358
has body: I'm using SQLAlchemy ORM for a Flask project where I want to join across an eagerly loaded model but this leads to two joins to the same intermediary model. If you run the code below you'll see in the generated SQL that there are two joins between the Author model and the Book model. If the lazy=joined bit is removed the sql generated is perfect. I don't know if I'm doing something wrong or this is by design. How do I get SQLAlchemy to emit the right SQL while maintaining the joinedload in this case? Note: I have tried this with MySQL and SQLite and it happens with both those dbs. from sqlalchemy import create_engine, Integer, String, Column from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) Base = declarative_base() from sqlalchemy import create_engine, Integer, String, Column from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) Base = declarative_base() class Author(Base): __tablename__ = 'authors' id = Column(Integer, primary_key=True) name = Column(String) pseudo = Column(String) books = relationship("Book", lazy='joined') def __repr__(self): return "&lt;User(name='%s', fullname='%s', password='%s')&gt;" % ( self.name, self.fullname, self.password) class Book(Base): __tablename__ = 'books' id = Column(Integer, primary_key=True) author_id = Column(Integer, ForeignKey('authors.id')) name = Column(String) user = relationship("Author", back_populates="books") pages = relationship("Page") class Page(Base): __tablename__ = 'pages' id = Column(Integer, primary_key=True) book_id = Column(Integer, ForeignKey('books.id')) text = Column(String) book = relations…
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47243397
type: AnsweredQuestion

http://stackoverflow.com/q/48428679
upvote count: 9
has comment: http://stackoverflow.com/comment/83848914
answer count: 3
has answer: http://stackoverflow.com/a/62284940
tagged with: pandas
possible better answer: http://stackoverflow.com/a/62284940
has answer: http://stackoverflow.com/a/70657504
tagged with: python
favorite count: 0
type: Question
score: 9
has title: opposite of df.diff() in pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/83851170
has comment: http://stackoverflow.com/comment/83851662
has answer: http://stackoverflow.com/a/48428852
accepted answer: http://stackoverflow.com/a/48428852
has body: I have searched the forums in search of a cleaner way to create a new column in a dataframe that is the sum of the row with the previous row- the opposite of the .diff() function which takes the difference. this is how I'm currently solving the problem df = pd.DataFrame ({'c':['dd','ee','ff', 'gg', 'hh'], 'd':[1,2,3,4,5]} df['e']= df['d'].shift(-1) df['f'] = df['d'] + df['e'] Your ideas are appreciated.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83851764

http://stackoverflow.com/a/77494480
type: Answer
has body: Exmaple: 20 * * * * bash -lc mypythonscript This will bring in your paths defined in your bashrc/profile etc
answers question: http://stackoverflow.com/q/48342202
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/48409178
upvote count: 0
has comment: http://stackoverflow.com/comment/83809923
has comment: http://stackoverflow.com/comment/83816660
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/83809750
type: Answer
has comment: http://stackoverflow.com/comment/83809595
has body: I have sometimes encountered this when not referencing the correct sub-library import matplotlib.pyplot
answers question: http://stackoverflow.com/q/48408670

http://stackoverflow.com/comment/83728739
comment on: http://stackoverflow.com/q/48370962
has text: @cricket_007, it's just a simple object with some attributes which are strings
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83994237
has text: Yes I can understand but I'll check executable file before run. :) I'm not just gonna run all .exe files I just need them.
type: Comment
comment on: http://stackoverflow.com/q/48483765
type: QuestionComment
score: 0

http://stackoverflow.com/q/48410254
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48410392
has title: Error: 'dict_values' object does not support indexing
tagged with: python
has body: I am trying to play with Kaggle Bag of Words module, and at one point, it is throwing out this error: kmeans_clustering = KMeans( n_clusters = num_clusters ) idx = kmeans_clustering.fit_predict( word_vectors ) word_centroid_map = dict(zip( model.wv.index2word, idx )) Now, for cluster in range(0,10): print("\nCluster %d" % cluster) words = [] for i in range(0,len(word_centroid_map.values())): if( word_centroid_map.values()[i] == cluster ): words.append(word_centroid_map.keys()[i]) print(words) The error is: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-24-f230ff75f988&gt; in &lt;module&gt;() 3 words = [] 4 for i in range(0,len(word_centroid_map.values())): ----&gt; 5 if( word_centroid_map.values()[i] == cluster ): 6 words.append(word_centroid_map.keys()[i]) 7 print(words) TypeError: 'dict_values' object does not support indexing
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48410326
accepted answer: http://stackoverflow.com/a/48410326
possible better answer: http://stackoverflow.com/a/48410392

http://stackoverflow.com/q/48470159
has answer: http://stackoverflow.com/a/48506448
has answer: http://stackoverflow.com/a/48530676
upvote count: 0
score: -3
accepted answer: http://stackoverflow.com/a/48506448
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84132966
has body: I'm looking to save/write photos that are not blurry. How would one go about combining the two codes below? import cv2 image = cv2.imread('./facesData/ID.jpg') cv2.Laplacian(image, cv2.CV_64F).var() while 1: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.2, 8) for x,y,w,h in faces: sampleN = sampleN + 1 cv2.imwrite("./facesData/ID." + str(sampleN) + ".jpg", gray[y:y+h, x:x+w]) cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2) cv2.waitKey(2) cv2.imshow('user', img) cv2.waitKey(1) if sampleN &gt; 20: break cap.release() cv2.destroyAllWindows()
downvote count: 3
tagged with: python
has title: Save photo only if not blurry (Laplacian >200)?
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48530676
answer count: 2

http://stackoverflow.com/q/48453695
tagged with: kivy
has answer: http://stackoverflow.com/a/48462389
answer count: 2
has answer: http://stackoverflow.com/a/48462131
score: 1
tagged with: user-interface
has title: Making a slightly more efficient function structure
has comment: http://stackoverflow.com/comment/83910329
upvote count: 1
has comment: http://stackoverflow.com/comment/83901398
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83909986
type: UnansweredQuestion
has body: I have a bunch of lights I'm trying to control. Rather than have each button state change call a unique function I want to try and have a multipurpose function as thats what functions are for (as far as I understand). Button calling function: ToggleButton: id: KitchenSpot1Toggle text: "Kitchen Spot 1" on_press: root.changeKS1(1) The function: def changeKS1(self,change): if change==1 and b.get_light(1, 'on'): self.KitchenSpot1(False) else: self.KitchenSpot1(True) That function then calls this function to physically change the state of the light using a 3rd part library. def KitchenSpot1(self,state): lights[0].name lights[0].on = state The reason I passed "1" inside of the function is because it didn't like having nothing passed in it (I don't know why it didn't like it). If you hadn't already guessed it, I am new at this. I have a bit of a cpp micro controller background but I'm trying to get my head around python and PC based programming. I'm looking for a bit of advice on how best I can condense this and make it as efficient as possible. I may not know much about python, but, I know I shouldn't be typing practically the same thing out 30 times. Thanks in advance to anyone that can share some of their wisdom. Its with noting I am using kivy with python to generate the button. Full main.py code: from kivy.properties import StringProperty import kivy from kivy.uix.togglebutton import ToggleButton from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.clock import Clock from kivy.lang import Builder from kivy.app import App kivy.require('1.10.0') from phue import Bridge import nest b = Bridge('xx.xxx.xxx.xxx') b.connect() b.get_api() lights = b.lights class Controller(GridLayout): state = StringProperty('down') def __init__(self, **kwargs): super(Controller, self).__init__(**kwargs) Clock.schedule_interval(self.update, 1.0 / 60.0) def KitchenSpot1(self,state): lights[0].name lights[0].on = state def changeKS1(self,change): if change==1 and b.get_…
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/83720019
type: QuestionComment
comment on: http://stackoverflow.com/q/48365802
type: Comment
score: 0
has text: @Cyzanfar Thanks a lot. I tried wikipedia api. But it did not support conda.

http://stackoverflow.com/comment/83859289
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48433872
score: 2
has text: Your code would be easier to understand and the purpose of the asterisk would be more obvious if you left some space after the *: `"*" * len(word)`.

http://stackoverflow.com/comment/83948125
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48477305
has text: thank you. I dont understand return super and I had to change 'detail' to 'film:detail' but it is working now.
score: 0

http://stackoverflow.com/a/48487722
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48487688
has comment: http://stackoverflow.com/comment/83968269
accepted answer of: http://stackoverflow.com/q/48487688
type: Answer
score: 4
upvote count: 4
has body: A function aptly named mask does just this. overview.mask(overview == overview.shift(), '') Alternatively, use df.where - overview.where(overview != overview.shift(), '') model p_1 p_2 q_1 mse black_test blue_model 0.1 2 10 0.2 yellow_test 1 0.1 gray_test green_model 0.3 5 10 0.25 Don't assign this back to anything, this sort of data representation is only useful for display, nothing more.

http://stackoverflow.com/q/48335994
type: Question
tagged with: knn
has answer: http://stackoverflow.com/a/48701185
has body: My question is, Does the machine learning algorithm takes care of selecting the best features in my data ? or shall I do feature selection and scaling prior to my machine learning algorithm. I am aware of few supervised classification machine learning algorithms such as kNN, Neural Networks, Adaboast etc. But is there some you recommend me looking at ?
tagged with: classification
answer count: 1
upvote count: 1
downvote count: 1
type: AnsweredQuestion
score: 0
tagged with: algorithm
tagged with: supervised-learning
tagged with: python
has title: Do I have to do feature selection prior to applying my machine learning algorithm?
accepted answer: http://stackoverflow.com/a/48701185
favorite count: 0

http://stackoverflow.com/comment/83664018
has text: A possible next step might be to remove all your code from the script and slowly start adding it until your script stops working again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48339383

http://stackoverflow.com/comment/83780151
type: AnswerComment
has text: Thanks for the feedback. Added some caveats.
score: 0
comment on: http://stackoverflow.com/a/48396045
type: Comment

http://stackoverflow.com/comment/83848951
type: QuestionComment
has text: (I'm the author of this library) if you create an issue here https://github.com/nicolaskruchten/jupyter_pivottablejs/issues/new I'd be glad to help you :)
score: 0
comment on: http://stackoverflow.com/q/48415690
type: Comment

http://stackoverflow.com/q/48401803
upvote count: 3
answer count: 1
downvote count: 0
has title: How to get inactive records in One2many/Many2many fields?
favorite count: 0
type: Question
has body: Let's put an example with an One2many, which is clearer: imagine that a person can have several pets, but a pet can only have an owner: class Pet(models.Model): _name='pet' owner_id = fields.Many2one( comodel_name='person', string='Owner', ) active = fields.Boolean( string='Active', default=True, ) class Person(models.Model): _name='person' pet_ids = fields.One2many( comodel_name='pet', inverse_name='owner_id', string='Pets', ) Now you have a person (Id: 1) who has two pets (Ids: 56, 57), but one of them is inactive (the one with Id: 57). If you print person.pet_ids, Odoo returns pet(56,). Inactive records are not included there. Is there any way to show them when printing person.pets_ids? I did this so far: pets = self.env['pet'].search([ ('owner_id', '=', person.id), '|', ('active', '=', True), ('active', '=', False), ]) But I was wondering if there is a better way.
tagged with: odoo
tagged with: odoo-8
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48402622
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48402622

http://stackoverflow.com/a/48357682
downvote count: 0
score: 1
upvote count: 1
has body: You can use this regular expression: \(.*?\). Demo here: https://regexr.com/3jgmd Then you can remove the part with this code: import re test_string = 'This is a string (here is a text to remove), and here is a text not to remove' new_string = re.sub(r" \(.*?\)", "", test_string) This regular expression (regex) will look for any text (without line break) in brackets prepended by a space
type: Answer
answers question: http://stackoverflow.com/q/48357619

http://stackoverflow.com/q/48471915
tagged with: python-imaging-library
tagged with: python
has title: When using Image.new(...) from PIL importing image what does size start at?
has answer: http://stackoverflow.com/a/48472366
type: Question
score: 1
has body: Say I use this code img = Image.new('RGB', (500,500), "white") Is the maximum of the created area 499 or 500? I understand that the minimum is 0 but I can not find documentation on if the 500 in this case would be inclusive or exclusive.
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48472366
type: AnsweredQuestion

http://stackoverflow.com/a/48477233
has body: The markevery option allows to subsample the marked datapoints on a line. Which points are marked or not is only determined at the moment the line is drawn. There is hence no attribute of the line that would store the data of the shown points, because they might change all the time, depending on the size and limits of the plot. The solution is indeed to replicate the drawing behaviour of the line to access the coordinates of the marked points, using _mark_every_path. import numpy as np from matplotlib import pyplot as plt from matplotlib import lines line, = plt.plot(np.arange(100)**2, marker='o', markevery=(0, 0.1)) tpath, affine = line._get_transformed_path().get_transformed_points_and_affine() p = lines._mark_every_path(line.get_markevery(), tpath, affine, line.axes.transAxes) print(len(p.vertices)) # prints 10 print(p.vertices) # print array of points, shape (10,2) plt.show()
answers question: http://stackoverflow.com/q/48476275
type: Answer
accepted answer of: http://stackoverflow.com/q/48476275
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83808540
type: Comment
comment on: http://stackoverflow.com/a/48408576
type: AnswerComment
score: 1
has text: OK, yes if neither has the `n` dimension, then some sort of `repeat` is needed.

http://stackoverflow.com/comment/83808960
comment on: http://stackoverflow.com/q/48409527
type: Comment
type: QuestionComment
has text: Added a sample data. I have removed the body column which will usually be very very large utf8 text(non-english). @wwii No. Its mostly removing some special characters, newline etc...
score: 0

http://stackoverflow.com/a/48349093
has comment: http://stackoverflow.com/comment/83685506
has comment: http://stackoverflow.com/comment/83685408
has comment: http://stackoverflow.com/comment/83685131
score: 2
upvote count: 3
answers question: http://stackoverflow.com/q/48348953
has body: Looking at wikipedia https://en.wikipedia.org/wiki/Spherical_coordinate_system the standard conversion is: You need to be in radial coordinates (theta, phi). If not use math.radians on theta and phi. import math def polar2cart(r, theta, phi): return [ r * math.sin(theta) * math.cos(phi), r * math.sin(theta) * math.sin(phi), r * math.cos(theta) ]
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/83685725
has comment: http://stackoverflow.com/comment/83685349

http://stackoverflow.com/comment/83652144
has text: Possible duplicate of [How to query as GROUP BY in django?](https://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django)
type: Comment
comment on: http://stackoverflow.com/q/48333189
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83762188
score: 0
comment on: http://stackoverflow.com/q/48387198
type: QuestionComment
has text: I would suggest codereview SO site for questions like this
type: Comment

http://stackoverflow.com/q/48363539
has title: Selenium Python scrape element returns blank text
has answer: http://stackoverflow.com/a/48369880
tagged with: selenium
type: Question
has body: I'm trying to extract the year 2016 (shown in a red box in the picture). I have tried: driver.find_element_by_xpath(&quot;//*[@class = 'zsg-table yui3-toggle-content-minimized']/tbody/tr[1]/td[1]&quot;) but it only returns a blank text. Any help is appreciated!
has answer: http://stackoverflow.com/a/51081693
type: UnansweredQuestion
tagged with: python
answer count: 4
score: 0
has answer: http://stackoverflow.com/a/48364019
has answer: http://stackoverflow.com/a/48366509

http://stackoverflow.com/q/48365443
accepted answer: http://stackoverflow.com/a/48365498
has answer: http://stackoverflow.com/a/48366106
has body: I have a list Tmp in Python, looks like below: A1 A2 B1 B2 C1 C2 0 17.387 17.470 19.93 13.29 19.93 19.93 1 17.680 17.896 21.85 14.57 21.86 21.86 2 17.787 17.228 24.46 16.30 24.45 24.45 I used this code to select different columns: cols1 = [col for col in cols if '1' in col] combined1 = combined[cols1] cols2 = [col for col in cols if '2' in col] combined21 = combined[cols2] I want to make a list looks like: A1 A2 0 17.387 17.470 1 17.680 17.896 2 17.787 17.228 3 B1 B2 #I also want to delet the titles in between 4 19.93 13.29 5 21.85 14.57 6 24.46 16.30 7 C1 C2 8 19.93 19.93 9 21.86 21.86 10 24.45 24.45 I tried pd.concat, append, both of them seem not working. Do you have any solutions? Thank you in advance!
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48365585
upvote count: 1
has comment: http://stackoverflow.com/comment/83717495
score: 1
tagged with: python
favorite count: 0
type: Question
has title: How to put lists below each other? Python 3.6
possible better answer: http://stackoverflow.com/a/48365585
tagged with: list
has answer: http://stackoverflow.com/a/48365498
downvote count: 0

http://stackoverflow.com/comment/83809624
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48409078
has text: Ok, thanks for the link, the delegate pattern is what I'm using now but it seemed like a better solution than writing a bunch of wrappers existed.
score: 0

http://stackoverflow.com/comment/83964556
type: Comment
comment on: http://stackoverflow.com/a/48476465
type: AnswerComment
has text: Btw why has "Date" become the dataframe index? Can I prevent it? I need to do a certain loop through the data and I would prefer having the indexes 0, 1, 2... instead of having to reference individual dates. Thanks!
score: 0

http://stackoverflow.com/q/48367283
has answer: http://stackoverflow.com/a/60524082
has answer: http://stackoverflow.com/a/48367384
has answer: http://stackoverflow.com/a/75929651
has answer: http://stackoverflow.com/a/76314094
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/65528688
has answer: http://stackoverflow.com/a/64347125
has answer: http://stackoverflow.com/a/56876280
type: UnansweredQuestion
tagged with: pip
tagged with: python
has title: Error: install mglearn
answer count: 11
has answer: http://stackoverflow.com/a/54976018
has body: I have used "pip install mglearn" and "conda install mglearn". But it shows me the following error: Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - mglearn Current channels: - https://conda.anaconda.org/conda-forge/win-64 - https://conda.anaconda.org/conda-forge/noarch - https://repo.continuum.io/pkgs/main/win-64 ... - https://repo.continuum.io/pkgs/msys2/win-64 - https://repo.continuum.io/pkgs/msys2/noarch I have "Python 3.6.3 :: Anaconda custom (64-bit)"
tagged with: conda
has answer: http://stackoverflow.com/a/54204658
score: 0
has answer: http://stackoverflow.com/a/61793493
tagged with: installation
upvote count: 1
has answer: http://stackoverflow.com/a/78418891
downvote count: 1

http://stackoverflow.com/q/48410684
has comment: http://stackoverflow.com/comment/83811289
has title: Setting Pandas Dataframe Value
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31593201
tagged with: dataframe
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48410967
has answer: http://stackoverflow.com/a/48410967
tagged with: python
has body: I am trying to loop through a pandas dataframe and every time that a specific string appears, it will set the value for the cell on the same row but 2 columns previous, to the value of the cell one row before the specific text. I have attached a visual explanation of what I am trying to do if that does not make sense. Code: for index, row in df.iterrows(): if row[3] == 'National Account Job Coordinator': row[1] = df.iloc[index-1, 3] else: continue The code will print out the correct values, but does not set the dataframe values... Any ideas? Thanks
answer count: 1
has comment: http://stackoverflow.com/comment/83811321

http://stackoverflow.com/q/48478711
tagged with: pandas
has title: series of list to OHE
tagged with: python
tagged with: one-hot-encoding
downvote count: 0
answer count: 1
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48863662
favorite count: 0
type: Question
has body: I have total pandas series of list like below.I have full list of values which can be contained in each list. superset= ['a1','b1'...,'z1'] panda series ps = ['a1','b1'] ['c1'] ['d1'] Now I want to convert them into below form. columns : a1 b1 c1 d1 e1 ... z1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48863662

http://stackoverflow.com/comment/83703799
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48349031
has text: well I will dig into it to find the fault cause on my computer. But the code code seems to work so this is good, thanks you !
type: AnswerComment

http://stackoverflow.com/comment/132409807
type: AnswerComment
comment on: http://stackoverflow.com/a/48479858
type: Comment
has text: Right, Daniel. Python writes ```round(1.0, 2)``` as ```1.0```.
score: 0

http://stackoverflow.com/q/48450534
type: UnansweredQuestion
tagged with: jupyter
linked to: http://stackoverflow.com/q/48429807
tagged with: jupyter-notebook
has body: After updating Jupyter Notebook (versions below): jupyter 1.0.0 py36h422fd7e_2 jupyter_client 5.2.1 py36_0 jupyter_console 5.2.0 py36h6d89b47_1 jupyter_core 4.4.0 py36h56e9d50_0 I now cannot create a Python notebook in a directory - other than the root directory I spawned my notebook server. As an example, if I spawn my server in \home but then navigate to \home\a and attempt to create a new Python notebook, it automatically redirects me to \home in my navigation window and creates the notebook there. Further, the server gives me the following: [W 14:26:34.925 NotebookApp] 404 GET /nbextensions/notify.js?v=20180125141725 (::1) 2.00ms referer=http://localhost:1234/notebooks/Untitled.ipynb?kernel_name=python3 [W 14:26:34.934 NotebookApp] 404 GET /nbextensions/theme_toggle.js?v=20180125141725 (::1) 2.00ms referer=http://localhost:1234/notebooks/Untitled.ipynb?kernel_name=python3 [I 14:26:35.025 NotebookApp] Kernel started: d5e26b01-8420-4e07-a74e-35531ce16625 [W 14:26:35.071 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20180125141725 (::1) 2.51ms referer=http://localhost:1234/notebooks/Untitled.ipynb?kernel_name=python3 [I 14:26:36.818 NotebookApp] Adapting to protocol v5.1 for kernel d5e26b01-8420-4e07-a74e-35531ce16625 In the prior version (or whatever version I was previously on), I was able to create new notebooks in my current directory.
has title: Jupyter Notebook unable to create notebook in non root directory
downvote count: 0
answer count: 0
score: 1
upvote count: 1
favorite count: 0
tagged with: anaconda
type: Question
has comment: http://stackoverflow.com/comment/83993994
has comment: http://stackoverflow.com/comment/83994266
has comment: http://stackoverflow.com/comment/86743835
tagged with: python

http://stackoverflow.com/comment/113786613
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48338194
has text: @EHM Can you use pygame to control the volume of individual speaker (of a headset), such that at one point the volume from the right speaker is 100% and the volume of the left speaker is 50%?
type: AnswerComment

http://stackoverflow.com/q/48454540
type: Question
upvote count: 0
tagged with: python
tagged with: flask
answer count: 1
downvote count: 1
tagged with: ajax
has body: I am trying a simple Flask API in JS and it fails. I tested the URL using curl and it works fine. Not sure where I am doing it wrong. Your help is much appreciated. the http response code is fine (200). May be something wrong in the way i wrote the js.... python script: from flask import Flask import simplejson as json app = Flask(__name__) @app.route('/api/person', methods=['GET']) def get_person(): str = {'id':'1','first_name':'John','last_name':'Smith'} res = json.dumps(str) return res if __name__ == '__main__': app.run(debug=True) testapp.js: $(document).ready(function() { $.ajax({ type: "GET", url: "http://localhost:5000/api/person", success: function(data){ $('.person-id').append(data.id); $('.person-first_name').append(data.first_name); $('.person-status').append('success'); }, error: function(){ $('.person-status').append('failed'); } }); }); index.html: TestApp jQuery The Status is The ID is First name is html response curl testing
accepted answer: http://stackoverflow.com/a/48454574
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48454574
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/83902126
has title: Java script : Calling Flask API with AJAX fails

http://stackoverflow.com/a/48414741
type: Answer
has body: This solution satisfies your requirements by construction. In other words, the number of elements chosen is uniformly random. import random from collections import Iterable def count(l, r=0): for i in l: if isinstance(i, Iterable): r += count(i) else: r += 1 return r def listrand(target): N = count(target) nchosen = random.randint(0, N-1) chosen = set(random.sample(range(N), nchosen)) def build(l, c=0): output = [] for i in l: if isinstance(i, Iterable): c, sublist = build(i, c) if sublist: output.append(sublist) else: if c in chosen: output.append(i) c += 1 return c, output return build(target)[1] Sample output: target = [1,2,3,[3,4], [65,[3]]] for i in range(5): print(listrand(target)) [1, 2, 3, [3, 4], [[3]]] [2] [] [2, 3, [3, 4]] [[4]]
answers question: http://stackoverflow.com/q/48414404
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48414404
has comment: http://stackoverflow.com/comment/83819455
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83819504

proxy
tags question: http://stackoverflow.com/q/48454161
tags question: http://stackoverflow.com/q/48427498
tags question: http://stackoverflow.com/q/48378106
tags question: http://stackoverflow.com/q/48411823
type: Tag
tags question: http://stackoverflow.com/q/48435200
tag name: proxy
tags question: http://stackoverflow.com/q/48421714
tags question: http://stackoverflow.com/q/48481668
tags question: http://stackoverflow.com/q/48446368
tags question: http://stackoverflow.com/q/48469252

http://stackoverflow.com/q/48348267
accepted answer: http://stackoverflow.com/a/48348445
has answer: http://stackoverflow.com/a/48348445
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/75614586
has answer: http://stackoverflow.com/a/72592892
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/75614586
favorite count: 0
score: 2
has title: Django REST framework queryset object has no attribute pk
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73839540
has body: I am building a larger Django-based web app, but I have a blocking issue with an API view that should return some data. I the application I have a model (mail.models.Message) and a matching serializer and viewset. For a reporting feature, I need to get filtered set of results and have therefoer created a seperate rest_framework.views.APIView for the purpose of the reporting. The model is located in one app and the reporting is in another app. Here is the model: class Message(models.Model): class Meta: ordering = ('-timestamp',) get_latest_by = 'timestamp' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) from_address = models.CharField("From", max_length=511, blank=True, default="", db_index=True) from_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) to_address = models.CharField("To", max_length=511, blank=True, default="", db_index=True) to_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) subject = models.TextField(blank=True, default="", db_index=True) client_ip = models.GenericIPAddressField("Client IP", db_index=True, null=True) mailscanner_hostname = models.CharField(max_length=255, db_index=True) spam_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) mcp_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) timestamp = models.DateTimeField(db_index=True) size = models.FloatField(default=0) token = models.CharField(max_length=255, null=True) mailq_id = models.TextField("Mailqueue identification", null=True) whitelisted = models.BooleanField(db_index=True, default=False) blacklisted = models.BooleanField(db_index=True, default=False) is_spam = models.BooleanField(db_index=True, default=False) is_mcp = models.BooleanField(db_index=True, default=False) is_rbl_listed = models.BooleanField("Is RBL listed", db_index=True, default=False) quarantined = models.BooleanField(db_index=True, default=False) infec…
has answer: http://stackoverflow.com/a/77506404
answer count: 5
tagged with: python

http://stackoverflow.com/comment/83790409
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48391680
has text: Thank you I got it, the primary data frame is really big and the above script is running since an hour now
type: Comment

http://stackoverflow.com/q/48475907
duplicate of: http://stackoverflow.com/q/10879137
has comment: http://stackoverflow.com/comment/83947402
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83947011
tagged with: python
tagged with: factory
has body: The background is that I have Cells associated with a coordinate system and I want to create them on the fly. Each point will have a unique Cell if it has one but there will be many points that do not. It would be much easier to code and use if I could just say Cell() and I automatically get the pre-existing one if it exists and a new one it if doesn't. I could use a factory-constructor like this class Cell(): lookup = {} index = -1 # index is a one-up counter to distinguish objects def __init__(self,coord): Cell.index += 1 self.index = Cell.index self.coord = coord Cell.lookup[coord] = self def __repr__(self): return "{}&lt;{}&gt;".format(self.__class__.__name__,self.index,self.coord) @classmethod def factory(self,coord): try: return Cell.lookup[coord] except KeyError: return Cell(coord) # This creates four different Cells print([Cell(i) for i in (0,1,0,1)]) # but this creates only two print([Cell.factory(10+i) for i in (0,1,0,1)]) but I think it's unaesthetic and there is the danger that I might accidentally use the Cell constructor directly. I could hide Cell as a different class class _Cell(): lookup = {} index = -1 def __init__(self,coord): _Cell.index += 1 self.index = _Cell.index self.coord = coord _Cell.lookup[coord] = self def __repr__(self): return "{}&lt;{}&gt;".format(self.__class__.__name__,self.index,self.coord) @classmethod def factory(self,coord): try: return _Cell.lookup[coord] except KeyError: return _Cell(coord) def Cell(coord): return _Cell.factory(coord) # This creates only two different Cells print([Cell(i) for i in (0,1,0,1)]) but now I'm not creating objects of type Cell. Is there a way of making the constructor I want aesthetic and safer? Post Edit .. I had not recognised this as an application for memoisation. Thank you to the person who did. This code works _memoized = {} def memoize(f): """ A special-case memoizer """ def memoized(*args): key = (*args,) if key not in _memoized: _memoized[key] = f(*args) return _memoized[key] return memoiz…
has title: make a Factory constructor look like a normal constructor in Python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83946759
linked to: http://stackoverflow.com/q/10879137
has comment: http://stackoverflow.com/comment/83947101
type: Question
has comment: http://stackoverflow.com/comment/83947266
has comment: http://stackoverflow.com/comment/83946336
duplicate of: http://stackoverflow.com/q/13054250
tagged with: constructor

http://stackoverflow.com/a/48448694
type: Answer
accepted answer of: http://stackoverflow.com/q/48448450
score: 0
has body: Your comparison is backwards. You're checking permitted in pcode, but you want pcode in permitted instead.
has comment: http://stackoverflow.com/comment/83890151
has comment: http://stackoverflow.com/comment/83892956
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48448450

http://stackoverflow.com/comment/101247569
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48434089
has text: @dubbbdan Yes, you updated to matplotlib 3.1. Since the original code used a private attribute, which is subject to change without notice, this suddenly broke. I updated the answer with a new version.
type: AnswerComment

http://stackoverflow.com/comment/83819696
comment on: http://stackoverflow.com/a/48414364
type: AnswerComment
has text: If the they have the same keys then I don't think you need to do that. All you need to do is remove the keys that you don't need from `data` dictionary by using something like `del data["key-that-you-dont-want"]` and do `.create(**data)`.
score: 0
type: Comment

http://stackoverflow.com/q/48433601
tagged with: python
duplicate of: http://stackoverflow.com/q/37754948
possible better answer: http://stackoverflow.com/a/48433631
has body: I tried np.where but without success: &gt;&gt;&gt;a = np.array([np.nan, 1]) &gt;&gt;&gt;np.where(a == np.nan) (array([], dtype=int64),)
has answer: http://stackoverflow.com/a/48433636
type: AnsweredQuestion
score: 2
has title: How do I find the coordinates of nan values in a numpy array?
has answer: http://stackoverflow.com/a/48433631
accepted answer: http://stackoverflow.com/a/48433636
favorite count: 0
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/37754948
answer count: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48366574
type: Answer
has comment: http://stackoverflow.com/comment/83720368
answers question: http://stackoverflow.com/q/48366561
type: AcceptedAnswer
has body: Option 1 pd.Series.between seems suited for this task. df[~df['values'].between('2017-03-02', '2017-03-05', inclusive=False)] values 2018-01-01 2017-03-01 2018-01-02 2017-03-02 2018-01-05 2017-03-05 2018-01-06 2017-03-06 Details between identifies all items within the range - m = df['values'].between('2017-03-02', '2017-03-05', inclusive=False) m 2018-01-01 False 2018-01-02 False 2018-01-03 True 2018-01-04 True 2018-01-05 False 2018-01-06 False Freq: D, Name: values, dtype: bool Use the mask to filter on df - df = df[~m] Option 2 Alternatively, with the good ol' old logical OR - df[~(df['values'].gt('2017-03-02') &amp; df['values'].lt('2017-03-05'))] values 2018-01-01 2017-03-01 2018-01-02 2017-03-02 2018-01-05 2017-03-05 2018-01-06 2017-03-06 Note that both options work with datetime objects as well as string date columns (in which case, the comparison is lexicographic).
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48366561
downvote count: 0

http://stackoverflow.com/q/48429882
answer count: 0
tagged with: directory
has title: Using python, how do I copy a folder (and all of its contents) to clipboard?
type: Question
has comment: http://stackoverflow.com/comment/83979426
tagged with: clipboard
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83857568
has body: I would like to create a program that looks through every file in a folder tree, grabs every file with the extension ".py", and then copies a new folder containing only the .py files to the clipboard. As far as I'm aware, the code would have to look something like this: import os, shutil os.makedirs("All .py files") for foldername, subfolders, filenames in os.walk(folder): for filename in filenames: if filename.endswith(".py"): shutil.copy(filename, "All .py files") # CODE TO COPY "ALL .PY FILES" FOLDER TO CLIPBOARD What fill-in-the-blank code would work here? The simpler the answer, the more appreciative I would be :) I'm very new to python and don't know that much yet!
score: 0

http://stackoverflow.com/comment/83663297
type: QuestionComment
comment on: http://stackoverflow.com/q/48338971
type: Comment
score: 0
has text: Do you want to get rid of all C2? Or keep the first?

http://stackoverflow.com/q/48351139
has comment: http://stackoverflow.com/comment/83689404
tagged with: python
has comment: http://stackoverflow.com/comment/83689341
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83689017
accepted answer: http://stackoverflow.com/a/48360702
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83689844
upvote count: 3
has answer: http://stackoverflow.com/a/48360702
tagged with: python-module
downvote count: 0
has title: Loading config from class in such a way that it behaves like a property
has comment: http://stackoverflow.com/comment/83689568
answer count: 1
favorite count: 0
has body: I'm trying to create a yaml-driven config module for python that loads both from a flat yaml file, and optionally loads params from sys.argv. It also saves the loaded properties to a local variable (which is ugly, but it's still preferable to parsing the yaml file every time config is referenced). I have this working, but the way I have to import it seems over-the-top, and not very pythonic. Is there a more elegant way to construct this so that: I can use a single import statement I can ensure that the config isn't loaded more times (throughout different modules where it's used) than absolutely necessary Structure: /app /__init__.py /__main__.py # calls __init__.py /config.yaml /applib /__init__.py /__config_loader.py In the app's main __init__.py, I load config like so: from applib.config_loader import Config; config = Config() # ^ ew! In config_loader.py, I have: import argparse import yaml class Config: _config = None @property def config(self): if self._config is not None: print('Using what we already loaded') return self._config or Config() def __init__(self): if self._config is None: print('Loading config') with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.yaml')) as yaml_config_file: self._config = yaml.load(yaml_config_file) parser = argparse.ArgumentParser(description = 'MyApp') parser.add_argument('--an_arg') args = parser.parse_args() def __getattr__(self, name): return self._config[name] or None Certainly not the prettiest way to get this to work, and it seems like my failing to understand the old vs. new way of doing things in python is overcomplicating the situation. I'd like to be able to load it like: from applib.config_loader import config print(config['an_arg'])
type: Question

http://stackoverflow.com/comment/83665734
score: 0
type: Comment
has text: For clarity, can you fix the indentation on the `add` method (can't propose an edit with only indentation changes).
type: QuestionComment
comment on: http://stackoverflow.com/q/48340212

http://stackoverflow.com/comment/83829786
type: Comment
comment on: http://stackoverflow.com/q/48416035
score: 0
has text: My guess is that the built in `openssl_sha256` doesn't have a `name` property on this version of ubuntu / python. The error message indicates this, since it should usually say **unsupported hash type sha256**, but in your case, there's no name there. https://docs.python.org/3.5/library/hashlib.html#hashlib.hash.name
type: QuestionComment

http://stackoverflow.com/a/48372803
downvote count: 0
upvote count: 1
has body: Whatever you're passing in as infilename is already a file, rather than a file's path name.
answers question: http://stackoverflow.com/q/48372785
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48372785
type: AcceptedAnswer

http://stackoverflow.com/comment/83866099
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48437504
score: 0
has text: You don't display the form errors anywhere in the template. If you did, you would know exactly why the form didn't validate.

http://stackoverflow.com/comment/83920381
type: QuestionComment
comment on: http://stackoverflow.com/q/48463459
score: 0
has text: I use hypot to compute the distance between two points using their coordinates. This part is working fine and I obtain the table of distances which I posted already. My problem is that I cannot sort it. https://docs.python.org/2/library/math.html (math.hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y).)
type: Comment

http://stackoverflow.com/q/48365315
has comment: http://stackoverflow.com/comment/83717279
favorite count: 0
type: Question
has title: python .apply() throwing ValueError: cannot reindex from a duplicate axis
has answer: http://stackoverflow.com/a/48368452
tagged with: pandas
has answer: http://stackoverflow.com/a/48365385
has comment: http://stackoverflow.com/comment/83720249
score: 1
has comment: http://stackoverflow.com/comment/83717272
tagged with: dataframe
tagged with: python
has body: I have a dataframe and I'm trying to do some string checks, however I'm getting this error ValueError: cannot reindex from a duplicate axis What does it mean? Code: #get name titles def process_name(name): if 'Mr' in name: return 'Mr' elif ('Mrs' in name) or ('Miss' in name): return 'Mrs' elif 'Master' in name: return 'Ms' else: return 'Other' df['Name_Title']=df['Name'].apply(process_name) Dataframe:
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83717315
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/83739872
type: Comment
type: QuestionComment
has text: Do you want to replace the scientific notation to show all numbers?
score: 0
comment on: http://stackoverflow.com/q/48375776

http://stackoverflow.com/q/48390030
has title: Python object returning integer/float on object reference
has comment: http://stackoverflow.com/comment/83768106
has comment: http://stackoverflow.com/comment/83768275
downvote count: 1
tagged with: reference
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83767912
has comment: http://stackoverflow.com/comment/83768181
answer count: 1
has comment: http://stackoverflow.com/comment/83768364
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83768479
has body: I have a class like so: class NumberGenerator(object): def __init__(self, seed=0): random.seed(seed) self.current = random.random() def __next__(self): self.next() def next(self): self.current = random.random() return self.current Ideally, I would like to do the following via some magic method if available. &gt;&gt;&gt; numGen = NumberGenerator(99) &gt;&gt;&gt; numGen.next() 0.15 &gt;&gt;&gt; numGen + 2 2.15 I know __str__ and __repr__ and __add__ etc. But what I want is a magic method to return something whenever the object is referenced other than a pointer to the object. I will not assign another variable to the object reference, downstream, I promise. Is this available in Python?
has comment: http://stackoverflow.com/comment/83768105
has comment: http://stackoverflow.com/comment/83768053
has comment: http://stackoverflow.com/comment/83768085
accepted answer: http://stackoverflow.com/a/48390384
has comment: http://stackoverflow.com/comment/83768014
tagged with: object
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48390384
tagged with: oop
has comment: http://stackoverflow.com/comment/83767975

http://stackoverflow.com/q/48364168
has comment: http://stackoverflow.com/comment/83728238
answer count: 4
has answer: http://stackoverflow.com/a/78127280
tagged with: opencv
has comment: http://stackoverflow.com/comment/83715414
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83715284
accepted answer: http://stackoverflow.com/a/48371716
has comment: http://stackoverflow.com/comment/83716562
has comment: http://stackoverflow.com/comment/83716749
has answer: http://stackoverflow.com/a/48366441
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/76187273
has title: Flickering video in opencv-tkinter integration
downvote count: 0
has comment: http://stackoverflow.com/comment/83716112
possible better answer: http://stackoverflow.com/a/48366441
tagged with: python
has body: I am trying to build a GUI using tkinter in Python 3.6.4 64-bit on Windows 8 by integrating opencv components into the program. I can get the video to play, but there is a significant flicker going on. Namely, a screen the same color as the native tkinter background shows up briefly several times a second. I've tested several cameras with similar results, and double-checked that the cameras work properly via native video playback software. Here is my code: from tkinter import * from PIL import Image, ImageTk import cv2 import threading cap = cv2.VideoCapture(0) root = Tk() def videoLoop(): global root global cap vidLabel = None while True: ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = Image.fromarray(frame) frame = ImageTk.PhotoImage(frame) if vidLabel: vidLabel.configure(image=frame) else: vidLabel = Label(root, image=frame, anchor=NW) vidLabel.pack(expand=YES, fill=BOTH) videoThread = threading.Thread(target=videoLoop, args=()) videoThread.start() root.mainloop() Could anyone suggest what I might be doing wrong? I did hear that Tkinter doesn't always play well with threads, but that's about all I can think of. In response to a comment suggesting the flicker is caused by label updating, I added some code that still reads from video and updates the label within the loop, but uses an image loaded outside of the loop to update the label. The flicker then goes away, although (to my understanding) the efficiency of the loop and updating of the label hasn't changed. Here is the changed videoLoop function (with flicker gone): def videoLoop(): global root vidLabel = None cap = cv2.VideoCapture(0) ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = Image.fromarray(frame) frame = ImageTk.PhotoImage(frame) while True: ret, lame = cap.read() lame = cv2.cvtColor(lame, cv2.COLOR_BGR2RGB) lame = Image.fromarray(lame) lame = ImageTk.PhotoImage(lame) if vidLabel: vidLabel.configure(image=None) vidLabel.configure(image=fram…
has answer: http://stackoverflow.com/a/48371716

http://stackoverflow.com/comment/84053437
type: Comment
type: AnswerComment
has text: I opened [an issue on the bug tracker](https://bugs.python.org/issue32698) but I closed it shortward after that because there is a workaround using [`gzip.GzipFile()`](https://docs.python.org/3/library/gzip.html#gzip.GzipFile).
comment on: http://stackoverflow.com/a/48489587
score: 1

http://stackoverflow.com/comment/83977487
type: QuestionComment
has text: I thinks it's wiser to move to Python3 anyhow, since Python2 is discontinued and your issue does not take place on Python3
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48353601

http://stackoverflow.com/q/48384452
type: Question
has answer: http://stackoverflow.com/a/48384666
has comment: http://stackoverflow.com/comment/83756045
possible better answer: http://stackoverflow.com/a/48384807
has comment: http://stackoverflow.com/comment/83756052
has comment: http://stackoverflow.com/comment/83756673
has title: check if a string in a list is a subset of another string in the same list
tagged with: python
has body: I am working on a python script with a list of strings. I want to create a method that takes in a list of strings and returns a list of supersets and removes the subsets. Consider the below case: A = ['this is a sentence', 'who is alice', 'sentence', 'hi i am carrot', 'i am carrot'] Now if you see the array A, it has two elements that are a pair superset and subset, 'this is a sentence' is a superset of 'sentence' and similarly 'hi i am carrot' and 'i am carrot' I want to write a function that removes the subsets from the list and returns the updated list. In the above example the output would look like: ResultA = ['this is a sentence', 'who is alice', 'hi i am carrot'] I've written a quick code sample that can showcase what I am looking for but the I am not sure if using two for loops is the right way: elements_to_keep = [] for i in phase_two_match: for j in phase_two_match: if i == j: continue else: if j not in i: elements_to_keep.append(j)
has comment: http://stackoverflow.com/comment/83756008
score: 2
type: AnsweredQuestion
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/83756188
has comment: http://stackoverflow.com/comment/83756716
downvote count: 0
has answer: http://stackoverflow.com/a/48384807
has comment: http://stackoverflow.com/comment/83756709
has comment: http://stackoverflow.com/comment/83756108
has comment: http://stackoverflow.com/comment/83756042
has answer: http://stackoverflow.com/a/48384921
has comment: http://stackoverflow.com/comment/83756009
accepted answer: http://stackoverflow.com/a/48384666
favorite count: 0

http://stackoverflow.com/a/48345457
has body: Several issues here, first the range separator inside a quantifier is a comma not a hyphen, so: {4,15} instead of {4-15}. Second, you need to match both my and My, so the match should be case insensitive (re.IGNORECASE). Third, if you use a capturing parentheses group (the round brackets) with finditer then you don't need to hack off the prefix. Try this: import re def suffix(txt, prefix): rv = [] for m in re.finditer(prefix + r' (\w{4,15})', txt, re.IGNORECASE): rv.append(m.groups()[0]) return rv print suffix("My mother gave my sister my robot.", "my") Gives: ['mother', 'sister', 'robot'] Depending on needs, \b (word boundary) might be better than a space to separate words. For example: "my, and your, stuff" would not match using a space.
type: Answer
answers question: http://stackoverflow.com/q/48345250
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83730682
type: AnswerComment
has text: Not my code, just curious to see what's going on here since it didn't jump out immediately for me when I scanned it. In any case, thank you :)
comment on: http://stackoverflow.com/a/48371821
type: Comment
score: 0

http://stackoverflow.com/comment/89522340
has text: Read: https://learnbatta.com/blog/usage-of-group_by-string_agg-in-django-postgresql-74/
type: QuestionComment
comment on: http://stackoverflow.com/q/48353485
score: 1
type: Comment

http://stackoverflow.com/q/48424045
has answer: http://stackoverflow.com/a/49461895
tagged with: excel
favorite count: 0
linked to: http://stackoverflow.com/q/69488725
upvote count: 30
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/58593151
has title: How to read SharePoint Online (Office365) Excel files in Python with Work or School Account?
tagged with: sharepoint-online
score: 30
type: Question
tagged with: office365
has comment: http://stackoverflow.com/comment/84281335
has comment: http://stackoverflow.com/comment/84433938
type: UnansweredQuestion
has body: I am a university student and I have registered as an Office 365 Education user via my university Email address. I usually log into https://www.office.com with my Email account: alice@abc.edu. The path to my profile is like: https://abcedu-my.sharepoint.com/personal/alice_abc_edu I have an Excel (.xlsx) file in my Office 365. And I want to use Python to programmatically access (or download) the Excel file. I have googled about some solutions. But most of them require a NTLM credential. But I only have my Email account and password. I don't know my NTLM credential. Is it alice@abc.edu or alice_abc_edu? Or the Email username and NTLM are totally different authentication ways. And I can't use NTLM? It seems that my Email address that is used to log in is officially called Work or School Account or Azure Active Directory Credential. But I don't know how to use such an account to realize my requirement? Moreover, I need to do it in Python. RESTful would also be OK. But I just got stuck in the first authentication step. Thanks! I have followed the Microsoft Graph tutorial here and it told me to register a Python app. Then I got a App ID and App Secret. But when I use the official python-sample-send-mail """send-email sample for Microsoft Graph""" # Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. # See LICENSE in the project root for license information. import base64 import mimetypes import os import pprint import uuid import flask from flask_oauthlib.client import OAuth import config APP = flask.Flask(__name__, template_folder='static/templates') APP.debug = True APP.secret_key = 'development' OAUTH = OAuth(APP) MSGRAPH = OAUTH.remote_app( 'microsoft', consumer_key=config.CLIENT_ID, consumer_secret=config.CLIENT_SECRET, request_token_params={'scope': config.SCOPES}, base_url=config.RESOURCE + config.API_VERSION + '/', request_token_url=None, access_token_method='POST', access_token_url=config.AUTHORITY_URL + config.TOKEN_ENDPOINT, authorize_…
downvote count: 0
tagged with: sharepoint
has answer: http://stackoverflow.com/a/69680555

http://stackoverflow.com/comment/83931861
type: QuestionComment
comment on: http://stackoverflow.com/q/48468827
has text: @MeghaliAgrawal how come you get different result for `matrix multiplication` ? ;) Please check your array inputs. Are you sure that you're running the code that you posted?
score: 1
type: Comment

http://stackoverflow.com/comment/83950907
type: QuestionComment
score: 0
has text: Is this a dictionary or a string?
comment on: http://stackoverflow.com/q/48478896
type: Comment

http://stackoverflow.com/comment/106979700
type: AnswerComment
comment on: http://stackoverflow.com/a/60467040
has text: it did solve my problem because I was successfully able to execute my program and it had created two .pkl files as expected.
type: Comment
score: 1

http://stackoverflow.com/comment/83955108
comment on: http://stackoverflow.com/a/48479105
score: 1
type: Comment
type: AnswerComment
has text: Isn't this just the code from the question with an altered function name? You should include an explanation for your answer. How did you solve it, why is your code different, and so on.

http://stackoverflow.com/a/48357148
upvote count: 1
score: 1
has body: Something like this maybe? import aiohttp import asyncio loop = asyncio.get_event_loop() async def main(): async with aiohttp.ClientSession() as session: ws = await session.ws_connect("ws://192.168.86.31:8000/hello") while True: data = await ws.receive() print(data) multiple_coroutines = [main() for _ in range(10)] loop.run_until_complete(asyncio.gather(*multiple_coroutines))
answers question: http://stackoverflow.com/q/48355353
has comment: http://stackoverflow.com/comment/83717996
type: Answer
has comment: http://stackoverflow.com/comment/83718352
downvote count: 0

http://stackoverflow.com/q/48365275
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/1271320
has body: I have just started learning python Generator For the following code getting a blank list Aircraft_typelst = ['Boeing','Airbus','MiJ','goes'] upper_case_name = ( name.upper() for name in Aircraft_typelst ) print(list(upper_case_name)) reverse = (rev[::-1]for rev in upper_case_name) print(list(reverse)) Output ['BOEING', 'AIRBUS', 'MIJ', 'GOES'] []
has answer: http://stackoverflow.com/a/48365285
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83717232
answer count: 1
favorite count: 0
tagged with: list
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/1271320
has comment: http://stackoverflow.com/comment/83717152
has comment: http://stackoverflow.com/comment/83717212
tagged with: generator
tagged with: python-3.x
linked to: http://stackoverflow.com/q/45400013
has title: Generator is empty after initial use
accepted answer: http://stackoverflow.com/a/48365285

http://stackoverflow.com/q/48400133
has comment: http://stackoverflow.com/comment/83788205
has title: Is there a regex statement to remove all print() statements from my Python/Django project?
has comment: http://stackoverflow.com/comment/83810726
has comment: http://stackoverflow.com/comment/83788445
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83788214
score: -3
has answer: http://stackoverflow.com/a/48400463
tagged with: django
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83788357
has comment: http://stackoverflow.com/comment/83788145
downvote count: 3
answer count: 1
has body: I'm preparing to go into production so want to remove all my print() statements before pushing my development code onto my server. Wondering if there is a clean way to do this.
has comment: http://stackoverflow.com/comment/83810635
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83789755

http://stackoverflow.com/q/48405442
score: 1
has comment: http://stackoverflow.com/comment/83800002
has answer: http://stackoverflow.com/a/48405725
downvote count: 1
has comment: http://stackoverflow.com/comment/83799913
favorite count: 0
has title: Why this code for Linked List is showing error in HackerRank?
has comment: http://stackoverflow.com/comment/83799862
type: Question
answer count: 2
has body: I have implemented the linked list with this code in IDLE. If I traverse it shows the expected output. But in hackerrank I'm in trouble. What am I missing? Here is the problem link class Node: def __init__(self,data=None,next_node = None): self.data = data self.next_node = next_node def get_data(self): return self.data def get_next(self): return self.next_node def set_next(self,new_next): self.next_node = new_next class LL: def __init__(self,head=None,tail=None): self.head = head #head self.tail = tail #tail def Insert(self,data): new_node = Node(data) #new_node new_node.set_next(None) if self.head == None: self.head = new_node self.tail = new_node else: self.tail.set_next(new_node) self.tail = new_node
upvote count: 2
has comment: http://stackoverflow.com/comment/83799566
tagged with: python
tagged with: data-structures
has comment: http://stackoverflow.com/comment/83800383
type: AnsweredQuestion
tagged with: linked-list
possible better answer: http://stackoverflow.com/a/48406050
accepted answer: http://stackoverflow.com/a/48405725
has comment: http://stackoverflow.com/comment/83799696
has answer: http://stackoverflow.com/a/48406050

http://stackoverflow.com/q/48413249
type: Question
type: UnansweredQuestion
tagged with: python
has title: tensor flow copy an entire graph
score: 0
has body: I am trying to create a fairly generic genetic algorithm implementation I'm TensorFlow. I have an implementation that is slow and am trying to increase its speed. I will provide a really simple example of where the program is getting slow and would welcome recommendations of improving the speed of the current implementation. Let us say that we create the following: W = tf.Variable(tf.convert_to_tensor(Warr, dtype=tf.float32)) X = tf.placeholder(dtype=tf.float32, shape=(3, None)) y = tf.placeholder(dtype=tf.float32, shape=(None) ) And we want to find W for the condition: Warr = np.array([[0.1, 0, 0]]) Xarr = np.random.random((3, 100)) yarr = np.dot(Warr, Xarr) A naive implementation (like the one I have created) goes thus: 1 a cost function is created for this implementation: yHat = tf.matmul(W, X) costFunction = tf.reduce_mean( tf.sqrt((y - yHat)*(y - yHat)) ) Note that the cost function can be arbitrarily complex and is not known apriori. Hence, it is something that will be passed into a class. Note that the rest of the code are excerpts within a class, but the main idea is easy to follow: 2 A population is generated (within a class). self.population = [] for i in tqdm(range(self.GAconfig['numChildren'])): temp = [] for j, v in enumerate(locVars): v = (v + (np.random.random( v.shape ) - 0.5) * 2) v = tf.Variable(tf.convert_to_tensor(v, dtype=tf.float32)) temp.append(v) self.population.append( temp ) Finding the cost function for this population is a rather arduous task. First copy the weights in the population into the original weight tensor and then calculate the original cost function: for ps in self.population: for i, v in enumerate(self.variables): sess.run(tf.assign( self.variables[i], ps[i] )) result = sess.run(self.costFunction, feed_dict={ self.X : X, self.y : y }) This implementation is obviously slow. One possible way would be to to generate a set of cost function tensors rather than weight variables, which can all be updated at once. However, this is the…
answer count: 1
has answer: http://stackoverflow.com/a/51401424
tagged with: tensorflow

http://stackoverflow.com/comment/83802506
score: 1
comment on: http://stackoverflow.com/a/48406419
has text: Another option would be `pd.crosstab(df.col1, df.col2).replace({1: np.nan}).stack()...`
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48368605
score: 1
downvote count: 0
upvote count: 1
has body: Your first problem is that your detail path is invalid: path('bajki/(?P&lt;pk&gt;\d+)/$', views.detale_bajki, name='detale_bajki'), If you want to use a regex, then use re_path. With path you should use &lt;converter:name&gt; instead. path('bajki/&lt;int:pk&gt;/', views.detale_bajki, name='detale_bajki'), Then, if you want to use a slug in the URL then change it to: path('bajki/&lt;slug&gt;/', views.detale_bajki, name='detale_bajki'), You'll then need to update the view: def detale_bajki(request, slug): detale_bajki = get_object_or_404(Wpisy, slug=slug) Finally, you need to use the slug when you reverse the URL, e.g.: {% url 'detale_bajki' slug=bajki.slug %}
type: Answer
answers question: http://stackoverflow.com/q/48367153

http://stackoverflow.com/a/48359404
score: 1
has comment: http://stackoverflow.com/comment/83705983
downvote count: 1
upvote count: 2
answers question: http://stackoverflow.com/q/48359150
type: Answer
has body: In check_if_sorted you do not check for equal. This causes the duplicates in your list to trigger another (unneeded) calling to bubble_sort causing an infinite loop. To fix it change the comparison line in check_if_sorted to: if details[i] &lt;= details[i+1]: Edit: This solves the infinite loop, However your algorithm is very inefficient. To improve your algorithm I suggest a google search for 'bubble sort algorithm', and/or a discussion with your instructor

http://stackoverflow.com/comment/83857090
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48432904
has text: @juanpa.arrivillaga Correct. That's why I said _if all `list2` items are unique_.

http://stackoverflow.com/a/48404322
score: 0
has comment: http://stackoverflow.com/comment/83797563
has body: Iteration on dictionary with map can be used: for k,v in a.items(): a[k] = "".join(map(lambda c: c if 32&lt;ord(c)&lt;127 else " " , v)) print(a) give following output: {'name': 'pks ', 'age': '12 '}
answers question: http://stackoverflow.com/q/48403793
type: Answer

http://stackoverflow.com/q/48387397
has comment: http://stackoverflow.com/comment/83762381
has comment: http://stackoverflow.com/comment/83766614
has comment: http://stackoverflow.com/comment/83824128
answer count: 2
has comment: http://stackoverflow.com/comment/83762314
downvote count: 0
tagged with: cmd
has comment: http://stackoverflow.com/comment/83766661
favorite count: 0
has answer: http://stackoverflow.com/a/48394087
type: Question
has answer: http://stackoverflow.com/a/48398853
tagged with: python
has comment: http://stackoverflow.com/comment/83763800
type: UnansweredQuestion
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/83762919
has body: I have written a script in python 3.5. I have made an .exe file of it using pyinstaller. The script has some print statements which are displayed in the console during execution. When i ran my script from command prompt i can see all the messages in my cmd but when i run .exe file from cmd than i do not see any msgs in command prompt. Is there any way to see msgs in command prompt from .exe file. For example lets suppose below is my script named abc.py: def sum(): first = 5 print('First number is {}'.format(first)) second = 10 result = first + second print('second number is {}'.format(second)) print('Sum is = {}'.format(result)) sum() Now when i run this file from cmd like: python \pathto\abc.py, i can see all the messages in cmd. Now when i make .exe of this and now do something like \pathto\abc.exe from cmd then i do not see anything. Is there anyway to see ,msgs in a cmd from .exe file?
tagged with: exe
tagged with: command-line
has comment: http://stackoverflow.com/comment/83767355
has title: How to see Python executable output in a cmd window?

http://stackoverflow.com/q/48405674
tagged with: templates
has answer: http://stackoverflow.com/a/48457119
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83803414
has body: So I have looped over an object variable in the respective template in Django, every item loops over well except the image variable. I am not sure what I am doing wrong. But here are my codes: MODEL: See where I have routed the uploaded image files. class Car(models.Model): def fileLocation(instance, filename): return 'media/cars/{0}/{1}'.format(instance.agent.username, os.path.basename(filename)) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField() car_registration = models.CharField(max_length=100, unique=True) insurance_exp = models.DateField(max_length=100) cost_per_day = models.IntegerField() description = models.TextField(max_length=1000) agent = models.ForeignKey(Agent, on_delete=models.CASCADE) image1 = models.ImageField(upload_to=fileLocation) image2 = models.ImageField(upload_to=fileLocation) image3 = models.ImageField(upload_to=fileLocation) image4 = models.ImageField(upload_to=fileLocation) image5 = models.ImageField(upload_to=fileLocation) available = models.BooleanField() added_date = models.DateField(default = timezone.now()) def __str__(self): return self.model VIEW: from django.shortcuts import render from .models import Car, Agent # Create your views here. def index(request): all_cars = Car.objects.all() context = {'all_cars':all_cars} return render(request, "home.html", context) TEMPLATE (home.html): {% extends 'basic.html' %} {% block content %} {% for car in all_cars %} {{car.make}} {{car.model}} {{car.description}} Kshs {{car.cost_per_day}} Per Day {% if car.available == True %} Available {% else %} Not Available When will it be available? {% endif %} {% endfor %} {% endblock %} SETTINGS.PY: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media')…
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83821109
score: 0
has comment: http://stackoverflow.com/comment/83800714
has title: ImageField variable in Django Template
answer count: 1

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/48441863
type: Tag

http://stackoverflow.com/a/48574297
score: 33
answers question: http://stackoverflow.com/q/48373419
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48373419
has comment: http://stackoverflow.com/comment/84224485
type: Answer
has body: This just got me as well, looks like you're using a DynamoDB resource, not a client. They both provide the same function but it acts very slightly differently. Here's what you're looking for: http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.ServiceResource.batch_write_item That aside, the docs are still pretty unclear. Here's what I found: When using a resource (what you're currently doing), you may specify the type of non-key attributes, and you must not specify the type of key attributes When using a client (the other option), you must specify the type of all attributes. Using the DynamoDB resource: resource = boto3.resource('dynamodb', endpoint_url='http://localhost:8000') mytable = resource.create_table( TableName='mytable', KeySchema=[{ 'AttributeName': 'name', 'KeyType': 'HASH' }], AttributeDefinitions=[{ 'AttributeName': 'name', 'AttributeType': 'S' }], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) try: resource.batch_write_item(RequestItems={ 'mytable': [{ 'PutRequest': { 'Item': { 'name': { 'S': 'myname' }, 'value': { 'S': 'myvalue' } }}}] }) print(f'resource, specify all types : write succeeded.') except Exception as e: print(f'resource, specify all types : write failed: {e}') try: resource.batch_write_item(RequestItems={ 'mytable': [{ 'PutRequest': { 'Item': { 'name': 'myname', 'value': { 'S': 'myvalue' } }}}] }) print(f'resource, specify value only: write succeeded.') except Exception as e: print(f'resource, specify value only: write failed: {e}') try: resource.batch_write_item(RequestItems={ 'mytable': [{ 'PutRequest': { 'Item': { 'name': 'myname', 'value': 'myvalue' }}}] }) print(f'resource, specify none : write succeeded.') except Exception as e: print(f'resource, specify none : write failed: {e}') Output resource, specify all types : write failed: An error occurred (ValidationException) when calling the BatchWriteItem operation: Invalid attribute value type resource, specify value only: wri…
upvote count: 33

http://stackoverflow.com/comment/83847399
type: Comment
type: QuestionComment
has text: In the above code solution is `htext.delete('end-1c', 'end')`. But you should be aware of what you're putting in your widget, so it's only a cope out if you don't know.
score: 0
comment on: http://stackoverflow.com/q/48426950

http://stackoverflow.com/q/48348611
has comment: http://stackoverflow.com/comment/83711422
upvote count: 6
has comment: http://stackoverflow.com/comment/83857123
has comment: http://stackoverflow.com/comment/83908837
tagged with: python
accepted answer: http://stackoverflow.com/a/48441636
has answer: http://stackoverflow.com/a/58911785
has comment: http://stackoverflow.com/comment/84088933
has comment: http://stackoverflow.com/comment/83871713
possible better answer: http://stackoverflow.com/a/52541212
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52541212
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83836293
has comment: http://stackoverflow.com/comment/83825997
score: 6
tagged with: glpk
has title: How to use GLPK with cvxopt in Windows 10?
tagged with: cvxopt
has answer: http://stackoverflow.com/a/48441636
has comment: http://stackoverflow.com/comment/83866277
favorite count: 0
type: Question
has body: I use 64 bit Windows 10. I downloaded glpk-4.64 for Windows. I unzipped the file to my documents. I added the w64 path in this folder to Windows' environment variables. I check if the glpk works in command line by executing this: C:\Users\userz&gt;glpsol GLPSOL: GLPK LP/MIP Solver, v4.64 No input problem file specified; try glpsol --help So I think glpk is installed properly. Then I install cvxopt using this in command line: python -m pip install cvxopt Then it installs cvxopt. When I do: import cvxopt.glpk I get this error: import cvxopt.glpk ImportError: No module named glpk So, how do I fix this?

http://stackoverflow.com/q/48402245
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48402383
has comment: http://stackoverflow.com/comment/83793554
has comment: http://stackoverflow.com/comment/83793164
has comment: http://stackoverflow.com/comment/83792860
has comment: http://stackoverflow.com/comment/83792708
tagged with: virtualenv
answer count: 1
type: Question
has title: source /bin/activate activates the system interpreter not the venv one
has comment: http://stackoverflow.com/comment/83792810
tagged with: python
has comment: http://stackoverflow.com/comment/83793500
has comment: http://stackoverflow.com/comment/83793303
accepted answer: http://stackoverflow.com/a/48402383
has comment: http://stackoverflow.com/comment/83792581
has body: When I run source bin/activate , the virtual environment seems to be activated since I can see (venv). However when I run which python , I realise its using the system wide interpreter i.e /usr/bin/python and therefore any modules in install are installed system wide. I created the virtual environment using Pycharm and when I my scripts through Pycharm, it works fine. But right now I need to run them through terminal and therefore I need the virtual environment.

http://stackoverflow.com/comment/84849767
has text: my data format and data is as specified by 'data_values' and as specified by the 'Storing Data' header in 'https://happybase.readthedocs.io/en/latest/user.html' I do think I am doing it right, but please let me know if something is wrong. As for the column families, the happybase docs does not mention providing column familes while getting connection to a table.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48444293
score: 0

http://stackoverflow.com/a/48452536
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has body: You can remove every non-digit and slice the last 10 digits. df.PNum1.str.replace('\D+', '').str[-10:] 0 8888888888 1 1999999999 2 1231243134 Name: PNum1, dtype: object
accepted answer of: http://stackoverflow.com/q/48452090
answers question: http://stackoverflow.com/q/48452090

http://stackoverflow.com/a/48376037
has body: Your specific issue at the moment is caused by the check in your __next__ method not being general enough to detect all situations where you've iterated past the last value in self.contents. Since self.contents can change, you need to use a greater-than-or-equal test: if self.index &gt;= len(self.contents): This will fix the current issue, but you'll still have other problems, since your Deck can only be iterated once. That's because you've implemented the iterator protocol, rather than the iterable protocol. These are easy to confuse, so don't feel bad if you don't understand the difference immediately. An iterable is any object with an __iter__ method that returns an iterator. Some iterables return different iterators each time they're called, so you can iterate on them multiple times. An iterator implements a __next__ method, which yields the next value or raises StopIteration. An iterator must also have an __iter__ method, which returns itself, which allows an iterator to be used wherever an iterable is expected, though it can only be iterated on once. For your Deck, it probably makes sense to implement the iterable protocol, and return a separate iterator each time __iter__ is called. It's only rarely useful to implement your own iterator type, but if you want to test your knowledge of how the different protocols fit together, it can be interesting: class Deck: def __init__(self): self.contents = [Card(suite, rank) for suite in Card.get_suites() for rank in Card.get_ranks()] random.shuffle(self.contents) # no index here def __iter__(self): return DeckIterator(self) # other methods, but no __next__ class DeckIterator: def __init__(self, deck): self.deck = deck self.index = 0 def __iter__(self): return self def __next__(self): if self.index &gt; len(self.deck): raise StopIteration value = self.deck.contents[self.index] self.index += 1 return value A more practical approach is to have Deck.__iter__ borrow some convenient iterator type. For instance, you could do r…
answers question: http://stackoverflow.com/q/48375250
type: Answer
score: 0

http://stackoverflow.com/comment/83657336
has text: look at this example https://docs.python.org/2.3/lib/node304.html
comment on: http://stackoverflow.com/q/48336095
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85736725
score: 1
has text: Can you elaborate?
type: Comment
comment on: http://stackoverflow.com/a/49367599
type: AnswerComment

http://stackoverflow.com/comment/83862237
comment on: http://stackoverflow.com/q/48434459
score: 0
has text: would you agree with my assumption that the correct size of `y_trn` should be: (160 x 128 x 128 x 7) , which would then be fed to `model.fit` ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48467027
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83927608
has comment: http://stackoverflow.com/comment/83927610
has body: Below code : import json j = json.loads(" {\"id123\":{\"test\" : 1} } ") j renders : {'id123': {'test': 1}} I'm attempting to access the property test while ignoring the outer property id. This can be achieved using : j['id123']['test'] which returns 1 But as I do not know ahead of time what value the key will be ( in this case it's id123 ) is there a generic way to access the value of property test while omitting the property key id123 ?
tagged with: python
has comment: http://stackoverflow.com/comment/83927531
has answer: http://stackoverflow.com/a/48467444
has answer: http://stackoverflow.com/a/48467086
accepted answer: http://stackoverflow.com/a/48467444
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48467385
has comment: http://stackoverflow.com/comment/83928166
answer count: 3
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has title: How to access inner json property value while ignoring outer property key?
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/48467086

http://stackoverflow.com/comment/83741463
comment on: http://stackoverflow.com/q/48375484
type: QuestionComment
has text: such as the first two row 33,Jogging,49105962326000,-0.6946377,12.680544,0.50395286; 33,Jogging,49106062271000,5.012288,11.264028,0.95342433; The output file's data is 33,Jogging,99945000.0,5.7069257,-1.4165159999999997,0.4494714700000001 If the two lines of data are the same activity, perform a subtractive operation.The latter four column of output data is generate by second row reduce first row.
score: 0
type: Comment

http://stackoverflow.com/a/48398132
answers question: http://stackoverflow.com/q/48397845
has body: You have to initialize the variable newsockfd (and declare it ? ) before read and you need a variable of type socklen_t something like : socklen_t addr_size = sizeof cli_addr; newsockfd = accept(sockfd,&amp;cli_addr,&amp;addr_size); and just then use the read function.
type: Answer
score: 0

http://stackoverflow.com/comment/83766916
comment on: http://stackoverflow.com/q/48389545
score: 1
type: QuestionComment
type: Comment
has text: What do you mean by "add each values from series2 to the new expanded dimension"? Do you mean that you want each `series1[:,:,i]` to be equal to `series1[:,:] + series2[:, i]`?

http://stackoverflow.com/q/48434459
has comment: http://stackoverflow.com/comment/83862145
has comment: http://stackoverflow.com/comment/83862414
has comment: http://stackoverflow.com/comment/83873350
has title: How can I apply one-hot encoding correctly in Keras for a 2D pixel image classification CNN?
has comment: http://stackoverflow.com/comment/83862321
type: Question
tagged with: one-hot-encoding
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83862237
has body: I am working on a 2D RGB pixel-based image classification problem via convolution neural networks (CNN). I will fully describe my problem and provide as much details as possible. I split my training and validation as follows: x_trn, x_val, y_trn, y_val = train_test_split(img, msk,test_size=0.2, random_state=42) where img is an array of (number_of_image_patches x image_rows x image_columns x number_of_image_channels). So I have 200 RGB(i.e., 3 channels) image patches at 128x128 each. Thus, the img array is a (200 x 128 x 128 x 3). Also, msk is an array containing the class labels of each image patch that will be used to train the CNN and has a size of (200 x 128 x 128). Each msk patch is a 128x128 array with the class labels. In my problem, I have 7 classes. Since my problem is a multi-class classification, I am using categorical_crossentropy as my loss function. And softmax as my activation function for output results. My full CNN model can be found here. The shape of y_trn is (160 x 128 x 128) and y_val is (40 x 128 x 128). Now, categorical_crossentropy requires that the y_trn and y_val variables to be one-hot encoded. I do this as follows: from keras.utils import to_categorical y_trn= to_categorical(y_trn, num_classes=len(np.unique(y_trn))) y_val= to_categorical(y_val, num_classes=len(np.unique(y_val))) The new shape of y_trn after applying one-hot encoding is (2621440 x 7) due to the fact that I have 7 classes. The 2621440 comes from the multiplication of 160x128x128 Afterwards, I do the following to train/fit the CNN model: model = my_CNN_unet() model_checkpoint = ModelCheckpoint('unet6_test_{epoch:02d}.hdf5') model.fit(x_trn, y_trn, batch_size=50, epochs=3, verbose=1, shuffle=True, callbacks=[model_checkpoint], validation_data=(x_val, y_val)) But I get the following error: ValueError: Error when checking target: expected conv2d_138 to have 4 dimensions, but got array with shape (2621440 , 7) This means that my one-hot encoding is obviously not being applied cor…
tagged with: keras
has comment: http://stackoverflow.com/comment/83862370
has comment: http://stackoverflow.com/comment/83862773
has comment: http://stackoverflow.com/comment/83863098
has comment: http://stackoverflow.com/comment/83862843
score: 0
has comment: http://stackoverflow.com/comment/83861696
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/83862678
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83861636
has comment: http://stackoverflow.com/comment/83862874
tagged with: python

http://stackoverflow.com/comment/83687526
comment on: http://stackoverflow.com/q/48349678
score: 1
type: Comment
type: QuestionComment
has text: I've updated the question, hopefully that makes it more clear!

http://stackoverflow.com/comment/83904694
type: AnswerComment
has text: This is great, perfect example of [EAFP](https://docs.python.org/2/glossary.html)
comment on: http://stackoverflow.com/a/48441455
type: Comment
score: 0

http://stackoverflow.com/comment/83784295
type: AnswerComment
comment on: http://stackoverflow.com/a/48343166
score: 0
type: Comment
has text: I created the credentials through this link https://cloud.google.com/storage/docs/authentication#service_accounts. I can load data to BigQuery using cmd, but when using the task scheduler with the same commands my code never ends. I am building a machine learning classifier using for 4 computer nodes.

http://stackoverflow.com/comment/83946598
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48476162
has text: if I try to run "pip install Adafruit_Python_DHT" in ~/berryconda3/bin the output is: Collecting Adafruit_Python_DHT Using cached Adafruit_Python_DHT-1.1.2.tar.gz Complete output from command python setup.py egg_info: [....] import platform_detect ModuleNotFoundError: No module named 'platform_detect'
score: 0

http://stackoverflow.com/q/48368879
has answer: http://stackoverflow.com/a/48369125
has comment: http://stackoverflow.com/comment/83724521
has comment: http://stackoverflow.com/comment/83724642
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83724416
has comment: http://stackoverflow.com/comment/83724434
tagged with: python
has title: regex help to remove a +
has answer: http://stackoverflow.com/a/48368948
tagged with: bash
answer count: 3
has answer: http://stackoverflow.com/a/48369103
has body: I am having a problem with a + sign. Here is my format of my CSV wifichannelnumber+ssid+macaddress of AP Here is an example of a good line 6+Jills-Equinox+78:61:7c:19:xx:xx And here is the problem mine. Note the + next to S8. 11+Samsung-Galaxy-S8+-4469+a2:cc:2b:8d:xx:xx I would like to remove plus in bash or python (Edit) for a whole CSV
tagged with: regex
downvote count: 1
has comment: http://stackoverflow.com/comment/83724552
favorite count: 0
score: -1
type: Question

http://stackoverflow.com/comment/83797480
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48404453
type: Comment
has text: It seemed like all you needed was `df1[df1.columns.intersection(df2.columns)]`.

http://stackoverflow.com/comment/83898349
type: Comment
score: 0
has text: I guess what I need then is just to be able to use subprocess as a specific user?
type: QuestionComment
comment on: http://stackoverflow.com/q/48452316

http://stackoverflow.com/comment/83654827
has text: No, pandas ignores NaNs. OTOH, those empty strings won't. Do you want them ignored or no?
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48334572

http://stackoverflow.com/a/48351306
score: 1
downvote count: 0
has body: Here, I have to use driver.execute_script("window.scrollTo(0, Y)") Y is the height, to scroll down the page.
answers question: http://stackoverflow.com/q/48350906
type: Answer
upvote count: 1

http://stackoverflow.com/a/59060980
type: Answer
has body: This works in Tensorflow 2.0. import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Layer class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim self.update = [] super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # Create a trainable weight variable for this layer. self.my_kernel = self.add_weight(name='my_kernel', shape=(input_shape[1], self.output_dim), initializer='uniform', trainable=True) super(MyLayer, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): return K.dot(x, self.kernel) def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) my_layer = MyLayer((1))
score: 0
answers question: http://stackoverflow.com/q/48353617

http://stackoverflow.com/comment/83885718
comment on: http://stackoverflow.com/a/48446782
type: Comment
score: 0
type: AnswerComment
has text: @Wondercricket If a user inputted a animal it will output in a seperate array like he is trying to get ^^^ . It is a suggestion might need a few tweaks.

http://stackoverflow.com/comment/83912245
score: 0
has text: I have accepted the answer with the scipy.stats.mode solution which leads to the smallest of the two. But suppose I want the largest, how would I control it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48448091

http://stackoverflow.com/comment/83861638
type: QuestionComment
has text: `literal_eval`, please.
score: 0
comment on: http://stackoverflow.com/q/48435051
type: Comment

http://stackoverflow.com/a/48412602
has comment: http://stackoverflow.com/comment/83832588
score: 0
has body: your dict does not have duplicate keys, that is not possible in python without monkey patching what you have created is a dictionary of lists that contain the values {a:[b,c],b:[d]} to convert such a dict into tuples, simply iterate over the lists data = {"a":["b","c"], "b":["d"]} def to_tuples(data_dictionary): for key, values in data_dictionary.items(): for value in values: yield key, value print(list(to_tuples(data))) &gt;&gt;&gt;[('a', 'b'), ('a', 'c'), ('b', 'g')]
answers question: http://stackoverflow.com/q/48412437
has comment: http://stackoverflow.com/comment/83817753
type: Answer

http://stackoverflow.com/a/48363414
score: 1
upvote count: 1
has body: The print statement you have there is misleading you -- the worker process does not terminate at the end of the function. In fact, the worker processes stay alive until the pool is closed. Additionally, multiprocessing already takes care of breaking up the list into chunks and queueing up each task for you. As for your other question, normally you would pass a callback to map_async if you wanted to trigger an asynchronous event upon the entire list being completed. Calling once per chunk takes some mucking about with the internals, but if you really want to you could: def mapstar_custom(args): result = list(map(*args)) print "Task completed" return result ... pool._map_async(f, x, mapstar_custom, None, None, None).get() Edit: we seem to be conflating terminology. When I say worker I mean the processes the pool spawns, whereas you seem to mean the processes Selenium spawns from those processes (which wasn't in your question). Opening the webdriver only once is easy enough: if you have pool.map(module.task, ...), then in module.py just do: # ... selenium init here ... def task(...): # ... use webdriver ... The module will only be imported once by the pool workers, no matter how many times you dispatch that task. So the top level init will happen only once.
downvote count: 0
answers question: http://stackoverflow.com/q/48363237
type: Answer

http://stackoverflow.com/comment/83777909
has text: This is not the proper way of asking question on stackoverflow.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48395084

http://stackoverflow.com/q/48334315
linked to: http://stackoverflow.com/q/17285154
has comment: http://stackoverflow.com/comment/83733606
favorite count: 0
has comment: http://stackoverflow.com/comment/83658245
type: Question
linked to: http://stackoverflow.com/q/41597177
has comment: http://stackoverflow.com/comment/83733560
answer count: 2
has title: How to fill the bars of a pyplot barchart with arrows?
tagged with: bar-chart
downvote count: 0
linked to: http://stackoverflow.com/q/14279344
upvote count: 1
has comment: http://stackoverflow.com/comment/83724825
has body: I am trying to create a barplot, where the bars contains additional information by letting arrows inside the bar point to cardinal point. For now I only managed to create one with colored bars. Since 8 colors for the direction plus one for nonexisting are needed, it's not as good as I hoped. There is also the difficulty to distinguish colors. import matplotlib.pyplot as plt import numpy as np x = range(12) y_bar = np.random.random(12) colors = ['green', 'yellow', 'blue', 'pink', 'orange'] bar_cols = [ colors[int(b*100) % len(colors)] for b in y_bar] plt.bar(x, y_bar, color=bar_cols) plt.show() Therefore arrows, which point in a direction that is provided by a separate variable, are intuitive and easy to see. I have no clue how to do that. I already tried using hatches, but there seem to be only a limited set of symbols. Is there a way to get some arrows in the bars? EDIT: Here is a pciture, how it can look like, what I am after. The shapes of the arrows can be different. Sure, more pillars are expected. There might even be some without any arrows due to mission data. barchar with arrows
has comment: http://stackoverflow.com/comment/83714073
has comment: http://stackoverflow.com/comment/83724062
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48441031
accepted answer: http://stackoverflow.com/a/48441031
has answer: http://stackoverflow.com/a/48553015
possible better answer: http://stackoverflow.com/a/48553015
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/48508793
has comment: http://stackoverflow.com/comment/83704607
tagged with: python

http://stackoverflow.com/comment/83812351
type: AnswerComment
has text: Ok, thats solved my issue - I'll consider tuples. Thanks for the fast reply.
comment on: http://stackoverflow.com/a/48411245
type: Comment
score: 0

http://stackoverflow.com/comment/83948174
score: 1
type: Comment
has text: https://stackoverflow.com/questions/34046887/django-python-understanding-how-super-is-used-in-function this helped me understand super
comment on: http://stackoverflow.com/a/48477305
type: AnswerComment

http://stackoverflow.com/comment/83959353
type: QuestionComment
score: 0
has text: where does `r_v1` get defined?
comment on: http://stackoverflow.com/q/48483032
type: Comment

http://stackoverflow.com/comment/87646112
score: 0
comment on: http://stackoverflow.com/q/48486042
has text: did you find something to do only inference using gpu ?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48369452
type: Answer
has body: It is because you are using this line if w in line: You are checking if a part of that line contains the input so the below are correct: "w" in "password" -&gt; True "pass" in "password" -&gt; True "word" in "password" -&gt; True and this is of course not correct, you need to check for equality thus: if w == line.strip(): should do the job
score: 2
answers question: http://stackoverflow.com/q/48369377
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83725607

http://stackoverflow.com/a/48392004
has comment: http://stackoverflow.com/comment/83772082
type: Answer
has comment: http://stackoverflow.com/comment/83772059
has comment: http://stackoverflow.com/comment/83772991
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48391851
downvote count: 0
has comment: http://stackoverflow.com/comment/83772011
has comment: http://stackoverflow.com/comment/83773808
has comment: http://stackoverflow.com/comment/83772074
has comment: http://stackoverflow.com/comment/83772179
has body: From a design standpoint, it would make more sense to have a pull_goalie method. Classes are a tool to create more meaningful abstractions. Pulling a goalie is an action. If you think of Team as representing a real-life team, it makes more sense to say "The team pulled their goalie!" rather than "The team set their pulled-goalie attribute to X player!" class Team(object): ... def pull_goalie(self, player): self.pulled_goalie = player tweet = '&lt;your format string&gt;'.format( self.pulled_goalie, # Yes, your Team *could* store a reference to the current game. # It's hard to tell if that makes sense in your program without more context. self.game.period_remaining ) I was going to recommend a property, but I think that would solve the immediate problem without considering broader design clarity. NOTE: There is no such thing as a "private" attribute in Python. There is a convention that attributes beginning with a single underscore (self._pulled_goalie) is treated as private, but that's just so that people using your code know that they can't depend on that value always doing what they think it will. (i.e., it's not part of the public contract of your code, and you can change it without warning.) EDIT: To create a register_team method on a Game object, you might do something like this: class Game(object): def __init__(&lt;stuff&gt;): ... self.teams = {} ... def register_team(self, team): if len(self.teams) &gt; 1: raise ValueError( "Too many teams! Cannot register {} for {}" .format(team, game) ) self.teams[team] = team team.game = self def unregister_team(self, team): try: del self.teams[team] except KeyError: pass team.game = None Note that by using a dictionary, register_team and unregiser_team can be called multiple times without ill effect.

http://stackoverflow.com/comment/83876447
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48442603
has text: use Regular Expressions..
score: 0

http://stackoverflow.com/comment/83702878
has text: EX: outtweets = [[tweet.fullname, tweet.id, tweet.likes, tweet.replies, tweet.retweets, tweet.text.encode('utf-8'),tweet.timestamp,tweet.url,tweet.user] for account in all_tweets for tweet in all_tweets[account]]
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48357410
type: AnswerComment

http://stackoverflow.com/q/48364263
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
answer count: 0
has title: Multiple labels with tensorflow regression
has comment: http://stackoverflow.com/comment/92777952
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/42888277
tagged with: numpy
has body: I'm trying to get a multilabel model going in tensorflow. I saw a related question here: Multiple labels with tensorflow, but couldn't get the solution working. The code is from a tensorflow tutorial. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/input_fn/boston.py FEATURES = ["crim", "zn", "indus", "nox", "rm", "dis", "tax", "ptratio"] LABELS = ["medv", "age"] def get_input_fn(data_set, num_epochs=None, shuffle=True): return tf.estimator.inputs.pandas_input_fn( x=pd.DataFrame({k: data_set[k].values for k in FEATURES}), # y=pd.Series(data_set[LABEL].values), y=list(map(lambda label: data_set[label].values, LABELS)), num_epochs=num_epochs, shuffle=shuffle) In my regression I set the label dimension to 2. regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols, label_dimension=2, hidden_units=[10, 10], model_dir="/tmp/boston_model") With my try I get: Traceback (most recent call last): File "./boston.py", line 85, in &lt;module&gt; tf.app.run() File "/home/jillian/.eb/software/machine-learning/1.00/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 48, in run _sys.exit(main(_sys.argv[:1] + flags_passthrough)) File "./boston.py", line 67, in main regressor.train(input_fn=get_input_fn(training_set), steps=5000) File "./boston.py", line 43, in get_input_fn shuffle=shuffle) File "/home/jillian/.eb/software/machine-learning/1.00/lib/python3.6/site-packages/tensorflow/python/estimator/inputs/pandas_io.py", line 87, in pand as_input_fn 'Index for y: %s\n' % (x.index, y.index)) ValueError: Index for x and y are mismatched. Index for x: RangeIndex(start=0, stop=400, step=1) Index for y: &lt;built-in method index of list object at 0x7f6f64a5bb48&gt; I also tried setting y to a numpy array instead of a list.

http://stackoverflow.com/a/48371434
answers question: http://stackoverflow.com/q/48370122
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I get the impression from your question that the majority of your confusion is in, what should the function return? Should it return a score, or a move? Generally, you should actually split up this thing in two separate functions; A minimax() function, which should look mostly like what you seem to have so far (I did not check in detail for correctness, maybe there are little mistakes, but overall it seems close to fine at least). This should only return an integer/float/whatever, the value of a node (which is defined as either the evaluation function if you're deep enough already, or the max/min of all the children (max or min depending on which player is to move). Something like a choose_move() function, which should return a move to play. It should do this by calling minimax() for all the children, and then returning the move that leads to the child with the greatest value (it's recommended to break ties randomly). Note: There appear to be some mistakes in your code as well, it seems to return too often. For example, in the case of a maximizing player, you already return when you see for the first time that score &gt; best_val, whereas you should continue looping through all the other moves too to figure out if any of them may have an even higher score. The code for the case of the minimizing player should be more ''symmetric'' with the code for the maximizing player, it looks too different now. EDIT: To fix the problem where a score is returned too quickly, this line: return best_move_q_1, best_move_q_2, score should simply be moved outside the loops going through all the possible actions. The idea is, loop through all the actions, evaluate them all (through recursive minimax calls), then return the moves and score associated with the best move. This means it has to be outside of the loops through actions, you cannot already return while still inside those loops because then you haven't finished looping through all the actions and may have missed a better altern…
type: Answer
accepted answer of: http://stackoverflow.com/q/48370122

http://stackoverflow.com/comment/83848493
comment on: http://stackoverflow.com/q/48428917
type: Comment
has text: Can't test atm but my suspicion is that `w_last = w.copy()` might fix the issue, in which case we can direct you to the right resources.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83803224
type: Comment
comment on: http://stackoverflow.com/a/48393240
score: 0
has text: Noted. I will keep my code as it is for now because it's then more naturally extendable.
type: AnswerComment

http://stackoverflow.com/comment/83855615
type: Comment
has text: well, just make a new conda environment, with only pandas, and try and see if you can replicate the behavior. Maybe use a different interpreter: `conda create -n test_pandas python=3.6 pandas`
type: QuestionComment
comment on: http://stackoverflow.com/q/48432038
score: 0

http://stackoverflow.com/a/55066932
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48423782
has body: I use cx_Freeze and package have this error. I add this code to solve this problem: self.build_exe_options = { 'includes': "scipy._distributor_init" }

http://stackoverflow.com/a/48355853
type: Answer
answers question: http://stackoverflow.com/q/48355825
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48355825
has body: It is not recommended to change default python. You just type 'python3' $ python3 yourscript.py Or take a look at this Two versions of python on linux. how to make 2.7 the default
score: 1

http://stackoverflow.com/q/48337016
has comment: http://stackoverflow.com/comment/117045204
tagged with: anaconda
has answer: http://stackoverflow.com/a/64969281
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53091584
has comment: http://stackoverflow.com/comment/83660627
has title: How to uninstall package in Anaconda installed with pip
tagged with: python
linked to: http://stackoverflow.com/q/41060382
has comment: http://stackoverflow.com/comment/117032861
answer count: 4
has answer: http://stackoverflow.com/a/66012782
score: 33
has comment: http://stackoverflow.com/comment/83659624
upvote count: 34
has body: The problem: I have installed Anaconda: conda -V conda 4.4.7 Also I installed a lot of packages for it using python3 setup.py install. I used it for some packages created from setup.py files. Now I want to uninstall one package. What I tried: pip uninstall packageName pip3 uninstall packageName conda uninstall packageName It works for python: check pip list and pip3 list and there isn't such package. Error: But for conda I got this: conda uninstall packageName Solving environment: failed PackagesNotFoundError: The following packages are missing from the target environment: - packageName Let's check: conda list packageName P.S. I found info that conda uninstall and conda remove doesn't work in this case. But what to do then? P.S.S. Actually I changed real package name at packageName but if this information is important I will add it. My info: conda info active environment : None user config file : /home/masamok4/.condarc populated config files : /home/masamok4/anaconda3/.condarc /home/masamok4/.condarc conda version : 4.4.7 conda-build version : 3.0.27 python version : 3.6.3.final.0 base environment : /home/masamok4/anaconda3 (writable) channel URLs : https://conda.anaconda.org/conda-forge/linux-64 https://conda.anaconda.org/conda-forge/noarch https://repo.continuum.io/pkgs/main/linux-64 https://repo.continuum.io/pkgs/main/noarch https://repo.continuum.io/pkgs/free/linux-64 https://repo.continuum.io/pkgs/free/noarch https://repo.continuum.io/pkgs/r/linux-64 https://repo.continuum.io/pkgs/r/noarch https://repo.continuum.io/pkgs/pro/linux-64 https://repo.continuum.io/pkgs/pro/noarch package cache : /home/masamok4/anaconda3/pkgs /home/masamok4/.conda/pkgs envs directories : /home/masamok4/anaconda3/envs /home/masamok4/.conda/envs platform : linux-64 user-agent : conda/4.4.7 requests/2.18.4 CPython/3.6.3 Linux/4.4.0-87-generic ubuntu/16.04 glibc/2.23 UID:GID : 1003:1003 netrc file : None offline mode : False
tagged with: pip
downvote count: 1
has answer: http://stackoverflow.com/a/60492355
favorite count: 0
type: Question

http://stackoverflow.com/q/48430081
upvote count: 2
has comment: http://stackoverflow.com/comment/83851340
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48430523
has answer: http://stackoverflow.com/a/48431846
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/48430523
has body: I am looking for a memory/cpu efficient one-liner to subsample n out of every m elements on a list. So far I have got: sb = [11,12,21,22,31,32]*4 #stream buffer, e.g. 4 identical frames ci = 1 #1-indexed channel index cs = 2 #channel (sample) size nc = 3 #number of channels in each frame fs = nc*cs #frame size [i for l in [sb[j+ci-1:j+ci-1+cs] for j in [x*fs+ci-1 for x in xrange(len(sb)/fs)]] for i in l] Out: [11, 12, 11, 12, 11, 12, 11, 12] Breaking it down I am creating a list of sample lists and then flattening it to a one dimensional list with [i for l in ll for i in l] Alternatively, not a one liner, but easier to read, I can do: os = [] for i in [sb[j+ci-1:j+ci-1+cs] for j in [x*fs+ci-1 for x in xrange(len(sb)/fs)]]: os = os+i Both solutions look way too convoluted when compared, for example, with the super simple shorthand for cs=1 particular case: sb[ci-1::fs]. Can you help me come up with a decent solution?
answer count: 4
has comment: http://stackoverflow.com/comment/83851177
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48431295
has answer: http://stackoverflow.com/a/48431295
has comment: http://stackoverflow.com/comment/83851014
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48430594
has title: Efficient one-liner to subsample `i`th `n` elements out of every `m` elements on a list
favorite count: 0
tagged with: multiplexing
type: Question
has comment: http://stackoverflow.com/comment/83851179

http://stackoverflow.com/comment/83869320
type: QuestionComment
has text: A few advices to avoid these issues: 1) when you open a parentheses, close it right away and *then* insert the code within the parentheses; 2) enable parenthesis matching in your editor; 3) enable a linter in your editor
score: 3
comment on: http://stackoverflow.com/q/48439059
type: Comment

http://stackoverflow.com/comment/83913884
score: 0
comment on: http://stackoverflow.com/q/48446676
type: Comment
has text: Ev. Kounis, certainly, working at this.
type: QuestionComment

monkeypatching
tag name: monkeypatching
type: Tag
tags question: http://stackoverflow.com/q/48350131

http://stackoverflow.com/comment/83920776
score: 2
comment on: http://stackoverflow.com/a/48462317
has text: Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48424990
downvote count: 2
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/83839995
has comment: http://stackoverflow.com/comment/83839745
upvote count: 0
has comment: http://stackoverflow.com/comment/83839907
answer count: 1
has answer: http://stackoverflow.com/a/48425152
tagged with: submatrix
favorite count: 0
type: Question
has body: How can I extract a submatrix from matrix in python? I have a .mat file that when uploaded to python has a nested array that is something similar to the following but with 12,000 items each: letters= array([[(array([[a],[a],[a]]), array([[b],[b],[b]]),array([[c],[c],[c]])]]) I want to separate each submatrix into a matrix, that will be something like this: letter_a= array([[a],[a],[a]]) letter_b= array([[b],[b],[b]]) letter_c= array([[c],[c],[c]]) I want this separation because I want to work with each individual array type(letter) Thanks!
has comment: http://stackoverflow.com/comment/83839761
has title: extract a submatrix from matrix
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/83854992
comment on: http://stackoverflow.com/a/48431906
type: Comment
has text: I was looking at your solution to a similar problem just a few minutes ago ... thank you!
score: 0
type: AnswerComment

http://stackoverflow.com/q/48435008
has comment: http://stackoverflow.com/comment/83861575
has answer: http://stackoverflow.com/a/48435576
type: Question
has comment: http://stackoverflow.com/comment/83861678
tagged with: turtle-graphics
has body: I'm learning about classes on Udacity and we started by learning turtle. There was an exercise where you were supposed not to repeat brad.forward(100) brad.right(90) four times (Brad is the turtle's name), and instead create a loop. My guess was: while True: brad.forward(100) brad.right(90) if turtle.position() == (0,0): break However, Brad just draws the first, upper line. What am I getting wrong? If needed, the full code is below. Thank you! import turtle def square(): turtle.colormode(255) window = turtle.Screen() window.bgcolor(0,0,0) #meet brad brad = turtle.Turtle() brad.shape('arrow') brad.speed(1) brad.color(0,255,255) #brad creates a square while True: brad.forward(100) brad.right(90) if turtle.position() == (0,0): break turtle.exitonclick() square()
has comment: http://stackoverflow.com/comment/83861567
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83861530
tagged with: python
has answer: http://stackoverflow.com/a/48435105
has comment: http://stackoverflow.com/comment/83861661
answer count: 4
has comment: http://stackoverflow.com/comment/83861559
has answer: http://stackoverflow.com/a/48435132
has comment: http://stackoverflow.com/comment/83861633
has title: Making turtle draw a square with a loop
score: 0
has comment: http://stackoverflow.com/comment/83861524
has comment: http://stackoverflow.com/comment/83861628
has answer: http://stackoverflow.com/a/48437317

http://stackoverflow.com/a/48381940
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48379290
answers question: http://stackoverflow.com/q/48379290
type: Answer
score: 0
has body: Use self.table_name: class BaseClassExample: table_name = None def test_field_for_both_devices(self): firstname = get_field(self.table_name) class SubClass1(BaseClassExample): table_name = 'Pacer' def test_field1(): field1 = get_field(self.table_name) class SubClass2(BaseClassExample): table_name = 'ICD' def test_field2(self): field2 = get_field(self.table_name) Explanation: Python has a few namespaces — global, local, class and instance. You cannot access table_name because Python looks it up in local and global namespaces and fails. You can access self.table_name because it's instance namespace which also has access to class namespace if the name is not shadowed in instance (in self).

http://stackoverflow.com/comment/83901261
score: 0
comment on: http://stackoverflow.com/q/48437262
type: QuestionComment
has text: the image you place has a blank border as a background? You could place one of those images, in addition to placing another image that describes what you want to obtain.
type: Comment

http://stackoverflow.com/comment/83713029
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48363040
score: 1
has text: (Depressing subjective empirical observations): If you are lucky, it's modelled as requirement in setup.py / package-resources. If not, *readme's* have been the most important source for me with the following result: if it's py3 only, people usually warn about that! If it's py2 only, this is often unmentioned (as this was not important in the past; so yes, more for old unmaintained projects). (the keyword *depressing* somewhat tackles the *why* in previous comments; it's not an issue with well-maintained software, but with smaller ones)

http://stackoverflow.com/comment/83928088
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48467273
has text: use a for loop for i in a: print i['data'] print i['format']
score: 0

http://stackoverflow.com/q/48360650
tagged with: class
tagged with: object
has comment: http://stackoverflow.com/comment/83711918
upvote count: 1
has comment: http://stackoverflow.com/comment/83708194
score: -1
has comment: http://stackoverflow.com/comment/83708107
has comment: http://stackoverflow.com/comment/83708204
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83709118
has body: I started to study class object with python (never done before) the program should get from a list (harvest list) the info that the class apple need to count the grams of apple if the quality is high then they go on the good barrel if it's not then on the bad barrel, I want to implement a counter that counts how many barrels I have used the code that is in bold and italic should count how many barrels are used totApple should be the total grams of all the apples and countBarrel should use totApple to check if it is >=100 gr, if so then a new barrel should be counted and used but these codes are not either in relationship with the rest of the code If you run the code without the "italic bold part" should work, This is the output: "Harvested 2 high-quality apples with a total weight of 230 g Harvested 2 cider apples with a total weight of 219 g" what I am looking for, it's to get an output that says how many barrels is used, like if it is filled up then a new barrel should be used I have been googling this topic (class and object) but any good resource (except python API) what I'm looking for is something more practical class Apple: def __init__(self,weight,quality): self.weight=weight self.quality=quality self.totApple=0 def pickApple(self,goodBarrel,badBarrel): if self.quality=="High": goodBarrel.addApple(self.weight) else: badBarrel.addApple(self.weight) *** def totApple(self,barreln): for Apple.weight in list: self.totApple = barreln.addApple(self.weight)*** class Barrel: def __init__(self): #empty barrel self.weight=0 #number of apples in the barrel self.count=0 #number of barrel used self.barreln=0 def addApple(self,weight): self.count+=1 self.weight+=weight ***def countBarrel(self,barreln): x=Apple() #I know thi is an erro but I don't know get the #totApple from Apple class if x.totApple(barreln) &gt;=100: self.barreln+=1*** def harvestApples(): barrel1=Barrel() barrel2=Barrel() harvest = [Apple(98,"High"),Apple(120,"Low"),Apple(132,"High"),Apple(99,"Medium")] …
has answer: http://stackoverflow.com/a/48360964
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83708249
downvote count: 2
answer count: 1
has title: I need to fix this python code, I want to create a counter using data from two different classes
tagged with: python
has comment: http://stackoverflow.com/comment/83712650
has comment: http://stackoverflow.com/comment/83708059
favorite count: 0

http://stackoverflow.com/comment/83875255
comment on: http://stackoverflow.com/q/48441705
type: QuestionComment
has text: Thank you, can you add expected output from your sample data?
score: 0
type: Comment

http://stackoverflow.com/a/48444701
has comment: http://stackoverflow.com/comment/83881108
answers question: http://stackoverflow.com/q/48444603
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48444603
has body: You can use Series.apply with one column: df['expiry'] = df['t'].apply(lambda x: datetime.utcnow() + timedelta(x * 365)) Or convert column t to timedeltas by to_timedelta: df['expiry'] = datetime.utcnow() + pd.to_timedelta(df['t'] * 365, unit='d') df['expiry1'] = df['t'].apply(lambda x: datetime.utcnow() + timedelta(x * 365)) df['expiry2'] = datetime.utcnow() + pd.to_timedelta(df['t'] * 365, unit='d') print (df) atmVol t expiry1 expiry2 0 0.043220 0.02 2018-02-01 21:14:02.057250 2018-02-01 21:14:02.057250 1 0.042139 0.04 2018-02-09 04:26:02.057250 2018-02-09 04:26:02.057250 2 0.041174 0.06 2018-02-16 11:38:02.057250 2018-02-16 11:38:02.057250 3 0.040328 0.08 2018-02-23 18:50:02.057250 2018-02-23 18:50:02.057250 4 0.039606 0.10 2018-03-03 02:02:02.057250 2018-03-03 02:02:02.057250 5 0.038364 0.15 2018-03-21 08:02:02.057250 2018-03-21 08:02:02.057250 6 0.037971 0.20 2018-04-08 14:02:02.057250 2018-04-08 14:02:02.057250 7 0.038480 0.25 2018-04-26 20:02:02.057250 2018-04-26 20:02:02.057250
has comment: http://stackoverflow.com/comment/83881273
has comment: http://stackoverflow.com/comment/83881146
has comment: http://stackoverflow.com/comment/83881183
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83881164

http://stackoverflow.com/comment/83650509
type: Comment
type: QuestionComment
has text: I've tried both.
score: 0
comment on: http://stackoverflow.com/q/48332385

http://stackoverflow.com/comment/83735965
comment on: http://stackoverflow.com/a/48373047
score: 1
type: Comment
type: AnswerComment
has text: For 2 reasons - 1. `time.sleep(5)` is slow and a waste of time if the page loads faster. 2. It is unreliable if the internet connection or the site is slow.

http://stackoverflow.com/comment/83955019
has text: Without a sample of the data you're working with there's no way anyone will be able to help you.
comment on: http://stackoverflow.com/q/48480946
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/83663364
type: AnswerComment
has text: It works, but how to handle when port does not exist ? It is showing error, but if connection refused then I want to show a readable message like "can not connect" something.
comment on: http://stackoverflow.com/a/48338878
type: Comment
score: 0

http://stackoverflow.com/comment/83757220
comment on: http://stackoverflow.com/a/48345544
score: 0
type: AnswerComment
has text: @LucyThomas No worries, keep it up!
type: Comment

http://stackoverflow.com/a/48477361
has body: I found a way to solve the problem by going the path of the 2nd proposed answer: Passing a PseudoInteger to Scikit-Learn that has all the same properties as a normal integer when compared or done mathematical operations with. However, it also acts as a wrapper for the int, and instance variables (such as the cost of an instance) can also be stored. As already stated in the question, this causes Scikit-learn to recognize that the values inside the passed label array are in fact of type object rather than int. So I just replaced the test in the type_of_target(y) method of Scikit-Learn's multiclass.py in line 273 to return 'binary' even though it doesn't pass the test. So that Scikit-Learn just treats the whole problem (as it should be) like a binary classification problem. So line 269-273 in the type_of_target(y) method in multiclass.py now looks like: # Invalid inputs if y.ndim &gt; 2 or (y.dtype == object and len(y) and not isinstance(y.flat[0], string_types)): # return 'unknown' # [[[1, 2]]] or [obj_1] and not ["label_1"] return 'binary' # Sneaky, modified to force binary classification. My code then looks like this: import sklearn import sklearn.model_selection import sklearn.base import sklearn.metrics import numpy as np import sklearn.tree import sklearn.feature_selection from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.metrics.scorer import make_scorer class PseudoInt(int): # Behaves like an integer, but is able to store instance variables pass def grid_search(x, y_normal, x_amounts): # Change the label set to a np array containing pseudo ints with the costs associated with the instances y = np.empty(len(y_normal), dtype=PseudoInt) for index, value in y_normal.iteritems(): new_int = PseudoInt(value) new_int.cost = x_amounts.loc[index] # Here the cost is added to the label y[index] = new_int # Normal train test split x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)…
accepted answer of: http://stackoverflow.com/q/48468115
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48468115
score: 1
type: Answer

static-methods
tags question: http://stackoverflow.com/q/48445403
tags question: http://stackoverflow.com/q/48409012
tag name: static-methods
type: Tag

http://stackoverflow.com/q/48461562
has answer: http://stackoverflow.com/a/48461715
tagged with: python
score: 0
answer count: 1
has title: Snowboy and Python - when testing demo.py bash chooses wrong file directory?
has body: I'm trying to use the simple python demo.py snowboy.udml on bash and it constantly says it cant find my file - that's because the directory its suggesting doesn't exist - how can i change this on bash so it leads to the correct working directory with my demos inside it??
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/111158285
comment on: http://stackoverflow.com/a/48399309
type: Comment
score: 0
type: AnswerComment
has text: thanks @Kinght金 , with this code I get cropped img with white background. How do I make it transparent?

http://stackoverflow.com/comment/83909151
comment on: http://stackoverflow.com/a/48457930
score: 0
type: AnswerComment
has text: @Shivam - yes, sure. Is same number of `--->` symbols in each row?
type: Comment

http://stackoverflow.com/a/48374108
upvote count: 3
has body: I think you can remember for the first element of list, and then check if the remains element in the list is the same type of first element. total = 0 first_type = type(a[0]) data_mixed = False if isinstance(a[0], int): total += a[0] if len(a) &gt; 1: for i in a[1:]: if not isinstance(i, first_type): data_mixed = True print("This list has a mix of data types") if isinstance(i, int): total += i if not data_mixed: print("not a mix of data types")
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48374039
type: Answer

http://stackoverflow.com/q/48470221
tagged with: python
has answer: http://stackoverflow.com/a/48470388
has comment: http://stackoverflow.com/comment/83934608
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83934412
has comment: http://stackoverflow.com/comment/83934491
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
has body: I have a rather simple block that obtains the absolute valued difference between two selected elements from two arrays. import numpy as np # Input data with proper format. N_bb, N_cc = np.random.randint(1e5), np.random.randint(1e5) bb = np.random.uniform(0., 1., N_bb) cc = np.random.uniform(0., 1., N_cc) # My actual code repeats this process ~500 times. all_ds = [] for _ in range(500): # An index into cc for each element in bb. idx_into_cc = np.random.randint(0, len(cc), len(bb)) # This is the block I need to make faster. aa = [] for i, b in enumerate(bb): aa.append(abs(b - cc[idx_into_cc[i]])) d = np.median(aa) # Use 'd' before the next iteration, and store the result. all_ds.append(some_func(d)) I use the absolute difference because I need positive values, I could also use a squared difference. The bb and cc arrays stay unchanged during the entire process, but idx_into_cc changes with each iteration. How can I improve the performance of this code?
type: Question
tagged with: performance
has title: Improve performance of difference between elements block
accepted answer: http://stackoverflow.com/a/48470388

http://stackoverflow.com/comment/83667620
comment on: http://stackoverflow.com/a/48341130
type: AnswerComment
has text: This would produce the same error message, the OP gets in the first place.
score: 0
type: Comment

http://stackoverflow.com/q/48364044
tagged with: inheritance
has body: Specifically, is it acceptable/good practice to use a class attribute to create more class attributes, and then remove the original? Say I have a superclass. From that, I derive many subclasses, but all of these need some class attributes defined. If I were to do this normally, it would look something like: class Bar(Foo): someval = 0 someotherval = ('a', 'b', 'c') importantval = [1, 2, 3] thisval = 'this' names = ['John', 'Joe'] Every subclass would need to define all of these attributes. However, if we somehow use one variable to create all of these it would look something like: class Bar(Foo): classvars = (0, ('a', 'b', 'c'), [1, 2, 3], 'this', ['John', 'Joe']) Then, after the class is created, it would internally look the same as the version of the class where we define all of the attributes separately. See, I tried to do this before by using just a superclass without a metaclass with something like: class Foo: @classmethod def __init__(cls, val): cls.val = val class Bar(Foo): Foo.__init__(5) But if you know how @classmethod works, then you know that cls ends up being a class Foo reference, instead of a class Bar reference (when called during Bar's creation, and cls only ends up being a Bar reference during a Bar instance creation). I then also tried to use @staticmethod instead, but, to my knowledge, when creating a class, you cannot reference to the class being created outside of a method definition. i.e. class Bar(Foo): Foo.__init__(Bar, 5) That would raise a NameError (if Foo's __init__ method were a static method). Eventually, I learned about metaclasses, and I figured out that I could do this: class MetaFoo(type): def __init__(cls, name, bases, namespace): super(MetaFoo, cls).__init__(name, bases, namespace) if '_superclass' not in namespace: # A special attribute to distinguish between classes that we want to affect and those that we don't attrnames = ('someval', 'someotherval', 'importantval', 'thisval', 'names') if 'classvars' in namespace: for attr, at…
tagged with: class
type: AnsweredQuestion
score: 2
tagged with: metaclass
has comment: http://stackoverflow.com/comment/83729715
upvote count: 3
has comment: http://stackoverflow.com/comment/83718363
answer count: 1
has comment: http://stackoverflow.com/comment/83715046
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83730542
has comment: http://stackoverflow.com/comment/83714972
type: Question
accepted answer: http://stackoverflow.com/a/48370033
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48370033
has comment: http://stackoverflow.com/comment/83724635
has comment: http://stackoverflow.com/comment/83731911
has title: In Python, is it acceptable to use a metaclass to add and remove many class attributes?
tagged with: python
has comment: http://stackoverflow.com/comment/83729789

http://stackoverflow.com/a/48456269
type: Answer
has body: duck_index must already be assigned - this can happen in various different places. If it's a web interface, you have no idea what they have already defined; if its ipython it may have been defined in the history.
answers question: http://stackoverflow.com/q/48456202
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/48456202

http://stackoverflow.com/q/48476180
downvote count: 2
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/83945634
has comment: http://stackoverflow.com/comment/83945655
has comment: http://stackoverflow.com/comment/83945639
type: Question
has comment: http://stackoverflow.com/comment/83945642
upvote count: 0
score: -2
has title: How do I make a variables value reflect text in a .txt file?
tagged with: python
linked to: http://stackoverflow.com/q/5214578
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/83945816
has comment: http://stackoverflow.com/comment/83945557
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48476468
accepted answer: http://stackoverflow.com/a/48476468
has body: SO I'm making a calculator that turns any number into a specified number. The way that I want to specify this by having something like numbertoturninto=*anynumber* in a .txt file at the location c:/python/calc2#/config.txt. How do I do this? If you don't understand I will help. Example: I have a .txt file. In that file, I have the number 4. I want var3 to be this number in a python program. (Hope this helps)
favorite count: 0

http://stackoverflow.com/q/48380663
has comment: http://stackoverflow.com/comment/83747722
favorite count: 0
type: Question
tagged with: image-resizing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83748281
tagged with: resize
tagged with: python
has answer: http://stackoverflow.com/a/48384788
has title: Difficulty in resizing image for OLED display
has body: I am trying to resize an image to display on my OLED device. My image I want to display is: Currently, my OLED display only shows a fraction of the image: Based on How to resize image?, I added new_img = img.resize((128,128)) to my script to resize the image. The same fraction of the image however appears on the screen. When I tried to enter a lower image size for the resize argument (64x64), terminal prints: pi@raspberrypi:~/project $ python colors.py --display ssd1351 --width 128 --height 128 --interface spi --spi-bus-speed 16000000 --gpio-data-command 20 Version: luma.oled 2.3.1 (luma.core 1.3.0) Display: ssd1351 Interface: spi Dimensions: 128 x 128 ------------------------------------------------------------ Traceback (most recent call last): File "colors.py", line 87, in &lt;module&gt; main() File "colors.py", line 30, in main device.display(new_img) File "/usr/local/lib/python2.7/dist-packages/luma/oled/device.py", line 371, in display assert(image.size == self.size) AssertionError Any ideas on how I can resize the image properly for the OLED display? My full script is: #!/usr/bin/env python import math import time import random import os.path from demo_opts import get_device from luma.core.render import canvas from PIL import Image def main(): img_path = os.path.abspath(os.path.join( os.path.dirname(__file__), 'plot.jpg')) img = Image.open(img_path) \ .transform(device.size, Image.AFFINE, (1, 0, 0, 0, 1, 0), Image.BILINEAR) \ .convert(device.mode) new_img = img.resize((128,128)) while True: # Image display device.display(new_img) time.sleep(5) if __name__ == "__main__": try: device = get_device() main() except KeyboardInterrupt: pass
tagged with: image
linked to: http://stackoverflow.com/q/37631611
has comment: http://stackoverflow.com/comment/83751940
score: 1
has comment: http://stackoverflow.com/comment/83748107
has comment: http://stackoverflow.com/comment/83747855
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83748431

http://stackoverflow.com/a/48462131
has comment: http://stackoverflow.com/comment/83917366
type: Answer
score: 1
has body: Have each button call the same function but with a different parameter. # Add the a number parameter here based on what you've def KitchenSpot(self,state, light_index): lights[light_index].name lights[light_index].on = state Then in the KV file, Button: text: "Kitchen Spot 3" on_press: root.KitchenSpot(state, light_index = 3) Button: text: "Kitchen Spot 4" on_press: root.KitchenSpot(state, light_index = 4) You only have to create the function one, with each button passing in the relevant light_index number.
downvote count: 0
answers question: http://stackoverflow.com/q/48453695
upvote count: 1

http://stackoverflow.com/comment/83674464
comment on: http://stackoverflow.com/q/48339263
type: QuestionComment
has text: @Rishikesh - you are welcome!
type: Comment
score: 0

http://stackoverflow.com/comment/137233732
type: AnswerComment
comment on: http://stackoverflow.com/a/74452716
has text: Is there anyway to do this for multiple columns that does not look ugly?
score: 0
type: Comment

http://stackoverflow.com/comment/83732875
type: QuestionComment
has text: I see the curve when I move the horizontal scrollbar, but to do this you must place scrollArea.setWidgetResizable(False), but what I do not like is that the drawing is very slow, it seems to me that the method you use to paint is not correct.
comment on: http://stackoverflow.com/q/48368901
score: 0
type: Comment

http://stackoverflow.com/comment/83946210
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48476206
type: QuestionComment
has text: Since you've made me consider this, I probably do need the output for a "Nothing" result to be [0] and in that sense, I would hope dterms_1 returned four results in your example; [[0], [1], [2], [4]] although I don't know how to apply this parameter either.

http://stackoverflow.com/q/48372758
tagged with: python
has answer: http://stackoverflow.com/a/48372819
has body: I have a couple of data series, each of which is a noiseless theoretical curve, and an Nx2 array of noisy data that I need to display with a legend. The following code works, but because of the Nx2 data I get two entries in the legend... is there a way to avoid this? import numpy as np import matplotlib.pyplot as plt t = np.arange(0,1,0.001) td = np.arange(0,1,0.1) td = np.atleast_2d(td).T N = len(td) x1 = t x1r = td + 0.1*np.random.randn(N,2) x2 = 2-t x2r = 2-td + 0.1*np.random.randn(N,2) plt.plot(t,x1,color='red') plt.plot(td,x1r,'.',color='red',label='A') plt.plot(t,x2,color='green') plt.plot(td,x2r,'x',color='green',label='B') plt.legend()
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83732990
answer count: 2
has comment: http://stackoverflow.com/comment/83732666
has comment: http://stackoverflow.com/comment/83732650
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83732602
possible better answer: http://stackoverflow.com/a/48373254
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48373254
type: Question
upvote count: 4
has title: matplotlib legend: I see everything twice
accepted answer: http://stackoverflow.com/a/48372819

http://stackoverflow.com/q/48388511
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83764872
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83769698
has comment: http://stackoverflow.com/comment/83768090
has comment: http://stackoverflow.com/comment/83768271
has comment: http://stackoverflow.com/comment/83765167
has title: Why can't I call globals() from an imported module?
has answer: http://stackoverflow.com/a/48388775
has body: let's say I have a module, spam. In spam, I put this code: import __main__ print(__main__.globals()) Then, from any old python script, I import spam. From this I would get the following error: Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; import spam File "/home/runner/spam.py", line 7, in &lt;module&gt; print(__main__.globals()) AttributeError: module '__main__' has no attribute 'globals' But, however, when I do this inside of the script importing spam; import spam a = globals() and I repeat the same code with one difference; ... print(eval(main_mod[0]).a) I get the result I hoped for, which was a list of all the globals in __main__. Why can't I just call it normally? I don't want to have to code in a variable to hold globals() every time I import "spam". I'm sure others could benefit from this, I tried it with other builtins from __main__ like abs but same error. By the way, I'm trying to get __main__'s globals so that I can get the names of functions of whatever is importing spam. I need it so that I can also access variables from __main__.
tagged with: python
has comment: http://stackoverflow.com/comment/83765975
tagged with: global
tagged with: python-3.x
upvote count: 3
type: UnansweredQuestion
tagged with: program-entry-point

http://stackoverflow.com/a/48431082
score: 10
has comment: http://stackoverflow.com/comment/83967037
has comment: http://stackoverflow.com/comment/83967070
accepted answer of: http://stackoverflow.com/q/48431036
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83967096
answers question: http://stackoverflow.com/q/48431036
has body: No, tuple and list do not inherit from any collections abstract base class. Instead, the collections classes customize instance and subclass checks, with the class.__instancecheck__() and class.__subclasscheck__() hooks. These hooks are called whenever you use isinstance() or issubclass() with a class that implements them, and their result is returned: &gt;&gt;&gt; import collections.abc &gt;&gt;&gt; collections.abc.MutableSequence.__subclasscheck__(tuple) False &gt;&gt;&gt; collections.abc.MutableSequence.__subclasscheck__(list) True Specifically, the hooks are implemented by the abc.ABCMeta Abstract Base Class metaclass, which abstracts the process. Your Abstract Base Class only needs to implement the __subclasshook__() class method; this is easier to implement, as the __subclasscheck__ and __instancecheck__ special methods must be implemented on a metaclass. The ABCMeta implementation also includes a registry to add types to an ABC, with the ABCMeta.register() method. The tuple and list classes are registered explicitly with the Sequence type, for example: Sequence.register(tuple) Sequence.register(str) Sequence.register(range) Sequence.register(memoryview)
type: Answer
upvote count: 10

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/48445154
tags question: http://stackoverflow.com/q/48352615
tags question: http://stackoverflow.com/q/48475608
tags question: http://stackoverflow.com/q/48455200
tags question: http://stackoverflow.com/q/48454086
tags question: http://stackoverflow.com/q/48413192
tags question: http://stackoverflow.com/q/48360894
tags question: http://stackoverflow.com/q/48456590
tags question: http://stackoverflow.com/q/48364284
tags question: http://stackoverflow.com/q/48434180
tags question: http://stackoverflow.com/q/48388550
tags question: http://stackoverflow.com/q/48470114
tags question: http://stackoverflow.com/q/48436929
tags question: http://stackoverflow.com/q/48446684
tags question: http://stackoverflow.com/q/48361755
tags question: http://stackoverflow.com/q/48478946
tags question: http://stackoverflow.com/q/48410479
tags question: http://stackoverflow.com/q/48376577
tags question: http://stackoverflow.com/q/48410664
tags question: http://stackoverflow.com/q/48362667
tags question: http://stackoverflow.com/q/48373991
tags question: http://stackoverflow.com/q/48336544
tags question: http://stackoverflow.com/q/48386862
tags question: http://stackoverflow.com/q/48393253
tags question: http://stackoverflow.com/q/48415412
tags question: http://stackoverflow.com/q/48361281
tags question: http://stackoverflow.com/q/48363722
tags question: http://stackoverflow.com/q/48352895
tags question: http://stackoverflow.com/q/48361413
tags question: http://stackoverflow.com/q/48393355
tags question: http://stackoverflow.com/q/48373812
tags question: http://stackoverflow.com/q/48367292
tags question: http://stackoverflow.com/q/48396103
tags question: http://stackoverflow.com/q/48448900
tags question: http://stackoverflow.com/q/48453474
tags question: http://stackoverflow.com/q/48355713
tags question: http://stackoverflow.com/q/48397489
tags question: http://stackoverflow.com/q/48433543
type: Tag
tags question: http://stackoverflow.com/q/48364682
tag name: html
tags question: http://stackoverflow.com/q/48477666
tags question: http://stackoverflow.com/q/48340352
tags question: http://stackoverflow.com/q/48478337
tags question: http://stackoverflow.com/q/48361104
tags question: http://stackoverflow.com/q/48357407
tags question: http://stackoverflow.com/q/48478203
tags question: http://stackoverflow.com/q/48365897
tags question: http://stackoverflow.com/q/48363913
tags question: http://stackoverflow.com/q/48425672
tags question: http://stackoverflow.com/q/48395079
tags question: http://stackoverflow.com/q/48451806
tags question: http://stackoverflow.com/q/48373164

http://stackoverflow.com/comment/83661493
score: 0
comment on: http://stackoverflow.com/q/48337864
type: Comment
type: QuestionComment
has text: @GwendalGrelier i don't want to create new file ,but i want something like this : first play sound with 10dB second is 20dB and third is 30dB

http://stackoverflow.com/q/48469155
answer count: 4
has answer: http://stackoverflow.com/a/48469731
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48469227
favorite count: 0
type: Question
tagged with: python-3.x
has title: use recursion to find values of nested dict and return keys of the dict
type: UnansweredQuestion
has body: I have an exercise where a dictionary of birthdays is given as follows: birthdays = {"Anne": {"month":"Jan","day":"27"}, "Mike":{"month":"Feb","day":"13"}, "Nicolas":{"month":"Jun","day":14}, "Marta": {"month":"Jan","day":16}} The question is to define a function which, given a month, prints a list of all the people who have birthdays in that month, with the dates. Here's what I've got so far: def birthbymonth(book, month): for k,v in book.items(): if isinstance(v, dict): birthbymonth(v,month) else: if month == v: print(book) Which when called birthbymonth(birthdays,"Jan") prints: {'month': 'Jan', 'day': '27'} {'month': 'Jan', 'day': 16} Yet I dont know how to also print the names of the people that have birthdays then.
tagged with: python
has answer: http://stackoverflow.com/a/48469797
score: -1
has answer: http://stackoverflow.com/a/48469198
tagged with: dictionary

http://stackoverflow.com/comment/83735635
comment on: http://stackoverflow.com/q/48373944
score: 0
type: Comment
has text: Seems like you're preprocessing the images before feeding into some CNNs. As @sascha mentioned, `joblib` should do the job for you. I have worked on such a project before. Go for it
type: QuestionComment

http://stackoverflow.com/q/48434423
downvote count: 0
tagged with: bytesio
favorite count: 0
has comment: http://stackoverflow.com/comment/83860912
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/76410729
type: Question
upvote count: 9
score: 9
has title: Why is TextIOWrapper closing the given BytesIO stream?
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/76410729
tagged with: python
accepted answer: http://stackoverflow.com/a/48434568
has answer: http://stackoverflow.com/a/48434568
has body: If I run following code in python 3 from io import BytesIO import csv from io import TextIOWrapper def fill_into_stringio(input_io): writer = csv.DictWriter(TextIOWrapper(input_io, encoding='utf-8'),fieldnames=['ids']) for i in range(100): writer.writerow({'ids': str(i)}) with BytesIO() as input_i: fill_into_stringio(input_i) input_i.seek(0) I get an error: ValueError: I/O operation on closed file. While if I don't use the TextIOWrapper the io stream stays open. As an example if I modify my function to def fill_into_stringio(input_io): for i in range(100): input_io.write(b'erwfewfwef') I don't get any errors any more so for some reason TestIOWrapper is closing the stream from which I would like to read afterwards. Is this intended to be like this and whether it is is there a way to achieve what I am trying without writing the csv writer myself?
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/48433722
has comment: http://stackoverflow.com/comment/83860558
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48433642
type: Answer
has comment: http://stackoverflow.com/comment/83860493
has body: you have to generate all those question marks... execu = mycursor.execute( """ Select columnA ,columnb ,columnc where columnc in ({}) """.format(','.join("?"*len(df_col))), df_col) rows = mycursor.fetchall() print(rows)

http://stackoverflow.com/comment/83665102
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48339616
has text: In some platforms, Python does not support tk v8.6, so it won't be a portable solution. For instance in macOS, we can only use tk v8.5, wich does not support PNG. We would need to either convert the image to GIF, or to use an external library, like Pillow.

gmail
type: Tag
tags question: http://stackoverflow.com/q/48367201
tags question: http://stackoverflow.com/q/48350329
tag name: gmail
tags question: http://stackoverflow.com/q/48362621

http://stackoverflow.com/comment/83745922
has text: Please post a MCVE.
type: Comment
comment on: http://stackoverflow.com/q/48379405
type: QuestionComment
score: 0

http://stackoverflow.com/a/48345966
downvote count: 0
has body: From what I remember, a drawdown is the amount by which your portfolio profit is less than the high. (In the future, you should explicitly define your desired output and don't assume people know what you are asking.) There may be better ways, but you can calculate this in pandas using a itertuples(): import pandas as pd from StringIO import StringIO # read the data df = pd.DataFrame.from_csv(StringIO("""Date Profit Cumulative 1/6/2005 248.8500 248.85 1/12/2005 48.3500 297.20 1/13/2005 29.2900 326.49 1/13/2005 -500.0000 -173.51 1/13/2005 -250.9500 -424.46 1/14/2005 126.6600 -297.80 1/16/2005 58.7400 -239.06 1/19/2005 68.3500 -170.71 1/21/2005 140.0000 -30.71 1/23/2005 200.0000 169.29 1/26/2005 -250.6800 -81.39 1/27/2005 162.5000 81.11 1/27/2005 135.5100 216.62 1/27/2005 -650.0000 -433.38 1/28/2005 96.8800 -336.50 1/28/2005 -1000.0000 -1336.50 1/31/2005 140.0000 -1196.50 2/1/2005 140.0000 -1056.50"""), sep="\s+").reset_index() # calculate drawdown prev_high = 0 for i, date, profit, cumulative in df.itertuples(): prev_high = max(prev_high, cumulative) dd = cumulative - prev_high df.loc[i, 'Drawdown'] = dd if dd &lt; 0 else 0 The resultant dataframe: &gt;&gt;&gt; print(df) Date Profit Cumulative Drawdown 0 2005-01-06 248.85 248.85 0.00 1 2005-01-12 48.35 297.20 0.00 2 2005-01-13 29.29 326.49 0.00 3 2005-01-13 -500.00 -173.51 -500.00 4 2005-01-13 -250.95 -424.46 -750.95 5 2005-01-14 126.66 -297.80 -624.29 6 2005-01-16 58.74 -239.06 -565.55 7 2005-01-19 68.35 -170.71 -497.20 8 2005-01-21 140.00 -30.71 -357.20 9 2005-01-23 200.00 169.29 -157.20 10 2005-01-26 -250.68 -81.39 -407.88 11 2005-01-27 162.50 81.11 -245.38 12 2005-01-27 135.51 216.62 -109.87 13 2005-01-27 -650.00 -433.38 -759.87 14 2005-01-28 96.88 -336.50 -662.99 15 2005-01-28 -1000.00 -1336.50 -1662.99 16 2005-01-31 140.00 -1196.50 -1522.99 17 2005-02-01 140.00 -1056.50 -1382.99 Investopedia definition of drawdown.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/109250966
answers question: http://stackoverflow.com/q/48344727
score: 5

http://stackoverflow.com/comment/85532375
score: 0
comment on: http://stackoverflow.com/q/48352048
type: Comment
type: QuestionComment
has text: @DanielHaley sorry i undeleted it. I got a negative vote so i thought i might need to reword it , you can post your answer now

http://stackoverflow.com/a/48415061
upvote count: 4
has body: That's simply: &gt;&gt;&gt; a = "123 456 7sr" &gt;&gt;&gt; list(a) ['1', '2', '3', ' ', '4', '5', '6', ' ', '7', 's', 'r']
downvote count: 0
answers question: http://stackoverflow.com/q/48415038
type: Answer
score: 4

http://stackoverflow.com/comment/83767525
has text: Well, your `date1` and `date2` never get updated to their latest. They are always their initial objects. You need to assign the latest value manually they're not in sync with the right-hand side of their `=` assignment.
score: 0
comment on: http://stackoverflow.com/q/48389806
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83989962
type: Comment
comment on: http://stackoverflow.com/q/48425278
type: QuestionComment
has text: Hi Cam_Aust, I was referring to a previous comment by Piinthesky that he/she has since deleted. The comment suggesting to include the full traceback is one I have no issues with at all. Thanks for your comment, I will indeed be sticking around as this site is a massive help in learning. Thanks!
score: 0

http://stackoverflow.com/q/48475080
type: Question
upvote count: 0
answer count: 1
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/48475116
downvote count: 1
has answer: http://stackoverflow.com/a/48475116
type: AnsweredQuestion
has title: Failed to import the TensorFlow module
has body: I have problems with my installation of tensorflow. I got a mrry/tensorflow_self_check.py script and made some adjustment MurDoDePar / tensorflow_self_check.py I get this result: - Python version is 3.6. - TensorFlow is installed at: C:\Users\domin\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow *** Failed to import the TensorFlow module. - Find msvcp140.dll - Find cudart64_91.dll - Find nvcuda.dll - Find cuDNN 7 cudnn64_7.dll. *** ERROR Liste - Failed to import the TensorFlow module. If I make the order pip3 install --ignore-installed --upgrade tensorflow I have errors : C:\Users\domin&gt;pip3 install --ignore-installed --upgrade tensorflow-gpu Collecting tensorflow-gpu Using cached tensorflow_gpu-1.5.0-cp36-cp36m-win_amd64.whl Collecting tensorflow-tensorboard&lt;1.6.0,&gt;=1.5.0 (from tensorflow-gpu) Using cached tensorflow_tensorboard-1.5.0-py3-none-any.whl ...OK Using cached setuptools-38.4.0-py2.py3-none-any.whl Installing collected packages: six, html5lib, numpy, markdown, wheel, werkzeug, setuptools, protobuf, bleach, futures, tensorflow-tensorboard, absl-py, tensorflow-gpu Exception: Traceback (most recent call last): File "c:\users\domin\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\domin\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\users\domin\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\users\domin\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\users\domin\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\users\domin\appdata\local\programs\python\python36\…
tagged with: tensorflow
favorite count: 0
linked to: http://stackoverflow.com/q/31172719

http://stackoverflow.com/comment/84591113
has text: Hey, just going back through the code, and noticed that I assign something to 'base' but then never use it. Why do I have this code in there? :)... base = importr('base', robject_translations={'with': '_with'})
type: Comment
comment on: http://stackoverflow.com/a/48465588
type: AnswerComment
score: 0

http://stackoverflow.com/a/48453159
type: Answer
has comment: http://stackoverflow.com/comment/83900047
has body: That came out wrong. At a first step, I need to find out how to update the attribute when the tx changes. And at a second step I need to auto update the values if I select another object. By the way, I found more about enterCommand in fact and try something like this, which isn't working.. transX_value = cmds.textField( w=100 , h=22 , tx= cmds.getAttr("%s.translateX" %selected[0]) , ec = 'updateValue( "Key_Manager|translateX|transX" )' ) def updateValue (name) : name = name.split('|') name = name[-1] attr = name.split('|') attr = name[1] cmds.setAttr ("%s + .attr" %selected, textField.tx)`
answers question: http://stackoverflow.com/q/48451459
score: 0

http://stackoverflow.com/comment/83728643
type: Comment
type: AnswerComment
has text: @MartijnPieters What are these O(1) and O(N) things?
score: 0
comment on: http://stackoverflow.com/a/48367451

http://stackoverflow.com/a/48475142
score: 0
has comment: http://stackoverflow.com/comment/83944002
type: AcceptedAnswer
has body: The error 'AnonymousUser' object has no attribute 'name' says that current user is not authenticated. You can make your view available only for authenticated users with login_required decorator: @login_required def profile_edit(request): pass Also User model dont have name attribute, you need to access user's student attribute to get it: form = StudentForm(request.POST or None, initial={'name': user.student.name, 'surname': user.student.surname})
has comment: http://stackoverflow.com/comment/83943789
has comment: http://stackoverflow.com/comment/83943720
has comment: http://stackoverflow.com/comment/83943918
accepted answer of: http://stackoverflow.com/q/48475039
type: Answer
answers question: http://stackoverflow.com/q/48475039
has comment: http://stackoverflow.com/comment/83943830
has comment: http://stackoverflow.com/comment/83943817

http://stackoverflow.com/q/48452092
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/48470192
tagged with: python
has body: I have a stack of DICOM images that I'm reading in with the Python dicom package: my_dicom = dicom.read_file('my_dicom.dcm') my_dicom = my_dicom.pixel_array My image is a actually a stack of 256 images, each with 3 channels and with dimensions of 256 height, and 256 width. So I try: my_dicom.shape and get (3, 256, 256, 256) What is the order of the entries in the dimension output? I have a 1 in 6 change of picking the correct hypothesis. The documentation is not illuminating.
favorite count: 0
type: Question
upvote count: 2
score: 2
type: UnansweredQuestion
tagged with: dicom
answer count: 1
downvote count: 0
tagged with: pydicom
has title: Dimensional axis when using read_file in dicom package in python

http://stackoverflow.com/comment/83729444
has text: Well, for some reason, I broke down the the list comprehension into its unpythonic form and it worked. Thanks.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48368059
type: AnswerComment

http://stackoverflow.com/comment/83861907
type: AnswerComment
comment on: http://stackoverflow.com/a/48435244
score: 0
has text: @JacobGellhaus a char is fundamentally a binary number but python I think does make a distinction so yes you should
type: Comment

http://stackoverflow.com/q/48338600
answer count: 1
tagged with: pip
has body: I have downloaded chromedriver. It lives in downloads. when I run chromedriver it starts up I run my python command and get the error: Message: 'chromedriver' executable needs to be in PATH. How do I put it in path? I just need to copy the exec file to the correct place but im not sure where to put it. I dont want any of this: from selenium import webdriver driver = webdriver.Chrome() I just want to change the location Im using a mac
has answer: http://stackoverflow.com/a/48338642
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
has title: Message: 'chromedriver' executable needs to be in PATH, where do I put it using the command line?
tagged with: python
tagged with: selenium-chromedriver
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/83820531
score: 0
comment on: http://stackoverflow.com/q/48415403
type: Comment
type: QuestionComment
has text: Does it work? I mean is the interpreter functional?

windows
tags question: http://stackoverflow.com/q/48443215
tags question: http://stackoverflow.com/q/48334579
tags question: http://stackoverflow.com/q/48480771
tags question: http://stackoverflow.com/q/48466578
tags question: http://stackoverflow.com/q/48371993
tags question: http://stackoverflow.com/q/48407865
tags question: http://stackoverflow.com/q/48336981
tags question: http://stackoverflow.com/q/48355319
tags question: http://stackoverflow.com/q/48445616
tags question: http://stackoverflow.com/q/48387241
type: Tag
tags question: http://stackoverflow.com/q/48374345
tags question: http://stackoverflow.com/q/48369747
tags question: http://stackoverflow.com/q/48456106
tags question: http://stackoverflow.com/q/48416570
tags question: http://stackoverflow.com/q/48357223
tags question: http://stackoverflow.com/q/48461122
tags question: http://stackoverflow.com/q/48376226
tags question: http://stackoverflow.com/q/48410530
tags question: http://stackoverflow.com/q/48343698
tags question: http://stackoverflow.com/q/48352049
tags question: http://stackoverflow.com/q/48401560
tags question: http://stackoverflow.com/q/48474940
tags question: http://stackoverflow.com/q/48424956
tags question: http://stackoverflow.com/q/48352645
tag name: windows
tags question: http://stackoverflow.com/q/48480173
tags question: http://stackoverflow.com/q/48479848
tags question: http://stackoverflow.com/q/48355960
tags question: http://stackoverflow.com/q/48399167
tags question: http://stackoverflow.com/q/48358941
tags question: http://stackoverflow.com/q/48401060
tags question: http://stackoverflow.com/q/48348362
tags question: http://stackoverflow.com/q/48433172
tags question: http://stackoverflow.com/q/48400838
tags question: http://stackoverflow.com/q/48343024
tags question: http://stackoverflow.com/q/48390299
tags question: http://stackoverflow.com/q/48465649
tags question: http://stackoverflow.com/q/48385818

http://stackoverflow.com/a/48373062
upvote count: 1
answers question: http://stackoverflow.com/q/48372903
has body: You could convert everything to int and catch any errors that aren't of type int and append them as a string like this: badList = ['56','45','01','cat','64','dog'] goodList = [] for o in badList: try: goodList.append(int(o)) except ValueError: goodList.append(str(o)) print(goodList)
has comment: http://stackoverflow.com/comment/83746854
type: Answer
has comment: http://stackoverflow.com/comment/83749672
has comment: http://stackoverflow.com/comment/83741779
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83748389

shopify
tag name: shopify
tags question: http://stackoverflow.com/q/48445131
type: Tag
tags question: http://stackoverflow.com/q/48483554

http://stackoverflow.com/q/48441095
has comment: http://stackoverflow.com/comment/83893643
tagged with: imagemagick
answer count: 0
has comment: http://stackoverflow.com/comment/83899986
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83921225
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I need help using ImageMagick in Python, I have a C# code that applies lens correction using MagickNet, the sequence is as it follows: using ImageMagick; // Step 0: Loading the image var img = new MagickImage("input.JPG"); img.Quality = 100; img.FilterType = FilterType.Lagrange; // Step 1: Increase the canvas size img.Extent(new MagickGeometry(new Percentage(125), new Percentage(125)), Gravity.Center); // Step 2: Apply barrel distortion correction img.Distort(DistortMethod.Barrel, new[] { -0.92578, 1.3845, -2.09958 }); // Step 3: Fix the perspective img.Distort(DistortMethod.Perspective, new double[] { 1072, 1512, 0, 0, 3404, 1524, w, 0, 3100, 2220, w, h, 1484, 2344, 0, h }); // Step 4: Crop and sharpen img.Extent(2300, 1000); img.AdaptiveSharpen(); Basically what that does is corrects the eyefish effect produced by the Go Pro Hero 5 camera. So, my question now is how do I do the same in Python: import PythonMagick img = PythonMagick.Image(r"input.jpg") img.quality(100) img.filterType = PythonMagick.FilterTypes.LagrangeFilter # Steps here img.write(r"output.jpg") I cannot find the functions or even similar names inside any ImageMagick wrapper.
score: 1
has comment: http://stackoverflow.com/comment/83891850
tagged with: python
has title: PythonMagick lens correction

http://stackoverflow.com/a/48389805
has comment: http://stackoverflow.com/comment/83767678
has body: Before you follow these steps, download the python-package-version.rpm file to a local directory on the same machine. See step-0 below to get the exact version. 0. Get the python package name $ rpm -q python 1. Remove python forcefully $ rpm -e --nodeps &lt;python-package-name&gt; 2. Install the rpm from local dir. $ rpm -ivvh python-some-version.rpm 3. Retry your yum command $ yum install &lt;some package&gt; If (3) fails, you can reinstall yum using rpm, same way that you reinstall python. From OP's comment, it seems python was never installed on the system, otherwise the dependencies would have been on the system. If on step-2, it asks for dependencies, then one has to download them manually to the same local dir and then invoke. $ rpm -ivh *.rpm or do a dry-run first $ rpm -ivh --test *.rpm
answers question: http://stackoverflow.com/q/48389406
has comment: http://stackoverflow.com/comment/83767878
has comment: http://stackoverflow.com/comment/83768035
score: 3
has comment: http://stackoverflow.com/comment/83767936
type: Answer
has comment: http://stackoverflow.com/comment/83767741
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/83877045
comment on: http://stackoverflow.com/q/48441982
score: 0
type: Comment
type: QuestionComment
has text: @BaileyParker I changed the question, maybe now better?

http://stackoverflow.com/a/48474668
has comment: http://stackoverflow.com/comment/84012776
score: 0
answers question: http://stackoverflow.com/q/48462184
type: Answer
has body: Just iterate through sitio elements, and use XPath to find all information needed within current sitio in every iteration : for s in root.findall('sitio'): id = s.find('sitio_id') fa = s.find('fecha_alta') i24 = s.find('*/item[@id="imps24blank"]') estado = s.find('estado') url = s.find('url') nombre = s.find('nombre') print(id.tag, id.text) print(fa.tag, fa.text) print(i24.tag, i24.text) print(estado.tag, estado.text) print(url.tag, url.text) print(nombre.tag, nombre.text) eval.in demo Break down of the XPath expression used to find i24 value : *: find child element of any name /item: then from such elements, find child elements named item where... [@id="imps24blank"]: ...id attribute value equals string "imps24blank"
has comment: http://stackoverflow.com/comment/84020475
has comment: http://stackoverflow.com/comment/84020311

http://stackoverflow.com/comment/83725612
comment on: http://stackoverflow.com/q/48369356
type: Comment
type: QuestionComment
has text: Find out, because I don't think ` ConnectionRefusedError` is supported on 2.5 (not certain because I don't have that version).
score: 0

http://stackoverflow.com/a/48369364
answers question: http://stackoverflow.com/q/48369331
has comment: http://stackoverflow.com/comment/83868887
has body: Yes it is possible, from the doc. You can create a shared object and if set globally you can do it. See this SO answer.
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83871645
score: 1
has comment: http://stackoverflow.com/comment/83725327

http://stackoverflow.com/comment/83936446
type: Comment
type: QuestionComment
has text: @Darkonaut But for bytes, that’s because you cannot mix those with strings… You should rather compare constant f-strings with raw string literals.
comment on: http://stackoverflow.com/q/48471086
score: 1

http://stackoverflow.com/a/48383734
score: 1
downvote count: 0
has body: OP's follow-up question: With df.append(new_row, verify_integrity=True), we can check for all columns, but how can we check for only one or two columns? To check uniqueness of just one column, say the column name is value, one can try df['value'].duplicated().any() This will check whether any in this column is duplicated. If duplicated, then it is not unique. Given two columns, say C1 and C2,to check whether there are duplicated rows, we can still use DataFrame.duplicated. df"C1", "C2".duplicated() It will check row-wise uniqueness. You can again use any to check if any of the returned value is True. Given 2 columns, say C1 and C2, to check whether each column contains duplicated value, we can use apply. df"C1", "C2".apply(lambda x: x.duplicated().any()) This will apply the function to each column. NOTE pd.DataFrame([[np.nan, np.nan], [ np.nan, np.nan]]).duplicated() 0 False 1 True dtype: bool np.nan will also be captured by duplicated. If you want to ignore np.nan, you can try select the non-nan part first.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48357853

http://stackoverflow.com/comment/83757348
score: 0
has text: I inserted os.environ["CUDA_VISIBLE_DEVICES"]="0" ad the beginning of the python code. For infering the time I use time.time() in python and std::chrono::steady_clock for C++ one. I get 0.02 for python and 0.3 for C++
comment on: http://stackoverflow.com/q/48384209
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48411636
type: Question
upvote count: 4
tagged with: python-3.x
has body: I am new to python and learning the stuff from scratch. One thing I want to do, but couldn't find out how is to create a key-value pair list using the for loop and update just the value. A sample code is: for i in range(0,6) #####some code that gives an output integer x. print(i,x) The integer x is different for each i. How do I create a list like {0:x0,1:x1,2:x2,3:x3,4:x4,5:x5}, using the for loop?
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83813091
has title: create a key- value pair in a for loop using python and update the value
has answer: http://stackoverflow.com/a/48411727
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83813104
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48411692
score: 4
has comment: http://stackoverflow.com/comment/83813175
has comment: http://stackoverflow.com/comment/83813059
has answer: http://stackoverflow.com/a/48411692
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/48411727
has comment: http://stackoverflow.com/comment/83813325
has comment: http://stackoverflow.com/comment/83813162
favorite count: 0

http://stackoverflow.com/comment/83850053
has text: @Alex and @cᴏʟᴅsᴘᴇᴇᴅ - `foo.reshape((8, 128, 128, 128))` gives the correct shape but the incorrect representation of the data. I am working with 3-D magnetic resonance volumes and the reshape corrupts the volumes. Thanks @Divakar. That's the answer to my question.
comment on: http://stackoverflow.com/q/48429596
type: Comment
type: QuestionComment
score: 0

raspberry-pi3
tags question: http://stackoverflow.com/q/48447005
tag name: raspberry-pi3
tags question: http://stackoverflow.com/q/48373267
tags question: http://stackoverflow.com/q/48384175
type: Tag
tags question: http://stackoverflow.com/q/48455649
tags question: http://stackoverflow.com/q/48434405
tags question: http://stackoverflow.com/q/48452994
tags question: http://stackoverflow.com/q/48359229
tags question: http://stackoverflow.com/q/48466006
tags question: http://stackoverflow.com/q/48444552

http://stackoverflow.com/q/48434485
score: 2
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83863714
has body: I'm trying to run some tests to go with the Django REST tutorial (see source code). I got a solution working using the APIClient's .force_authenticate method, but I'd prefer to construct the credentials more explicitly. I've tried the following: import json import base64 from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APITestCase, force_authenticate from snippets.models import Snippet class SnippetTestCase(APITestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) # self.client.force_authenticate(user=self.user) credentials = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8')) self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials)) def test_1(self): response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json') self.assertEqual(response.status_code, 201) This test passed with the commented-out line with .force_authenticate, but fails in its current form, which I based on Using Basic HTTP access authentication in Django testing framework: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Apparently, the authentication is not working because I'm getting a 403 Forbidden error. Any ideas on how to fix this?
has answer: http://stackoverflow.com/a/48450231
has title: Specifying basic authentication credentials for a Django REST framework API client
linked to: http://stackoverflow.com/q/5495452
tagged with: python
has answer: http://stackoverflow.com/a/48438042

http://stackoverflow.com/comment/83920083
score: 0
has text: What if I wanted to get the text from the video headline. For example, they use to print one of the video headlines. Would this be the proper code:.......................................................‌​............. header_info = driver.find_element_by_css_selector("#Main > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div > u[data-reactid='18']") print(header_info.text) –
type: Comment
comment on: http://stackoverflow.com/a/48458527
type: AnswerComment

http://stackoverflow.com/comment/83953697
comment on: http://stackoverflow.com/q/48471826
type: Comment
score: 0
has text: That doesn't work. What worked for that string was `json.loads(str(data.encode('unicode_escape'), 'utf-8'))` However, it didnt work with the larger string. The error I get doing this is `JSONDecodeError: Invalid \escape` on the larger json string. [see it here on repl.it](https://repl.it/@dennis_pitt/keep-control-characters)
type: QuestionComment

http://stackoverflow.com/comment/83728502
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48370410
type: AnswerComment
has text: I'll try it. Thanks for the tip.

http://stackoverflow.com/comment/84137049
has text: Ohhhhhhhh then it's big news @NathanVērzemnieks. Maybe I misunderstood `only allow one writer at any instant`. I understood this sentence (thus I posted a few questions on SO about that) as *"Don't try to use several scripts writing the same database, it will fail! Data will be lost! We only allow one writer at any instant!"* whereas you say it is more "SQLite will do everything for you *to ensure that only one writer writes at the same time*, so that it will work". Is that right?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48473953
type: Comment

http://stackoverflow.com/a/48447597
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83887910
downvote count: 0
answers question: http://stackoverflow.com/q/48447434
has comment: http://stackoverflow.com/comment/83887798
has body: I would looking into using pythons built in functions of .isdigit(), .isupper(), and .islower() this could save you some lines to check the passwords for those conditions. Also you should replace your elif's with if's. The way your code is now, once one if condition is met it doesn't check the rest. So if you want all conditions to be met you need to check if each of those is true. EDIT: As Fred noted below the second part of this is not technically correct. Although the statement about if vs. elif is true, it need not be used in your code, for the very reason Fred mentioned.
type: Answer
has comment: http://stackoverflow.com/comment/83888048

http://stackoverflow.com/comment/83699987
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48356638
type: QuestionComment
has text: That answer actually looks like it won't work (needs to be changed a little bit). Better take a look at [my answer here](https://stackoverflow.com/a/45791683/6220679).

http://stackoverflow.com/q/48475006
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: angular
accepted answer: http://stackoverflow.com/a/48475184
answer count: 1
has answer: http://stackoverflow.com/a/48475184
has title: Passing date from Angular to Python
type: Question
has body: I have Flask back-end and Angular front-end. My backend working well when I test it via Postman. I send the this kind of data { "date": "2018-01-27" } @app.route("/schedule", methods=['GET', 'POST']) def schedule(): cursor = mysql.connection.cursor() get_date = request.get_json(force = True) day_name = datetime.datetime.strptime(get_date['date'], '%Y-%m-%d').strftime('%A') week_number = datetime.datetime.strptime(get_date['date'], '%Y-%m-%d').strftime('%V') ... But I have problems when I'm trying to send it from Angular. My service : @Injectable() export class RequestService { constructor(private http:Http) { } getData(model): Observable&lt;any&gt;{ return this.http.post("http://127.0.0.1:5000/schedule",model) .map((response:Response)=&gt;{return response.json() }); } } My component: export class CalendarComponent implements OnInit { public myDatePickerOptions: IMyDpOptions = { dateFormat: 'yyyy-mm-dd', openSelectorOnInputClick: true, satHighlight: true }; data:any; public model:any = { jsdate: new Date()}; constructor(private http:RequestService) { } ngOnInit() { } getData(){ this.http.getData(this.model.formatted).subscribe(result =&gt; { this.data = result; }); console.log(this.model.formatted) } the error: zone.js:2933 POST http://127.0.0.1:5000/schedule 400 (BAD REQUEST) ERROR Response {_body: "&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…object: Extra data: line 1 column 5 (char 4)&lt;/p&gt;↵", status: 400, ok: false, statusText: "BAD REQUEST", headers: Headers, …} And this is structure of this.model: {date: {…}, jsdate: Sat Jan 27 2018 00:00:00 GMT+0300 (RTZ 2 (зима)), formatted: "2018-01-27", epoc: 1517000400} What should I send to get a normal reponse?

http://stackoverflow.com/a/48334464
score: 4
has comment: http://stackoverflow.com/comment/83736946
has comment: http://stackoverflow.com/comment/84022161
has comment: http://stackoverflow.com/comment/84048264
accepted answer of: http://stackoverflow.com/q/48333516
has comment: http://stackoverflow.com/comment/83674242
type: Answer
answers question: http://stackoverflow.com/q/48333516
upvote count: 4
has comment: http://stackoverflow.com/comment/83674717
has comment: http://stackoverflow.com/comment/83737286
downvote count: 0
has body: Part 1: MFCC to tag conversion It's not obvious from the librosa documentation but I believe the mfcc's are being calculated at about a 23mS frame rate. With your code above mfcc.shape will return (20, x) where 20 is the number of features and the x corresponds to x number of frames. The default hop_rate for mfcc is 512 samples which means each mfcc sample spans about 23mS (512/sr). Using this you can compute which frame goes with which tag in your text file. For example, the tag Music goes from 0.0 to 2.5 seconds so that will be mfcc frame 0 to 2.5*sr/512 ~= 108. They will not come out exactly equal so you need to round the values. Part 2A: DNN Data Format For the input (mfcc data) you'll need to figure out what the input looks like. You'll have 20 features but do you want to input a single frame to your net or are you going to submit a time series. You're mfcc data is already a numpy array, however it's formatted as (feature, sample). You probably want to reverse that for input to Keras. You can use numpy.reshape to do that. For the output, you need assign a numeric value to each tag in your text file. Typically you would store the the tag to integer in a dictionary. This will then be used to create your training output for the network. There should be one output integer for each input sample. Part 2B: Saving the Data The simplest way to do this is to use pickle to save and the reload it later. I like to use a class to encapsulate the input, output and dictionary data but you can choose whatever works for you.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84543128

http://stackoverflow.com/comment/83762381
has text: Basically, i do not see any message in the cmd. I have designed a gui as well, so i do see gui windows but nothing in cmd for messages.
type: QuestionComment
comment on: http://stackoverflow.com/q/48387397
score: 1
type: Comment

http://stackoverflow.com/q/48411007
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Python ggplot Barchart not displaying data as expected
has comment: http://stackoverflow.com/comment/83811791
has comment: http://stackoverflow.com/comment/83811874
tagged with: python-ggplot
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83811920
has body: I'm trying to create a basic barchart using python ggplot implementation. I want the percentages on the y-axis and the type on the x-axis rotated 90deg. The code I have written is below. from ggplot import * import pandas as pd df1 = pd.DataFrame({'Percentage':[91.45, 16.73, 8.61], 'Type':['protein_coding', 'antisense_RNA', 'sense_overlapping']}) ggplot(aes(x="Type",y='Percentage'), data=df1) +\ geom_bar(stat='identity')+\ xlab('Biotype') +\ theme(axis_text_x = element_text(angle = 90)) It has converted my "Types" to numbers and is not plotting the percentages correctly on the y axis. Does anyone have any suggestions? Thank you.
has comment: http://stackoverflow.com/comment/83812069
answer count: 0
type: UnansweredQuestion
tagged with: bar-chart

http://stackoverflow.com/q/48448048
type: AnsweredQuestion
has title: pip is able to search package but install fails with error
downvote count: 0
tagged with: apache
answer count: 1
tagged with: pip
linked to: http://stackoverflow.com/q/50248524
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48460582
accepted answer: http://stackoverflow.com/a/48460582
has body: I have local pypi server, where I uploaded cffi package. When I try to search, it return the package. $ pip search -i https://localhost --trusted-host localhost cffi cffi (1.11.4) - 1.11.4 But when try to install, it gives error. $ pip install -i https://localhost --trusted-host localhost cffi==1.11.4 Collecting cffi==1.11.4 Could not find a version that satisfies the requirement cffi==1.11.4 (from versions: ) No matching distribution found for cffi==1.11.4 I am running pypi server under apache webserver to handle https requests on centos. I check the apache log /var/log/httpd/ssl_access_log, for install command. Its return 200 for GET Call. 127.0.0.1 - - [25/Jan/2018:16:46:23 +0000] "GET /cffi/ HTTP/1.1" 303 - 127.0.0.1 - - [25/Jan/2018:16:46:23 +0000] "GET /simple/cffi/ HTTP/1.1" 200 339 I check the log again. For celery it works, after that for cffi it fails. 127.0.0.1 - - [25/Jan/2018:16:50:58 +0000] "GET /celery/ HTTP/1.1" 303 - 127.0.0.1 - - [25/Jan/2018:16:50:58 +0000] "GET /simple/celery/ HTTP/1.1" 200 321 127.0.0.1 - - [25/Jan/2018:16:50:58 +0000] "GET /packages/celery-4.0.2-py2.py3-none-any.whl HTTP/1.1" 200 396437 127.0.0.1 - - [25/Jan/2018:16:50:59 +0000] "GET /cffi/ HTTP/1.1" 303 - 127.0.0.1 - - [25/Jan/2018:16:50:59 +0000] "GET /simple/cffi/ HTTP/1.1" 200 339 The problem is, for cffi its not redirect to /packages/cffi-1.11.4-cp35-cp35m-manylinux1_x86_64.whl. While in celery its goes to /packages/celery* after GET /simple/celery/. I tried to curl, to check if there is change in response between these 2 packages, but there is not difference. $ curl -k https://localhost/simple/celery/ -i HTTP/1.1 200 OK Date: Thu, 25 Jan 2018 16:59:27 GMT Server: Apache/2.2.15 (CentOS) Content-Length: 321 Connection: close Content-Type: text/html; charset=UTF-8 Links for celery Links for celery celery-4.0.2-py2.py3-none-any.whl $ curl -k https://localhost/simple/cffi/ -i HTTP/1.1 200 OK Date: Thu, 25 Jan 2018 16:59:29 GMT Server: Apache/2.2.15 (CentOS) Content-Length: 339…
tagged with: python
score: 2
tagged with: pypiserver
upvote count: 2

http://stackoverflow.com/a/48483089
downvote count: 0
upvote count: 1
has body: It’s good to start with reading the documentation for the built-in function all(): Return True if all elements of the iterable are true (or if the iterable is empty). That means that c in it for c in x is a “generator expression”: it produces values. The values it produces are of the boolean expression c in it (see the in operator) for all characters c in string x. Here, the in operator is responsible for advancing the iterator. Note, however, that the True result is probably lucky. The iterator it can advance only once and because x = "bde" contains the letters in the same sequence as they appear in s = "abcdef", the whole expression works out to the expected result True. Reverse x = "edb" and the expression is False because the iterator is exhausted.
has comment: http://stackoverflow.com/comment/83959412
has comment: http://stackoverflow.com/comment/83959240
has comment: http://stackoverflow.com/comment/83959276
score: 1
has comment: http://stackoverflow.com/comment/83959427
type: Answer
accepted answer of: http://stackoverflow.com/q/48483030
answers question: http://stackoverflow.com/q/48483030
has comment: http://stackoverflow.com/comment/83959386
type: AcceptedAnswer

http://stackoverflow.com/q/48434919
type: Question
has answer: http://stackoverflow.com/a/48435185
upvote count: 5
duplicate of: http://stackoverflow.com/q/9303728
has answer: http://stackoverflow.com/a/48435147
tagged with: python
score: 4
type: AnsweredQuestion
tagged with: x-axis
has comment: http://stackoverflow.com/comment/83861783
answer count: 3
has comment: http://stackoverflow.com/comment/83893374
possible better answer: http://stackoverflow.com/a/48435147
tagged with: matplotlib
has title: Why are bar chart x-axis ticks showing strange and wrong negative values?
accepted answer: http://stackoverflow.com/a/48435235
has body: Why is my X-axis ticks showing Negative values when the Xaxis values range from 43990 - 44003. import matplotlib.pyplot as plt x=[44000, 44001, 44002, 44003, 43990, 43991, 43992, 43993, 43994, 43995, 43996, 43997, 43998, 43999] y=[8, 5, 3, 1, 1, 3, 4, 10, 4, 11, 4, 10, 17, 19] plt.bar(x,y) plt.show() I am seeing the following output. I was expecting x-axis to range from 43990 - 44003 I have tried this on a couple of machines, all showing similar strange behaviour on recent versions of python and matplotlib (tried a few different versions) Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19) [GCC 7.2.0] on linux Python 3.4.3 (default, Nov 17 2016, 01:08:31) Strangely enough many trivial toy example x and y arrays are giving me expected figures. For e.g the follwowing snippet shows the expected graph with correct x-axis tick labels x=[20,30,90,70, 50, 60, 80, 70] y=[3,2,5,10, 3, 9, 7, 6] plt.bar(x,y) plt.show() What obvious thing am i missing here ?
downvote count: 1
linked to: http://stackoverflow.com/q/9303728
favorite count: 0
has answer: http://stackoverflow.com/a/48435235

http://stackoverflow.com/comment/83905094
comment on: http://stackoverflow.com/q/48436875
type: Comment
type: QuestionComment
has text: Thank you skrx. Next time I will be more careful
score: 0

http://stackoverflow.com/q/48381711
has comment: http://stackoverflow.com/comment/83750569
has answer: http://stackoverflow.com/a/48401788
has comment: http://stackoverflow.com/comment/83750428
has comment: http://stackoverflow.com/comment/83750118
score: 1
has comment: http://stackoverflow.com/comment/83791343
has comment: http://stackoverflow.com/comment/83791311
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: mocking
has body: I need to redefine MagicMock's magic method in the child class and then use child class for testing, so I've tried: from unittest.mock import MagicMock class MockForTest(MagicMock): def __lt__(self): return self t1 = MockForTest() print(t1.__lt__()) # prints NotImplemented But why NotImplemented? I know I can do it: class A(): def __lt__(self): return NotImplemented class B(A): def __lt__(self): return self b = B() print(b.__lt__()) # prints &lt;__main__.B object at 0x000001D6EE77B2B0&gt; So, I can't redefine MagicMock's magic methods?
type: UnansweredQuestion
has title: How to redefine python3 MagicMock magic method?
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83829069
type: QuestionComment
has text: Note that the use of `hold` is deprecated. Maybe you should inform your instructor about that.
score: 0
comment on: http://stackoverflow.com/q/48413470
type: Comment

http://stackoverflow.com/comment/83779424
score: 2
has text: https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement?
type: QuestionComment
comment on: http://stackoverflow.com/q/48395838
type: Comment

http://stackoverflow.com/a/48415556
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48415038
type: Answer
has body: This might not be better, but an alternative approach would be to use a list comprehension: a = "123 456 7sr" print([e for e in a]) Output: ['1', '2', '3', ' ', '4', '5', '6', ' ', '7', 's', 'r']
score: 2

http://stackoverflow.com/comment/83685687
has text: yeah - i've scoured the documentation for something like that to no avail, unfortunately. thanks for the thoughts!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48348910
score: 0

http://stackoverflow.com/comment/83863353
has text: I found that whatever which import statement I am using, both the `tfe.__file__` is pointed to a same location: `/usr/local/lib/python3.6/dist-packages/tensorflow/contrib/eager/python/tfe.py`. I don't understand how `import tensorflow.contrib.eager as tfe` can end up with importing the correct `tfe.py`. Do you have any idea?
type: Comment
comment on: http://stackoverflow.com/a/48420497
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83898368
has text: https://stackoverflow.com/questions/5909/get-size-of-a-file-before-downloading-in-python
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48452422
type: Comment

http://stackoverflow.com/comment/83986778
has text: Well, no one is going to hand you a flash drive with it, is my point. And storing it in a database would hopefully make it 1) compressed 2) reasonably searchable
comment on: http://stackoverflow.com/q/48459913
score: 0
type: Comment
type: QuestionComment

list-comprehension
tags question: http://stackoverflow.com/q/48475110
tags question: http://stackoverflow.com/q/48380512
type: Tag
tags question: http://stackoverflow.com/q/48464958
tags question: http://stackoverflow.com/q/48411344
tags question: http://stackoverflow.com/q/48461234
tags question: http://stackoverflow.com/q/48363552
tags question: http://stackoverflow.com/q/48443151
tags question: http://stackoverflow.com/q/48432224
tags question: http://stackoverflow.com/q/48465407
tags question: http://stackoverflow.com/q/48487468
tags question: http://stackoverflow.com/q/48430360
tags question: http://stackoverflow.com/q/48465508
tags question: http://stackoverflow.com/q/48406312
tag name: list-comprehension
tags question: http://stackoverflow.com/q/48474882
tags question: http://stackoverflow.com/q/48430081

http://stackoverflow.com/q/48476900
has answer: http://stackoverflow.com/a/48477734
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83947610
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83947326
has title: Conditional Django Model Creation
score: 3
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/83948002
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58193463
has body: I am writing a app for django which i am planning to publish. This app requires a Bolean Setting variable CONSUMER_REGISTRATION. Aim of getting this variable is to decide whether to define ConsumerRegistrationModel or not. This is what I did. from django.db import models from django.conf import settings if getattr(settings, 'CONSUMER_REGISTRATION', False): class ConsumerRegistration(models.Model): ... Its working fine. The only Issue i am facing that developers will need to run makemigrations and migrate commands each time they change the variable in settings. 1- Can this work be automated ?. So if they change the variable then some code in django auto run the makemigrations and migrate commands. 2- Or is it perfectly fine to leave this work on developers ?? 3- Also I want to ask that is it a good aproach to do this in django ?
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/58193463
accepted answer: http://stackoverflow.com/a/48477734
has comment: http://stackoverflow.com/comment/83947074
downvote count: 0
tagged with: django

http://stackoverflow.com/q/48483443
linked to: http://stackoverflow.com/q/11277518
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50535673
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/76612950
answer count: 2
score: 1
tagged with: python-turtle
has title: How to turn turtle.shape with image?
downvote count: 0
has comment: http://stackoverflow.com/comment/133416855
upvote count: 1
has comment: http://stackoverflow.com/comment/129516539
favorite count: 0
has body: This is my code to make a rocket move around in a turtle screen: import turtle s = turtle.Screen() image = "rocket.gif" s.addshape(image) turtle.shape(image) s.bgcolor("black") def fd(): turtle.fd(5) def bk(): turtle.bk(10) def lt(): turtle.lt(5) def rt(): turtle.rt(5) turtle.penup() turtle.speed(0) turtle.home() s.listen() s.onkeypress(fd, "Up") s.onkeypress(bk, "Down") s.onkeypress(lt, "Left") s.onkeypress(rt, "Right") When I press the up button the rocket moves forward, and when I press the right button, the rocket image does not turn, but when it moves forward again the direction of the movement does change. I read this at the help() section at Python3 IDLE: Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle! But, I do not understand is this for turtle.rt() or turtle.setheading()? Even if it is for both, how do I rotate the image? Note: Surprisingly it works with trinket.io
type: Question

http://stackoverflow.com/q/48436073
linked to: http://stackoverflow.com/q/39048984
has answer: http://stackoverflow.com/a/48451444
type: Question
has comment: http://stackoverflow.com/comment/83864576
accepted answer: http://stackoverflow.com/a/49075735
has answer: http://stackoverflow.com/a/49075735
has comment: http://stackoverflow.com/comment/84023932
tagged with: python
has title: How to create new Tensorflow op from composition of existing Tensorflow ops
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/36456436
answer count: 3
has body: I know how to use tf.py_func to create a new custom op that runs on CPU. I also know from the TF guide you can create a new op and its gradient in C++ What I am looking for is none of the above. I want to define a custom gradient function for a composition of TF ops. tf.register_gradients can be used along with gradient_override_map to define a custom gradient for an existing op, but how do you register a composition of TF ops as a new op in the first place? A similar question has been asked here with no answer.
has answer: http://stackoverflow.com/a/49324138
has comment: http://stackoverflow.com/comment/84016852
possible better answer: http://stackoverflow.com/a/48451444
tagged with: tensorflow

http://stackoverflow.com/comment/83803608
type: QuestionComment
comment on: http://stackoverflow.com/q/48403986
type: Comment
has text: Same question as [this one](https://stackoverflow.com/questions/40470175/boxplot-outliers-labels-python). The other at least provides a [mcve].
score: 1

http://stackoverflow.com/comment/83859238
type: Comment
comment on: http://stackoverflow.com/q/48432325
has text: I'm runing it on wing idle 101 6.0. It has no problem on running terminal.
type: QuestionComment
score: 0

http://stackoverflow.com/a/48393288
has comment: http://stackoverflow.com/comment/83795717
has comment: http://stackoverflow.com/comment/83902871
accepted answer of: http://stackoverflow.com/q/48382662
score: 0
has body: I got a CO implementation to work for the sellar problem, but I did it in OpenMDAO 2.0. The apis are a little different, but you should be able to back convert to 1.0 if you want to. Or make the jump to 2.0! OpenMDAO - CO (Collaborative Optimization) on Sellar test case
type: Answer
answers question: http://stackoverflow.com/q/48382662
has comment: http://stackoverflow.com/comment/83877907
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83798444

http://stackoverflow.com/a/48401487
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48401428
accepted answer of: http://stackoverflow.com/q/48401428
has body: First, print all its properties to see what's available: print(dir(security)) Then think about which properties you want to print, and print them. For example if dir() tells you it has price, exchange, symbol, you can: print(security.price, security.symbol, security.exchange)
type: AcceptedAnswer

http://stackoverflow.com/comment/83923006
comment on: http://stackoverflow.com/a/48464786
has text: Thanks, i ve generally came to same code while writing this post. Is far i can see, it doesnt work if variable declared but doesnt has value (setted to `None`).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48405870
has comment: http://stackoverflow.com/comment/83800695
has body: I find this module, that have some string similarity methods implemented, on github https://gist.github.com/StuartGordonReid/90c8301f9403707a22ff. I'm new to python and I'm having some troubles to use de manhattan_distance function. The code for the function is: def manhattan_distance(self, p_vec, q_vec): """ This method implements the manhattan distance metric :param p_vec: vector one :param q_vec: vector two :return: the manhattan distance between vector one and two """ return max(np.sum(np.fabs(p_vec - q_vec)), self.e) But when a try to use this function (something like this) t = similarity.Similarity(1) t.manhattan_distance(np.array(["this is a testee"]), np.array(["this is a test"])) or: vector_one = ["this", "is", "a", "test"] vector_two = ["this", "is", "a", "testee"] t.manhattan_distance(vector_one, vector_two) I get the following error: TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('S16') dtype('S16') dtype('S16')
tagged with: python
tagged with: nlp
has title: What is the right way to use the manhattan function described bellow?
tagged with: distance
answer count: 0
has comment: http://stackoverflow.com/comment/83802168
score: 0
has comment: http://stackoverflow.com/comment/83801386
has comment: http://stackoverflow.com/comment/83800768
has comment: http://stackoverflow.com/comment/83800668
type: Question
has comment: http://stackoverflow.com/comment/83800710
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83800562

http://stackoverflow.com/comment/83819455
type: AnswerComment
has text: This is exactly what I was after! Can you explain why the double `def listrand()` was added?
type: Comment
comment on: http://stackoverflow.com/a/48414741
score: 0

http://stackoverflow.com/q/48347849
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83687517
has comment: http://stackoverflow.com/comment/83686330
linked to: http://stackoverflow.com/q/41968732
has comment: http://stackoverflow.com/comment/83686167
has comment: http://stackoverflow.com/comment/83688081
type: Question
has comment: http://stackoverflow.com/comment/83683920
type: UnansweredQuestion
has body: I have a dictionary, 'values', in Python. The 'values' contains lists of integers, except the 'RowHeaders'. I would like to have the 'RowHeaders' as the first column in the excel file. In the following code, I cannot add a condition in 'from_items' method to put it as the first column. When I run this code, it doesn't put the 'RowHeaders' data in the first column. values['RowHeaders'] = list_of_headers for feat in features: values.setdefault(feat, list()) for p in data: values[feat].append(int(data[p][feat])) writer = pd.ExcelWriter('output.xlsx') df = pd.DataFrame.from_items([(f,values[f]) for f in values]) df.to_excel(writer, 'Sheet1', index=False) writer.save() Thanks.
tagged with: python
linked to: http://stackoverflow.com/q/13148429
has title: How to change the order of columns while converting to excel in Pandas?
score: 0

svd
type: Tag
tags question: http://stackoverflow.com/q/48424084
tag name: svd

resolution
tag name: resolution
tags question: http://stackoverflow.com/q/48332282
type: Tag

http://stackoverflow.com/comment/83705940
comment on: http://stackoverflow.com/a/48359495
score: 0
has text: Thanks for your answer. It works. Then i will learn hard to undersand how it's works.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83956146
has text: How have you setup the init system to run in the container at startup?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48475138
type: Comment

http://stackoverflow.com/comment/83961817
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48484240
type: QuestionComment
has text: @JonathanLeffler Thank you. getline() works. Time down to 1 second now. But could you explain why mmap is less efficient if I read the file just once?

http://stackoverflow.com/a/48475317
has body: You may want to use zip() built-in function to mix two lists and split() to split the output to lists of strings. Zip will make a list of tuples: [('one', 1), ('two', 2), ('three', 3), ('four', 4)] Then you'll need to print it out. Here's the full code: zipped = zip(cmd_input1.split('\n'), cmd_input2.split('\n')) for line in zipped: print(line[0], line[1])
has comment: http://stackoverflow.com/comment/83944101
has comment: http://stackoverflow.com/comment/83944168
type: Answer
accepted answer of: http://stackoverflow.com/q/48475129
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48475129
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48347347
has comment: http://stackoverflow.com/comment/83681404
accepted answer of: http://stackoverflow.com/q/48347290
has comment: http://stackoverflow.com/comment/83681773
upvote count: 15
answers question: http://stackoverflow.com/q/48347290
has comment: http://stackoverflow.com/comment/83681655
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83681708
score: 14
has body: The method returns True if the request was successful. The status codes in the 2xx and 3xx ranges all indicate a correct and successful response, while other status codes all indicate errors. Under the hood, the __bool__ method is essentially an alias for the response.ok attribute: Returns True if status_code is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK. This echoes the response.raise_for_status() method, which will raise an HTTPError exception when there is an 'error' status code. Any function or method in the requests API that can return a Response instance, will always do so, or raise an exception. You can't ever get a None or other false-y value from the API, so there is no other usecase for testing for a boolean value. As such, the boolean value of a response can be overloaded to mean anything, and here it is used to make it easy to test for the 'okayness' of the response: response = requests.get(...) if response: # success! yay, do something meaningful with the response data This fits some use-cases better than raising an exception for the opposite state, where you got an error status from the server.
has comment: http://stackoverflow.com/comment/83681145
type: Answer

http://stackoverflow.com/comment/83753175
type: AnswerComment
comment on: http://stackoverflow.com/a/48382841
score: 0
type: Comment
has text: @SRingne I'm not saying mine is the fastest between the two answerERs, but I'm saying my first option is the fastest of the two. In any case, I'd strongly suggest testing all options before deciding what to use in your code. Cheers.

http://stackoverflow.com/q/48395051
possible better answer: http://stackoverflow.com/a/48395415
has answer: http://stackoverflow.com/a/48404523
has comment: http://stackoverflow.com/comment/83778070
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48395415
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83777702
favorite count: 0
has body: I have a host dict that contains a hostname key, and list values. I would like to be able to remove any item of fruit_ from the list of each value. host = { 'abc.com': ['fruit_apple', 'fruit_orange', 'veg_carrots'], '123.com': None, 'foo.com': ['fruit_tomatoes', 'veg_potatoes'] } for v in host.values(): if v is not None: for x in v: try: # creating my filter if x.startswith('fruit_'): # if x finds my search, get, or remove from list value host(or host.value()?).get/remove(x)# this is where i'm stuck print(hr.values(#call position here?)) # prove it except: pass I'm stuck around the commented area, I feel like I'm missing another iteration (new list somewhere?), or maybe I'm not understanding how to write the list value back. Any direction would be helpful.
tagged with: python-3.x
has title: How do I remove a list item from a dict value?
type: Question
has comment: http://stackoverflow.com/comment/83777865
accepted answer: http://stackoverflow.com/a/48395100
has answer: http://stackoverflow.com/a/48395100
tagged with: python
has comment: http://stackoverflow.com/comment/83778018
tagged with: dictionary
score: 4
upvote count: 4
tagged with: list

http://stackoverflow.com/a/48410520
type: Answer
has body: Your code cannot call bad_my_function until it has all of the arguments to pass to it. It gets one of those arguments by calling bad_f1() and bad_f2(), so those calls have to happen first. Simpler example: def foo(a,b,c): print("foo") def bar(): print("bar") return 2 foo(1, bar(), 3) This will output "bar" before "foo". How could it be otherwise? Exactly what do you expect to be passed into foo as the value of its b parameter if bar has not been called yet?
has comment: http://stackoverflow.com/comment/83810865
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48410490
answers question: http://stackoverflow.com/q/48410490
score: 5
upvote count: 5

http://stackoverflow.com/comment/116324792
comment on: http://stackoverflow.com/a/48472420
score: 0
type: Comment
has text: This simple change from a `yield from` to unbatching in my custom generator dataset reduced data generation time from >10h to 6 minutes. Kudos!
type: AnswerComment

http://stackoverflow.com/q/48357202
answer count: 0
type: UnansweredQuestion
has body: I have models: class Web2Types(models.Model): name = models.CharField(max_length=200, unique=True) status = models.IntegerField(default=0) class Web2Domains(models.Model): domain = models.CharField(max_length=255, unique=True) web2type = models.ForeignKey(Web2Types) Now I have a string containing commas, I want that string first split by comma then all values of that list will save into Web2Domains model. &lt;------------------------------------------------UPDATE-------------------------------------------------------------------> In Web2Types name='social', status=0 and assume it's auto incremented is 1. In Web2Domains domain='facebook.com', web2type=1 Now I want something like this in serializer: webid = 1 domain_str = 'google.com,yahoo.com,stackoverflow.com,test.com' domain_str_list = domain_str.split(',') for domain1 in domain_str_list: Web2Domains.objects.create(domain=domain1, web2type=webid) serializer: class Web2DomainsSerializer(serializers.ModelSerializer): web2type = serializers.SlugRelatedField(read_only=True, slug_field='name') class Meta: model = Web2Domains fields = '__all__ ' This logic I want in Django rest framework serializer.
has comment: http://stackoverflow.com/comment/83702409
tagged with: django
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/83702479
has comment: http://stackoverflow.com/comment/83701963
has comment: http://stackoverflow.com/comment/83702309
tagged with: python
has title: split data and save values using django rest framework
type: Question
score: 0

http://stackoverflow.com/comment/83658296
score: 0
type: AnswerComment
has text: @Code_Sipra See edit, I've attempted to address that.
type: Comment
comment on: http://stackoverflow.com/a/48336208

http://stackoverflow.com/comment/83734198
comment on: http://stackoverflow.com/q/48373506
type: QuestionComment
has text: NameErrors can't be caught at parse time. For all Python knows, some other code it can't see is intended to bind the `ValueErro` name in the cases where that expression would be evaluated.
score: 5
type: Comment

qfont
type: Tag
tag name: qfont
tags question: http://stackoverflow.com/q/48381351

http://stackoverflow.com/comment/83795404
score: 1
has text: The code that uses `pd.DataFrame` does the importing, no the code that imports the function. *This is not something the module that imports a function ever needs to worry about*. If you are concerned about the dependency being *installed*, then you can't test for that with the `sys.modules` test, as that only lists modules that are already imported. The `import pandas as pd` statement will throw an `ImportError` if the module is not installed, just handle that exception.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48403374

http://stackoverflow.com/comment/83829654
type: Comment
score: 0
type: AnswerComment
has text: Where to run this command? Please tell me exactly where should I run this command
comment on: http://stackoverflow.com/a/48419369

http://stackoverflow.com/comment/83929162
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48467759
has text: How would you do that exactly? if else loop?
type: Comment

http://stackoverflow.com/comment/83817605
has text: `\.*` matches `.` zero to unlimited times
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48413762

http://stackoverflow.com/comment/83766432
score: 0
type: Comment
type: QuestionComment
has text: do you want accuracy on each cross validation set or the average?
comment on: http://stackoverflow.com/q/48389166

http://stackoverflow.com/q/48447149
tagged with: python
score: 2
upvote count: 2
has body: I want to run an external optimizer using Keras' TFOptimizer wrapper and giving it a tf.contrib.opt.ScipyOptimizerInterface but I'm not succeeding. My model is this (very small example): model = Sequential() model.add(InputLayer(input_shape=(6,)) model.add(Dense(3, activation='sigmoid')) model.add(Dense(5, activation='linear')) I'm tried compiling with: model.compile(optimizer=TFOptimizer(ScipyOptimizerInterface())) But of course, it doesn't work because the ScipyOptimizerInterface constructor needs the loss parameter during initialization. So, I created two own classes: class CGTFOptimizer(object): def compute_gradients(self, loss, params): optimizer = ScipyOptimizerInterface(loss, method='cg') result = optimizer.minimize(loss) return result class CGTF(TFOptimizer): """ Wrapper for TFOptimizer """ def __init__(self): super(CGTF, self).__init__(optimizer=CGTFOptimizer()) And compiling the model with model.compile(optimizer=CGTF()) succeeds but upon training I receive the following error from the ScipyOptimizerInterface call: Traceback (most recent call last): File "venv/py3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 455, in _apply_op_helper as_ref=input_arg.is_ref) File "venv/py3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 991, in internal_convert_n_to_tensor ctx=ctx)) File "venv/py3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 926, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "venv/py3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 774, in _TensorTensorConversionFunction (dtype.name, t.dtype.name, str(t))) ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("training/TFOptimizer/Reshape_25:0", shape=(1,), dtype=int64)' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "directly_with_tensorflow.py", line…
downvote count: 0
answer count: 0
tagged with: keras
tagged with: tensorflow
has title: TypeError in tensorflow ScipyOptimizerInterface when using in Keras
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/83942567
score: 0
type: Comment
has text: Okay, I think I got it now. Thanks!
type: QuestionComment
comment on: http://stackoverflow.com/q/48470059

http://stackoverflow.com/q/48428023
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83846651
has answer: http://stackoverflow.com/a/48428192
tagged with: django
tagged with: python
has title: Reset a value in a model for all users each year - Django.
has body: I am developing a Django application that tracks an employees holiday. I am not to sure how I would go about resetting the holiday each year at a specific date. Are there any good known solutions/libraries for how to do this? class User(models.Model): avatar = models.ImageField( default='images/avatars/profile.png', upload_to=user_directory_path) name = models.CharField(max_length=100) title = models.CharField(max_length=200, default="Employee") email = models.EmailField(max_length=254) present = models.BooleanField(default=False) code = models.CharField(max_length=4, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_clocked = models.DateTimeField(default=timezone.now) total_holiday = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) holiday_remaining = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) My model is shown above I need to reset the remaining_holiday field on a admin user defined day each year.
accepted answer: http://stackoverflow.com/a/48428192
score: 0
answer count: 1

http://stackoverflow.com/comment/83704424
comment on: http://stackoverflow.com/q/48358084
score: 0
type: Comment
has text: @Nae I wanted to avoid repeating the same code. One can simply add the command shown above to the last line of `def selectItem(self, event):` in the [test code](https://stackoverflow.com/questions/48268506/select-a-cell-in-tkinter-treeview-and-get-the-cell-data?noredirect=1#comment83523709_48268506) that I wrote previously.
type: QuestionComment

http://stackoverflow.com/comment/83966456
comment on: http://stackoverflow.com/q/48486776
score: 0
has text: Do you mean *terms*? https://simple.wikipedia.org/wiki/Term_(mathematics)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48335823
downvote count: 0
upvote count: 1
has title: Tensorflow: KL divergence for a Gaussian Mixure
has comment: http://stackoverflow.com/comment/89702538
tagged with: tensorflow
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/42392887
has comment: http://stackoverflow.com/comment/83903035
type: UnansweredQuestion
tagged with: gmm
tagged with: gaussian
tagged with: mixture
tagged with: python
linked to: http://stackoverflow.com/q/26079881
has comment: http://stackoverflow.com/comment/83760135
has comment: http://stackoverflow.com/comment/91428456
answer count: 0
score: 1
has body: I know with python and scikit learn, how to calculate KL divergence for Gaussian mixture given that its parameters such as weight, mean, and covariance as np.array,as shown below. GaussianMixture initialization using component parameters - sklearn KL-Divergence of two GMMs But I am wondering, with Tensorflow, is there any way to calculate KL divergence between two Gaussian mixture given that its parameters as Tensor, 1) I tried scikit above in Tensorflow, but it didn't work since Tensorflow doens'T give it a actual values until session is executed. 2) There are some TF packages, but not exactly KL for Gaussian mixture. https://www.tensorflow.org/api_docs/python/tf/contrib/distributions/Mixture https://www.tensorflow.org/api_docs/python/tf/distributions/kl_divergence Any help is greatly appreciated. Later, I tried with a latest TF library as below. import tensorflow as tf print('tensorflow ',tf.__version__) # for Python 3 import numpy as np import matplotlib.pyplot as plt ds = tf.contrib.distributions kl_divergence=tf.contrib.distributions.kl_divergence # Gaussian Mixure1 mix = 0.3# weight bimix_gauss1 = ds.Mixture( cat=ds.Categorical(probs=[mix, 1.-mix]),#weight components=[ ds.Normal(loc=-1., scale=0.1), ds.Normal(loc=+1., scale=0.5), ]) # Gaussian Mixture2 mix = 0.4# weight bimix_gauss2 = ds.Mixture( cat=ds.Categorical(probs=[mix, 1.-mix]),#weight components=[ ds.Normal(loc=-0.4, scale=0.2), ds.Normal(loc=+1.2, scale=0.6), ]) # KL between GM1 and GM2 kl_value=kl_divergence( distribution_a=bimix_gauss1, distribution_b=bimix_gauss2, allow_nan_stats=True, name=None ) sess = tf.Session() # with sess.as_default(): x = tf.linspace(-2., 3., int(1e4)).eval() plt.plot(x, bimix_gauss1.prob(x).eval(),'r-') plt.plot(x, bimix_gauss2.prob(x).eval(),'b-') plt.show() print('kl_value=',kl_value.eval()) Then I got this error... NotImplementedError: No KL(distribution_a || distribution_b) registered for distribution_a type Mixture and distribution_b type Mixture I am very sad now. :…

http://stackoverflow.com/q/48346258
score: -2
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I'm trying to save some data into my db after receiving it Here's my api.py file: from flask import Flask, request, abort, jsonify from flask_cors import cross_origin from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost:5432/****' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Communication(db.Model): __tablename__ = 'comm' id = db.Column('comm_id', db.Integer, primary_key=True) early = db.Column(db.Boolean, nullable=False) late = db.Column(db.Boolean, nullable=False) message = db.Column(db.String, nullable=False) def __init__(self, early, late, message): self.early = early self.late = late self.message = message db.drop_all() db.create_all() @app.route('/api/form', methods=['POST']) @cross_origin(origin='localhost', headers=['Content- Type', 'Authorization']) def retrieve_info(): if not request.json: abort(400) else: early = request.json.get('early') late = request.json.get('late') message = request.json.get('message') test = Communication(early=early, late=late, message=message) db.session.add(test) db.session.commit() return jsonify('ok'), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True) Here's the json that i send: { "early": true , "late": false , "message": "Hello world" } Weirdly i get 0 exception or error message, but nothing is saved on my db. I don't understand what's wrong with my code (i checked the connection with the db is ok btw)
accepted answer: http://stackoverflow.com/a/48351390
has title: Flask-SQLAlchemy - Unable to insert data
tagged with: python
possible better answer: http://stackoverflow.com/a/48346402
has answer: http://stackoverflow.com/a/48351390
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/48346402
answer count: 2

http://stackoverflow.com/q/48453341
tagged with: python
has answer: http://stackoverflow.com/a/48453672
has body: Is there an efficient way to return array positions where the value in a given position is greater than a threshold value AND the subsequent position is less than that threshold? I am able to accomplish this in a loop, but it is very slow for arrays with 100,000+ entries. As an example, x=[4,9,1,5,7,8,10,11,2,4] threshold=3 # find elements greater than 3 and where the next element is less than 3 return [1,7] #corresponding to indexes for values 9 and 11 in x
has title: Find array position greater than a threshold where the next position is less than the threshold (numpy)
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48453393
type: Question
has answer: http://stackoverflow.com/a/48453393
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48453672
tagged with: arrays

http://stackoverflow.com/comment/83956912
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48481902
has text: So you want to shuffle a random 5%?

http://stackoverflow.com/a/48414086
upvote count: 1
answers question: http://stackoverflow.com/q/48413848
score: 1
type: AcceptedAnswer
has body: from pyramid.view import notfound_view_config @notfound_view_config(renderer='404.html') def not_found(request): return {}
type: Answer
accepted answer of: http://stackoverflow.com/q/48413848
has comment: http://stackoverflow.com/comment/83818689
downvote count: 0

http://stackoverflow.com/q/48442561
upvote count: 4
answer count: 2
tagged with: pandas
has body: This is my table timestamp date month day hour price 0 2017-01-01 00:00 01/01/2017 Jan Sun 00:00 60.23 1 2017-01-01 01:00 01/01/2017 Jan Sun 01:00 60.73 2 2017-01-01 02:00 01/01/2017 Jan Sun 02:00 75.99 3 2017-01-01 03:00 01/01/2017 Jan Sun 03:00 60.76 4 2017-01-01 04:00 01/01/2017 Jan Sun 04:00 49.01 I have data for all 24 hours of the day for everyday and every month for a whole year. I want to group the data per season for a weekdays and weekend, for example Weekend_Winter = All Saturday and Sunday datas for months Nov,Dec,Jan,Feb Quite a newbie to this so any help would be useful
downvote count: 0
linked to: http://stackoverflow.com/q/44124436
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83876689
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48443991
has answer: http://stackoverflow.com/a/48442689
tagged with: python
score: 4
has title: How to group data on Pandas with multiple conditions?

http://stackoverflow.com/a/48465029
downvote count: 0
has comment: http://stackoverflow.com/comment/83942300
answers question: http://stackoverflow.com/q/48463080
type: Answer
has body: You could use the Base.@raw_str non standard string literal macro: julia&gt; using PyCall: @pyimport julia&gt; @pyimport re julia&gt; regex = raw"[\w']+|[.,!?;]" "[\\w']+|[.,!?;]" julia&gt; re.findall(regex, "Hello, I'm a string!") 6-element Array{String,1}: "Hello" "," "I'm" "a" "string" "!" julia&gt;
score: 2
accepted answer of: http://stackoverflow.com/q/48463080
upvote count: 2
has comment: http://stackoverflow.com/comment/83953128
type: AcceptedAnswer

http://stackoverflow.com/a/48438219
type: Answer
has body: Instead of just define an operator, you can write your own interpreter for your own language inside python. Basically, you need to create 4 modules parser environment eval repl Then you can program with your own language within python. read Peter Novig's article for a detailed example of a python LISP interpreter
score: 0
answers question: http://stackoverflow.com/q/48436963

http://stackoverflow.com/a/48347295
downvote count: 0
upvote count: 1
has body: You can prevent the multiIndex column with this code by eliminating a ',': df = pd.DataFrame(pd.Series(my_counts, name=("count")).rename_axis("letter")) df.columns Output: Index(['count'], dtype='object') OR you can flatten your multiindex columns like this: df = pd.DataFrame(pd.Series(my_counts, name=("count",)).rename_axis("letter")) df.columns = df.columns.map(''.join) df.columns Output: Index(['count'], dtype='object')
accepted answer of: http://stackoverflow.com/q/48345640
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48345640
type: AcceptedAnswer

http://stackoverflow.com/comment/83938392
has text: In the `cursor.execute` function, try changing syntax to this: `cursor.execute(sql, (Day0, ))`
type: QuestionComment
comment on: http://stackoverflow.com/q/48472028
score: 1
type: Comment

dynamic
tags question: http://stackoverflow.com/q/48487788
tag name: dynamic
tags question: http://stackoverflow.com/q/48371219
type: Tag

http://stackoverflow.com/a/48526457
downvote count: 0
has comment: http://stackoverflow.com/comment/102327119
upvote count: 7
answers question: http://stackoverflow.com/q/48479206
score: 7
type: Answer
has body: Try: graph = Graph("http://localhost:7474/db/data/", user="neo4j", password="mypassword") As described in the py2neo docs: http://py2neo.org/v3/database.html#py2neo.database.Graph The authenticate function is used for HTTP basic auth, e.g. when neo4j runs behind a webserver.
accepted answer of: http://stackoverflow.com/q/48479206
type: AcceptedAnswer

http://stackoverflow.com/q/48359714
has comment: http://stackoverflow.com/comment/83706244
has body: I am trying to create a Python function that maps nodes of a web created by Odoo relational fields, and returns such map as a dictionary. I'll try to explain. Let us consider the model 'account.account', and its fields 'child_parent_ids' (o2m to same class) and 'parent_id' (m2o to same class, inverse of previous field). How can I create a dictionary where every key is a record of 'account.account', and every key's values are dictionaries made of their children records recursively, or 'True' if such record has no child records? E.g., let us consider this web: account | |_child-1 | |_child-2 | | | |_child-21 | |_child-22 | |_child-23 | |_child-3 | | | |_child-31 | |_child-32 | | | | | |_child-321 | | |_child-322 | | |_child-323 | | |_child-324 | | | |_child-33 | |_child-4 The function I'm looking for should return a dictionary like this: {'account': {'child-1': True}, {'child-2': {'child-21': True}, {'child-22': True}, {'child-23': True}, }, {'child-3': {'child-31': True}, {'child-32': {'child-321': True}, {'child-322': True}, {'child-323': True}, {'child-324': True} }, {'child-33': True}, } {'child-4': True}, } I tried to create a recursive function as follows: @api.multi def get_tree_dict(self): tree_dict = {} if self.child_parent_ids: for child in child_parent_ids: tree_dict[self] = child.get_tree_dict() return tree_dict else: tree_dict[self] = True return tree_dict It doesn't seem to work (it doesn't return the expected output, dictionary stops at first True value), and I can't find out why (please don't be too hard on me). Can please anyone help me, by showing the error I'm making and how can I solve it? Please note that the depth of the dictionary is not known a priori, so I think the method should be recursive (or iterative).
tagged with: python
accepted answer: http://stackoverflow.com/a/48382262
tagged with: dictionary
type: AnsweredQuestion
tagged with: recursion
has title: How to create a recursive function in Python to create a dict which maps Odoo 8 relational field records?
has comment: http://stackoverflow.com/comment/83706295
score: 1
tagged with: odoo-8
answer count: 1
tagged with: orm
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83706343
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48382262

http://stackoverflow.com/comment/86584191
type: AnswerComment
has text: You don't need transform at all
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48384788

http://stackoverflow.com/q/48445147
type: Question
has comment: http://stackoverflow.com/comment/84030044
tagged with: python
accepted answer: http://stackoverflow.com/a/48445214
has comment: http://stackoverflow.com/comment/83882679
score: -4
downvote count: 6
has answer: http://stackoverflow.com/a/48445214
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83881921
upvote count: 2
answer count: 1
has title: python add value to a list when iterate the list
has body: values = [2,3,4] for v in values: values.append([v,255,255]) Why do the statements above never end? I make a mistake in my code. However, I find it will never stop when I execute the code above.
favorite count: 0

http://stackoverflow.com/q/48368523
has answer: http://stackoverflow.com/a/48370291
downvote count: 0
tagged with: autodoc
has title: How to generate sphinx docks in nested directory?
tagged with: python
type: UnansweredQuestion
answer count: 1
favorite count: 0
type: Question
upvote count: 5
score: 5
linked to: http://stackoverflow.com/q/7948494
has body: I want to generate sphinx autodoc documentation from scripts in nested folder structure : └── programs └── general_name └── another_folder ├── script1.py └── script2.py For some reason script1.py and script2.py is not displayed with autodocs, I'm getting I can see just script name: programs.general_name.another_folder package ¶Submodules programs.general_name.another_folder.script1 module programs.general_name.another_folder.script2 module Full folder structure: ../ ├── docs │ ├── _build │ │ ├── doctrees │ │ │ ├── environment.pickle │ │ │ ├── index.doctree │ │ │ └── rst │ │ └── html │ │ ├── genindex.html │ │ ├── index.html │ │ ├── objects.inv │ │ ├── rst │ │ ├── search.html │ │ ├── searchindex.js │ │ ├── _sources │ │ └── _static │ ├── conf.py │ ├── index.rst │ ├── make.bat │ ├── Makefile │ ├── rst │ │ ├── modules.rst │ │ ├── programs.general_name.another_folder.rst │ │ ├── programs.general_name.rst │ │ └── programs.rst │ ├── _static │ └── _templates └── programs └── general_name └── another_folder ├── script1.py └── script2.py I'm running this command: /docs $ sphinx-apidoc -f -o rst/ ../programs/ &amp;&amp; make html Also I tried: $ sphinx-apidoc -f -o rst/ ../programs/general_name/another_folder/ &amp;&amp; make html But script1 module and script2 module are empty in generating html files. Solution: Found what was causing the problem - dash symbol "-". another_folder was actually named get_requests_from_server-10 After renaming folder to get_requests_from_server_10, auto-docks started to work
tagged with: python-sphinx

apache-beam-io
type: Tag
tag name: apache-beam-io
tags question: http://stackoverflow.com/q/48373131

http://stackoverflow.com/comment/83965925
type: Comment
has text: Yep agreed. To add to @WillemVanOnsem point, if you are checking for this often (and on large dataset) it just makes sense to add a column in your database
type: AnswerComment
comment on: http://stackoverflow.com/a/48486477
score: 0

http://stackoverflow.com/a/48418408
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48417972
upvote count: 1
has body: If I understand your question correctly, what you effectively need to do is make listb into a list of lists. To make the least amount of changes to combine, iterate over each item of listb and each index using zip, both of which should now be a lists of lists: def combine(lista, listb, index_in_list_a_to_start_insert): if isinstance(listb[0], list): # check if the first item in listb # is a list; check for empty lists for actual_list_b, actual_insert_index in zip(listb, index_in_list_a_to_start_insert): lista = combine(lista, actual_list_b, actual_insert_index) return lista newb = [0]*index_in_list_a_to_start_insert + listb max_len = max(len(lista), len(newb)) newa = lista if len(lista) &gt;= max_len else lista + [0]*(max_len-len(lista)) newb = newb if len(newb) &gt;= max_len else newb + [0]*(max_len-len(newb)) return [a + b for a, b in zip(newa,newb)][0:len(a)] And using your example lists above: &gt;&gt;&gt; a = [0, 1, 2, 3, 4, 5, 6, 7] &gt;&gt;&gt; b = [2, 4, 6, 8, 10, 12] &gt;&gt;&gt; c = [1, 1, 1, 1, 1] &gt;&gt;&gt; d = [2, 2, 2, 2, 2] &gt;&gt;&gt; &gt;&gt;&gt; combine(a, [b, c], [3, 4]) [0, 1, 2, 5, 9, 12, 15, 18] &gt;&gt;&gt; You'll need to add more isinstance() checks for both listb and the list of indexes, to ensure that either both are lists or neither are lists and both of the same length, with shortest one determining the result of the zip.
answers question: http://stackoverflow.com/q/48417972

http://stackoverflow.com/q/48483454
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83959909
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48484080
tagged with: python
has answer: http://stackoverflow.com/a/48484080
has comment: http://stackoverflow.com/comment/83959775
score: 2
type: AnsweredQuestion
answer count: 1
has title: Tag not removed after .decompose()
has body: I wanted to remove the text inside of the strong tags so I did this: for strong in soup.find('strong'): strong.decompose() But when I opened the file the last one wasn't deleted:

http://stackoverflow.com/q/48401162
tagged with: pygame
tagged with: sdl-2
has comment: http://stackoverflow.com/comment/83816070
has comment: http://stackoverflow.com/comment/83822546
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83815585
score: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83815524
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83833366
accepted answer: http://stackoverflow.com/a/48442467
has title: pygame_sdl2 - app is crashing on mobile during pygame.mouse.get_pressed()
has comment: http://stackoverflow.com/comment/83793853
upvote count: 2
has comment: http://stackoverflow.com/comment/83808270
has answer: http://stackoverflow.com/a/48442467
has body: I am developing a game for android with pygame and pygame_sdl2, and rapt for deploy. Currently, the game is at a very first stage of development. I have a joypad draw in the bottom left of my screen, and, when the mouse is pressed in the coordinates of the joypad's buttons, a character is moved according to the button durection. The mouse events are used as touch events as in this (working) example. The problem is: the game is working on my laptop (I am using Ubuntu), but not on my mobile device. When I start the game, everything shows up as expected, but as soon as I touh the screen (no matter if it's on the buttons or somewhere else), the app goes in background. My game is in a public github repo if you want to see the whole code (everything relevant is in the main.py file). I think the error is triggered by the call to pygame.mouse.get_pressed(). Here is some relevant code which hopefully would help in understanding the problem. Joypad class (btn_pressed method) def btn_pressed(self, mouse_event): # check if left mouse is being pressed if pygame.mouse.get_pressed()[0]: x, y = mouse_event.pos if self.btn_up.rect.collidepoint(x, y): return 'UP' elif self.btn_down.rect.collidepoint(x, y): return 'DOWN' elif self.btn_left.rect.collidepoint(x, y): return 'LEFT' elif self.btn_right.rect.collidepoint(x, y): return 'RIGHT' Character class (move method) def move(self, joypad_direction): """ move the character to be used along with Joypad.btn_pressed returns ('UP', 'DOWN' 'LEFT', 'RIGHT') """ self.dx = 0 self.dy = 0 # check for horizontal move if joypad_direction == 'LEFT': self.dx = -self.speed self.rect.move_ip(-self.speed, 0) if joypad_direction == 'RIGHT': self.dx = +self.speed self.rect.move_ip(self.speed, 0) self.dx = 0 # check for vertical move if joypad_direction == 'UP': self.dy = -self.speed self.rect.move_ip(0, -self.speed) if joypad_direction == 'DOWN': self.dy = +self.speed self.rect.move_ip(0, self.speed) self.dy = 0 main loop while True: ev = pygame.event.wa…
tagged with: android
tagged with: python

http://stackoverflow.com/comment/83675059
comment on: http://stackoverflow.com/q/48344632
has text: Thank you! Somehow in my searching around I had not found that.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83927844
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48467144
score: 0
has text: You should show your insert code. With SQLite you would store that as a textual string, that's ok for storage but if you want to use SQL later on to query the data say for a specific key value then that's not the way to do it.

http://stackoverflow.com/q/48425685
tagged with: python
upvote count: 4
linked to: http://stackoverflow.com/q/43938672
has answer: http://stackoverflow.com/a/48514082
accepted answer: http://stackoverflow.com/a/48514082
has title: Pyspark levenshtein Join error
has comment: http://stackoverflow.com/comment/83841519
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83841217
answer count: 1
downvote count: 1
tagged with: levenshtein-distance
has body: I want to perform a join based on Levenshtein distance. I have 2 tables: Data: Which is a CSV in HDFS file repository. one of the columns is Disease description, 15K rows. df7_ct_map: a table I call from Hive. one of the columns is Disease Indication, 20K rows. I'm trying to join both tables by matching each description with the indication (they are text descriptions of sicknesses). Ideally they need to be the same, but if both texts are different I wish to select matching text containing the maximum number of common words. from pyspark.sql.functions import levenshtein joinedDF = df7_ct_map.join( Data, levenshtein(df7_ct_map("description"), Data("Indication")) &lt; 3) joinedDF.show(10) The problem is Data is a DataFrame which is why I obtain the following error: TypeError: 'DataFrame' object is not callable TypeError Traceback (most recent call last) in engine ----&gt; 1 joinedDF = df7_ct_map.join( Data, levenshtein(df7_ct_map("description"), Data("Indication")) &lt; 3) TypeError: 'DataFrame' object is not callable Some advice? Can I use Fuzzywuzzy package? If so, how?
favorite count: 0
tagged with: fuzzywuzzy
type: Question
score: 3
tagged with: apache-spark-sql
tagged with: pyspark

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/48335474
type: Tag

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/48438158

http://stackoverflow.com/a/54500635
upvote count: 14
has comment: http://stackoverflow.com/comment/117087842
answers question: http://stackoverflow.com/q/48357030
downvote count: 1
score: 13
has body: Add. from pytesseract import Output
type: Answer

http://stackoverflow.com/comment/83830286
score: 0
type: Comment
type: AnswerComment
has text: That's a funny bug. It actually happens because of the property of index to stop at the first instance of the search argument it finds. The call `list[list.index(item2)]=temp` finds the location of the student that you swapped in the line just before this one - and restores the state before the swap. Your approach works if you swap the other way round, first `item2` and then `item1`, because the second swap will find the correct swap target that way. You can then also drop the `tmp` assignment because passing the arguments directly to the swap function copies them already.
comment on: http://stackoverflow.com/a/48398398

http://stackoverflow.com/q/48426834
has answer: http://stackoverflow.com/a/48426958
accepted answer: http://stackoverflow.com/a/48426958
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48426964
answer count: 3
has title: How to use global variables in imported libraries?
has body: I've a main.py file with a block of code like this: import urtc import machine rtc = urtc.DS3231(machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2))) from func import * #line 4 Now, func.py file which is imported on line 4 has code something like this: def current_time(): import urtc import machine rtc = urtc.DS3231(machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2))) return urtc.tuple2seconds(rtc.datetime()) In main.py, I'm already importing urtc and machine and defining rtc. Is it possible to eliminate these 3 lines from function current_time(): import urtc import machine rtc = urtc.DS3231(machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2))) It seems redundant as I already have them in main.py global. How can I use them from main.py global instead of importing them again in function current_time()?
type: Question
has answer: http://stackoverflow.com/a/48426916
possible better answer: http://stackoverflow.com/a/48426916
tagged with: python

http://stackoverflow.com/q/48435391
downvote count: 0
has answer: http://stackoverflow.com/a/50435380
score: 1
has title: Py2App generating Segmentation fault: 11 on run OS X
upvote count: 1
answer count: 1
has body: I have a python application ready for production. I am able to build and run the application in Py2App's Alias mode. However, when I try to build it in production mode, python3 setup.py py2app it will indicate a successful build, but when I run, ./dist/main.app/Contents/MacOS/main, immediately, I will get an error producing only, Segmentation fault: 11. I am running Python 3.6 and Py2App 0.14.1. Can anyone shed some light on where segmentation fault comes from? Obviously it is somewhere in my code, but there are a couple thousand lines and I don't want to post it right now. Has anyone else had this issue?
tagged with: py2app
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83932326
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48468975
score: 0
has text: Ups that should be a comment. Not sure If you understood me right... When you install with pip your prompt should be prefixed with your current environment after you activated it. Else you will update the package in your root and not for your environment.

http://stackoverflow.com/comment/83946123
comment on: http://stackoverflow.com/q/48476162
has text: Can you check the python3’s location by something like ‘which python3’?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83764005
type: QuestionComment
type: Comment
has text: Are they single column DataFrames?
comment on: http://stackoverflow.com/q/48388144
score: 0

http://stackoverflow.com/comment/83799891
comment on: http://stackoverflow.com/q/48405592
score: 3
type: Comment
type: QuestionComment
has text: From the [documentation of `np.nansum`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.nansum.html): "Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero."... I'd say it returning `0.0` is exactly the expected behaviour. Note that this changed in `numpy` 1.8 (again from the docs: "In NumPy versions <= 1.8.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned.")

http://stackoverflow.com/a/48345344
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/48345205
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48345205
has body: Well, I think at first glance it seems it is difficult to do it with regex but there is a way to do it by applying regex in multiple levels (in this case 2 levels). Here is an example: &gt;&gt;&gt; f = "abc 123 def 23435 kill x22 y2986" &gt;&gt;&gt; import re &gt;&gt;&gt; exp = re.sub(r"(?&lt;=def)(.*)(?=y)", lambda x:re.sub(r"\d", '#', x.group()), f) &gt;&gt;&gt; exp 'abc 123 def ##### kill x## y2986' &gt;&gt;&gt;
type: Answer

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48449249
tags question: http://stackoverflow.com/q/48394807
tags question: http://stackoverflow.com/q/48465941
tags question: http://stackoverflow.com/q/48459465
type: Tag

http://stackoverflow.com/q/48427484
has comment: http://stackoverflow.com/comment/83845958
has comment: http://stackoverflow.com/comment/83845747
has comment: http://stackoverflow.com/comment/83845539
has answer: http://stackoverflow.com/a/48428464
has body: My current setup is this: 1 x computer 1 x GS308v2 ethernet HUB 7 x raspberry pi's The pi's are given static ip's ranging from 192.168.1.2 to 192.168.1.9. The dhcpcd.conf file is as follows: The python script for sender: #!/usr/bin/python import socket import struct import sys import IN import subprocess import fcntl MULTICAST_GROUP = '224.1.1.1' MULTICAST_PORT = 12345 path = "-o /var/www/html/images-folder/pic.jpg" SCMD = chr(1) SEND = SCMD + path sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) dev = "eth0" + "\0" sock.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, dev) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) sock.sendto(SEND, (MULTICAST_GROUP, MULTICAST_PORT)) sock.close() The python for reciever: #!/usr/bin/python import socket import struct import fcntl from subprocess import call import sys MULTICAST_GROUP = '224.1.1.1' MULTICAST_PORT = 12345 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MULTICAST_PORT)) req = struct.pack("4sl", socket.inet_aton(MULTICAST_GROUP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req) while True: data = sock.recv(10240) This all works with dynamic ip's on a router. But is not working on the HUB with static ip's. The reciever script gives the following error: Traceback (most recent call last): File "/home/pi/dummyPi.py", line 17, in &lt;module&gt; sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 19] No such device How can this hub x pi network be configured to carry out this multicast?
has comment: http://stackoverflow.com/comment/83846460
tagged with: raspberry-pi
downvote count: 0
tagged with: multicast
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83846121
has comment: http://stackoverflow.com/comment/83845969
answer count: 1
has title: Raspberry Pi Python - Multicasting UDP using Socket not working on local network
has comment: http://stackoverflow.com/comment/83846653
has comment: http://stackoverflow.com/comment/83846858
favorite count: 0
has comment: http://stackoverflow.com/comment/83845570
type: Question
has comment: http://stackoverflow.com/comment/83846289
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python

http://stackoverflow.com/q/48473133
type: Question
duplicate of: http://stackoverflow.com/q/6294179
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83939950
has comment: http://stackoverflow.com/comment/83939952
has answer: http://stackoverflow.com/a/48473181
score: 2
has answer: http://stackoverflow.com/a/48473211
tagged with: python-2.7
answer count: 3
upvote count: 3
has title: Indexing elements in a list
has body: I want to take the indices of each element in the list a=[2,4,5,2] when I enter a.index(2) I get 0 as output. How can I take the index of the fourth element like that way in Python?
linked to: http://stackoverflow.com/q/6294179
downvote count: 1
has comment: http://stackoverflow.com/comment/83939951
favorite count: 0
has answer: http://stackoverflow.com/a/48473161

http://stackoverflow.com/a/48347818
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48347002
has body: Modulus is your best solution, but this is also possible in a fairly simple for loop if you insist on a looping solution. &gt;&gt;&gt; x = 2885 &gt;&gt;&gt; y = 1440 &gt;&gt;&gt; for i in range(x, -1, -y): # -1 as substitution for inclusive 0 ... pass ... &gt;&gt;&gt; i 5
type: Answer

http://stackoverflow.com/q/48407813
score: 0
has body: I'm trying set an offset but I want to limit it to a maximum of 99 hours by only allowing either one- or two-digit numbers but I'm not sure of the syntax to use with Django 2.0. I've tried to look for updated documentation but I can't find it, maybe I missed it but I did look before posting here. Here is the code in my views.py file: # Creating a view for showing current datetime + and offset of x amount of hrs def hours_ahead(request, offset): try: offset = int(offset) except ValueError: # Throws an error if the offset contains anything other than an integer raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = " In %s hour(s), it will be %s. " % (offset, dt) return HttpResponse(html) Here is the code from my urls.py file, this allows me to pass an integer but I want to limit this to 1- or 2- digit numbers only: path('date_and_time/plus/<int:offset>/', hours_ahead), I've tried path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead), but I get the Page not found (404) error. Thanks in advance!
answer count: 1
has answer: http://stackoverflow.com/a/48407901
type: Question
has title: Django 2.0 URL regular expressions
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48407901
type: AnsweredQuestion
tagged with: django-2.0

http://stackoverflow.com/q/48477809
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/48477888
type: Question
score: 0
answer count: 2
tagged with: macros
has answer: http://stackoverflow.com/a/48477888
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/13603215
has body: Context Hi all, i'm trying to split up my dataset into 180 unique pieces and then run it through a geocoder (my n is ~180,000 and the geocoder has a 1,000 batch limit). I'm pretty new to Python but some googling led me to shuffle within sklearn.utils. It seems to do the trick and this code here does what I want (conceptually): from sklearn.utils import shuffle df = shuffle(addresses) df1 = df[0:1000] df2 = df[1000:2000] df3 = df[2000:3000] However, I obviously don't want to sit down and manually construct 180 dataframes like this so am looking for a way to put it in a loop. This is my basic idea: start = 0 end = 1000 for a in range(1,180): print(start, end, a) start = start+1000 end = end+1000 The above works fine. Code that doesn't work However when I try and integrate the actual splitting into the loop (not just printing) it fails. I'm pretty sure the issue is in how i'm calling the macro a when i'm naming the dataframes. I have no idea how to solve this though. from sklearn.utils import shuffle df = shuffle(addresses) start = 0 end = 1000 for a in range(1,180): df_str(a) = df[start:end] start = start+1000 end = end+1000
accepted answer: http://stackoverflow.com/a/64908429
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64908429
has title: Splitting up a dataframe into N pieces
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48348781
score: 0
answer count: 2
has body: I read i text file line by line and want to find out if a line ends on a specifik word. My code looks lika this, but result always get false #!/usr/bin/env python # -*- coding: utf-8 -*- import os import wget with open("data.txt","r") as f: text = f.readlines() for line in text: print line result = line.endswith("jpg") print(result) And the text file like this: file1.jpg file2.jpg file3.png file4.html
has title: Read a text file and find if a line end on a specific word?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21667511
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/21667511
tagged with: python
duplicate of: http://stackoverflow.com/q/3925641
duplicate of: http://stackoverflow.com/q/41906598
has comment: http://stackoverflow.com/comment/83683890
has answer: http://stackoverflow.com/a/48348870
has answer: http://stackoverflow.com/a/48348857

http://stackoverflow.com/q/48365001
has answer: http://stackoverflow.com/a/48365074
tagged with: return
has comment: http://stackoverflow.com/comment/83716636
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83716971
score: 0
has comment: http://stackoverflow.com/comment/83722865
answer count: 2
tagged with: introspection
has comment: http://stackoverflow.com/comment/83716622
has comment: http://stackoverflow.com/comment/83716640
upvote count: 3
has answer: http://stackoverflow.com/a/48366253
has title: Get return elements of a function
downvote count: 3
has body: Is there a way to introspect the variable names returned by a function? Eg. def foo(): x = 10 y = 20 return x,y I am looking for a way to see the return variable names "x" and "y". Is there a clean way to do this?
has comment: http://stackoverflow.com/comment/83716601
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/83717363
has text: thanks so much! Also, can someone explain to me why it returns `None`? is it just a tkinter thing or is there an actual reason behind it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48359399
type: AnswerComment

http://stackoverflow.com/a/48490038
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48470529
answers question: http://stackoverflow.com/q/48470529
score: 1
type: Answer
has body: When you get a message saying that part of a package is missing the first thing to do is to try adding the name of the missing package. You may get further errors which say that further modules are missing but just include those as well. You can do this by simply adding the name of the package in the packages option. Like this: from cx_Freeze import setup, Executable base = None executables = [Executable("borzacommercial.py", base=base)] packages = ["idna", "_cffi_backend"] options = { 'build_exe': { 'packages':packages, }, } setup( name = "&lt;any name&gt;", options = options, version = "&lt;any number&gt;", description = '&lt;any description&gt;', executables = executables )

http://stackoverflow.com/a/48360753
type: AcceptedAnswer
has body: def identify_cycles(l1, l2): d1 = {val: idx for idx, val in enumerate(l1)} # This assumes unique values in input l1, but I think the question does too out = [] for idx, val in enumerate(l1): curr = l2[idx] if curr == val or any(val in s for s in out): continue # If this value doesn't move, or we've seen this cycle, then skip x = set([val]) # Otherwise, we're at the start of a new cycle while curr != val: x.add(curr) # The value at this index in l2 is also in this cycle curr = l2[d1[curr]] # The next value in the cycle will be in l2 at the index that curr is at in l1 out.append(x) return out print(identify_cycles(lista, output)) # [{8, 6, 7}, {9, 10, 11}, {12, 13, 14}, {16, 17, 15}, {18, 19, 20}] I believe the above should be able to identify cycles of any length > 1.
accepted answer of: http://stackoverflow.com/q/48360390
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48360390

http://stackoverflow.com/comment/83701517
has text: Care to explain why the downvotes?
type: Comment
comment on: http://stackoverflow.com/q/48350948
score: 0
type: QuestionComment

http://stackoverflow.com/q/48447250
has comment: http://stackoverflow.com/comment/83892285
favorite count: 0
type: Question
type: UnansweredQuestion
has title: ValueError: Error when checking target: expected dense_17 to have shape (None, 1) but got array with shape (8, 4800000)
has comment: http://stackoverflow.com/comment/83892174
has comment: http://stackoverflow.com/comment/83895569
has comment: http://stackoverflow.com/comment/83889806
tagged with: python
has body: Hi everyone I must implement a cnn + lstm model and I've this error: ValueError: Error when checking target: expected dense_17 to have shape (None, 1) but got array with shape (8, 4800000) this is my code with: X_train.shape = (8, 4800000, 1) y_train_arousal.shape=(8, 4800000). X_train are 8 audio tracks, 4800000 are the samples and 1 channel y_train_arousal: for each audio track and for each sample correspond to an arousal value. So my model reads sequentially the samples and for each sample produces 1 value, I must evaluate the variance between the output value vary with the sample model_arousal = Sequential() model_arousal.add(Conv1D(filters=40, kernel_size=40, strides=2, activation='tanh', input_shape=(4800000, 1))) model_arousal.add(MaxPooling1D(pool_size=2)) model_arousal.add(Dropout(0.5)) model_arousal.add(Conv1D(filters=40, kernel_size=400, strides=2, activation='tanh')) model_arousal.add(MaxPooling1D(pool_size=20)) model_arousal.add(Dropout(0.5)) model_arousal.add(LSTM(128, activation='tanh', return_sequences=True)) model_arousal.add(LSTM(128, activation='tanh', return_sequences=True)) model_arousal.add(Flatten()) model_arousal.add(Dense(2)) adam = Adam(0.002) model_arousal.compile(loss='mse', optimizer=adam, metrics=['accuracy']) model_arousal.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv1d_47 (Conv1D) (None, 2399981, 40) 1640 _________________________________________________________________ max_pooling1d_42 (MaxPooling (None, 1199990, 40) 0 _________________________________________________________________ dropout_39 (Dropout) (None, 1199990, 40) 0 _________________________________________________________________ conv1d_48 (Conv1D) (None, 599796, 40) 640040 _________________________________________________________________ max_pooling1d_43 (MaxPooling (None, 29989, 40) 0 ______________________________________________________…
has comment: http://stackoverflow.com/comment/83889728
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83894332
upvote count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/83888778
tagged with: tensorflow

http://stackoverflow.com/q/48381870
tagged with: python
has comment: http://stackoverflow.com/comment/83750699
accepted answer: http://stackoverflow.com/a/48383804
has comment: http://stackoverflow.com/comment/83750459
has title: A better way to split a sequence in chunks with overlaps?
answer count: 4
has answer: http://stackoverflow.com/a/48383804
has comment: http://stackoverflow.com/comment/83750807
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/83750609
has comment: http://stackoverflow.com/comment/83750513
tagged with: overlap
has body: I need a function to split an iterable into chunks with the option of having an overlap between the chunks. I wrote the following code, which gives me the correct output but that is quite inefficient (slow). I can't figure out how to speed it up. Is there a better method? def split_overlap(seq, size, overlap): '''(seq,int,int) =&gt; [[...],[...],...] Split a sequence into chunks of a specific size and overlap. Works also on strings! Examples: &gt;&gt;&gt; split_overlap(seq=list(range(10)),size=3,overlap=2) [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]] &gt;&gt;&gt; split_overlap(seq=range(10),size=3,overlap=2) [range(0, 3), range(1, 4), range(2, 5), range(3, 6), range(4, 7), range(5, 8), range(6, 9), range(7, 10)] &gt;&gt;&gt; split_overlap(seq=list(range(10)),size=7,overlap=2) [[0, 1, 2, 3, 4, 5, 6], [5, 6, 7, 8, 9]] ''' if size &lt; 1 or overlap &lt; 0: raise ValueError('"size" must be an integer with &gt;= 1 while "overlap" must be &gt;= 0') result = [] while True: if len(seq) &lt;= size: result.append(seq) return result else: result.append(seq[:size]) seq = seq[size-overlap:] Testing results so far: l = list(range(10)) s = 4 o = 2 print(split_overlap(l,s,o)) print(list(split_overlap_jdehesa(l,s,o))) print(list(nwise_overlap(l,s,o))) print(list(split_overlap_Moinuddin(l,s,o))) print(list(gen_split_overlap(l,s,o))) print(list(itr_split_overlap(l,s,o))) [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [6, 7, 8, 9]] [(0, 1, 2, 3), (2, 3, 4, 5), (4, 5, 6, 7), (6, 7, 8, 9)] [(0, 1, 2, 3), (2, 3, 4, 5), (4, 5, 6, 7), (6, 7, 8, 9), (8, 9, None, None)] #wrong [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [6, 7, 8, 9], [8, 9]] #wrong [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [6, 7, 8, 9]] [(0, 1, 2, 3), (2, 3, 4, 5), (4, 5, 6, 7), (6, 7, 8, 9)] %%timeit split_overlap(l,7,2) 718 ns ± 2.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %%timeit list(split_overlap_jdehesa(l,7,2)) 4.02 µs ± 64.7 ns per loop (mean ± std. dev. of …
has comment: http://stackoverflow.com/comment/83752794
has answer: http://stackoverflow.com/a/48382376
possible better answer: http://stackoverflow.com/a/48382467
has comment: http://stackoverflow.com/comment/83750432
has comment: http://stackoverflow.com/comment/83754939
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/83754986
has comment: http://stackoverflow.com/comment/83752647
has comment: http://stackoverflow.com/comment/83753946
favorite count: 0
has answer: http://stackoverflow.com/a/48382467
has comment: http://stackoverflow.com/comment/83753706
has comment: http://stackoverflow.com/comment/83752711
has answer: http://stackoverflow.com/a/48382314
has comment: http://stackoverflow.com/comment/83750535
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83750695
has comment: http://stackoverflow.com/comment/83750392
has comment: http://stackoverflow.com/comment/83750672
has comment: http://stackoverflow.com/comment/83750495
has comment: http://stackoverflow.com/comment/83753585
has comment: http://stackoverflow.com/comment/83750519
has comment: http://stackoverflow.com/comment/83750358
upvote count: 5
has comment: http://stackoverflow.com/comment/83753652
has comment: http://stackoverflow.com/comment/83754128
has comment: http://stackoverflow.com/comment/83750681

http://stackoverflow.com/a/56408968
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/99495829
type: Answer
answers question: http://stackoverflow.com/q/48336820
has body: I was recently looking for something similar and here's what I came up with. It works by intercepting the __setattr__ method -- a useful stunt I plan on keeping in my pocket for later. def watchableClass(cls): """ Class Decorator! * If the class has a "dirty" member variable, then it will be automatically set whenever any class value changes * If the class has an "onChanged()" method, it will be called automatically whenever any class value changes * All this only takes place if the value is different from what it was that is, if myObject.x is already 10 and you set myObject.x=10 nothing happens * DOES NOT work with getter/setter functions. But then, you are already in a function, so do what you want! EXAMPLE: @watchableClass class MyClass: def __init__(self): self.dirty=False def onChanged(self): print('class has changed') """ if hasattr(cls,'__setattr__'): cls.__setattr_unwatched__=cls.__setattr__ cls.__setattr__=_setObjValueWatchedCascade else: cls.__setattr__=_setObjValueWatched return cls def _setObjValueWatched(ob,k,v): """ called when an object value is set """ different=not k in ob.__dict__ or ob.__dict__[k]!=v if different: ob.__dict__[k]=v if k not in ('dirty'): if hasattr(ob,'dirty'): ob.dirty=True if hasattr(ob,'onChanged'): ob.onChanged() def _setObjValueWatchedCascade(ob,k,v): """ called when an object value is set IF the class had its own __setattr__ member defined! """ different=not k in ob.__dict__ or ob.__dict__[k]!=v ob.__setattr_unwatched__(k,v) if different: if k not in ('dirty'): if hasattr(ob,'dirty'): ob.dirty=True if hasattr(ob,'onChanged'): ob.onChanged()

http://stackoverflow.com/q/48340411
answer count: 1
has title: How to create Django Model with Many-To-Many Parents-Children Relationship?
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48341022
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I already know, that I can achieve ForeignKey Parent-Children relationship within the same model, that allows to create relations with 1 parent = multiple children. But how can I accomplish Many-To-Many relationship within the same model ? At this moment I wrote and tested this: class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) parents = models.ManyToManyField( 'self', blank=True ) And it works, but not as I expected. What it does is: john = Person.objects.get(id=1) sam = Person.objects.get(id=2) &gt;&gt;&gt; john.parents.all() &lt;QuerySet [&lt;Person: Alex&gt;, &lt;Person: Peter&gt;, &lt;Person: Sam&gt;]&gt; &gt;&gt;&gt; sam.parents.all() &lt;QuerySet [&lt;Person: John&gt;]&gt; As you can see, Sam was supposed to be child of John, not his child and parent at the same time. What I want is to get John when I'm retrieving sam.parents.all() But not to get Sam when I'm retrieving john.parents.all() Is there a way to accomplish what I want ? Or that's not gonna work with this logic at least ? Do I have to create second separate model withing the same app ?
tagged with: relationship
score: 1
has answer: http://stackoverflow.com/a/48341022

http://stackoverflow.com/q/48420005
tagged with: python
tagged with: keras
tagged with: lstm
linked to: http://stackoverflow.com/q/47618285
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/84278154
score: 1
accepted answer: http://stackoverflow.com/a/48605766
has comment: http://stackoverflow.com/comment/84263385
has title: Predict a variable that is not in the input sequences with LSTM-Keras
has comment: http://stackoverflow.com/comment/84061437
has comment: http://stackoverflow.com/comment/84274248
downvote count: 1
has body: Assume that I have five columns in my dataset (A,B,C,D,E) and I want to build an LSTM model by training just on A,B,D,E (i.e. I want to exclude C) My problem is that I still want to use this model to predict C. Is it possible if I didn't train my model with this variable? How can I do that? EDIT 1 I'm working with categorical and numerical data modeled as time series. In this specific case, C is a categorical time series (given in a one-hot representation).
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84281994
has comment: http://stackoverflow.com/comment/84260399
has comment: http://stackoverflow.com/comment/84255777
upvote count: 2
has answer: http://stackoverflow.com/a/48605766
has answer: http://stackoverflow.com/a/48532682
possible better answer: http://stackoverflow.com/a/48532682

http://stackoverflow.com/q/48355747
answer count: 4
tagged with: hmmlearn
has comment: http://stackoverflow.com/comment/83698209
has comment: http://stackoverflow.com/comment/83698263
downvote count: 0
has body: I'm new to hmmlearn and am trying to use the Jupyter Notebook to work through this Gaussian HMM of stock data example. However, when I run the following code, I get an error. from __future__ import print_function import datetime import numpy as np from matplotlib import cm, pyplot as plt from matplotlib.dates import YearLocator, MonthLocator try: from matplotlib.finance import quotes_historical_yahoo_ochl except ImportError: # For Matplotlib prior to 1.5. from matplotlib.finance import ( quotes_historical_yahoo as quotes_historical_yahoo_ochl ) from hmmlearn.hmm import GaussianHMM print(__doc__) The error is as follows: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-2-02bbde14d4d4&gt; in &lt;module&gt;() 14 ) 15 ---&gt; 16 from hmmlearn.hmm import GaussianHMM 17 18 ModuleNotFoundError: No module named 'hmmlearn' I have spent a while searching the Internet and trying to find out why this is happening. I've ensured that I've downloaded the dependencies (scikit-learn, numpy and scipy), and I've run pip install -U --user hmmlearn, both via the Windows cmd and as mentioned here. However, I keep getting the same error. I'm not sure if it may be something to do with the location of the different packages on my computer (I'm using Windows). Does anyone have suggestions on what I could try to solve this? (My main aim is just to be able to get set up with hmmlearn so that I can start using it to explore HMMs.)
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78066242
has comment: http://stackoverflow.com/comment/83698225
favorite count: 0
score: 4
has title: How to resolve No module named 'hmmlearn' error in Jupyter Notebook
has answer: http://stackoverflow.com/a/78509982
has comment: http://stackoverflow.com/comment/83715419
type: Question
has answer: http://stackoverflow.com/a/74505719
has comment: http://stackoverflow.com/comment/83706096
tagged with: jupyter-notebook
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/85663104
has answer: http://stackoverflow.com/a/55229751
has comment: http://stackoverflow.com/comment/83704223

http://stackoverflow.com/q/48475118
tagged with: if-statement
tagged with: python
type: AnsweredQuestion
score: 0
has body: Let's consider two ways to check for all conditions to be true Option 1 if all([cond1, cond2, cond3]): return true Option 2 if (cond1 and cond2 and cond3): return true Do both evaluate the same way? AFAIR that all will fail as soon as one statement fails, making it possible, that a condition can presume that all previously listed conditions evaluated to true. E.g. making it safe in Option 1 to access a variable in cond3, that was previously (in cond1 or cond2) tested to be accessible. Does that hold true also for Option 2? Also, are there performance differences?
has answer: http://stackoverflow.com/a/48475165
has comment: http://stackoverflow.com/comment/83943684
answer count: 1
has comment: http://stackoverflow.com/comment/83944162
has title: Python: Evaluation of all/any vs spelling them out
type: Question
tagged with: logic
accepted answer: http://stackoverflow.com/a/48475165
tagged with: performance

http://stackoverflow.com/q/48461151
has comment: http://stackoverflow.com/comment/83915116
downvote count: 0
has answer: http://stackoverflow.com/a/48463070
answer count: 1
has title: ConcatOp : Dimensions of inputs should match: shape[0] = [1363,300] vs. shape[1] = [128,128]
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: So it seems I'm doing something wrong here and I would appreciate some help. When I input my validation set into the network, the dimensions are not the same as the ones used for training. I would've expected "shape[0] = [1363,300] vs. shape[1] = [128,300]" since my dimension for the word embedding is 300. def make_cell(): cell = tf.contrib.rnn.BasicLSTMCell(lstmUnits) if dropout_rate.eval(session=tf.Session()) == 1: cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=dropout_rate) return cell labels = tf.placeholder(tf.float32, [None, numClasses]) input_data = tf.placeholder(tf.int32, [None, maxSeqLength]) dropout_rate = tf.placeholder_with_default(1.0, shape=()) rnn_input = tf.Variable(tf.zeros([batchSize, maxSeqLength, numDimensions]), dtype=tf.float32) rnn_input = tf.nn.embedding_lookup(vectors_fasttext, input_data) # fastext lookup multiLSTMCell = tf.contrib.rnn.MultiRNNCell([make_cell() for _ in range(num_layers)], state_is_tuple=True) init_state = state = multiLSTMCell.zero_state(batchSize, tf.float32) rnn_output, _ = tf.nn.dynamic_rnn(multiLSTMCell, rnn_input, initial_state=init_state, dtype=tf.float32) # training for i in range(iterations): nextBatch, nextBatchLabels = getBatch(train_ids, train_labels) _, batch_loss = sess.run([optimizer, loss], feed_dict={input_data: nextBatch, labels: nextBatchLabels, dropout_rate: 0.5}) if (i % 500 == 0 and i != 0): acc, prec, rec, f1 = sess.run([accuracy, pre_op, rec_op, f1_op], feed_dict={input_data: validation_data, labels: validation_data_labels}) print(validation_data_labels.shape) print(validation_data.shape) (1363, 2) (1363, 20) And I'm getting this error: InvalidArgumentError Traceback (most recent call last) c:\users\tony\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1322 try: -&gt; 1323 return fn(*args) 1324 except errors.OpError as e: c:\users\tony\appdata\local\programs\python\python36\lib\site-packages\tensorflow\python\clien…
score: 2
upvote count: 2

http://stackoverflow.com/q/48483514
type: Question
has title: Django server close on closing browser tab
score: 1
has comment: http://stackoverflow.com/comment/85385175
has comment: http://stackoverflow.com/comment/83960249
tagged with: python
tagged with: python-3.x
has body: I want to close the django server (CMD) when closing browser tab. After some hours of research, I tried the codes below. I added onbeforeunload javascript inside my header template so that every page that contains my web app will have that event handler. {% block js %} &lt;script&gt; //close ui on tab click window.onbeforeunload = function(){ $.ajax({ // Ajax call type: "POST", url: "closeui", success: function(k){ alert('Good bye'); return false; }); return "Do you really want to close?"; }; &lt;/script&gt; {% endblock js %} For routing, I added URL as closeui. In views, I created a closeui function which will perform closing the CMD. def closeui(): import os from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'): print("Killing PID:", p.Properties_('ProcessId').Value) os.system("taskkill /pid "+str(p.Properties_('ProcessId').Value)) return True I didn't get my desired results. Can someone correct me where I went wrong?
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: javascript
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83921898
type: AnswerComment
has text: The string has all numbers only. I just need to find if it has all the numbers 0,1,2,3,4,5,6,7,8,9 somewhere or the other in the string.
type: Comment
comment on: http://stackoverflow.com/a/48464239
score: 0

http://stackoverflow.com/comment/137805620
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52919794
has text: I have `df_augmented['date_of_birth'] = pd.to_datetime(df_augmented.date_of_birth, format='mixed')` working, but not `df_augmented.loc[:, 'date_of_birth'] = pd.to_datetime(df_augmented.date_of_birth, format='mixed')` - the latter gives an Object column, the former a datetime64[ns]; why? are there differences between df['col'] and df[:, 'col'] in this case?
type: Comment

http://stackoverflow.com/comment/83911632
type: Comment
type: QuestionComment
has text: Sorry for the awful formatting.
comment on: http://stackoverflow.com/q/48459357
score: 0

http://stackoverflow.com/comment/83860540
has text: Can you check the effect of processor affinity on the receiving end? This would be the taskset command, basically pinning the server process to a specific cpu/core. Here is an excerpt from the man page which may be relevant: the scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. Therefore, forcing a specific CPU affinity is useful only in certain applications.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48433985
type: QuestionComment

http://stackoverflow.com/q/48359259
has comment: http://stackoverflow.com/comment/83706030
has comment: http://stackoverflow.com/comment/83705508
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has title: How to merge pandas dataframe and filter duplicate content in different column?
has comment: http://stackoverflow.com/comment/83706316
accepted answer: http://stackoverflow.com/a/48359495
tagged with: python
has answer: http://stackoverflow.com/a/48359495
type: AnsweredQuestion
score: 3
has body: I'm currently learning pandas in python 2.7. I'm learning merge() method in pandas. Here is my code to create dataframe: import pandas as pd eibi = {'A': ['aaa','bbb','ccc','eee','fff'], 'B': ['bbb','aaa','ccc','fff','eee'] } df = pd.DataFrame(eibi) print df and the ouput is: A B 0 aaa bbb 1 bbb aaa 2 ccc ddd 3 eee fff 4 fff eee I want to merge the dataframe by the row in the dataframe itself. The goal is if the cell in column B match with the cell in column A, move that cell to column C and D. I hope the dataframe below will make it clear about my expected dataframe. A B C D 0 aaa bbb bbb aaa 2 ccc ddd 3 eee fff fff eee I was trying to duplicate df dataframe then merge it using merge() method and using left merge. Here is my code: fd = df new_dataframe = pd.merge(left=df, right=fd, left_on='A', right_on='B', how='left') print new_dataframe and the output is: A_x B_x A_y B_y 0 aaa bbb bbb aaa 1 bbb aaa aaa bbb 2 ccc ddd 3 eee fff fff eee 4 fff eee eee fff My question is "How to remove index 1 and 4?" and "Is there the other way to get the expected result?"
has comment: http://stackoverflow.com/comment/83705526
tagged with: pandas
upvote count: 3

http://stackoverflow.com/a/48490085
upvote count: 1
downvote count: 1
type: Answer
has body: You can convert the units of time from seconds since 1996-07-30 00:00:00 to calendar dates using netCDF num2date. import netCDF4 ncfile = netCDF4.Dataset('file.nc', 'r') time = ncfile.variables['time'] #don't cast to numpy array yet time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
has comment: http://stackoverflow.com/comment/84021814
accepted answer of: http://stackoverflow.com/q/48486461
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48486461

http://stackoverflow.com/q/48480751
has answer: http://stackoverflow.com/a/48480883
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has title: Round an activation function in Keras
has body: I am trying to create an activation function to use in my keras model. Basically, what I want is an sigmoid function that has only two decimal places. So I was trying to create my own activation function like this: def mySigmoid(x): return np.around(K.sigmoid(x), decimals=2) and then: get_custom_objects().update({'mySigmoid': Activation(mySigmoid)}) but for some reason I get erros doing that. Can someone please help me? Thanks a lot Stack trace: AttributeError Traceback (most recent call last) &lt;ipython-input-52-891a9f63ca56&gt; in &lt;module&gt;() 3 model.add(Dense(30, activation='softmax')) 4 ----&gt; 5 model.add(Dense(10, activation='mySigmoid')) 6 model.summary() 7 sgd = optimizers.SGD(lr=0.1, decay=1e-5, momentum=0.3, nesterov=True) /usr/local/lib/python2.7/dist-packages/keras/models.pyc in add(self, layer) 473 output_shapes=[self.outputs[0]._keras_shape]) 474 else: --&gt; 475 output_tensor = layer(self.outputs[0]) 476 if isinstance(output_tensor, list): 477 raise TypeError('All layers in a Sequential model ' /usr/local/lib/python2.7/dist-packages/keras/engine/topology.pyc in __call__(self, inputs, **kwargs) 600 601 # Actually call the layer, collecting output(s), mask(s), and shape(s). --&gt; 602 output = self.call(inputs, **kwargs) 603 output_mask = self.compute_mask(inputs, previous_mask) 604 /usr/local/lib/python2.7/dist-packages/keras/layers/core.pyc in call(self, inputs) 843 output = K.bias_add(output, self.bias) 844 if self.activation is not None: --&gt; 845 output = self.activation(output) 846 return output 847 /usr/local/lib/python2.7/dist-packages/keras/engine/topology.pyc in __call__(self, inputs, **kwargs) 600 601 # Actually call the layer, collecting output(s), mask(s), and shape(s). --&gt; 602 output = self.call(inputs, **kwargs) 603 output_mask = self.compute_mask(inputs, previous_mask) 604 /usr/local/lib/python2.7/dist-packages/keras/layers/core.pyc in call(self, inputs) 284 285 def call(self, inputs): --&gt; 286 return self.activation(inputs)…
downvote count: 0
answer count: 1
tagged with: activation-function
has comment: http://stackoverflow.com/comment/83955034
tagged with: keras
has comment: http://stackoverflow.com/comment/83954831
favorite count: 0
type: Question
score: 5
upvote count: 5

http://stackoverflow.com/comment/83686097
comment on: http://stackoverflow.com/q/48349812
type: Comment
score: 0
type: QuestionComment
has text: I don't know UnholySheep

http://stackoverflow.com/comment/83891787
type: AnswerComment
has text: Ahhh! Thanks a lot. Appreciate it.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48449404

http://stackoverflow.com/comment/83711531
has text: I'm not sure concurrency will improve this. Try changing the algorithm first. What about keeping all the file B strings in memory (read one time) and reverse the loops?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48360729

http://stackoverflow.com/a/48373820
has body: I find a temporary solution via the implemented tfrecordio.py. The code below is working. But I am still open to any comment that could solve the above problem. import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions import phone_pb2 def WriteTextToTFRecord(): class ToProtoFn(beam.DoFn): def process(self, element): phone = phone_pb2.PhoneNumber() phone.number, phone.country = element.strip().split(',') yield phone with beam.Pipeline(options=PipelineOptions()) as p: lines = p | beam.Create(["123-456-789,us", "345-567-789,ca"]) processed = ( lines | beam.ParDo(ToProtoFn()) | beam.io.WriteToTFRecord('/Users/greeness/data/phone-pb', coder=beam.coders.ProtoCoder(phone_pb2.PhoneNumber().__class__))) def ReadTFRecordAndSaveAsCSV(): class ToCsvFn(beam.DoFn): def process(self, element): yield ','.join([element.number, element.country]) with beam.Pipeline(options=PipelineOptions()) as p: lines = (p | beam.io.ReadFromTFRecord('/Users/greeness/data/phone-pb-*', coder=beam.coders.ProtoCoder(phone_pb2.PhoneNumber().__class__)) | beam.ParDo(ToCsvFn()) | beam.io.WriteToText('/Users/greeness/data/phone-csv')) if __name__ == '__main__': WriteTextToTFRecord() ReadTFRecordAndSaveAsCSV()
downvote count: 0
answers question: http://stackoverflow.com/q/48373131
upvote count: 5
score: 5
type: Answer

http://stackoverflow.com/comment/83711668
has text: a Minimal example would just start with the cubic parameters, we don't need the fitting process if your problem is where you believe
type: QuestionComment
comment on: http://stackoverflow.com/q/48362180
score: 0
type: Comment

sanic
tags question: http://stackoverflow.com/q/48339838
tag name: sanic
tags question: http://stackoverflow.com/q/48487032
tags question: http://stackoverflow.com/q/48355353
type: Tag
tags question: http://stackoverflow.com/q/48358297

http://stackoverflow.com/q/48416570
favorite count: 0
has comment: http://stackoverflow.com/comment/83823295
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48417487
has body: Hello I want to get the file id from files on windows with python. When I searched I could only find how to do it in other languages. Does anybody know how I can achieve this in python?
has comment: http://stackoverflow.com/comment/83830106
has comment: http://stackoverflow.com/comment/83850079
tagged with: windows
has comment: http://stackoverflow.com/comment/83823208
has title: Get file id in windows with python?
tagged with: python
has comment: http://stackoverflow.com/comment/83822760
has comment: http://stackoverflow.com/comment/83829118
linked to: http://stackoverflow.com/q/237079
has comment: http://stackoverflow.com/comment/83834752
type: Question
has comment: http://stackoverflow.com/comment/83829750
score: 0
has answer: http://stackoverflow.com/a/48417487
answer count: 2
has comment: http://stackoverflow.com/comment/83839703
has comment: http://stackoverflow.com/comment/83822991
has comment: http://stackoverflow.com/comment/83828822
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/83823610
downvote count: 1
has answer: http://stackoverflow.com/a/63688219
possible better answer: http://stackoverflow.com/a/63688219

http://stackoverflow.com/comment/83834610
has text: may i ask what shoud be the return @VivekKumar
score: 0
comment on: http://stackoverflow.com/q/48422569
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48471955
score: 2
type: AnsweredQuestion
tagged with: sympy
upvote count: 2
has comment: http://stackoverflow.com/comment/83981448
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/48466845
has answer: http://stackoverflow.com/a/48472035
has body: I have the following Sympy expression expr=b0*d0*u0 - b0*d1*u1 - b1*d0*u1 - b1*d1*u0 + d0*b0*u0 - d0*b1*u1 - d1*b0*u1 - d1*b1*u0 And I want to know if, for example, the product d0*u0 is in this expression. For this, I use print(expr.has(d0*u0)) but the result is False However, if I replace this subexpression without asking if it is in the expression, Sympy does it without any problem, e.g. print(expr.subs(d0*u0,x0)) b0*x0 - b0*d1*u1 - b1*d0*u1 - b1*d1*u0 + d0*b0*u0 - d0*b1*u1 - d1*b0*u1 - d1*b1*u0 So, how can I know if the subexpression I want to find is in the expression?
favorite count: 0
type: Question
has title: Test the presence of a subexpression involving noncommutative symbols
accepted answer: http://stackoverflow.com/a/48472035
has comment: http://stackoverflow.com/comment/83938054
tagged with: python
has comment: http://stackoverflow.com/comment/83938027

http://stackoverflow.com/comment/83808389
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48409128
has text: A decent explanation here https://stackoverflow.com/questions/38886080/python-pandas-series-why-use-loc

http://stackoverflow.com/a/48372180
upvote count: 1
answers question: http://stackoverflow.com/q/48370499
type: Answer
has body: as a simple idea the inserting of new msg in database should be with a condition to limit their numbers (the count of the previous msg isn't > max ) another method : you will show the input of the msg jsut when (selet * form table where userid=sesion and count(usermsg)&lt; max )
has comment: http://stackoverflow.com/comment/83770099
score: 1
downvote count: 0

http://stackoverflow.com/q/48452155
has comment: http://stackoverflow.com/comment/83954853
tagged with: click
has comment: http://stackoverflow.com/comment/83902236
has comment: http://stackoverflow.com/comment/83899091
has comment: http://stackoverflow.com/comment/83897855
tagged with: selenium
linked to: http://stackoverflow.com/q/5797014
favorite count: 0
type: Question
upvote count: 2
score: 2
has title: How to efficiently scrape many elements (reviews) on a single page with Selenium
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83901707
has body: I have been trying to scrape all the reviews available at a single url by repeatedly clicking on the button 'Show 6 more reviews'. I believe this problem would apply to anyone scrapping many dynamic elements at a single url with Selenium. Problem: when the number of reviews is more than a few hundreds, the loop becomes very slow. I am using Selenium since the website involves Javascript. HTML of button I am clicking (towards bottom of page) Show 6 more reviews Things I tried: not loading images: no improvement (not shown below) using most efficient selector possible in loop Things I thought of: Replacing Chrome with PhantomJS. I’m having issues scrolling with PhantomJS. I didn’t pursue as it seems the gains would be incremental, not orders of magnitude which I need (I could be wrong). Loading the reviews as they become available instead of when the whole page has been 'expanded'. I don’t think this would solve the performance problem finding a way to parse the button faster. I read about how browsers match CSS selectors but couldn't find a way to improve my code This is my first SO question. Thank you very much for your patience and help. Reproducible code in python 2 or 3 (the slow loop is at the bottom): 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 import time # Page with 5591 reviews url = "https://www.sephora.com/product/soy-face-cleanser-P7880?icid2=:p7880:product" driver = webdriver.Chrome() driver.get(url) time.sleep(4) # Navigation steps (feel free to skip) # scroll to section 'Similar Products' (above Reviews) timeout = 10 wait_driver = WebDriverWait(driver, timeout) section_title = wait_driver.until(EC.presence_of_element_located(\ (By.XPATH, '//h2[@class="css-1orm38z"]'))) driver.execute_script("arguments[0].scrollIntoView();", section_title) # Sort by newest review wait_driver.until(EC.presence_of_element_…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83897570
has comment: http://stackoverflow.com/comment/83992270
has comment: http://stackoverflow.com/comment/83899861
tagged with: python

http://stackoverflow.com/comment/83700474
type: Comment
type: QuestionComment
has text: Use `str(num)` to do a string comparison?
comment on: http://stackoverflow.com/q/48356973
score: 0

http://stackoverflow.com/comment/83653004
has text: I think your asking if you can do an inplace mapping if I'm not mistaken.
comment on: http://stackoverflow.com/q/48333445
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/83935125
score: 0
type: AnswerComment
has text: @BobHopez I had copied your code, so the initial soup.find_all()[0] only returns the first quote div. Remove the [0] and then loop over each div, and you should get them all.
type: Comment
comment on: http://stackoverflow.com/a/48448222

http://stackoverflow.com/a/54823222
type: Answer
accepted answer of: http://stackoverflow.com/q/48349025
answers question: http://stackoverflow.com/q/48349025
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: function uploadWithAjax() { var files = $('#images').prop("files"); if(files.length &gt; 0) { $.ajax({ type: "POST", url: "/UploadImages/", data: {"images": files} success: function(result) { alert('IMAGES UPLOADED'); } }); } } And there, you just passed a list of image files.

http://stackoverflow.com/a/48357267
type: Answer
answers question: http://stackoverflow.com/q/48353671
has comment: http://stackoverflow.com/comment/83705606
accepted answer of: http://stackoverflow.com/q/48353671
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The FFT of a real-valued signal yields a spectrum with Hermitian symmetry. That means that the upper half of the spectrum can be obtained from the lower half. Also, when the FFT size N is even, the mid point is its own symmetry. As a result the spectrum is fully determined by N//2 + 1 frequency point (which is the size of spectrum returned by scipy.signal.stft). In your case N is 4096, so you get a spectrum of 4096//2 + 1 or 2049 points along the frequency axis. You should be able to confirm that f is indeed an array of 2049 frequency values (from 0 to 44100/2 Hz in 44100/4096 or ~10.77Hz increments). As far at the number of time values is concerned you can compute it as number_of_samples = 169600 number_time_values = (number_of_samples+window_size)//(window_size - window_size//2) % = (169600 + 4096)//(4096 - 2048) % = 84 The +window_size (+4096 in your case) term in the numerator is due to the boundary = 'zeros' default option which pads the input with zeros before and after your actual 169,600 input samples.
score: 2

http://stackoverflow.com/q/48454455
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/83902650
has comment: http://stackoverflow.com/comment/83903192
tagged with: loss
has title: How to compute custom loss for tensorflow using numpy/sklearn based on the predictions
tagged with: python
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83902750
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has body: I'me facing an issue to combine numpy with tensorflow. For instance, I want to create a custom loss function and use it for the training. let loss function be loss = tf.reduce_mean(C * tf.nn.softmax_cross_entropy_with_logits(logits=self.y_logits, labels=self.y10)) where C is some value computed based on the following code: def C(logits, y_true, kmeans): # kmeans is sklearn model yp = tf.nn.softmax(logits) yp_cont = tf.reduce_sum(yp*kmeans.cluster_centers_.flatten(),axis=1) yp_discreat = kmeans.predict(yp_cont) ## this is where I'm having the problem ### the rest of the code ### The problem is that I can't use a tensor variable with kmeans sklearn model. Is there some work around to overcome this issue?
tagged with: scikit-learn

http://stackoverflow.com/q/48336937
has comment: http://stackoverflow.com/comment/83659020
has body: I have the following dataframes which has ORDER_ID as the common column. I have to match EMP_ID for each ORDER_ID in df2. The same EMP_ID can be matched for several Orders. DF: ORDER_ID TYPE EMP_ID 0 23991 A 9233 1 31106 A 2457 2 30062 A 2457 3 30062 A 1234 DF2: ORDER_ID O_INFO YEAR PRICE 0 23991 OK 2011 100 1 31106 OK 2000 200 2 30062 OK 2000 300 OUTPUT SHOULD BE: As one order will be attended by many employees, I would want to group and map all the employees who attended that order ORDER_ID O_INFO YEAR PRICE EMP_ID 0 23991 OK 2011 100 9233 1 31106 OK 2000 200 2457 2 30062 OK 2000 300 2457,1234 I tried the map function as below: df = df.set_index(‘ORDER_ID’) df2 ['EMP'] = df2[‘ORDER_ID’].map(df[‘EMP_ID']) I get the error: because values in the ORDER_ID are not unique to be set as index. But map function does not work without setting indexes. It returns NaN values without setting index. InvalidIndexError: Reindexing only valid with uniquely valued Index objects Performing merge does not map the EMP_ID for the ORDER but returns Nan values again df.merge(df2, on='ORDER_ID', how='left')
downvote count: 0
upvote count: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83659332
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83660175
has comment: http://stackoverflow.com/comment/83659345
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/48338921
accepted answer: http://stackoverflow.com/a/48338921
answer count: 1
has comment: http://stackoverflow.com/comment/83660115
favorite count: 0
has title: Pandas: Set index of column before map operation which has duplicate values
type: Question
has comment: http://stackoverflow.com/comment/83659082
has comment: http://stackoverflow.com/comment/83659210

amazon-ec2
tags question: http://stackoverflow.com/q/48363510
type: Tag
tags question: http://stackoverflow.com/q/48483612
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/48467575
tags question: http://stackoverflow.com/q/48415441
tags question: http://stackoverflow.com/q/48459764
tags question: http://stackoverflow.com/q/48335721
tags question: http://stackoverflow.com/q/48392109

http://stackoverflow.com/q/48386929
linked to: http://stackoverflow.com/q/43301262
score: 1
tagged with: kubernetes
tagged with: python
downvote count: 0
answer count: 0
has title: Tensorflow Kubernetes Integration Tutorial fails on Ubuntu Xenial
upvote count: 1
type: UnansweredQuestion
has body: I am following the "Serving Inception Model with TensorFlow Serving and Kubernetes" tutorial from the tensorflow.org website. When I get to loading and exporting the model using root@ecf82ac60c6b:/serving# bazel-bin/tensorflow_serving/example/inception_saved_model --checkpoint_dir=inception-v3 --output_dir=/tmp/inception-export I get following error. Traceback (most recent call last): File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/tf_serving/tensorflow_serving/example/inception_saved_model.py", line 202, in &lt;module&gt; tf.app.run() File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/org_tensorflow/tensorflow/python/platform/app.py", line 124, in run _sys.exit(main(argv)) File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/tf_serving/tensorflow_serving/example/inception_saved_model.py", line 198, in main export() File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/tf_serving/tensorflow_serving/example/inception_saved_model.py", line 91, in export table = tf.contrib.lookup.index_to_string_table_from_tensor(class_tensor) File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/org_tensorflow/tensorflow/python/util/lazy_loader.py", line 53, in __getattr__ module = self._load() File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/org_tensorflow/tensorflow/python/util/lazy_loader.py", line 42, in _load module = importlib.import_module(self.__name__) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/org_tensorflow/tensorflow/contrib/__init__.py", line 82, in &lt;module&gt; from tensorflow.contrib.eager.python import tfe as eager File "/serving/bazel-bin/tensorflow_serving/example/inception_saved_model.runfiles/org_tensorflow/tensorflow/contrib/eager/python/tfe.py", …
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/83822312
comment on: http://stackoverflow.com/q/48416289
type: Comment
type: QuestionComment
has text: @VikasDamodar without django can i do only in python ?
score: 0

http://stackoverflow.com/a/48347037
type: Answer
has body: Wouldn't a better way be to just use modulus. &gt;&gt;&gt; x = 2885 &gt;&gt;&gt; y = 1440 &gt;&gt;&gt; x%y 5 &gt;&gt;&gt; Or still using loops &gt;&gt;&gt; x = 2885 &gt;&gt;&gt; y = 1440 &gt;&gt;&gt; while x &gt;= y : ... x = x - y ... &gt;&gt;&gt; x 5 &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/48347002
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83681911
has comment: http://stackoverflow.com/comment/83682265
accepted answer of: http://stackoverflow.com/q/48347002
upvote count: 5

http://stackoverflow.com/a/48489449
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48486082
has body: You did misunderstand the paper. They retrieve the phase using only magnitude information, which is different from applying the IDFT using only magnitude information. Your FinalMagImg is not empty, it has a peak at the top-left corner. Apply fftshift to move it to the center, and apply logarithmic mapping to see the rest of the data. This is what an inverse DFT looks like if the phase is all zero.
accepted answer of: http://stackoverflow.com/q/48486082
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84270527
type: Comment
has text: I said to **add** it not replace it. Now the question has no mention about the previous error. And it will most likely be deleted. the best thing to do is revert the last edit and ask another question. And try to follow the basic ground rules (like posting the minimal code that reproduces the behavior in the question, not as a link - which may go bad).
type: AnswerComment
comment on: http://stackoverflow.com/a/48544185
score: 0

http://stackoverflow.com/comment/83968788
score: 0
has text: I am a newbie still learning, but I do have a data set where I have multiple y-data set (like y above) with shared single x-axis. To plot all together, I'd like to create [x,y1,x,y2,x,y3....] in an elegant way (shorter code?) I'm not sure I do explain well for your response. I really appreciate your help.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48487928

http://stackoverflow.com/q/48448935
has title: Sympy's Simplify function does not appear to simplify Rational numbers by removing common factors
tagged with: python
has comment: http://stackoverflow.com/comment/83890818
downvote count: 1
has comment: http://stackoverflow.com/comment/83926262
has comment: http://stackoverflow.com/comment/83890624
has comment: http://stackoverflow.com/comment/83890894
has comment: http://stackoverflow.com/comment/83925828
has comment: http://stackoverflow.com/comment/83890739
answer count: 1
has comment: http://stackoverflow.com/comment/83891243
has answer: http://stackoverflow.com/a/48466947
score: -1
has comment: http://stackoverflow.com/comment/83891640
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83900400
tagged with: sympy
has comment: http://stackoverflow.com/comment/83891020
upvote count: 0
type: UnansweredQuestion
has body: I am trying to use Sympy to define repeating decimal fractions using geometric series. In particular, I am trying to find the sequence limit (not partial sum limit) at infinity. My code work for simple cases, like: .33333333 + ... but when I try to do it for a more complicated case, like: .400840084008 + ... my code fails to calculate the sequence limit. When I troubleshoot my code, I get a very strange result for rational number, a, in the geometric series: geo_series = a*(r**n). My code is: import numpy as np import plotly.plotly as py from plotly.graph_objs import Scatter, Figure from sympy import limit_seq, lambdify, simplify, Symbol, Rational, Dummy def seq_limit(seq, n): try: n_ = Dummy("n", integer=True, positive=True) L1 = limit_seq(seq.subs(n, 2*n_), n_) if L1 is None: print('Sympy evaluates sequence limit, L1, to None') return np.NaN L2 = limit_seq(seq.subs(n, 2*n_ + 1), n_) if L2 is None: print('Sympy evaluates sequence limit, L2, to None') return np.NaN except: return np.NaN if L1 == L2 : return L1 else: print('L1 (even terms):', L1) print('L2 (odd terms):', L2) return np.NaN def sum_limit(a, r): if np.absolute(r) &gt;= 1 and a != 0: return np.NaN elif a == 0: return 0 elif np.absolute(r) &lt; 1: return a/(1 - r) def geo_term_eval(func, i): term = lambdify(n, func) if term is None: print('Cannot evaluate a lambdified term') return term(i) class Sequence(object): def __init__(self,geo_term, i): self.geo_term = geo_term self.sum = 0 self.partial_sum = np.array([]) self.dom = np.arange(i) self.rng = np.array([]) self.is_positive = True self.is_alternating = True for i in self.dom: rng_val = geo_term_eval(self.geo_term, i) self.rng = np.append(self.rng, [rng_val]) self.sum += rng_val self.partial_sum = np.append(self.partial_sum, [self.sum]) sign_array = np.sign(self.rng) for i in self.dom: if self.rng[i] &lt;= 0: self.is_positive = False break for i in self.dom[:-1]: if sign_array[i] == sign_array[i + 1]: self.is_alternating = False break self.seq_limit = s…
has comment: http://stackoverflow.com/comment/83890711

http://stackoverflow.com/a/48364460
has body: False not in S is equivalent to False not in S.index. Since the first index element is 0 (which, in turn, is numerically equivalent to False), False is technically in S.
answers question: http://stackoverflow.com/q/48364407
type: Answer
has comment: http://stackoverflow.com/comment/83730458
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48364407
downvote count: 0
upvote count: 1

mobile
tags question: http://stackoverflow.com/q/48453816
type: Tag
tag name: mobile

http://stackoverflow.com/q/48460264
tagged with: dictionary
has answer: http://stackoverflow.com/a/48460453
tagged with: list
has comment: http://stackoverflow.com/comment/83913645
type: Question
linked to: http://stackoverflow.com/q/19290762
score: 0
has comment: http://stackoverflow.com/comment/83913753
has comment: http://stackoverflow.com/comment/83913652
has body: Being new to Python, I am studying the following codes: a_0 = {"what": "b"} a_1 = {"what": "c"} a_2 = {"what": "d"} items = [] # empty list for i_no in range(10): # fill the list with 10 identical a_0 dicts i_new = dict(a_0) items.append(i_new) for i in items[0:5]: # change the first 5 items if i["what"] == "b": # try to change the 'i' to be a_1 dicts i = dict(a_1) # print(i) shows changes for i in items: print(i) # print(i) does not show changes If the above change works then first 5 items should be the same as a_1, while the last 5 unchanged. But the printed outcome did not match my expectation and this confused me. I want to know whether I missed something. Are there any more convenient ways to change each dictionary in the list? Many thanks.
has title: Assigning dictionaries to list
favorite count: 0
duplicate of: http://stackoverflow.com/q/19290762
has comment: http://stackoverflow.com/comment/83913628
upvote count: 2
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83913488
has answer: http://stackoverflow.com/a/48460406
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/83725306
has text: Did you copy/paste your post title into Google and read all the other SO entries on this topic?
score: 0
comment on: http://stackoverflow.com/q/48369331
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83795447
type: AnswerComment
comment on: http://stackoverflow.com/a/48403142
type: Comment
has text: @jezrael Ok. I have 5 options. Which is similar? Third? Last?
score: 0

http://stackoverflow.com/comment/83774232
comment on: http://stackoverflow.com/a/48374491
score: 0
type: Comment
has text: @Eric Also, please see this question: https://stackoverflow.com/questions/48387466/updating-batch-image-array-in-place-when-using-joblib
type: AnswerComment

http://stackoverflow.com/a/48392658
answers question: http://stackoverflow.com/q/48392365
type: Answer
has body: There is nothing inherently wrong with having a table in your database that only has one row. In designing systems, it is common to have pieces of data that do not change often, but can change. In systems that will be installed at multiple sites, this might be configuration settings like enable/disable feature A, or feature B, or which of three different methods to use for a certain calculation. In systems that will only have one installation, it might be the local sales tax rate, or who to contact, if needed, and how. Rather than hard-coding this information so that only a programmer can change it, this should be placed in a data store where it can be edited and updated by a user/power user/administrator. This can be in the main data store for the system, in a text configuration file, or in the windows registry. The windows registry would not be very appropriate for a server based python/django application. Python has a built-in configparser module which does a good job of keeping this type of information in a text file alongside the program(s). Other languages, I am sure, have similar functionality available. Django has an ORM to a relational database built in. Most (all?) django applications will be using the ORM/RDBMS functionality. I cannot see a reason to add another module (configparser) to an application that already has the ability to store/retrieve this information conveniently and reliably. That is just adding complexity to the system. That leaves storing in the main datastore/RDBMS. This is very convenient in Django because of the availability of the admin interface to allow editing. There are two main approaches to storing these pieces of data in a database. I will call these wide, and long. Wide configuration storage consists of a single row of data with a specified column for each piece of data required. Name | Phone | tax rate | ftr A | ftr B | … Joe Smith | 1234567890 |7.6 | Y | N | … Long configuration stores key value pairs – similar to a python d…
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48392365
type: AcceptedAnswer

http://stackoverflow.com/a/48458422
answers question: http://stackoverflow.com/q/48452041
score: 0
has body: You can use re.sub to insert that space: re.sub(r'\b(?:(\D+)(\d+)|(\d+)(\D+))\b', r"\1\3 \2\4", word) This matches digits followed by non-digits or vice-versa. The \b boundaries make sure the word is matched in its entirety, so that we don't match numbers in the middle of a word. The replacement pattern \1\3 \2\4 takes advantage of the fact that unmatched groups are replaced with the empty string. We know that either group 1 and 2 or group 3 and 4 will match, and the other groups will be empty, so \1\3 \2\4 will always produce a valid result (without duplicating any part of the input). Examples: &gt;&gt;&gt; re.sub(r'\b(?:(\D+)(\d+)|(\d+)(\D+))\b', r"\1\3 \2\4", "abc12") 'abc 12' &gt;&gt;&gt; re.sub(r'\b(?:(\D+)(\d+)|(\d+)(\D+))\b', r"\1\3 \2\4", "12abc") '12 abc' &gt;&gt;&gt; re.sub(r'\b(?:(\D+)(\d+)|(\d+)(\D+))\b', r"\1\3 \2\4", "a12bc") 'a12bc'
has comment: http://stackoverflow.com/comment/83931526
type: Answer

http://stackoverflow.com/comment/83938357
type: Comment
has text: Yup exactly. But you'll probably have to call `.astype(int)` if you want 1's and 0's (see my update). `data_df[column_name] < cutoff` will return booleans (`True` and `False`).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48472197

http://stackoverflow.com/a/53623848
has body: I ran into a similar problem as this and ended up needing to: Check "Add or remove programs" for previous versions of Python. Download the installer for that version. Repair the older version of Python Windows thought was installed. Uninstall the older version. Try to install the newer version again.
score: 0
answers question: http://stackoverflow.com/q/48416084
type: Answer

http://stackoverflow.com/q/48369862
tagged with: resize
has comment: http://stackoverflow.com/comment/83764560
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83764036
has title: RGB Image resize in Python
tagged with: python
tagged with: image
tagged with: interpolation
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83731762
has body: I have problems with manipulating an RGB image using Python and TensorFlow. I want to interpolate an RGB image using bicubic interpolation. In Matlab I can do that using a for loop as follows: for i= 1:3 im1(:,:,i)= imresize(im(:,:,i), [256 256], 'bicubic'); end But how can I do that in Python? I have tried using the following command, but it gives me an error. im1 = tf.image.resize_images(im, [256, 256, 3], method=tf.image.ResizeMethod.BICUBIC)
type: UnansweredQuestion

http://stackoverflow.com/q/48441193
has comment: http://stackoverflow.com/comment/83874185
score: 3
has comment: http://stackoverflow.com/comment/83874130
accepted answer: http://stackoverflow.com/a/48455803
has answer: http://stackoverflow.com/a/48455803
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83898877
has title: How to user Django REST serializer do validation on reserved key?
has comment: http://stackoverflow.com/comment/83892590
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83892366
linked to: http://stackoverflow.com/q/47630356
tagged with: django-rest-framework
favorite count: 0
type: Question
tagged with: serialization
has comment: http://stackoverflow.com/comment/83903594
has body: It might a simple question with eye blink workaround. But I can not be able to get it done. I am now creating the webhook endpoint. And stuck at serializer class My class can not use from as a class property Python 3.6.4 Django==1.11.9 djangorest==3.7.7 @pytest.fixture def like_object(): """LIKE object response from Facebook""" return { "object": "page", "entry": [{ "changes": [{ "field": "feed", "value": { "item": "reaction", "verb": "add", "reaction_type": "like", "created_time": 1516183830, "post_id": "1331351323541869_1844740022202994", "from": { "name": "Elcoie Sieve", "id": "1639217166122728" }, "parent_id": "1331351323541869_1844740022202994" } }], "time": 1516183830, "id": "1331351323541869" }] } serializers.py class FacebookReactionSerializer(serializers.Serializer): """ value serializer the inner most of the payload """ item = serializers.CharField() verb = serializers.CharField() reaction_type = serializers.CharField() created_time = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(4086831600)] ) # Limit the maximum epoch to 2099 July 4th 7:00AM post_id = serializers.CharField(max_length=40) from = FromSerializer() parent_id = serializers.CharField() def validate(self, attrs): """ `from` is a python reserved word the add _ to distinguish it from them :param attrs: :return: """ from_ = attrs.get('from') pass def create(self, validated_data): pass def update(self, instance, validated_data): pass Attempts: ffrom = FromSerializer(source='from') Does not work Attempt2: class FacebookReactionSerializer(serializers.Serializer): """ value serializer the inner most of the payload """ item = serializers.CharField() verb = serializers.CharField() reaction_type = serializers.CharField() created_time = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(4086831600)] ) # Limit the maximum epoch to 2099 July 4th 7:00AM post_id = serializers.CharField(max_length=40) from_key = FromSerializer() parent_id = serializers…

http://stackoverflow.com/q/48390893
has title: QWebEngineView Settings
has comment: http://stackoverflow.com/comment/83775532
has comment: http://stackoverflow.com/comment/83775500
type: UnansweredQuestion
tagged with: qwebengineview
has comment: http://stackoverflow.com/comment/83774341
has body: I have a code here: QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.PluginsEnabled, True) self.setUrl(QUrl("https://google.com")) "self" is QWebEngineView(new class) and nope it does not work. Can you help? I searched a lot... P.S. It has no errors.
tagged with: python
has comment: http://stackoverflow.com/comment/83788983
has comment: http://stackoverflow.com/comment/83775110
has comment: http://stackoverflow.com/comment/83774306
score: 0
has comment: http://stackoverflow.com/comment/83775523
answer count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/83774992
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/83774922

http://stackoverflow.com/q/48333817
has comment: http://stackoverflow.com/comment/83653080
has title: What will be the best alternative to Curl in Python?
has answer: http://stackoverflow.com/a/48334394
tagged with: curl
tagged with: urllib
favorite count: 0
has comment: http://stackoverflow.com/comment/83653095
type: Question
tagged with: urllib2
answer count: 2
has body: Curl has proved to be a good tool for testing Web API interfaces in the past. I am now looking to emulate the same in Python with its urllib and urllib2 Modules. I was wondering if there is already a module written for this specific purpose. Both Python 2 and Python 3 compatible solutions will work in my environment.
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48333834
score: 0

http://stackoverflow.com/q/48479693
has comment: http://stackoverflow.com/comment/83952463
has comment: http://stackoverflow.com/comment/83952618
has body: Basically what I'm supposed to do is make a program that gets the half-steps of a cord, and outputs the cord that many half steps away. I got that working, but I'm not sure what I need to do for my string_to_list function, where I am supposed to split the string that's getting passed into the function then iterate over that list that I split into create tuples. If someone could help I'd really appreciate it. def string_to_list(chords_str): return chords_str.split()
accepted answer: http://stackoverflow.com/a/48479856
has answer: http://stackoverflow.com/a/48479960
has comment: http://stackoverflow.com/comment/83952566
has comment: http://stackoverflow.com/comment/83952409
has answer: http://stackoverflow.com/a/48479856
has comment: http://stackoverflow.com/comment/83952366
tagged with: python
has comment: http://stackoverflow.com/comment/83952439
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83952429
possible better answer: http://stackoverflow.com/a/48479960
answer count: 2
has comment: http://stackoverflow.com/comment/83952387
has title: Splitting a String then iterating over that list
type: Question

http://stackoverflow.com/comment/83963171
score: 0
has text: Yes, this can be assumed true.
type: QuestionComment
comment on: http://stackoverflow.com/q/48485214
type: Comment

http://stackoverflow.com/comment/83683096
type: QuestionComment
comment on: http://stackoverflow.com/q/48348334
score: 0
has text: @eyllanesc Not sure if that's a good target for this (broad post).
type: Comment

mfcc
type: Tag
tags question: http://stackoverflow.com/q/48388641
tags question: http://stackoverflow.com/q/48333516
tag name: mfcc

http://stackoverflow.com/comment/83816649
type: AnswerComment
has text: It is worth pointing out that, since python 3.6, built-in dictionaries are ordered: https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6. It is debatable whether you want to take advantage of this "implementation detail."
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48413318

http://stackoverflow.com/comment/83861126
has text: @Dan i have added an answer, i hope that it can help you to solve your issues
comment on: http://stackoverflow.com/q/48433682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48484195
has comment: http://stackoverflow.com/comment/83980524
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48484074
has body: import re A = [{"No.":1,"source_link":"www.aa.com","brand":"Gorn","item_name":"Beautiful","category":"Red","message":"My email is abcdefg@gmail.com","create_date":"13\\/7\\/2017 20:04","date":"13\\/7\\/2017"},{"No.":2,"source_link":"www.bb.com","brand":"Mik","item_name":"Pork","category":"White","message":"My email is zxcvbg@gmail.com","create_date":"13\\/7\\/2017 20:04","date":"13\\/7\\/2017"}] for i in A: match = re.search(r'[\w\.-]+@[\w\.-]+',i["message"] ) i["Email"] = match.group(0) Output: [{'category': 'Red', 'date': '13\\/7\\/2017', 'No.': 1, 'create_date': '13\\/7\\/2017 20:04', 'item_name': 'Beautiful', 'source_link': 'www.aa.com', 'brand': 'Gorn', 'message': 'My email is abcdefg@gmail.com', 'Email': 'abcdefg@gmail.com'}, {'category': 'White', 'date': '13\\/7\\/2017', 'No.': 2, 'create_date': '13\\/7\\/2017 20:04', 'item_name': 'Pork', 'source_link': 'www.bb.com', 'brand': 'Mik', 'message': 'My email is zxcvbg@gmail.com', 'Email': 'zxcvbg@gmail.com'}] You can use the json module to convert ti back to string if you need. EX: import json print json.dumps(A)
answers question: http://stackoverflow.com/q/48484074
score: 0
type: Answer

http://stackoverflow.com/q/48455649
has title: Gnuplot on Raspberry Pi, plotting to X11 terminal, how can I re-use the same X window?
tagged with: x11
type: Question
tagged with: gnuplot
has answer: http://stackoverflow.com/a/48474946
type: UnansweredQuestion
answer count: 1
tagged with: raspberry-pi3
tagged with: python
has body: I am successfully gnuplotting to an X window in Python on a RPi. The python code gathers data, periodically appends it to a CSV file and plots the CSV file with: ('set terminal gif medium size 1100,600 background "#e7e7ff"\n') ('set output "/home/pi/pp/plotdata.gif"\n') This overwrites the gif and FTPs the gif file periodically. The gif file is FTP'd to a web host that refers to the plot image in HTML source. All is well. Problem: I would like to also display the plot locally from the Python program. I can do so with "set terminal X11", but every cycle thru the program spawns a new X11 plot window. gnuplot is called from python with: os.system('gnuplot -persist "/home/pi/pp/plotstuff.gnu"') After the plot is generated, gnuplot ends for that python program cycle, leaving the plot window persisting. But a new plot window is spawned every cycle. How can tell gnuplot to plot to the already open X window, overwriting the previous plot in that window? I find references to "set terminal x11 5#5n6#6" but can't figure it out.
score: 0

http://stackoverflow.com/comment/83732746
has text: yes, looking at @dvnguyen 's question, this feature is infact useful when developing packages
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48372766

http://stackoverflow.com/comment/83857638
comment on: http://stackoverflow.com/q/48433105
score: 0
has text: where is `naiveBayesClassifier` from? and how is `Trainer(tokenizer)` being called? what is `tokenizer`? like what sort of object is `tokenizer`?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48469916
has body: I'm using a python script to manage ssh fingerprint problems after a workstation(s) is reimaged. I attempt to connect with ssh, and if I get a any warnings I deal with them. However, if there are no errors, then I am asked for a password to connect. At this point I want to terminate the process. However, the script hangs on the password request. Here's the method: def ssh_fingerprint_changed(node): """ Checks if a node's ssh fingerprint has changed or an old key is found, which can occur when a node is reimaged. It does this by attempting to connect via ssh and inspecting stdout for an error message. :param node: the ip or hostname of the node :return: True if the node's fingerprint doesn't match the client's records. Else False. """ changed = False cmd = ["ssh", "-q", ADMIN_USER + "@" + node, "exit"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) print("Checking for fingerprint changes") for line in proc.stdout: # loop on lines print("in for loop") # NEVER REACHES HERE IF NO ERRORS, WAITING FOR PASSWORD if b"Offending key" in line: print("Offending key found.") proc.stdin.write(b"no\n") # don't connect changed = True elif b"REMOTE HOST IDENTIFICATION HAS CHANGED!" in line: print("REMOTE HOST IDENTIFICATION HAS CHANGED!") changed = True print(changed) # NEVER REACHES HERE IF NO ERRORS, WAITING FOR PASSWORD if not changed: # then everything's good, but it will be waiting for a password to connect print("Good to go, terminating ssh test.") rc = proc.terminate() else: rc = proc.wait() return changed If I run this from the terminal ./my_python_script.py, I have the problems. Oddly, if I run in PyCharm, it doesn't hang on the password request and terminates shh, continuing with the script as expected.
has comment: http://stackoverflow.com/comment/83933934
has comment: http://stackoverflow.com/comment/83934674
tagged with: subprocess
has comment: http://stackoverflow.com/comment/83934257
has comment: http://stackoverflow.com/comment/83934015
downvote count: 0
tagged with: ssh
answer count: 1
has answer: http://stackoverflow.com/a/48470048
has comment: http://stackoverflow.com/comment/83933953
favorite count: 0
type: Question
has title: ssh via python subprocess.Popen: terminate if password requested
has comment: http://stackoverflow.com/comment/83933969
has comment: http://stackoverflow.com/comment/83934109
upvote count: 2
has comment: http://stackoverflow.com/comment/83933979
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83934058
has comment: http://stackoverflow.com/comment/83933815
tagged with: python
has comment: http://stackoverflow.com/comment/83934180
has comment: http://stackoverflow.com/comment/83933895
has comment: http://stackoverflow.com/comment/83934019
has comment: http://stackoverflow.com/comment/83933832
score: 2
has comment: http://stackoverflow.com/comment/83934713

http://stackoverflow.com/a/48480883
upvote count: 3
has body: There are two issues here: np.round wants a compatible non-symbolic object, while K.sigmoid returns a symbolic tensor. (Update this is where your error is coming from). Keras itself needs a loss function that returns a symbolic tensor, while np.round returns a non-symbolic value. (Update this would've been the next error in line). The bottomline is that you must stick to functions from keras.backend in all your functions. If you are not keen on compatibility (i.e. you only intend to run your models on a particular backend, be it Theano or Tensorflow), you can also use the operations defined by your backend directly, because keras.backend is relatively limited. There is also no direct way to round a floating point value in any supported backend. More importantly, I don't think there is much sense in rounding an activation function, because it might severely harm the gradient. Update If you are doing this to get a rounded output, there is no need to fiddle with the activation function itself. You can simply round the output: np.round(yournetwork.predict(...), 2)
downvote count: 0
has comment: http://stackoverflow.com/comment/83956301
has comment: http://stackoverflow.com/comment/83954941
score: 3
has comment: http://stackoverflow.com/comment/83955051
has comment: http://stackoverflow.com/comment/83955207
has comment: http://stackoverflow.com/comment/83955176
type: Answer
has comment: http://stackoverflow.com/comment/83955522
answers question: http://stackoverflow.com/q/48480751

http://stackoverflow.com/comment/83860998
comment on: http://stackoverflow.com/q/48434732
type: Comment
has text: Opening the file and reading the contents would be a good start.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83763010
score: 0
type: QuestionComment
has text: @StevenRumbalski yes, I guess if the date format shown above is what OP wanted to preserve, we could just change the `fmt` and this depends on whether the data has a constant format.
comment on: http://stackoverflow.com/q/48387224
type: Comment

http://stackoverflow.com/q/48345346
downvote count: 0
upvote count: 1
has body: I'm creating a program needed for my master thesis. The program reads data from arduino and writes it into csv file. This is only part of the program, so I use multiprocessing module. But the program makes a few bugs in the csv file, especially at the beginning. It should write a 3-digit number in every line. And sometimes it "eats" some digits. It looks like this: 308,0 ,0 313,0 313,0 313,0 313,0 12,0 307,0 306,0 0,0 305,0 It happens randomly only in the first 100-200 lines (the whole file has several thousand lines). I don't know what causes the problem. This is part of the program: def port_reader(q, quit): ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0) while quit.empty(): try: q.put(ser.readline()) except ser.SerialTimeoutException: print('Data could not be read') time.sleep(0.04) def output_creator(num, q, flag, quit): out_path = "GSR_data/"+str(num.get())+"_GSR.csv" while quit.empty(): data = q.get() with open(out_path, 'a') as out_file: try: out_file.write(re.sub("[^0-9]", "", data)+","+str(int(flag.value))+"\n") except OSError: print "No file" resp_n = mp.Queue() gsr_data = mp.Queue() quit = mp.Queue() flag = mp.Value('d', 0) proc1 = mp.Process(target=port_reader, args=(gsr_data, quit)) proc2 = mp.Process(target=output_creator, args=(resp_n, gsr_data, flag, quit)) resp_n.put(resp_number) proc1.start() proc2.start() And this is part in arduino: const int analogInPin = A0; int sensorValue = 0; void setup() { Serial.begin(9600); } void loop() { sensorValue = analogRead(analogInPin); Serial.println(sensorValue); delay(40); }
favorite count: 0
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/83681727
has comment: http://stackoverflow.com/comment/83676643
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84331220
tagged with: python
has title: errors in csv output file; data collected from arduino
answer count: 0
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: arduino

http://stackoverflow.com/comment/83903092
type: AnswerComment
has text: I think the code without `np.array` produces the same result. But, in Python, nested brackets, like '`[[1, 2, 3], [4, 5, 6]]`', produces list of list, which differs from 2d-array. So, I added `np.array` so that it explicitly indicate you are assigning 2d-array.
comment on: http://stackoverflow.com/a/48454729
score: 1
type: Comment

http://stackoverflow.com/q/48488335
has comment: http://stackoverflow.com/comment/83970073
tagged with: sparse-matrix
has body: I have a pandas dataframe like this df document term X a X b X a X c Y a Y c Y d I want to create sparse matrix like this: This sparse matrix has rows as unique documents, columns as unique terms. I want to fill 1 if document and term co-exists in original dataframe irrespective number of times they co-existed, else 0 a b c d X 1 1 1 0 Y 1 0 1 1 I have tried with for loop, it is time consuming with million rows. My Answer after suggestion from piRsquared: #drop duplicates df = df.drop_duplicates() df.pivot_table(index='document', columns='term', fill_value=0, aggfunc='size')
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/83969546
score: 0
has comment: http://stackoverflow.com/comment/83969677
has comment: http://stackoverflow.com/comment/83970097
tagged with: pandas
tagged with: dataframe
tagged with: python
type: Question
tagged with: binary
has title: Creating Binary Sparse matrix in python using pandas which should be fast and efficient
answer count: 0
has comment: http://stackoverflow.com/comment/83970332
linked to: http://stackoverflow.com/q/47152691
type: UnansweredQuestion

http://stackoverflow.com/q/48383737
has body: I use pbr for packaging. It takes the version from git tags and applies that to setup.py Now I also want to have the version available inside the package. For instance to have a __version__ attribute. Can I use the pbr library for this? There is another library: versioneer that also extracts the version from the git tags, but that would add an extra requirement. I would prefer to get this functionality from pbr
linked to: http://stackoverflow.com/q/40562270
type: Question
linked to: http://stackoverflow.com/q/4760215
linked to: http://stackoverflow.com/q/58491577
has answer: http://stackoverflow.com/a/52740408
has title: Get version from git tags (through pbr)
tagged with: python
has answer: http://stackoverflow.com/a/53465101
has comment: http://stackoverflow.com/comment/83754370
linked to: http://stackoverflow.com/q/58549784
has comment: http://stackoverflow.com/comment/83756580
accepted answer: http://stackoverflow.com/a/58549761
possible better answer: http://stackoverflow.com/a/52740408
tagged with: versioning
type: AnsweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/58549761
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83752691
type: AnswerComment
score: 0
has text: @SRingne Sure, I can. Also, regex replacement in general is slow, unfortunately. With a non-regex replacement, you can probably gain something, but the moment you've invoked the regex parser, you've implicitly agreed to lose performance. The second option in both our answers suffers this problem, but there is no overhead in Pandas, so that's a plus...
comment on: http://stackoverflow.com/a/48382841
type: Comment

http://stackoverflow.com/a/48457930
has comment: http://stackoverflow.com/comment/83909151
has comment: http://stackoverflow.com/comment/83908789
has comment: http://stackoverflow.com/comment/83909129
answers question: http://stackoverflow.com/q/48457866
has comment: http://stackoverflow.com/comment/83908828
type: Answer
has comment: http://stackoverflow.com/comment/83909038
score: 2
upvote count: 2
downvote count: 0
has body: I think you need str.split for DataFrame, get columns and join to original: df1 = df['YMD-Time'].str.split(expand=True) df1.columns = ['Y', 'M', 'D', 'H', 'M', 'Secs'] df = df.join(df1)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48457866

http://stackoverflow.com/q/48392734
type: UnansweredQuestion
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48393128
downvote count: 1
favorite count: 0
type: Question
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/83773392
tagged with: pearson-correlation
has comment: http://stackoverflow.com/comment/83806075
has body: I am trying to calculate the pearsons correlation for every single possible pair of two columns in a dataframe. I have 57997 columns. But I am getting a memory error. t_logs = logs.T print t_logs results = t_logs.corr(method='pearson').applymap print results[enter image description here][1] Here is the trace back --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) &lt;ipython-input-99-d0010a131d17&gt; in &lt;module&gt;() 5 print logs 6 ----&gt; 7 results = t_logs.corr(method='pearson') 8 print results C:\Users\nne1s\Anaconda2\lib\site-packages\pandas\core\frame.pyc in corr(self, method, min_periods) 4938 4939 if method == 'pearson': -&gt; 4940 correl = libalgos.nancorr(_ensure_float64(mat), minp=min_periods) 4941 elif method == 'spearman': 4942 correl = libalgos.nancorr_spearman(_ensure_float64(mat), pandas\_libs\algos.pyx in pandas._libs.algos.nancorr (pandas\_libs\algos.c:15501)() MemoryError: picture of code linked here
tagged with: python
has title: Python: MemoryError for .corr(method='pearson').applymap
tagged with: vectorization
upvote count: 2
has comment: http://stackoverflow.com/comment/83773288

http://stackoverflow.com/q/48349930
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: How to upgrade tensorflow from 1.3 to 1.4 on Ubuntu?
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: ubuntu
has body: I have tensorflow 1.3.0 installed in my computer (Ubuntu Mate 16.04, Python 2.7) and need to upgrade to 1.4.1 (CPU). I type the following in the terminal sudo -H pip install --ignore-installed --upgrade \ https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.4.1-cp27-none-linux_x86_64.whl And everything seems okay. Then I go to python and type tf.VERSION and it outputs 1.3.0. I've been trying with this tutorial, and also with and without the -H option. I also tried simply with sudo pip install --ignore-installed --upgrade tensorflow but the result is the same. What am I doing wrong? Note: When I run sudo pip install --upgrade tensorflow it says I already have tensorflow 1.4.1 installed (it uninstalls it and installs it again), but pip list says it's 1.3.0.
has comment: http://stackoverflow.com/comment/83686711
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/83686638
has comment: http://stackoverflow.com/comment/83687041

http://stackoverflow.com/q/48436649
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83864861
has comment: http://stackoverflow.com/comment/83864658
score: 1
has body: I'm currently having issues with my Django pagination. I have a query set of 9 objects and am paginating one object to a page. So I should have 9 pages total. Paginator is showing that I have 9 pages, but when I click the "next" page button my (Always on the last/last two pages) my url turns to: http://127.0.0.1:8000/forum/1?page=7 Then I get a 404 page not found error along with "Invalid page (7): That page contains no results" Here is my class code: class DirectoryClass(generic.ListView): template_name = "forum_directory.html" model = Directory paginate_by = 1 def get_context_data(self, **kwargs): context = super(DirectoryClass, self).get_context_data(**kwargs) directory = Directory.objects.filter(pk=self.kwargs['directory_id']) context['page'] = 'forum' context['name'] = directory.first().name context['user'] = self.request.user topic_set = directory.first().topic_set.all().order_by('-last_post') print(topic_set.all()) paginator = Paginator(topic_set, self.paginate_by) page = self.request.GET.get('page') try: topic_set = paginator.page(page) except PageNotAnInteger: topic_set = paginator.page(1) except EmptyPage: topic_set = paginator.page(paginator.num_pages) context['topics'] = topic_set context['page'] = page return context Here is the HTML used to change the page: &lt;div style="width: 1240px; margin: auto; text-align: right;"&gt; {% if topics.has_other_pages %} &lt;ul class="pagination forum-pagination"&gt; {% if topics.has_previous %} &lt;li&gt;&lt;a href="?page={{ topics.previous_page_number }}"&gt;&amp;laquo;&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class="disabled"&gt;&lt;span&gt;&amp;laquo;&lt;/span&gt;&lt;/li&gt; {% endif %} {% for i in topics.paginator.page_range %} {% if topics.number == i %} &lt;li class="active"&gt;&lt;span&gt;{{ i }} &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/span&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="?page={{ i }}"&gt;{{ i }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% endfor %} {% if topics.has_next %} &lt;li&gt;&lt;…
tagged with: pagination
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83864761
accepted answer: http://stackoverflow.com/a/48436832
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48436832
has comment: http://stackoverflow.com/comment/83864734
has title: Django Pagination "Page not found"
tagged with: django

http://stackoverflow.com/q/48470228
has body: if message.content.lower().startswith('!kick') and (roleLFJob in message.author.roles or roleLFAba in message.author.roles): await client.delete_message(message) serverchannel = '405090256124248065' messageParsed = message.content.split() kick = messageParsed[0] mention = messageParsed[1] msg = messageParsed[2:] for member in message.mentions: await client.kick(member) await client.send_message(discord.Object(id=serverchannel), '{0} was kicked by {1}, with reason:"**'.format(member.mention, message.author.mention) + msg + '**"') When I wrote this command in discord: !kick @(member.mention) reason, reason and reason This error occur: Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\senuk\AppData\Local\Programs\Python\Python35\lib\site-packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "overmind.py", line 128, in on_message await client.send_message(discord.Object(id=serverchannel), '{0} was kicked by {1} with reason:"**'.format(member.mention, message.author.mention) + msg + '**"') TypeError: Can't convert 'list' object to str implicitly
type: AnsweredQuestion
score: 0
tagged with: discord
answer count: 1
tagged with: discord.py
type: Question
has comment: http://stackoverflow.com/comment/83935374
tagged with: python
has title: How to fix this error discord python?
accepted answer: http://stackoverflow.com/a/48470765
has answer: http://stackoverflow.com/a/48470765

http://stackoverflow.com/q/48392243
answer count: 1
has title: Python - Convert string to date
has answer: http://stackoverflow.com/a/48392256
accepted answer: http://stackoverflow.com/a/48392256
favorite count: 0
type: Question
score: -2
tagged with: datetime
tagged with: python
type: AnsweredQuestion
upvote count: 0
has body: Hi I have an input string "25-11-12" which needs to be converted to date time format. I have tried below datetime.strptime(string1,%d-%m-%Y) but since the input year is just '12' i am unable to proceed with error that time data doesnot match the format. Can someone please help with conversion. Thanks!
has comment: http://stackoverflow.com/comment/83772601
downvote count: 2
linked to: http://stackoverflow.com/q/5897263

http://stackoverflow.com/a/48465183
type: Answer
has comment: http://stackoverflow.com/comment/83924701
score: 1
has body: You simply need a class for this: class PseudoInteger(object): def __init__(self, num, hidden=None): self.num = num self.hidden = hidden def __add__(self, otherVal): if isinstance(otherVal, PseudoInteger): return self.num + otherVal.num else: return self.num + otherVal p = PseudoInteger(4, 'Tiger') q = PseudoInteger(6, 'lion') print (p+q) print (p+4) This prints out: 10 8 You have to add the other operations (division, substraction, eq, ...) you need to the class on your own :)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48464960
has comment: http://stackoverflow.com/comment/83925053
has comment: http://stackoverflow.com/comment/83924288

http://stackoverflow.com/q/48372903
has answer: http://stackoverflow.com/a/48373062
has answer: http://stackoverflow.com/a/48372937
accepted answer: http://stackoverflow.com/a/48372977
favorite count: 0
has comment: http://stackoverflow.com/comment/83756665
type: Question
has answer: http://stackoverflow.com/a/48372977
tagged with: python-3.x
has title: How to convert a String into an Int in a Python List
possible better answer: http://stackoverflow.com/a/48372949
answer count: 5
has comment: http://stackoverflow.com/comment/83739767
score: -3
has body: If I have a list of strings containing both numbers and words, how would I turn the numbers into ints and keep the words as strings still in the list? for example, this: badList = ['56','45','01','cat','64','dog'] would become: badList = [56, 45, 01, 'cat', 64, 'dog']
has answer: http://stackoverflow.com/a/48372949
tagged with: python
downvote count: 5
tagged with: int
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48373105
upvote count: 2

http://stackoverflow.com/q/48412611
has title: Django REST framework not picking up API endpoint
tagged with: django-rest-viewsets
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48412725
tagged with: django-rest-framework
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48412725
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I'm trying to refactor an API to use the Django REST framework. I've changed my urls.py to the following (still in Django 1.11): from django.conf.urls import url from . import views from rest_framework import routers, serializers, viewsets from .serializers import SessionSerializer from .viewsets import SessionViewSet router = routers.DefaultRouter() router.register(r'^api/v1\.0/feedback/$', SessionViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^api/v1\.0/profile/$', views.get_profile), url(r'^api/v1\.0/update_profile/$', views.update_profile), url(r'^api/v1\.0/update_password/$', views.update_password), url(r'^api/v1\.0/sessions/$', views.get_session), url(r'^api/v1\.0/user/$', views.get_user), url(r'^api/v1\.0/sessions/send_schedule_request/$', views.send_schedule_request), url(r'^api/v1\.0/sessions/confirm_session_time/$', views.confirm_session_time), url(r'^api/v1\.0/password_reset/$', views.password_reset), url(r'^api/v1\.0/me/apn/$', views.save_apn), url(r'^api/v1\.0/confirm_activation_code$', views.confirm_activation_code), url(r'^api/v1\.0/update_user_via_activation_code$', views.update_user_via_activation_code), url(r'^api/v1\.0/questions/$', views.get_questions), url(r'^api/v1\.0/answers/$', views.save_answers), # url(r'^api/v1\.0/feedback/$', views.record_feedback), url(r'^session_types/$', views.session_types), url(r'^send_custom_notification/(?P&lt;id&gt;\d+)/$', views.send_custom_notification, name='send_custom_notification'), url(r'^admin/lucy_web/send_session_time_notifications/(?P&lt;user_id&gt;\d+)/(?P&lt;session_id&gt;\d+)/$', views.send_session_time_notifications, name='send_session_time_notifications'), url(r'^admin/lucy_web/app_activate/(?P&lt;id&gt;\d+)/$', views.app_activate, name='app_activate'), url(r'^admin/lucy_web/create_activation_code/(?P&lt;id&gt;\d+)/$', views.create_activation_code, name='create_activation_code'), ] However, if I python manage.py runserver and go to localhost:8000/api/v1.0/feedback/, I get a 404 error respo…

http://stackoverflow.com/comment/83841305
score: 0
type: AnswerComment
has text: Make sure there are no quotation marks around `i**2`. Also, convert `i**2` to a string before writing to the file. I updated my post.
type: Comment
comment on: http://stackoverflow.com/a/48425586

http://stackoverflow.com/q/48437946
has title: Python Mulit-Index: Changing second level of index names
accepted answer: http://stackoverflow.com/a/48437994
tagged with: dataframe
tagged with: python
tagged with: multi-index
has answer: http://stackoverflow.com/a/48437994
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has body: I have a general question about multi-column index. I want to change name second level of index (nm) to 'ns1' and 'ns2'. Take a look at my df below. Out[13]: key nm 0 1 2 3 bar abc -0.424972 0.567020 0.276232 -1.087401 dse -0.673690 0.113648 -1.478427 0.524988 baz cws 0.404705 0.577046 -1.715002 -1.039268 cwd -0.370647 -1.157892 -1.344312 0.844885 foo efw 1.075770 -0.109050 1.643563 -1.469388 vqx 0.357021 -0.674600 -1.776904 -0.968914 qux zxe -1.294524 0.413738 0.276662 -0.472035 res -0.013960 -0.362543 -0.006154 -0.923061 Out[13]: key nm 0 1 2 3 bar ns1 -0.424972 0.567020 0.276232 -1.087401 ns2 -0.673690 0.113648 -1.478427 0.524988 baz ns1 0.404705 0.577046 -1.715002 -1.039268 ns2 -0.370647 -1.157892 -1.344312 0.844885 foo ns1 1.075770 -0.109050 1.643563 -1.469388 ns2 0.357021 -0.674600 -1.776904 -0.968914 qux ns1 -1.294524 0.413738 0.276662 -0.472035 ns2 -0.013960 -0.362543 -0.006154 -0.923061 Noticed that the second level of index name changed from all random strings to 'ns1' and 'ns2'. Is there a pythonic way to change this? My original dataframe is very big, so its hard to do manually. Thanks!
favorite count: 0
type: Question

http://stackoverflow.com/a/48390640
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48390381
downvote count: 0
has body: I will try to visualize the code for you to show how this works: &gt;&gt;&gt; for i in range(1, max(inputArray)): ... print("hop " + str(i),[x for x in inputArray if not x%i]) ... ('hop 1', [5, 3, 6, 7, 9]) ('hop 2', [6]) ('hop 3', [3, 6, 9]) ('hop 4', []) ('hop 5', [5]) ('hop 6', [6]) ('hop 7', [7]) ('hop 8', []) You can imagine that these are the hop lengths. You can see a hop length of "1" will hit every obstacle, but a hop length of "2" only hits obstacle number 6. Notice on hop 4 there is nothing in the array. This is where the any keyword comes in, to basically make this True/False: &gt;&gt;&gt; for i in range(1, max(inputArray)): ... print(any([x for x in inputArray if not x%i])) ... True True True False True True True False You can see as the code executes, when i == 4, divs == False, so you will trigger this logic: if not divs: return i However, in the case where every single hop hits an obstacle so you never have divs == False, the answer is simply hop the entire thing! In this problem "entire thing" is the length of max(inputArray)+1
has comment: http://stackoverflow.com/comment/83775296
score: 3
has comment: http://stackoverflow.com/comment/83770076

http://stackoverflow.com/comment/83739143
type: Comment
type: QuestionComment
has text: @LucasMeier Why do you want Worker to know the duration time? although I put the time to the animation with setDuration() this can vary for various reasons so it is not accurate.
score: 0
comment on: http://stackoverflow.com/q/48374487

http://stackoverflow.com/comment/83696668
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48350265
has text: I was suggesting that you have `lecture = ForeignKey('Lecture', on_delete=models.CASCADE)` on the `FileUpload` model. Although this assumes that *every* file upload is linked to a lecture. If you're still stuck, it would be better to ask a new question because this is a separate issue to your template.

http://stackoverflow.com/comment/83862321
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48434459
has text: y_trns shape would depend on both the problem and how you designed your output, is your final layer - 'conv10' returning 128x128x7? .. if so, you are right about y_trn shape.

http://stackoverflow.com/comment/83893127
type: AnswerComment
comment on: http://stackoverflow.com/a/48435382
score: 0
type: Comment
has text: I tried this set of code on the actual data set (`np.array` of `2163, 8719`) that I am using and I still receive the same answer for `precision`, `recall`, and `accuracy`

http://stackoverflow.com/comment/123477448
type: AnswerComment
has text: Aha. I had the same problem, and I did this, then it worked. So that's why I wrote this. That's how it's going to solve OP's problem? Anyways thanks for the feedback. I will edit this!
type: Comment
comment on: http://stackoverflow.com/a/69852027
score: 0

http://stackoverflow.com/comment/83763925
type: AnswerComment
comment on: http://stackoverflow.com/a/48387705
type: Comment
has text: the library is design that way : if source is named "f.x", image is named "f.x.png". I can't find any way to change it. But you can do it in python (module "os") or in shell.
score: 0

http://stackoverflow.com/q/48454525
type: AnsweredQuestion
has title: How to set Matplotlib to render greek letters in sans-serif font
linked to: http://stackoverflow.com/q/22348756
score: 1
tagged with: matplotlib
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48461596
has comment: http://stackoverflow.com/comment/83911365
linked to: http://stackoverflow.com/q/13338550
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2537868
has comment: http://stackoverflow.com/comment/83902094
has answer: http://stackoverflow.com/a/48461596
tagged with: tex
upvote count: 1
tagged with: python
has body: I am generating some plots using Python (2.7) and Matplotlib (1.4.3), and would like all of the text in my plots to be in a sans-serif font. The best I have been able to achieve, using external LaTeX and the sfmath package, fails to set greek letters in sans-serif. This is demonstrated in the following MWE: import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('text.latex', preamble=r'\usepackage{sfmath}') fig, ax = plt.subplots() ax.plot([0,1,2], [2,5,9]) #arbitrary data ax.set_xlabel(r'$x$ (m)', fontsize=16) ax.set_ylabel(r'$y = \alpha(x)x^2 - 2\mu$', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16, pad=8) fig.tight_layout() fig.show() [Output of above code (.png)] I am happy with the example axis labels except for the α and the μ which have been rendered in what looks like the default LaTeX serif font. Some other answers to questions I have looked at, involving changing various rc settings, which do not solve my problem: Sans-serif math with latex in matplotlib Upright mu in plot label: retaining original tick fonts Typing Greek letters etc. in Python Plots The only example I have seen which seems to do what I want is here (compare the first and last figures) but this requires modifying the matplotlibrc file. This is not suitable for my purposes; and in any case, I would be surprised if it were not possible to simply set it in the code as required. (1) How can I modify the above code so that greek letters are displayed in the same sans-serif font as the rest of the text in the plot?* (2) Is it possible to do all of this using Matplotlib's built-in mathtext rather than relying an external LaTeX installation? Many thanks in advance for any suggestions.

http://stackoverflow.com/a/48462604
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48445131
has body: Given the advice - this is the code that has worked for me on this problem: import csv import json with open('product.json') as file: x = json.load(file) print x f = csv.writer(open("test.csv", "wb+")) f.writerow(["url", "sku", "parent_id", "title", "vendor", "product type", "tags", "body_html", "image"]) f.writerow([x["handle"], x["id"], "", x["title"], x["vendor"], x["product_type"], x["tags"], x["body_html"], x["image"]]) for item in x["variants"]: f.writerow(["",item["sku"], x["id"],x["title"],"","","","", item["option1"]])

http://stackoverflow.com/q/48467460
answer count: 1
has comment: http://stackoverflow.com/comment/83928498
favorite count: 0
has title: Suppose to write an exponent in python, can't figure out what i'm dong wrong
type: Question
tagged with: python
type: UnansweredQuestion
has body: I'm supposed to calculate X to the Y and output the final result. for i in range (X): X, Y = Y, X print (X) this is what i get Program Failed for Input: 1 2 Expected Output: 1 Your Program Output: 2 What's wrong with the program?
downvote count: 4
has comment: http://stackoverflow.com/comment/83928564
has comment: http://stackoverflow.com/comment/83928458
upvote count: 0
has answer: http://stackoverflow.com/a/48467536
score: -4

http://stackoverflow.com/a/48345036
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48333189
type: AcceptedAnswer
has body: You can try qs.values('your_choice').annotate(dcount=Count('your_choice'))
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48333189

http://stackoverflow.com/q/48468069
tagged with: ember-data
has answer: http://stackoverflow.com/a/48519607
tagged with: ember.js
tagged with: django
tagged with: python
type: UnansweredQuestion
has title: Read String Array in Django API
score: 0
has comment: http://stackoverflow.com/comment/83933141
has body: I have EmberJS front-end which calls Django REST API. I am passing string array from front-end to the API as shown below: Back-end Request http://localhost:8000/api/v1/User/search/?active=true&amp;city%5B%5D=newyork&amp;city%5B%5D=chicago&amp;city%5B%5D=boston HTML Decoded http://localhost:8000/api/v1/User/search/?active=true&amp;city[]=newyork&amp;city[]=chicago&amp;city[]=boston Some how I am not able to get rid of the extra %5B%5D (which is square brackets) from this request as EmberJS automatically adds that as the parameter is passed as string array. I searched over several forums but did not get a solution for it. How to read the string array (City parameter) in Django API and get all passed values from EmberJS front-end?
answer count: 1
tagged with: ember-cli
linked to: http://stackoverflow.com/q/2602043
type: Question

http://stackoverflow.com/comment/83774375
comment on: http://stackoverflow.com/a/48392972
has text: Thanks, i edited it, can you see my last comment on the answer above? I commented about what i understand of it, could you say if i'm correct?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48414370
type: AnsweredQuestion
score: 1
has body: Please can someone help me with this, I am trying to find the average value of the values from B2:B1500 which was extracted from excel into python environment but i am stuck. This is the code i have written so far. wb=xl.load_workbook("J:/Data/T0444CH1.xlsx") type(wb) ws = wb.active tuple(ws['B2':'B1500']) for rowOfCellObjects in ws['B2':'B1500']: for cellObj in rowOfCellObjects: def avg(cellObj): return float(sum(cellObj))/len(cellObj) average = sum(cellObj)/len(cellObj) This is the error i am getting average = sum(cellObj)/len(cellObj) TypeError: 'Cell' object is not iterable
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83818612
has comment: http://stackoverflow.com/comment/83818616
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48414483
has title: Determining average values from excel sheet in python
has answer: http://stackoverflow.com/a/48414483
tagged with: python
tagged with: excel

http://stackoverflow.com/a/48488024
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48487936
has body: The culprit is the fact that you write: while x &lt; 2*x: Since x &gt; 0, that relation will always be False, you do not compare the new x with the old x, you compare the new x with twice the new x. We can solve this effectively by using a variable x0 that store the initial amount: def main(): x = x0 = eval(raw_input("Initial Principal: ")) y = eval(raw_input("Interest rate: ")) count = 0 while x &lt; 2*x0: x = x * (1 + y) count = count + 1 print (x) print (count) main() But there are still some problems with the code. For example you use eval. Do not use eval unless you absolutely have to: now a person can enter any type of Python code, also code that will break the system. Use float(..) instead to convert a string to an int: def main(): x = x0 = float(raw_input("Initial Principal: ")) y = float(raw_input("Interest rate: ")) count = 0 while x &lt; 2*x0: x = x * (1 + y) count = count + 1 print (x) print (count) main() But now the code is still inefficient. There exists a fast way to calcuate the number of years using logarithms: from math import log, ceil, pow def main(): x = x0 = float(raw_input("Initial Principal: ")) y = float(raw_input("Interest rate: ")) count = ceil(log(2.0, y+1.0)) newx = x * pow(1.0+y, count) print (newx) print (count)
answers question: http://stackoverflow.com/q/48487936
score: 3
upvote count: 3

http://stackoverflow.com/comment/83909790
comment on: http://stackoverflow.com/q/48458485
type: Comment
type: QuestionComment
has text: look-up in dictionaries is constant-time (`O(1)`) so I do not think you can optimize this further.
score: 0

http://stackoverflow.com/a/48464976
answers question: http://stackoverflow.com/q/48463647
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/83927161
has comment: http://stackoverflow.com/comment/83925951
has body: It's difficult to tell for sure without more details (such as seeing your code, knowing which gym environments you're training on, CPU utilization, hyperparam values, ...). Some possible reasons: Low batch size The step() function of the environment will still be running on your CPU, if that part takes a lot of time your GPU will be sitting idle for a while every iteration The same as above counts for all kinds of other code in every iteration of your training loop (such as tracking results, storing stuff in replay buffer, fetching stuff from replay buffer) EDIT after code was added to the question: After briefly inspecting the code, I suspect the easiest way to increase GPU utilization will be to reduce the training_interval parameter's value from 4 to, for example, 1. Basically, all the tensorflow-based code will be running on GPU (should be at least), and all the other code is going to be on CPU. In iterations where you do not train, this means that only the forwards-pass through the network to compute the Q-values runs on GPU, and all other code is on CPU. In the iterations where you do train, you'll have much more code running on GPU: the additional forwards pass with samples from the replay buffer, and the matching backwards pass for updating the network's parameters. So, if you want to increase GPU utilization, you'll want to do so by increasing how often you run the code that actually runs on GPU. Apart from that, I think it's also possible to move some of the computations you currently do outside of Tensorflow into Tensorflow (and therefore move them from CPU to GPU). For example, you do the epsilon-greedy action selection outside of Tensorflow, whereas the OpenAI Baselines DQN implementation does that within Tensorflow.
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83902917
score: 0
type: Comment
type: QuestionComment
has text: @KlausD. I think regular expression may be overkill here. Besides, could you show some code?
comment on: http://stackoverflow.com/q/48454826

http://stackoverflow.com/q/48372419
downvote count: 0
favorite count: 0
type: Question
has title: Conditional operations on a list of dictionaries in Python
has body: I'd like to sum the ages of all people in this list of dictionaries, based on a condition on another key (e.g. Gender == 'male'): list_of_dicts= [ {"Name": "Ethan", "Gender": "male", "Age": 11}, {"Name": "Nathan", "Gender": "male", "Age": 6}, {"Name": "Sophie", "Gender": "female", "Age": 14}, {"Name": "Patrick", "Gender": "male", "Age": 11} ] The following code accomplishes it, but I wonder if there is a more Pythonic/compact way to do it? Maybe something like an SQL query for list of dictionaries? total_male_age = 0 for dict in list_of_dicts: if dict.get("Gender") == "male": total_male_age = total_male_age + dict.get("Age") #total_male_age = 28
accepted answer: http://stackoverflow.com/a/48372438
linked to: http://stackoverflow.com/q/27905965
has answer: http://stackoverflow.com/a/48372438
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/47789
upvote count: 3
score: 3
tagged with: http://stackoverflow.com/tag/json
answer count: 1

http://stackoverflow.com/comment/83958911
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48482945
has text: Why are you trying to call `_usage` and `__usage` if your method's name is `usage`?

http://stackoverflow.com/a/48341767
has comment: http://stackoverflow.com/comment/83672849
downvote count: 0
has body: You should correctly install B/C/D files in the python path. Alternatively you can use the PYTHONPATH environmental variable: child_process = subprocess.Popen(['python', 'A.py'], env={'PYTHONPATH': '/path/to/the/directory'}) Where /path/to/the/directory is the path to the directory containing B, C and D. Depending on what A.py does you may need to pass also some more of the environment. This can be achieved by either: setting the env variable in the parent process and let the child process inherit it: import os os.environ['PYTHONPATH'] = '/path/...' Popen(['python', 'A.py']) # by default it inherits parent env or copy the parent environment: new_env = dict(os.environ) # make a copy new_env['PYTHONPATH'] = '/path/...' Popen(['python', 'A.py', env=new_env) Note: using shell=True is a security hazard. Also it is useless and less efficient. you should avoid it and pass the command line as a list of strings.
has comment: http://stackoverflow.com/comment/83693000
type: Answer
has comment: http://stackoverflow.com/comment/83740219
has comment: http://stackoverflow.com/comment/83775943
has comment: http://stackoverflow.com/comment/83672719
has comment: http://stackoverflow.com/comment/83671331
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48341612

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/48447371
tag name: multi-gpu
tags question: http://stackoverflow.com/q/48369473

http://stackoverflow.com/comment/83919711
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48463108
has text: From http://mathworld.wolfram.com/IdentityElement.html "The identity element I (also denoted E, e, or 1) of a group or related mathematical structure S is the unique element such that Ia=aI=a for every element a in S. The symbol "E" derives from the German word for unity, "Einheit." An identity element is also called a unit element." So, 1 it's a notation in this case, not the number 1... Or am I wrong?
type: Comment

http://stackoverflow.com/a/48701185
type: AcceptedAnswer
has body: There is no definite answer to this. The current trend is not do feature selection and let the classifier decide which features to use. Take current image datasets for example which also have 1000+ features (depending on the image resolution). They are fed to a CNN usually without any preprocessing. However, this is not generally true. If for example you assume to have a lot of correlations in the data, feature selection might help.
score: 0
accepted answer of: http://stackoverflow.com/q/48335994
type: Answer
answers question: http://stackoverflow.com/q/48335994

http://stackoverflow.com/comment/83690410
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48351742
has text: You could create a list of paths to the images to be overlaid and then process the list. You could even a a list-of-lists to perform batch processing if you wished.
score: 0

http://stackoverflow.com/q/48397608
has comment: http://stackoverflow.com/comment/83784397
upvote count: 4
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/48397804
has comment: http://stackoverflow.com/comment/83787175
has answer: http://stackoverflow.com/a/48397804
downvote count: 0
has title: Trying to extend AbstractUser to create multiple user types in Django
has comment: http://stackoverflow.com/comment/83784442
accepted answer: http://stackoverflow.com/a/48954256
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48954256
has comment: http://stackoverflow.com/comment/83787390
has comment: http://stackoverflow.com/comment/83786593
tagged with: django
tagged with: python
score: 4
has body: So I have been searching all around the internet for a full example of how to user AbstractUser when u have at least 2 different models. Didn't find anything conclusive.. at least that would work on latest version of Django (2.0.1). I have 2 models, teacher and student, and registration needs to be different. Besides username, email, name and surname, I need for example, for the student, to upload a profile picture, email, phone, student_ID. And for teacher, bio, academic title and website. Did I start good ? What is the right approach ? class Profile(AbstractUser): photo = models.ImageField(upload_to='students_images') email = models.EmailField() phone = models.CharField(max_length=15, ) class Student(Profile): student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) def __str__(self): return self.name class Teacher(Profile): academic_title = models.CharField(max_length=30) bio = models.TextField() website = models.URLField(help_text="E.g.: https://www.example.com", blank=True)
has comment: http://stackoverflow.com/comment/83786448

http://stackoverflow.com/q/48428250
favorite count: 0
has body: In Python with openpyxl I'd like to change the active cell when the user opens the spreadsheet. This produces 'A1': print("Active Cell: " + WorkSheetOne.sheet_view.selection[0].activeCell) This produces an error when the file is opened (Corrupted file): WorkSheetOne.sheet_view.selection[0].activeCell = 'A4' How can I set the active/selected cell to something other than A1?
type: Question
score: 9
has answer: http://stackoverflow.com/a/77522889
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51388010
answer count: 5
has title: Python openpyxl How to SET the active or selected cell
tagged with: openpyxl
accepted answer: http://stackoverflow.com/a/48430754
downvote count: 0
has answer: http://stackoverflow.com/a/48430754
type: AnsweredQuestion
upvote count: 9
possible better answer: http://stackoverflow.com/a/75237623
tagged with: python
has answer: http://stackoverflow.com/a/75165056
has answer: http://stackoverflow.com/a/75237623

http://stackoverflow.com/q/48357619
has comment: http://stackoverflow.com/comment/83701920
has answer: http://stackoverflow.com/a/48358087
has comment: http://stackoverflow.com/comment/83701972
has comment: http://stackoverflow.com/comment/83701983
answer count: 3
has answer: http://stackoverflow.com/a/48358461
upvote count: 2
has comment: http://stackoverflow.com/comment/83701992
downvote count: 3
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83702013
has answer: http://stackoverflow.com/a/48357682
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83701978
has title: Removing from a string all the characthers included between two specific characters in Python
tagged with: python
score: -1
has body: What's a fast way in Python to take all the characters included between two specific characters out of a string?
tagged with: regex

http://stackoverflow.com/comment/83793672
has text: You can try downsizing the resolution of image before sending it to PCA. That will decrease your features and may help the knn.
score: 0
comment on: http://stackoverflow.com/q/48402337
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48387318
tagged with: pandas
has answer: http://stackoverflow.com/a/48393244
tagged with: python
has comment: http://stackoverflow.com/comment/83762891
tagged with: vector
type: AnsweredQuestion
score: 0
has title: Pandas adding calculated vectors into df
has comment: http://stackoverflow.com/comment/83762652
has comment: http://stackoverflow.com/comment/83762525
has comment: http://stackoverflow.com/comment/83763163
answer count: 1
has body: my goal is to add formula based vectors to my following df: Day Name a b 1 2 x1 x2 1 ijk 1 2 3 3 0 1 2 mno 2 1 1 3 1 1 outcome: Day Name a b 1 2 x1 x2 y1 y2 z1 z2 1 ijk 1 2 3 3 0 1 (1*2)+3 (1*2)+3 (1+2)*(3*1+0*1) (1+2)*(3*2+1*2) 2 mno 2 1 1 3 1 1 (2*1)+1 (2*1)+3 (2+1)*(1*1+1*1) (2+1)*(3*2+1*2) This is my tedious approach: df[y1] = df[a]*df[b]+df[1] #This is y1 = a*b+value of column 1 df[y2] = df[a]*df[b]+df[2] #This is y2 = a*b+value of column 2 if column 3 and x3 were added in then: y3 would be y3 = a*b+value of column 3, if column 4 and x4 were added in then: y4 = a*b+value of column 4 and so on... df[z1] = (df[a]+df[b])*(df[1]*1+df[x1]*1) The "1" here is from the column name 1 and x1 #z1 = (a+b)*[(value of column 1)*1+(value of column x1)*1] df[z2] = (df[a]+df[b])*(df[1]*2+df[x1]*2) The "2" here is from the column name 2 and x2 #z2 = (a+b)*[(value of column 2)*2+(value of column x2)*2] if column 3 and x3 were added in then: z3 = (a+b)*[(value of column 3)*3+(value of column x3)*3] and so on This works fine; however, this will get tedious if there are more columns added in. For example, it might get "3 4,... x3 x4,..." I'm wondering if there's a better approach to this using a loop maybe? Many thanks :)
accepted answer: http://stackoverflow.com/a/48393244
type: Question

http://stackoverflow.com/comment/83712690
has text: Error : 'numpy.float64' object is not iterable
comment on: http://stackoverflow.com/q/48362903
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48344278
score: 2
upvote count: 2
downvote count: 0
has body: Hopefully your prize function yields next prize so I'll simulate it here: import pandas as pd df = pd.Dataframe({'Name': list('abcd'), 'Rank': range(1,5), 'Status': [0,1,1,0]}) prizes = iter([100,50,25,10]) df['Prize'] = df['Status'].apply(lambda x: next(prizes) if x else 0) df #Name Rank Status Prize #a 1 0 0 #b 2 1 100 #c 3 1 50 #d 4 0 0 EDIT Based on your comment you need: df['Prize'] = df.apply(lambda x: Prize(x['Rank']) if x['Status'] else 0, axis=1)
answers question: http://stackoverflow.com/q/48344027
has comment: http://stackoverflow.com/comment/83674283
has comment: http://stackoverflow.com/comment/83674310
type: Answer

http://stackoverflow.com/comment/83666645
type: Comment
comment on: http://stackoverflow.com/q/48336521
score: 0
has text: I meant it occurs when typing commands in Eclipse console, not in normal debug run.
type: QuestionComment

http://stackoverflow.com/q/48404120
has title: pandas: add new column computed from row and partner row
answer count: 4
has comment: http://stackoverflow.com/comment/83796902
has body: I have data that are paired such that rows come in pairs, their id named a and b: &gt;&gt;&gt; df = pd.DataFrame([['1a', 'A', 5], ['1b', 'B', 10], ['2a', 'C', 20],['2b', 'D', 4]], columns=['id', 'name', 'count']) &gt;&gt;&gt; df id name count 0 1a A 5 1 1b B 10 2 2a C 20 3 2b D 4 1a and 1b are a pair, and 2a and 2b are another pair. I want to create a new column rel_count in which the value is the row's own count divided by its partner's count: id name count rel_count 0 1a A 5 0.5 1 1b B 10 2.0 2 2a C 20 5.0 3 2b D 4 0.2 What is the best way to do this in pandas?
has answer: http://stackoverflow.com/a/48405617
score: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48404597
has answer: http://stackoverflow.com/a/48412953
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48406308
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48345857
has body: Is the batchnorm momentum convention (default=0.1) correct as in other libraries e.g. Tensorflow it seems to usually be 0.9 or 0.99 by default? Or maybe we are just using a different convention?
downvote count: 0
tagged with: neural-network
answer count: 1
has comment: http://stackoverflow.com/comment/83768149
favorite count: 0
type: Question
score: 14
tagged with: python
has title: BatchNorm momentum convention PyTorch
tagged with: batch-normalization
tagged with: deep-learning
upvote count: 14
has answer: http://stackoverflow.com/a/48950072
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/48950072
type: AnsweredQuestion

http://stackoverflow.com/comment/83674492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48344252
has text: What are you trying to achieve?
score: 0

http://stackoverflow.com/q/48446684
has comment: http://stackoverflow.com/comment/83886012
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48451176
accepted answer: http://stackoverflow.com/a/48451176
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: http://stackoverflow.com/tag/html
has title: How do I Access Specfic Elements of Webpage for Import into Pandas
tagged with: python
has body: I have this code that scrapes a website for menu information. I have got it working so that it gets the text from this week menu items: #Weekly Breakfast Menu import requests from bs4 import BeautifulSoup page = requests.get("https://trinity.campusdish.com/Commerce/Catalog/Menus.aspx?LocationId=1031&amp;PeriodId=1471&amp;MenuDate=&amp;Mode=week") soup = BeautifulSoup(page.content, 'html.parser') seven_day=soup.find(id="WebPartManager1_wpMenuDetails") menu_items=seven_day.find_all(class_="menu-details") week=menu_items[0] seven_days = week.find("div",class_="menu-details-week").get_text() print(seven_days) Currently, it prints the data in a long list that contains the date, meal station, and meal name. I'm stuck because I can't figure out a way to separate these values to make a pandas data frame with these three headers. I tried this code to access the days of the week and see if it prints but I keep getting this: AttributeError: 'NoneType' object has no attribute 'get_text' My non-working code to print the days looks like this: day = week.find("h2", class_="menu-details-day").get_text() print(day) Thanks, Chris
type: AnsweredQuestion

http://stackoverflow.com/comment/83955111
score: 0
type: AnswerComment
has text: @SnivyDroid Same thing. `var.set(2)`.
comment on: http://stackoverflow.com/a/48478816
type: Comment

http://stackoverflow.com/a/48331587
answers question: http://stackoverflow.com/q/48331501
has comment: http://stackoverflow.com/comment/83649866
type: Answer
has body: You can use clip with array indexing. a = np.array([0, 0, 0, 3, 7, 3, 0, 0, 0]) a[3:7] = a[3:7].clip(min=5) &gt;&gt;&gt; a array([0, 0, 0, 5, 7, 5, 5, 0, 0])
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/a/48410495
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48398923
has comment: http://stackoverflow.com/comment/83820878
score: 5
upvote count: 5
has body: Maybe I finally see the point of this question. Of course we cannot explain pyplot here, because that is much too complicated and would require a complete tutorial (which btw do exist). But we can have a look at how pyplot would work as a module in a very simplified manner. So let's create myplot, the ultimative console plotting library. ;-) The module myplot could look as follows. It has two functions, scatter and show and two variables, figures and plot. plot would store our coordinate system to plot to. figures would store the figures we create. plot = """ ^ | | | | | +-----------&gt;""" figures = [] def scatter(X,Y): thisplot = list(plot[:]) for x,y in zip(X,Y): thisplot[1+14*(6-y)+x] = "*" thisplot = "".join(thisplot) figures.append(thisplot) def show(): for fig in figures: print(fig) Calling scatter creates a new figure from plot and stores it in the figures list. Calling show takes all figures from that list, and shows them (prints them in the console). So using myplot would look exactly like the example above. import myplot as mlt mlt.scatter([2,3,4,5,6,8],[2,5,4,4,3,2]) mlt.show() Creating the output: ^ | * | ** | * | * * | +-----------&gt;
answers question: http://stackoverflow.com/q/48398923
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83832614
type: QuestionComment
comment on: http://stackoverflow.com/q/48421506
has text: My god. Thanks. I guess i need a vacation...
score: 0
type: Comment

http://stackoverflow.com/comment/83979537
comment on: http://stackoverflow.com/q/48344974
has text: That's what I'm saying. I ran the code, and it always gives 0. My feeling is that tf.reduce_sum() is somehow avoiding falling out of precision. If you replace `tf.reduce_sum(x)` with `x[0]+x[1]+x[2]`, then you get `nan`. I'm using tensorflow v1.3.0. How about you?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48447709
has comment: http://stackoverflow.com/comment/83887783
tagged with: python
tagged with: python-requests
linked to: http://stackoverflow.com/q/55872164
score: 16
has comment: http://stackoverflow.com/comment/83887788
favorite count: 0
type: AnsweredQuestion
has body: I am coding a web scraper for the website with the following Python code: import requests def scrape(url): req = requests.get(url) with open('out.html', 'w') as f: f.write(req.text) It works a few times but then an error HTML page is returned by the website (when I open my browser, I have a captcha to complete). Is there a way to avoid this “ban” by for example changing the IP address?
accepted answer: http://stackoverflow.com/a/48447938
has comment: http://stackoverflow.com/comment/83887890
has comment: http://stackoverflow.com/comment/83888088
possible better answer: http://stackoverflow.com/a/63095099
has answer: http://stackoverflow.com/a/70793831
has answer: http://stackoverflow.com/a/68451924
has answer: http://stackoverflow.com/a/63095099
has title: Python requests, change IP address
upvote count: 18
tagged with: http
answer count: 4
type: Question
downvote count: 2
has answer: http://stackoverflow.com/a/48447938

http://stackoverflow.com/comment/83666245
comment on: http://stackoverflow.com/a/48337509
type: AnswerComment
score: 1
has text: `np.r_[0:3, 15:16, 100:103]` should also work.
type: Comment

http://stackoverflow.com/comment/83719624
type: Comment
type: QuestionComment
score: 0
has text: Yes, I want to result in a new column
comment on: http://stackoverflow.com/q/48366506

http://stackoverflow.com/comment/83953073
comment on: http://stackoverflow.com/q/48480053
has text: Just do all operations on the whole array, not using vectorize! (like x += 1)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83862041
has text: Can you show the code you wrote using `ast.literal_eval`? It sounds like you didn't use it properly, so you were still iterating over the original string.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48435051
type: QuestionComment

http://stackoverflow.com/comment/83920115
type: Comment
type: QuestionComment
has text: Put `set_trace()` In your source code. It will pause execution at that line and let you debug. It's a python version of the original Gnu Project Debugger, so the interface might be a bit old fashioned. If you are using a full featured IDE, there might be a built-in debugger there, if you prefer more visual tools.
comment on: http://stackoverflow.com/q/48463349
score: 0

http://stackoverflow.com/q/48379702
tagged with: python
tagged with: indexing
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83745944
downvote count: 2
has answer: http://stackoverflow.com/a/48380155
has body: Simple indexing question. I have the following list object named as xlist. It could also be a df. [ result 6221 0.974214 6220 0.973909 6222 0.973447 3032 0.973444 3033 0.973387] I would like to get the index 'value' of a particular row (or is it column as a list?). So for example: I would like to specify row 2 and get 6222. Am confused as to why this is not straightforward (to me anyway).
answer count: 1
has title: Return index value of particular row in python dataframe OR list
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83755073
score: -2
accepted answer: http://stackoverflow.com/a/48380155
has comment: http://stackoverflow.com/comment/83745988

http://stackoverflow.com/comment/83926224
comment on: http://stackoverflow.com/a/48466336
score: 0
has text: @rohegde7 Nothing, really. Personal preference. I'll typically default to `[]` for throwaway iterables like that, but use `()` if you like. For trivial situations like this, it's pretty rare that it will make a difference. By "rare" I mean that I can't think of any such situations off the top of my head.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83676054
type: Comment
type: QuestionComment
has text: The `At least` you are looking for is `>`.
score: 0
comment on: http://stackoverflow.com/q/48344997

http://stackoverflow.com/a/48484637
answers question: http://stackoverflow.com/q/48482373
score: 1
has comment: http://stackoverflow.com/comment/83962616
has body: yes definitely agree with @joran-beasley fastest and advanced technique for this is Memoization technique, though it is complicated. Memoization avoids computing already computed values by storing them, here we can store it in the dictionary with its positions as keys. I learnt this from a very old answer in SO https://stackoverflow.com/a/18172463/5334188
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83980677
has comment: http://stackoverflow.com/comment/83963680
downvote count: 0

http://stackoverflow.com/comment/83883445
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48428533
type: Comment
has text: Unfortunately, Stack Overflow references use of `_getexif()` in ["In Python, how do I read the exif data for an image?"](https://stackoverflow.com/questions/4764932/in-python-how-do-i-read-the-exif-data-for-an-image#4765242) Using ExifRead seems to be the more robust approach despite the accepted best answer to the other post.

http://stackoverflow.com/q/48339497
has answer: http://stackoverflow.com/a/48339617
type: Question
duplicate of: http://stackoverflow.com/q/240178
answer count: 2
has answer: http://stackoverflow.com/a/48339556
has body: I have a list of dictionaries: dicty = [defaultdict(list)] * (2) dicty [defaultdict(list, {}), defaultdict(list, {})] Now I want to know how to index into these dictionaries? I have tried: dicty[0][0].append('abc') dicty [defaultdict(list, {0: ['abc']}), defaultdict(list, {0: ['abc']})] But as you can see that it appends in both the dictionaries. I want to learn how to append into an individual dictionary.
linked to: http://stackoverflow.com/q/3459098
has comment: http://stackoverflow.com/comment/83664242
has title: Index dictionaries inside a list
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/48339556
has comment: http://stackoverflow.com/comment/83664417
has comment: http://stackoverflow.com/comment/83664137
duplicate of: http://stackoverflow.com/q/3459098
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48339617

http://stackoverflow.com/a/69887628
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48469655
has body: I've tried the example provided by @theGtknerd to no avail. After hours of debugging, I got this example working with a few lines. import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk import sys class GUI: def __init__(self): window = Gtk.Window() window.connect('destroy', Gtk.main_quit) textview = Gtk.TextView() # (drag behaviour, targets (leave empty), action) textview.drag_dest_set(Gtk.DestDefaults.DROP, [], Gdk.DragAction.COPY) # add the ability to receive URIs (e.g. file paths) textview.drag_dest_add_uri_targets() textview.connect("drag-data-received", self.on_drag_data_received) window.add(textview) window.show_all() def on_drag_data_received(self, widget, drag_context, x,y, data,info, time): print(data.get_uris()) # (context, success, delete_from_source, time) Gtk.drag_finish(drag_context, True, False, time) # always call Gtk.drag_finish to receive as suggested by documentation def main(): GUI() Gtk.main() if __name__ == "__main__": sys.exit(main()) Own observations: Any Gtk.Widget can be enabled to receive data with .drag_dest_set() but needs to set the targets either here or calling methods that adds them like .drag_dest_add_uri_targets(). Gtk.TextView seems to have a bug where signal drag-data-received repeats twice after the very first call, thus the handler gets called twice. In the pair of calls, the first one contains new data and the second one contains the previous data.
type: Answer

http://stackoverflow.com/comment/83970123
score: 0
has text: Yes, it work without `self.handle_message`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48479602

http://stackoverflow.com/comment/84117538
type: AnswerComment
has text: @ApeDinky, Placing the json objects into an array does not *save the data*, but to get the data into an array, instead of object as in my example, you would write: `$arr = json_decode($json, true);`. And your python script, shows that you did indeed *print them out on the index.php page*. What do you think that stuff is between the ` ` tag?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48451572

http://stackoverflow.com/comment/83691499
score: 1
has text: @Cedric: if you replace `"0.0"` with `""`, you might as well not use `textvariable` at all. The _only_ reason to use `textvariable` is if you want to access it later. Otherwise it serves no purpose whatsoever
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48352197

http://stackoverflow.com/a/48412457
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48412362
type: AcceptedAnswer
has body: largest = {} list = ['a', 'b', 'c'] for value in values: rank = value['rank'] for x in list: if x in value['name']: largest[x] = max(largest.get(x, rank), rank)
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48412362

http://stackoverflow.com/q/48422744
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83836270
accepted answer: http://stackoverflow.com/a/48461401
has answer: http://stackoverflow.com/a/48461401
downvote count: 0
has comment: http://stackoverflow.com/comment/83835132
tagged with: python
has body: I was just following along an example given in a book to illustrate the Python shelve module on macOS High Sierra. As shown below only two small tuples of short strings get stored in a shelf. And as you can see in the very last line, the resulting file is 16 Megabyte large. The resulting file only gets that large when I try the example on macOS High Sierra with the Python version installed through Homebrew (either 3.6.4 or 2.7.14). If I run it on a Linux host or with the pre-installed Python version (2.7.10) or with Python 3.6.4 installed through the official installer in macOS, the resulting addresses file is just a few Kilobyte large, just as reported by others in the comments (thanks!). ~/tmp&gt; rm addresses ~/tmp&gt; python3 Python 3.6.4 (default, Jan 6 2018, 18:43:09) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin [...] &gt;&gt;&gt; import shelve &gt;&gt;&gt; book = shelve.open("addresses") &gt;&gt;&gt; book['flintstone'] = ('fred', '555-1234', '1233 Bedrock Place') &gt;&gt;&gt; book['rubble'] = ('barney', '555-4321', '1235 Bedrock Place') &gt;&gt;&gt; book.close() &gt;&gt;&gt; ~/tmp&gt; ll total 32768 -rw-r--r-- 1 moritz staff 16M Jan 24 13:05 addresses
score: 4
has comment: http://stackoverflow.com/comment/83835055
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83834992
has comment: http://stackoverflow.com/comment/83836192
has title: Why is a Python shelf file containing very little data so large on macOS?
has comment: http://stackoverflow.com/comment/83843176
has comment: http://stackoverflow.com/comment/83836548
answer count: 1
has comment: http://stackoverflow.com/comment/83844477
has comment: http://stackoverflow.com/comment/83834954
tagged with: shelve
has comment: http://stackoverflow.com/comment/83844067
has comment: http://stackoverflow.com/comment/83835078
favorite count: 0
tagged with: macos-high-sierra
type: Question
upvote count: 4

http://stackoverflow.com/q/48406389
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/83801626
has comment: http://stackoverflow.com/comment/83801805
downvote count: 1
tagged with: namespaces
has comment: http://stackoverflow.com/comment/83801960
has comment: http://stackoverflow.com/comment/83801846
accepted answer: http://stackoverflow.com/a/48406573
favorite count: 0
type: Question
has body: I want a class in Python with an interface like the following: import myclass client = myclass.Client("user", "password") client.users.create("user1") client.posts.create("user1", "Hello, World!") Note that instead of just create_user or create_post, I want to specify the method using two dots: users.create / posts.create I want this particular interface to mimic an HTTP API I'm trying to work with (which has endpoints like "/api/users/create" and "/api/posts/create") If I define my class as follows in myclass.py: class Client(object): def __init__(self, user, pass): self.user = user self.pass = pass Then how do I create these dot-namespaced methods? My first thought is to create subclasses like so: class Client(object): def __init__(self, user, pass): self.user = user self.pass = pass self.users = ClientUserAPI() self.posts = ClientPostAPI() class ClientUserAPI(object): def create(self): # Do some cURL magic class ClientPostAPI(object): def create(self): # Do some cURL magic However if I do this, then I run into one of two problems (one serious, the other just philosophical / ideological) If ClientUserAPI extends "Client" then the __init__ method creates an infinite loop If ClientUserAPI extends "object" then it won't directly have access to the self.user and self.pass variables. This means I must create __init__ methods on both of the helper classes which do nothing but assign self.user and self.pass. This is redundant not only in code, but also in memory Is there a better solution?
has answer: http://stackoverflow.com/a/48406573
has comment: http://stackoverflow.com/comment/83802279
has title: How to "namespace" methods in Python class
tagged with: python
tagged with: class
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/51081693
score: 0
answers question: http://stackoverflow.com/q/48363539
type: Answer
has body: Try this one will work: year = driver.find_elements_by_xpath('//*[@class = 'zsg-table yui3-toggle-content-minimized']/tbody/tr[1]/td[1]') If year: year= year[0].text.strip()

http://stackoverflow.com/q/48407365
has body: I am having issues trying to create a calendar event using the Google Calendar API with an AWS Lambda function call. The AWS CloudWatch logs are not giving me a whole lot of information to work with for debugging. I am very new to working with the Google API and can't figure out what is going wrong with my code. The code I am using is here: from __future__ import print_function from oauth2client import service_account from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage import httplib2 import boto3 import json import logging import requests def lambda_handler(event, context): logger = logging.getLogger() logger.setLevel(logging.INFO) ses = boto3.client('ses') email_address = 'myemail@gmail.com' # change it to your email address SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE = 'aws-iot-f3edea2d0394.json' credentials = service_account.ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('calendar', 'v3', http=http) calendarId = 'myemail@gmail.com' event = { "summary": "aws iot test", "location": "etc", "description": "aws iot test - pushed from button", "start": { "dateTime": "2018-01-31T09:00:00-07:00", "timeZone": "America/Los_Angeles" }, "end": { "dateTime": "2018-01-31T17:00:00-07:00", "timeZone": "America/Los_Angeles" } } event = service.events().insert(calendarId='primary', body=event).execute() The calendar event is not being created, and I cannot figure out why. The only information I am getting from the AWS CloudWatch logs has the last event here: [INFO] 2018-01-23T17:09:28.116Z 29b2e36a-0060-11e8-8c9e-1725945b009e URL being requested: POST https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json This is not very informative. Can anyone help out with maybe getting AWS to give me more information, or perhaps point out what…
type: Question
type: UnansweredQuestion
tagged with: google-calendar-api
tagged with: python
has comment: http://stackoverflow.com/comment/135072555
has answer: http://stackoverflow.com/a/48409735
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/45313376
downvote count: 0
has title: AWS - Calling Google Calendar API, Python
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48484226
score: 0
has body: You can use global keyword to use the global variable. Following points to keep in mind: Use global keyword only when you are changing the global variable value. You can use global variable if only reading just by using the variable name (global variable definition not required here). Example: var = 10 def change_var(): global var var = 2 return var def read_var(): print "Variable is:",var Hope this helps.
type: Answer
answers question: http://stackoverflow.com/q/48484166

http://stackoverflow.com/q/48460337
has comment: http://stackoverflow.com/comment/83913655
has comment: http://stackoverflow.com/comment/83916028
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83913503
tagged with: flask
has title: can't serve public static file flask
linked to: http://stackoverflow.com/q/20646822
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/20646822
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48460864
has body: app = Flask(__name__, static_path='', static_url_path=None, static_folder='templates/assets', template_folder='templates', instance_path=None, instance_relative_config=False) app.debug = False @app.route("/", methods=['GET']) def index(): return render_template("index.html") @app.route('/results/&lt;path:filename&gt;', methods=['GET']) def serve_static(filename): root_dir = os.path.dirname(os.getcwd()) #for windows too return app.send_static_file(os.path.join('results', filename).replace('\\','/')) What do I do wrong? http://127.0.0.1:5000/assets/result.csv this gives me an error: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
type: UnansweredQuestion

http://stackoverflow.com/comment/83798391
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48400655
score: 0
has text: @MattiLyra: You were right, apologies for the mistake. I've updated the code and it should run well now. Can you try running it using the code here https://github.com/hackintoshrao/blog-posts/blob/6af0f249b74c759b60d65fdb529d066004d68ba1/Neural%20Nets/Building%20Neural%20Nets%20From%20Scratch/Part%202/code/gradient_descent_visualization.ipynb

http://stackoverflow.com/q/48371969
score: 1
upvote count: 1
downvote count: 0
has title: Traversing an XML tree without namespace in Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48373909
accepted answer: http://stackoverflow.com/a/48373909
tagged with: python
has answer: http://stackoverflow.com/a/48372037
has body: I am parsing a large XML file, which essentially contains a table. The nodes in the XML don't always have names. Nested deep within several tags is what is basically an HTML-like table with s containing raw (numeric) data within row ( ) tags. Now before I can iterate through to the table there is a whole bunch of metadata tags that I'm not interested in. For instance: <?xml version="1.0" ?> <soap:Envelope xmlns:soap="--ommitted--" xmlns:xsi="--ommitted--"> <soap:Body> <FetchReportResponse xmlns="URL1"> <FetchReportResult xmlns="URL2"> <REPORT> <TITLE>CROSS VISITING REPORT <SUBTITLE/> <SUMMARY> --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- --ommitted-- I am new to XML parsing so I'm following this. I have the following code to read and XML file and create an ElementTree object. import xml.etree.ElementTree as ET tree = ET.parse('./../filename.xml') print(root.find("./")) This understandably prints the following: <Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at 0x00000230CAC23318> However, when I try to use the XPath convention to traverse it from here on, I'm unable to. For instance, print(root.find("./Body")) prints None, even though is clearly nested inside <Envelope>. EDIT: Following Mark Tolonen's answer I was able to get to the Body tag, but how do I get beyond that? More specifically, I want to reach the tag.
possible better answer: http://stackoverflow.com/a/48372037
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/48362041
has comment: http://stackoverflow.com/comment/83788091
has comment: http://stackoverflow.com/comment/83711093
type: Question
has answer: http://stackoverflow.com/a/48400059
accepted answer: http://stackoverflow.com/a/48400059
has body: I have application which scrapes some info from web and then prints the results on GUI as text. Some part of that text is link and i want to bind text to link that user could able to go to the correct link. (every text goes to different page when clicked) but the biggest issue is, that my program scans the web and if it finds the correct info it prints on GUI (tkinter) and because of that i can`t figure out the solution cause otherwise i will write manually functions to bind text to link. So my question is How can i bind text to different links if my program prints new text after some time? There is my code: from tkinter import * import webbrowser class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.Scrol = Scrollbar(self.master) self.Text = Text(self.master, height=50, width=500) self.Scrol.pack(side=RIGHT, fill=Y) self.Text.pack(side=LEFT, fill=X) self.Scrol.config(command=self.Text.yview) self.Text.config(yscrollcommand=self.Scrol.set) self.Text.tag_configure('red', foreground='red') self.Text.tag_configure('blue', foreground='blue') line1 = "This is line 1 with link: " myLink1 = "My_link1" line2 = "This is line 2 with link: link: " myLink2 = "My_link2" self.Text.insert(END, line1 + " ", "red") self.Text.insert(END, myLink1 + "\n", "blue") self.Text.insert(END, line2 + " ", "red") self.Text.insert(END, myLink2 + "\n", "blue") self.master.after(1000, self.more_text) def more_text(self): line3 = "This is line n with link: " my_link3 = "My_link3" self.Text.insert(END, line3 + " ", "red") self.Text.insert(END, my_link3 + "\n", "blue") self.Text.bind('&lt;Button-1&gt;', self.showLink) self.master.after(2000, self.more_text) def showLink(self, event): webbrowser.open('google.com') top = Tk() top.geometry('1000x1000') app = Window(top) top.mainloop()
tagged with: python
has comment: http://stackoverflow.com/comment/83711137
has comment: http://stackoverflow.com/comment/83711225
has comment: http://stackoverflow.com/comment/83711160
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83711336
tagged with: tkinter
has title: How to bind different links to different text tkinter python
answer count: 1

http://stackoverflow.com/q/48348176
has answer: http://stackoverflow.com/a/48348359
accepted answer: http://stackoverflow.com/a/48348359
score: 26
upvote count: 26
tagged with: python
type: AnsweredQuestion
has title: Convert data types of a Pandas dataframe to match another
answer count: 2
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52519634
possible better answer: http://stackoverflow.com/a/52519634
has body: I have two data frames with the same column names but different data types: df1.dtypes order int64 x int64 y int64 df2.dtypes order object x object y object The dataframes are much larger than this, so I would like to capture the names/dtypes of df1 and convert df2 to match.
favorite count: 0
type: Question

http://stackoverflow.com/comment/83797809
comment on: http://stackoverflow.com/a/48404597
type: Comment
score: 0
type: AnswerComment
has text: You can sort it by `df = df.sort_values('id')`

http://stackoverflow.com/comment/83950501
comment on: http://stackoverflow.com/q/48478339
type: Comment
score: 1
type: QuestionComment
has text: Note that `json.load` provides an `object_pairs_hook` keyword argument which you can use to correctly load objects with duplicate keys without suffering data loss.

http://stackoverflow.com/q/48466267
has title: How to map values of different data types in a single line of code from a single line of input in python3?
tagged with: python
has answer: http://stackoverflow.com/a/48466336
score: 3
answer count: 3
has body: Suppose the input is: string integer integer. Now i need to map only the 2nd and 3rd input to integer. name, d, j = input().split() d = int(d) j = int(j) Is this the only way to do it?
upvote count: 3
has answer: http://stackoverflow.com/a/48466539
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48466487
linked to: http://stackoverflow.com/q/10973766
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83995976
comment on: http://stackoverflow.com/q/48439330
type: Comment
type: QuestionComment
has text: @BaileyParker I tried that one but to no avail..
score: 0

http://stackoverflow.com/comment/83891104
score: 0
type: AnswerComment
has text: It is the same if you loop the list you will get single object and you can access in the same way...
comment on: http://stackoverflow.com/a/48448811
type: Comment

http://stackoverflow.com/comment/83764193
type: QuestionComment
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48388232
has text: string.replace() method would do. Here https://www.pythoncentral.io/pythons-string-replace-method-replacing-python-strings/

http://stackoverflow.com/comment/83927621
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48466886
type: Comment
has text: The `\w` class includes many characters that are never found in a hash value.

http://stackoverflow.com/q/48349779
has answer: http://stackoverflow.com/a/48359161
favorite count: 0
type: Question
has body: I am currently working on an Android App using the Python and the Kivy Framework. The majority of the screen's real estate is used by a text_input widget. I would like to resize this text_input when the android soft keyboard pops ups so that the text_input ends right at the top of the keyboard. To accomplish this I tried to use Window.softinput_mode='resize' and when that didn't work, reference the Window.keyboard_height to do my own resize and positioning. As per the documentation and comment in the Window source code I see that both are not supported when using SDL2 on Android (Kivy 1.9 - 1.10). I tested Window.softinput_mode='below_target' which doesn't seem to do anything and Window.softinput_mode='pan' which works but doesn't give me the correct functionality. The last thing I tried is to set Window.softinput_mode='pan' and with a function call that is bound to the on_keyboard event print out the value of Window.top so that if the panning simply shifted the Window location upward, I could use that point of reference to do my positioning and resizing. However the value of Window.top does not apear to change when panning up. The only other stack flow that referenced this issue and gave a working example made use of resize mode which doesn't work using SDL2. Properly resize main kivy window when soft keyboard appears on android Is there any work-around to accomplish this functionality or a different provider than SDL2 that will work well on Android?
tagged with: window-resize
type: UnansweredQuestion
tagged with: pysdl2
has comment: http://stackoverflow.com/comment/83704416
tagged with: python
tagged with: kivy
has title: Resizing Window in Kivy Android App on softkeyboard with SDL2
has comment: http://stackoverflow.com/comment/83694841
linked to: http://stackoverflow.com/q/36770050
score: 2
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83848665
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48428804
type: Comment
has text: @apipota Please mark the question as a duplicate. I'm not sure what there is to explain; the duplicate I linked contains a short explanation and a link to the official docs if for some reason you need more information about replacement functions.

http://stackoverflow.com/a/48481833
has body: From documentation class type(name, bases, dict) With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute. For example, the following two statements create identical type objects: class X(object): a = 1 X = type('X', (object,), dict(a=1)) So yes, I think you have the right idea. type() does create a class but a dynamic form.
has comment: http://stackoverflow.com/comment/83956763
type: Answer
has comment: http://stackoverflow.com/comment/83956879
answers question: http://stackoverflow.com/q/48481492
score: 0

http://stackoverflow.com/a/71045011
has body: Change this line: django.config.urls to: django.conf.urls
answers question: http://stackoverflow.com/q/48375823
type: Answer
score: 0

http://stackoverflow.com/q/48332491
has comment: http://stackoverflow.com/comment/83650707
has title: How to simplify multiple for statements in Python with relational lists
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48332584
has answer: http://stackoverflow.com/a/48332584
has comment: http://stackoverflow.com/comment/83650709
tagged with: python
has body: I'm currently trying to simplify the below Python, because I believe that it's likely very inefficient and I'm doing it the wrong way. Using SQL I would just use some joins, but I'm unsure how to simplify in Python. I'm using a database of politicians, which are dictionaries (legislative body) of areas/memberships/persons (lists) which then contain the individual records (dictionaries). For every single congressional district, I want to print the name of that district, then print the respective representative. These are linked through the memberships table. Is there a more efficient method to conduct this matching? for state in housedata['areas']: print(state['name']) for position in housedata['memberships']: if position['legislative_period_id'] == currentlegislature and state['id'] == position['area_id']: for person in housedata['persons']: if person['id'] == position['person_id']: print(person['given_name'], person['family_name'])

http://stackoverflow.com/comment/83799999
comment on: http://stackoverflow.com/a/48386868
score: 0
type: AnswerComment
has text: Looks like the yum package is an older release and looking for an older relear of python-libs as well. I'm not able to find a `python-devel` package for the `66.el6_8` release for RHEL (found one for CentOS). I believe finding a suitable release will solve this problem.
type: Comment

http://stackoverflow.com/q/48448431
upvote count: 2
has answer: http://stackoverflow.com/a/48686977
score: 2
has body: I spend some frustrating hours to write a simple model export and import with a GANEstimator but I just couldn't get it working. Basically it's a conditional GAN with GANEstimator, the last 4 LOC is the export. The last line throws: ValueError: export_outputs must be a dict and not&lt;class 'NoneType'&gt; I would really appreciate if someone can take a look at this. As I said, I just want to train the model and export it and in another python script, I want to reload the model (rather say the generator) and feed in data somehow. Here is my code: import tensorflow as tf #import tensorflow.contrib.eager as tfe #tfe.enable_eager_execution() tfgan = tf.contrib.gan slim = tf.contrib.slim layers = tf.contrib.layers ds = tf.contrib.distributions import time import datasets.download_and_convert_mnist as download_and_convert_mnist from mnist import data_provider,util import os import matplotlib.pyplot as plt import numpy as np import scipy from common import * MODEL_FILE_NAME = 'cond_garden_experimental' MODEL_SAVE_PATH = os.path.join(MODEL_SAVE_PATH, MODEL_FILE_NAME) IMGS_SAVE_PATH = os.path.join(IMGS_SAVE_PATH, MODEL_FILE_NAME) #constants and variables num_epochs = 2000 batch_size = 32 latent_dims = 64 from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops def _get_shape(tensor): tensor_shape = array_ops.shape(tensor) static_tensor_shape = tensor_util.constant_value(tensor_shape) return (static_tensor_shape if static_tensor_shape is not None else tensor_shape) def condition_tensor(tensor, conditioning): tensor.shape[1:].assert_is_fully_defined() num_features = tensor.shape[1:].num_elements() mapped_conditioning = layers.linear( layers.flatten(conditioning), num_features) print(mapped_conditioning.shape) if not mapped_conditioning.shape.is_compatible_with(tensor.shape): mapped_conditioning = array_ops.reshape( mapped_conditioning, _get_shape(tensor)) return tensor + mapped_conditioning def conditional_discriminator_fn(img, inputs, we…
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83915477
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83891925
has title: Tensorflow TFGAN GANEstimator export model
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83700011
comment on: http://stackoverflow.com/q/48356733
has text: What about `dataset.loc[fraud_indices]` ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83938112
comment on: http://stackoverflow.com/q/48472029
score: 0
type: Comment
type: QuestionComment
has text: If you trying to find the string with the highest number after the last the `.`, you can try this: `max(lst, key = lambda x: int(x.split('.')[-1]))`

http://stackoverflow.com/comment/83799044
comment on: http://stackoverflow.com/a/48362210
has text: I'm not sure what your Flask function is doing or what is returned in `rowTable = DataTables(params, query, columns)` - arrays or objects?. Initially I thought `ColumnDT` was used to build the column definition for Datatables but maybe not. If you are returning an array of objects then use [columns.data](https://datatables.net/reference/option/columns.data) to define your columns and remove the `""` I suggested above. Using objects will allow you to define the checkbox column without having to return data for it.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/55133828
answers question: http://stackoverflow.com/q/48439159
type: Answer
score: 11
upvote count: 11
downvote count: 0
has body: Had this same issue. Solved it by removing both the build versions AND package version (except for necessary package versions such as python=3.6.2 and any others.) The end yml file would look like this in order to be fully cross-platform: name: testenv channels: - esri - scitools - obspy - conda-forge - defaults dependencies: - appnope - libgfortran - pip - python=3.6.2 - wheel - pip: - ipython-genutils - jupyter-client==5.1.0 - jupyter-console - jupyter-core - prompt-toolkit

http://stackoverflow.com/q/48481941
answer count: 1
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: python
tagged with: kivy
accepted answer: http://stackoverflow.com/a/48491462
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48491462
has body: I'm trying to display an image on a button using kivy but in python file. self.add_widget(Button(source=('Image'),pos_hint={"x":0.3, "top":0.3},on_press="Screen")) Can anyone please help?
score: 2
has title: kivy how to display an image on a button with python

http://stackoverflow.com/q/48420022
has comment: http://stackoverflow.com/comment/83829911
has comment: http://stackoverflow.com/comment/83831162
has body: I'am just looking for Is there any particular Ids for files that are stored in a directory If yes how we can fetch that one through python. I have tried this one and i got a dict . But no where I can't see any unique Ids. import os cur = os.getcwd() info = os.stat(cur) print(info.__str__()) I got something like this : os.stat_result (st_mode=33204, st_ino=21511460, st_dev=2049, st_nlink=1, st_uid=1001, st_gid=1001, st_size=378, st_atime=1516787918, st_mtime=1516787918, st_ctime=1516787918) I have referred for st_ino that means inode number.But when I tried with program I observed that also changes some times. If there any such ids are available can we fetch the file with those Ids ? EDIT: As variables hold a id. Am wonder is there any similar one in file system while creating a file.
tagged with: python
linked to: http://stackoverflow.com/q/36092559
has comment: http://stackoverflow.com/comment/83871014
linked to: http://stackoverflow.com/q/4508998
type: Question
has comment: http://stackoverflow.com/comment/83830304
score: 2
has comment: http://stackoverflow.com/comment/83829835
has title: Is there any unique Ids for files that we can fetch through python?
upvote count: 3
has comment: http://stackoverflow.com/comment/83829897
type: UnansweredQuestion
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/83830084
has comment: http://stackoverflow.com/comment/83832723
downvote count: 1
has comment: http://stackoverflow.com/comment/83871023
favorite count: 0
has comment: http://stackoverflow.com/comment/83871039
has answer: http://stackoverflow.com/a/48420423
linked to: http://stackoverflow.com/q/3431825

http://stackoverflow.com/a/48624009
type: Answer
has body: You can subscript your tensor with another tensor in pytorch. Thus if I have: T = torch.from_numpy(np.arange(10)) 0 1 2 3 4 5 6 7 8 9 [torch.LongTensor of size 10] then T[torch.from_numpy(np.array([0, 3, 7]))] 0 3 7 [torch.LongTensor of size 3] So in your case, if you have your logits of shape MBxD, you can do idx = torch.from_numpy(np.array([0, 1, 2, 3, logits.size()[1]-1])) softmax = F.softmax(logits[:, idx])
answers question: http://stackoverflow.com/q/48363823
score: 0

http://stackoverflow.com/comment/83672580
type: QuestionComment
has text: If it's possible in sql, it's possible in Pandas or Dask. Vector-based operators are faster than loops
comment on: http://stackoverflow.com/q/48343464
score: 1
type: Comment

http://stackoverflow.com/a/48469811
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83933490
accepted answer of: http://stackoverflow.com/q/48469708
score: 3
has body: newString = regex.sub("", string).lower() Try to think of "functions returning" as "replacing the function call with the return value of the function". For example in the above case, regex.sub is evaluated first, and you should imagine that that call is replaced by the return value: newString = "some String after substitution".lower() This means that you can do everything you can do to a string on the return value of regex.sub. You can also call methods on the return value of lower(). This also means that you can do your whole function in one line! newString = re.compile('[^a-zA-Z]').sub("", string).lower() Although this might be less readable. By the way, the standard naming convention in python is not camel case but with underscores, so newString should be new_string.
has comment: http://stackoverflow.com/comment/83933792
type: Answer
has comment: http://stackoverflow.com/comment/83933575
upvote count: 3
answers question: http://stackoverflow.com/q/48469708

http://stackoverflow.com/comment/83711286
comment on: http://stackoverflow.com/q/48361516
has text: That should read cannot find Java.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83847958
has text: I don't think so because the 2 behaviors (& screenshots) are seen with the same input.+ I just tried without the trailing newline, and I got the same thing....
comment on: http://stackoverflow.com/a/48428574
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83923486
comment on: http://stackoverflow.com/a/48464786
score: 0
has text: Sorry, thats my bad, i was using `.__getattr__` instead `hasattr()`, and its expectedly return None.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48376092
answer count: 1
has body: How do I add an existing VM to an existing App gateway via the Python SDK for Azure? I've looked at this, and used it too, to create an app gateway programatically, but how do I go about adding newly created VMs to the existing gateway?
favorite count: 0
linked to: http://stackoverflow.com/q/42698609
type: Question
tagged with: azure-application-gateway
has title: Add VM to Azure App Gateway python
has answer: http://stackoverflow.com/a/48378190
tagged with: python
type: UnansweredQuestion
tagged with: azure-virtual-machine
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48423935
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83837473
has answer: http://stackoverflow.com/a/48424275
has answer: http://stackoverflow.com/a/48424079
type: AnsweredQuestion
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
score: 1
has body: I'm trying to read a csv file in python and build a data frame from it. Here is an example of a row from my csv file: |ab/5 (cd ef 6| text1/123 (lala| ghj) lal/1234/567| I would like to slice the row and assign each element to a column. The row should look sit in the data frame like so: col1 | col2 | col3 ab/5 | (cd ef 6| text1/123 (lala | ghj) Setting up a distributor while opening the file in excel is pointless because sometimes '|' appears in place, in which case it should not be split. For the first element ab/5 I was trying to do it like this: with open('actions2.csv', 'r') as csvfile_actions2: reader = csv.reader(csvfile_actions2) for row in reader: row2=row[0:23].split('|') print(row2) However, an error occurred: AttributeError: 'list' object has no attribute 'split' Does anyone have an idea how to solve this?
has answer: http://stackoverflow.com/a/48424249
has title: slicing rows from csv file
possible better answer: http://stackoverflow.com/a/48424079
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83849072
downvote count: 0
accepted answer: http://stackoverflow.com/a/48424275

colander
type: Tag
tags question: http://stackoverflow.com/q/48346917
tag name: colander

http://stackoverflow.com/comment/83712021
score: 0
type: AnswerComment
has text: It should be one single column of numbers
type: Comment
comment on: http://stackoverflow.com/a/48362464

http://stackoverflow.com/q/48343525
has comment: http://stackoverflow.com/comment/83673372
answer count: 1
has comment: http://stackoverflow.com/comment/83672865
has comment: http://stackoverflow.com/comment/83673154
has title: Choosing random values from a dictionary and afterwards ordering it
downvote count: 1
has comment: http://stackoverflow.com/comment/83673666
favorite count: 0
has body: I am trying to make a random class generator for COD WW2 and I'm almost done but I have one problem. I'm trying to choose random scorestreaks (in which I succeed), but when my program prints the scorestreaks they are not ordered from cheapest to most expensive. I understand that this is normally also not the case but I would like it differently. So I have been thinking and I think that dictionaries would be the key but I'm a beginner to Python and I haven't really used dictionaries before. This is my list with scorestreaks: scorestreaks = ["Molotov Cocktail", "Recon Aircraft", "Counter Recon Aircraft", "Care Package", "Fighter Pilot", "Glide Bomb", "Flamethrower", "Mortar Strike", "Artillery Barrage", "Flak Guns", "Emergency Airdrop", "Fire Bombing Run", "Paratroopers", "Carpet Bombing", "Ball Turret Gunner"] And this is my random choosing thing: ss1 = random.choice(scorestreaks) ss2 = random.choice(scorestreaks) ss3 = random.choice(scorestreaks) if ss1 == ss2 or ss1 == ss3: ss1 = random.choice(scorestreaks) if ss1 == ss2 or ss1 == ss3: ss1 = random.choice(scorestreaks) elif ss2 == ss3: ss2 = random.choice(scorestreaks) if ss2 == ss3 or ss2 == ss1: ss2 = random.choice(scorestreaks) print "Scorestreaks: %s, %s, %s" %(ss1, ss2, ss3) So idealy I would like to have the scorestreaks ordered when they are printed from cheapest to most expensive. Thank you for your answer. EDIT: I made a dictionary (I hope I made it the right way) containing the prices of the scorestreaks: scorestreaks_prices = {"Molotov Cocktail": 300, "Recon Aircraft": 500, "Counter Recon Aircraft": 525, "Care Package": 575, "Fighter Pilot": 625, "Glide Bomb": 650, "Flamethrower": 700, "Mortar Strike": 750, "Artillery Barrage": 850, "Flak Guns": 950, "Emergency Airdrop": 1000, "Fire Bombing Run": 1050, "Paratroopers": 1250, "Carpet Bombing": 1400, "Ball Turret Gunner": 1700} So to make it clear: When I choose three random scorestreaks It would print something like "Molotov Cocktail", "Counter Recon Aircr…
type: Question
has comment: http://stackoverflow.com/comment/83672630
has comment: http://stackoverflow.com/comment/83673473
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83673050
has comment: http://stackoverflow.com/comment/83672768
has comment: http://stackoverflow.com/comment/83672961
accepted answer: http://stackoverflow.com/a/48344535
type: AnsweredQuestion
score: 0
tagged with: random
has answer: http://stackoverflow.com/a/48344535

http://stackoverflow.com/comment/85746763
has text: Which version (or commit) of 'reticulate' are you using?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48373082
score: 0

http://stackoverflow.com/comment/83862349
type: AnswerComment
comment on: http://stackoverflow.com/a/48435411
has text: OK I will have a look @Jame
type: Comment
score: 0

http://stackoverflow.com/comment/88096062
has text: Funny thing. Getting the same error with proper loading the file in .load
comment on: http://stackoverflow.com/a/48345944
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48367293
answer count: 3
has answer: http://stackoverflow.com/a/48372163
has body: I am new to programming so take it easy on me. I am having issues understanding this kind of if statements and while loops: command = input() if command != "l" or command != "h" or command != "c" print("Please insert l, h or c: ") command = str(input("l, h or c: ")) else: print("working") I don't understand why 'h' or 'c' are not being checked. When I try this on my IDE I get: l Please insert l, h, or c: l, h or c:
upvote count: 0
score: -2
downvote count: 2
has title: How to check if the input is letter 'l', 'h' or 'c'
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48367330
tagged with: python
has answer: http://stackoverflow.com/a/48367330
possible better answer: http://stackoverflow.com/a/48367451
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48367451

http://stackoverflow.com/comment/83838301
comment on: http://stackoverflow.com/a/48421549
type: Comment
type: AnswerComment
has text: Well, no, it still can not work for me. The connection always fails. But thanks for responding.
score: 0

http://stackoverflow.com/a/48337576
answers question: http://stackoverflow.com/q/48337542
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: It's a set. There are also online examples that use the methods you mentioned. Next time you wonder, I suggest you just print the type, like this: print(type(explored));
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48337542

http://stackoverflow.com/comment/83943918
has text: Sorry I actually dont understand your problem. Can you post another question with details?
comment on: http://stackoverflow.com/a/48475142
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48479194
has comment: http://stackoverflow.com/comment/83951504
type: Answer
upvote count: 4
has body: I think you need if empty values are Nones or NaNs: d = themecodes.sort_values('name', na_position='first').set_index('code')['name'].to_dict() themecodes.loc[themecodes['name'].isnull(), 'name'] = themecodes['code'].map(d) Or: themecodes['name'] = themecodes['name'].combine_first(themecodes['code'].map(d)) themecodes['name'] = (themecodes.sort_values('name', na_position='last') .groupby('code')['name'] .transform(lambda x: x.fillna(x.iat[0])) .sort_index()) print (themecodes) code name 0 8 Human development 1 11 Environment and natural resources management 2 1 Economic management 3 6 Social protection and risk management 4 5 Trade and integration 5 2 Public sector governance 6 11 Environment and natural resources management 7 6 Social protection and risk management 8 7 Social dev/gender/inclusion 9 7 Social dev/gender/inclusion 10 5 Trade and integration 11 4 Financial and private sector development 12 6 Social protection and risk management 13 6 Social protection and risk management 14 2 Public sector governance 15 4 Financial and private sector development 16 11 Environment and natural resources management 17 8 Human development 18 10 Rural development 19 7 Social dev/gender/inclusion Solution if need replace empty space or some whitespaces: d = themecodes.sort_values('name', na_position='first').set_index('code')['name'].to_dict() themecodes.loc[themecodes['name'].str.strip() == '', 'name'] = themecodes['code'].map(d)
has comment: http://stackoverflow.com/comment/83951544
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83951830
accepted answer of: http://stackoverflow.com/q/48479162
score: 4
answers question: http://stackoverflow.com/q/48479162
has comment: http://stackoverflow.com/comment/83951597
downvote count: 0

http://stackoverflow.com/comment/83880653
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48442308
type: QuestionComment
has text: @ArnavBorborah regarding the 2nd link, is there a similar embedded version for python2.7? i can't seem to see it on its download page.

http://stackoverflow.com/a/48411569
has body: TLDR; for word in strings: sentences = [line if word in line else line + ' ' + word for line in sentences] So you are given a list of sentences, of which you need to check if each contains a string. When one of them does not, you want to append the string to the sentence. Let's first look at the second line of code and consider the case where you only have one word to search and append. This list comprehension iterates through your list of sentences then: Checks if the string is in the sentence Appends the string if it isn't in the sentence At the end of the iterations, it reconstructs the list and assigns it back to the original list. The first line of code than simply repeat this process for every word you wish to search and append.
has comment: http://stackoverflow.com/comment/83813228
answers question: http://stackoverflow.com/q/48410832
score: 0
has comment: http://stackoverflow.com/comment/83813792
type: Answer

http://stackoverflow.com/a/48474602
accepted answer of: http://stackoverflow.com/q/48474455
answers question: http://stackoverflow.com/q/48474455
score: 1
type: Answer
upvote count: 1
type: AcceptedAnswer
has body: You've to first install the Jack libriary for OS X, which is available on the Jackaudio download page.
downvote count: 0

http://stackoverflow.com/comment/83874521
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48436679
has text: Can you update the question with your code trials please?
score: 0

http://stackoverflow.com/a/48470152
answers question: http://stackoverflow.com/q/48469889
type: Answer
upvote count: 2
downvote count: 0
has body: Here is a way to do this using scipy.optimize.curve_fit: First, let's recreate your example (as a sanity check): import numpy as np from scipy.optimize import curve_fit ​ def f(x, x3, x2, x1, x0): """this is the polynomial function""" return x0 + x1*x + x2*(x*x) + x3*(x*x*x) ​ popt, pcov = curve_fit(f, x, y) print(popt) #array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) Which matches the values you get from np.polyfit(). Now adding the constraints for x1: popt, pcov = curve_fit( f, x, y, bounds = ([-np.inf, -np.inf, .999999999, -np.inf], [np.inf, np.inf, 1.0, np.inf]) ) print(popt) #array([ 0.04659264, -0.48453866, 1. , 0.19438046]) I had to use .999999999 because the lower bound must be strictly less than the upper bound. Alternatively, you could define your function with the constrained coefficient as a constant, and get the values for the other 3: def f_new(x, x3, x2, x0): x1 = 1 return x0 + x1*x + x2*(x*x) + x3*(x*x*x) popt, pcov = curve_fit(f_new, x, y) print(popt) #array([ 0.04659264, -0.48453866, 0.19438046])
score: 2

http://stackoverflow.com/q/48449120
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48449245
has comment: http://stackoverflow.com/comment/83890843
has answer: http://stackoverflow.com/a/48449245
tagged with: python
has title: Compare all float values against an integer and skip to next iteration of the loop
has comment: http://stackoverflow.com/comment/83890844
has body: Hello I am new to Python and I am having some trouble with some test program I am trying to code. Just started a few weeks ago; from a book from my local library, so excuse how nooby it may appear: print('''The next question will be having you find an exact number with divison Here is the question: with a 'value' of '420' what can you divide by to get '8' with a remainder?''') value = 420 while value &gt; 1: q2 = float(input(":")) if q2 == 0: print("You cannot divide by 0!") continue value /= q2 print(value) if value is float(8): print("Correct Answer") break print("Next Question!") So what I am trying to achieve here is once there is any value after dividing, such as 48 = 8.75 or any number through 8.xx, I would like the loop to stop and continue onward.
type: AnsweredQuestion

http://stackoverflow.com/a/48453317
has body: The syntax for signaling events in BokehJS changed some time back. Additionally, it's the glyph you are changing, so that you should be emitting a change signal. Here is a version of the callback that works: cb_cselect = bokeh.models.CustomJS(args=dict(cir=cir,csource=csource), code =""" var selected_color = cb_obj.value; cir.glyph.line_color.field = selected_color; cir.glyph.fill_color.field = selected_color; cir.glyph.change.emit() """)
answers question: http://stackoverflow.com/q/48451710
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/83947652
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48477241
has text: Thank you so much!
score: 0

http://stackoverflow.com/a/48365114
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48364836
downvote count: 0
upvote count: 1
has body: Late to the party: define a period repeat it times needed reshape import numpy as np period = [6*[1] + 54 * [0]] arr = np.reshape( [period] * 6 , [360]) # 6 * 60 = 360 datapoints print (arr) [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 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

http://stackoverflow.com/a/48362117
score: 1
type: AcceptedAnswer
downvote count: 0
has body: The proximal cause of your error is: del fImage which works like assignment, it causes fimage to be treated as local. Therefore, you are getting an unbound-local error, which makes sense, since you never assign to fImage in the first place in Salvataggio Anyway, yours is a special case of the typical UnboundLocalError, because it didn't involve assignment to the variable to make it get marked as local. A common cause being a hidden assignment: You get a plain name error if the variable is neither global nor local. In [1]: def f(): ...: if x in {}: ...: pass ...: In [2]: f() --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-2-0ec059b9bfe1&gt; in &lt;module&gt;() ----&gt; 1 f() &lt;ipython-input-1-80c063ba8db6&gt; in f() 1 def f(): ----&gt; 2 if x in {}: 3 pass 4 NameError: name 'x' is not defined However, the del marks the name as local: In [3]: def f(): ...: if x in {}: ...: pass ...: del x ...: In [4]: f() --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) &lt;ipython-input-4-0ec059b9bfe1&gt; in &lt;module&gt;() ----&gt; 1 f() &lt;ipython-input-3-5453b3a29937&gt; in f() 1 def f(): ----&gt; 2 if x in {}: 3 pass 4 del x 5 UnboundLocalError: local variable 'x' referenced before assignment This is why your check: if "fImage" in globals() and not(fImage==None): is the line where it fails. I do not understand why you always are checking whether fimage is in globals(). Note, 'fimage' in globals() can be true while fimage is a local name... hence the unbound local.
type: Answer
accepted answer of: http://stackoverflow.com/q/48362010
answers question: http://stackoverflow.com/q/48362010
upvote count: 1

http://stackoverflow.com/a/48370226
upvote count: 2
answers question: http://stackoverflow.com/q/48370175
has comment: http://stackoverflow.com/comment/83729825
downvote count: 1
has body: You probably looking for struct (to convert python int to unit8_t) I have used it to communicate with low level devices. So import struct var = 25 # try 2**17 and see what happens print(struct.pack('&lt;H', var)) # b'\x00\x19' print(struct.pack('&gt;H', var)) # b'\x00\x19' As you can see this &gt; or &lt; changing bytes between Little and Big Endian. H is for short (uint16_t) and B is for unsigned char (uint8_t). The b'' is python bytes string that allow you to see bytes data. So i would to suggest you to start from xbee.send(b'\x45\x15') and see what happens on the other side. If communication works then start to create function that convert python types to structure reperesents. See also: BitwiseOperators
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83760108

http://stackoverflow.com/comment/83826771
comment on: http://stackoverflow.com/a/48418529
score: 1
type: Comment
type: AnswerComment
has text: I would continue on this answer. Note that `a==0.0` is okay too, then set to 0.0

http://stackoverflow.com/a/48363080
answers question: http://stackoverflow.com/q/48363057
score: 5
upvote count: 5
type: Answer
has body: If you want changes to be made inplace, you'd need to perform operations that modify the list inplace. This would mean any of the list instance methods. In this particular instance, you could look at list.extend. def add(L1, L2, L3): L3.extend(L1 + L2) # creates a new list object and copies it into L3 Since this creates a an copy (which may be inefficient), you can instead use two extend calls in its place - def add(L1, L2, L3): L3.extend(L1) L3.extend(L2) Calling L3.extend modifies the original list in place. With your current code, L1 + L2 creates a new list, and re-assigns L3 to that object (and the original object that L3 was referring to was not touched). If you'd like to generalise this to any number of lists, I'd recommend taking a look at using variable arguments: from itertools import chain def add(L3, *L): L3.extend(chain.from_iterable(L)) Here's an example of how it works: &gt;&gt;&gt; L3 = [] &gt;&gt;&gt; add(L3, [1], [2], [3]) &gt;&gt;&gt; L3 [1, 2, 3] As a matter of good practice, you should either define a function that does not modify the original structure, but returns a new value you can assign from the caller, OR define a function that modifies structures in place, and returns nothing. Another user note: L3[:] = ... will replace L3 of all its previous contents with the items from L1 + L2. On the other hand, L3.extend(...) will not destroy what was previously in L3, but is instead extended by what it is passed. I'd recommend evaluating your use case and using the more appropriate method to the situation. However, to cater to that case, you can build on the accepted answer's method using inplace assignment with __setitem__: def add(L3, *L): L3[:] = chain.from_iterable(L) Which works the same way, and should be very efficient for many lists.
downvote count: 0

http://stackoverflow.com/comment/83743636
type: Comment
has text: Don't know anything about *rospy* but according to the traceback it may be the case that `linear` (and `angular` as well?) should not be a list of 3 *int* elements (I assume those are *3D* coordinates) but a dictionary (with `x`, `y` (and `z`) keys).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48378385

http://stackoverflow.com/a/48474134
has comment: http://stackoverflow.com/comment/84024755
type: Answer
has comment: http://stackoverflow.com/comment/83990804
score: -1
answers question: http://stackoverflow.com/q/48473543
has comment: http://stackoverflow.com/comment/84003038
has comment: http://stackoverflow.com/comment/83946075
has body: res_list = map(lambda (x,y): str(x) + str(y), list) map is higher order function which takes a function and a list and applies a function to every element of list. In above case str(x) + str(y) a '+' string concatenation operator working two string operands and returns a final string. Hence resultant list will be list of string. which is expected output. result: ['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
downvote count: 2
upvote count: 1

http://stackoverflow.com/a/48347311
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48346254
has body: IIUC you are using the name columns like indices. You should put them there and then update/add becomes trivial. def gen_df(): midx = pd.MultiIndex.from_tuples([ ('Joe', 'Smith'), ('Jake', 'Smith'), ('Jim', 'Smith'), ('Joanne', 'Smith') ], names=['Name 1', 'Name 2']) return pd.DataFrame( dict(Result=np.random.rand(4)), midx ) Option 1 You don't have to do it this way. But this is how I'd do it: from functools import reduce reduce(pd.DataFrame.add, (gen_df() for _ in range(1, 5))) Result Name 1 Name 2 Joe Smith 2.400550 Jake Smith 2.222812 Jim Smith 2.601639 Joanne Smith 0.503774 Option 2 In a loop df = gen_df() for _ in range(1, 5): df += gen_df() df Result Name 1 Name 2 Joe Smith 1.998055 Jake Smith 2.268697 Jim Smith 2.815204 Joanne Smith 2.253301
type: Answer

http://stackoverflow.com/comment/83728283
has text: You can check edited answer.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48368986

http://stackoverflow.com/q/48420759
tagged with: python
answer count: 6
upvote count: 32
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/57496624
has title: Upload local files using Google Colab
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48048279
accepted answer: http://stackoverflow.com/a/48427329
has body: Trying to upload local files using Google Collaboratory this way: from google.colab import files uploaded = files.upload() I get the following error: Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable. I rerun the cell but it doesn't work...
has answer: http://stackoverflow.com/a/48427329
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
type: Question
possible better answer: http://stackoverflow.com/a/58661947
has answer: http://stackoverflow.com/a/58661947
has answer: http://stackoverflow.com/a/59949604
score: 32
has answer: http://stackoverflow.com/a/48904662
has answer: http://stackoverflow.com/a/62864545
linked to: http://stackoverflow.com/q/48760475

http://stackoverflow.com/comment/83742907
type: QuestionComment
score: 0
has text: @NicoAlbers He just wants to add the `i`th and `i-1`th element in the array
type: Comment
comment on: http://stackoverflow.com/q/48377998

http://stackoverflow.com/comment/83990136
type: Comment
comment on: http://stackoverflow.com/a/48482475
score: 0
type: AnswerComment
has text: Tried with given code, it clicks first value in list but not matched value.

http://stackoverflow.com/a/48471870
type: Answer
has body: You better take the print out of the function. def list_conversion(items): return {i: x for i, x in enumerate(items, 1) if i % 2 == 1}
answers question: http://stackoverflow.com/q/48471841
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/83712514
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48362796
has text: +1 I'm not exactly sure why the OP wanted to do this with `numpy`. OP, there are fine solutions using pure Python, such as this one.
type: Comment

http://stackoverflow.com/comment/83677520
comment on: http://stackoverflow.com/a/48345798
has text: Appreciate the reply, this throws this error: print(key, file=f) ^ SyntaxError: invalid syntax. Can't see anything obvious causing that
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83952938
type: Comment
has text: !! It looks like that worked!! I'm so confused as to why include works here and didn't work originally in my other file, but thank you!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48479871

http://stackoverflow.com/q/48390709
favorite count: 0
type: Question
has body: I have read several different SO posts on using python as a TCP client and am not able to connect to a server sending data via TCP at 1hz which is hosted locally. The connection parameters I am using are: import socket client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip=socket.gethostbyname("127.0.0.1") port=1234 address=(ip,port) client.connect(address) while True: print("test1") data = client.recv(1024) print("test2") print(data) I believe that it is failing on the second line of the while statement but do not know why because it hangs and I am not given an error. Below are links to the SO articles, I have read and I have attached a screenshot from a TCP client tool that I am able to connect to the data server with. I'm expecting the data to stream in my print statement, is this not how it works? Whats the best way to make a persistent connection to a TCP connection with python? Researched: (Very) basic Python client socket example,Python continuous TCP connection,Python stream data over TCP
linked to: http://stackoverflow.com/q/41102775
has title: Streaming TCP data to a Client with Python
upvote count: 2
has comment: http://stackoverflow.com/comment/83769948
tagged with: sockets
has comment: http://stackoverflow.com/comment/83769857
downvote count: 0
has comment: http://stackoverflow.com/comment/83769784
accepted answer: http://stackoverflow.com/a/48390943
tagged with: python
has answer: http://stackoverflow.com/a/48390943
linked to: http://stackoverflow.com/q/42792834
linked to: http://stackoverflow.com/q/7749341
type: AnsweredQuestion
score: 2
tagged with: tcp
has comment: http://stackoverflow.com/comment/83770005
answer count: 1

http://stackoverflow.com/comment/83739019
comment on: http://stackoverflow.com/a/48375446
score: 1
type: Comment
type: AnswerComment
has text: @PeterDeGlopper `set(sorted(i) for i in itertools.product(*l))` won't work here, since lists are not hashable. I think you mean `tuple(sorted(i))` instead.

http://stackoverflow.com/comment/83904458
type: AnswerComment
comment on: http://stackoverflow.com/a/48455672
score: 1
type: Comment
has text: You could squash the file use into one context manager using the r+ mode (meaning you can read and write to it). Otherwise, I would look at a better way to write that arrpow function, it looks pretty dank.

http://stackoverflow.com/comment/83909969
type: QuestionComment
has text: I think that it only possible with the curses interface, allowing you to arbitrarily place character on the screen. This has for example been used in the old days for 'graphical' games on character displays. There is a curses module available for python. However, I am not sure if it works with windows as curses is originally a Unix thing.
score: 2
comment on: http://stackoverflow.com/q/48458526
type: Comment

http://stackoverflow.com/comment/83730602
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48371615
score: 0
has text: You never leave the inner loop. `player_number` can only be changed in the outer loop. This is covered up by your "Try again" question, where most people assume, they should enter the next number.

pyobject
type: Tag
tags question: http://stackoverflow.com/q/48471015
tag name: pyobject

http://stackoverflow.com/q/48371873
score: 1
upvote count: 1
has title: How to return python script response as Http response using Django framework
accepted answer: http://stackoverflow.com/a/48371981
tagged with: httpresponse
favorite count: 0
type: Question
tagged with: api
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48371981
has answer: http://stackoverflow.com/a/48371955
possible better answer: http://stackoverflow.com/a/48371955
has body: I am using Python Django framework, new to it. I am getting "None" in the browser, not sure what is wrong with my code. from django.http import HttpResponse def index(request): from amazon.api import AmazonAPI AMAZON_ACCESS_KEY = "cant share my key" AMAZON_SECRET_KEY = "cant share my key" AMAZON_ASSOC_TAG = "cant share my tag" REGION = "US" amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG) products = amazon.search(BrowseNode='3760911', SearchIndex='Beauty', MaximumPrice='30') for i, product in enumerate(products, 1): return HttpResponse(print(str(product))) The code works like a charm when I run in python shell however it doesn't run in the browser.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48374123
answer count: 3
downvote count: 0
tagged with: amazon-product-api

http://stackoverflow.com/comment/83715419
comment on: http://stackoverflow.com/q/48355747
type: Comment
type: QuestionComment
has text: I'll try that and let you know the result.
score: 0

http://stackoverflow.com/comment/83750932
score: 0
type: Comment
has text: You just have to search for common entries in the the two paths to the root. So it should O(log n)
type: QuestionComment
comment on: http://stackoverflow.com/q/48382047

http://stackoverflow.com/q/48439532
upvote count: 1
favorite count: 0
type: Question
has title: Django access form errors excluding non_field_errors in template
accepted answer: http://stackoverflow.com/a/48439670
has answer: http://stackoverflow.com/a/48439670
tagged with: python
tagged with: forms
type: AnsweredQuestion
tagged with: django-templates
score: 1
has body: In a django template I'd like to show all form errors on top of the form, the easiest way is by doing so: {{ form.errors }} The problem is that this also shows the form.non_field_errors, these are the entries contained in form.errors['__all__']. I want to show these special errors separately, so I've tried to loop over the dict and check if the key existed: {% for err in form.errors %} {% if not err.__all__ %} {# print error #} {% endif %} {% endfor %} but apparently this is not possible because in the template we cannot access dictionary keys starting with underscore (doc). Question: is there a built-in way to access (and possibly print) the standard field errors and separately the non_field_errors? Solution This was built on top of Daniel Roseman's answer: {% if form.errors %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} {% endfor %} {% endif %} {% for field in form %} {% if field.errors %} {{ field.name }} {% for error in field.errors %} {% endfor %} {% endif %} {% endfor %} {% endif %}
downvote count: 0
answer count: 1
tagged with: django

http://stackoverflow.com/q/48440957
has comment: http://stackoverflow.com/comment/83877008
has comment: http://stackoverflow.com/comment/83875984
has comment: http://stackoverflow.com/comment/83875807
has title: Cloud SQL insert error when missing values/ big file
has comment: http://stackoverflow.com/comment/83876104
has comment: http://stackoverflow.com/comment/83876261
answer count: 1
has comment: http://stackoverflow.com/comment/83876143
has body: I am reading csv and inserting it into cloud sql using the following procedure: df = pd.read_csv(csv_file, sep=';', encoding='utf-8', keep_default_na=False) ## from field “world” remove C. , County , Cnty df['world'] = df['world'].str.rstrip('C.CountyCnty') ## connects to mysql database and adds the dataframe to it connection_string = 'mysql+mysqlconnector://xxxx:xxxx@xx.xxx.x.xx:aaaa/mydatabase' engine = create_engine(connection_string, echo=False) conn = engine.connect() df.to_sql(name="mytable", con=engine, if_exists='append', index=False) conn.close() However, this does safe inserts into SQL until it faces a file which starts with empty row value in the world field. NOTE: It does safe inserts for files which has empty rows which appears later. I believe the error is occurring due to empty fields in the csv data. But I used keep_default_na=False to fix it. But still it persists. Any help will be highly appreciated. This is how the error looks like (mysql.connector.errors.OperationalError) 2055: Lost connection to MySQL server at 'xx.xxx.xx.x:aaaa', system error: 10053 An established connection was aborted by the software in your host machine
accepted answer: http://stackoverflow.com/a/48442904
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48442904
has comment: http://stackoverflow.com/comment/83873525
score: 0
has comment: http://stackoverflow.com/comment/83873432
tagged with: pandas
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/83875875
has comment: http://stackoverflow.com/comment/83876832

http://stackoverflow.com/comment/83721477
score: 0
type: Comment
type: AnswerComment
has text: Thank you very much, I have gone through all the methods I could , I was just not able to resolve the problem, I still get some unreasonable downvotes, it's like the members of the website think that everyone should be expert ! while I see very short questions with no detail getting very high votes, still can't digest this ! If everyone is an expert, there will be no need to a forum. now the problem solved
comment on: http://stackoverflow.com/a/48366301

http://stackoverflow.com/a/48456779
type: Answer
has comment: http://stackoverflow.com/comment/83906687
answers question: http://stackoverflow.com/q/48456459
score: 0
has body: 1) There is a module within the standard library called CSV. It is probably better to use that when creating CSV's. Used like this: import csv with open("file.csv", 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(ResultDir + "/srciplist-" + ToDay + ".csv") 2) Here is some code for opening a file in the command line: import sys with open(sys.argv[1], 'r') as f: contents = f.read() # Continue code below
has comment: http://stackoverflow.com/comment/83908110
has comment: http://stackoverflow.com/comment/83909280

http://stackoverflow.com/a/48432367
answers question: http://stackoverflow.com/q/48432153
downvote count: 1
has body: You can use quantile: np.random.seed(123) v=np.random.rand(100) s = pd.Series(v) arr = np.array([0.3,0.5,0.7]) s.quantile(arr) Output: 0.3 0.352177 0.5 0.506130 0.7 0.644875 dtype: float64
type: Answer
has comment: http://stackoverflow.com/comment/83856181
score: 2
upvote count: 3

http://stackoverflow.com/q/48483554
has comment: http://stackoverflow.com/comment/83968918
has body: I am currently running a script on a Shopify website, kith.com. I am trying to auto-checkout a certain item. What I am doing is I am getting the cart link and then opening it with selenium, automatically entering necessary details to complete the order. I have ran into an issue, though. I am able to get through the customer information page and the shipping method page; automatically entering details with selenium. The issue I am running into, is when I get onto the Payment method page. Whenever I try to insert the payment details such as credit card info, etc. it gives me an error: no such element: Unable to locate element. I am currently searching the element through ID, but I don't understand why it's not being read, because it has worked for all the previous pages.
type: Question
has comment: http://stackoverflow.com/comment/83959939
answer count: 0
has comment: http://stackoverflow.com/comment/83959955
has title: No such element in selenium python when running a script on a shopify site
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48471321
tagged with: shopify
tagged with: selenium
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83970070
downvote count: 1
has comment: http://stackoverflow.com/comment/83960011
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/83964965
tagged with: checkout
has comment: http://stackoverflow.com/comment/84011683
has comment: http://stackoverflow.com/comment/83979082
linked to: http://stackoverflow.com/q/18924146

http://stackoverflow.com/comment/83864911
type: Comment
has text: Can you send me your file to my email in my profile?
comment on: http://stackoverflow.com/a/48396555
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83975119
type: AnswerComment
score: 0
has text: Yep, 2.7.10 ...
type: Comment
comment on: http://stackoverflow.com/a/48465428

http://stackoverflow.com/q/48395995
has title: pywin32 installation PermissionError:[Errno 13]
has comment: http://stackoverflow.com/comment/88776652
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83779581
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5077625
tagged with: python
has comment: http://stackoverflow.com/comment/88439471
score: 0
answer count: 0
has body: I'm trying to install pywin32 using pip by following this link, but I get a: PermissionError:[Errno 13] Permission denied : ....\pythoncom.py I'm using: Python 3.6.0 pip 9.0.1 Windows 10 I primarily want to install pywin32 for accessing Outlook emails as shown here. How can I solve this?
tagged with: outlook-2010
has comment: http://stackoverflow.com/comment/88838957

http://stackoverflow.com/a/48476502
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84057075
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48461784
has body: The best thing that I can think of that may cause this error is that one of the functions that you call inside your try statement is handling the exception inside itself so that your exception handling becomes ineffective. To make sure: Try to throw an exception manually from your try block so that you make sure the exception handling works in general. If the aforementioned assumption is true you can figure out which function is handling the exception inside itself by manually raising an exception once before and once after the call. To demonstrate what I mean: while True: sleep(1) try: raise Exception("my exception") writer.save() os.startfile(company_code_choice + 'PLFY2018.xlsx') break except Exception as e: print ("Close the file: ", e) You should definitely capture your raised exception otherwise, something is wrong with your code. Try to simply or check what prevents the excepted behavior if happened. If you could capture your raised exception then the next time: while True: sleep(1) try: writer.save() raise Exception("my exception") os.startfile(company_code_choice + 'PLFY2018.xlsx') break except Exception as e: print ("Close the file: ", e) So that you either capture your raised exception which means writer.save() does not handle the exception inside itself or you get the same error which means writer.save() handles the exception. By continuing this procedure all over the try block of your code you must be able to figure out which function is making trouble. That's the best thing I can think of now. I hope it helps. But if I'm right then you could only figure out the source of the error but I don't know how you can achieve the behavior you would like. So maybe you can find a clue on the documentation.
type: Answer
accepted answer of: http://stackoverflow.com/q/48461784

http://stackoverflow.com/comment/83655957
score: 0
has text: It's response from django view HttpResponse, I'm using request.get to make the call.
comment on: http://stackoverflow.com/q/48335063
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48431846
has body: I advise to use more clear variable names instead of comments and not to use one-liners. Given import itertools as it stream = [11, 12, 21, 22, 31, 32] * 4 ch_idx = 1 ch_size = 2 num_chs = 3 Code Using the grouper itertools recipe: channels = grouper(ch_size, stream) frames = grouper(num_chs, channels) list(it.chain.from_iterable(*it.islice(zip(*frames), ch_idx))) # [11, 12, 11, 12, 11, 12, 11, 12] As a one-liner, it looks as follows: list(it.chain.from_iterable(*it.islice(zip(*grouper(num_chs, grouper(ch_size, stream))), ch_idx))) # [11, 12, 11, 12, 11, 12, 11, 12] Details The grouper recipe is implemented as follows: def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) See also the more_itertools third-party library for pre-implemented recipes.
upvote count: 0
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48430081

http://stackoverflow.com/comment/83966910
score: 2
type: Comment
type: QuestionComment
has text: Isn't` `int(value)` what you want?
comment on: http://stackoverflow.com/q/48487059

http://stackoverflow.com/a/50599669
score: 1
has body: One of the main differences that caused me problems was the same as posted in the question. Specifically: in R aes(x = x) or aes(x) in plotnine aes(x = 'x')
answers question: http://stackoverflow.com/q/48349713
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83859335
type: Comment
type: AnswerComment
score: 1
has text: @RajeshThevar I think it is easier for scikit learn to understand a DataFrame of scalars instead of a column of lists. Also, pre-processing scalars is more efficient than column of lists. But in the end it depends.
comment on: http://stackoverflow.com/a/48429523

http://stackoverflow.com/comment/83872427
type: Comment
type: QuestionComment
has text: are you 100% sure it is just a documentation issue? if it is just a documentation issue, then my question is certainly not a duplicate as you have marked it to be.
comment on: http://stackoverflow.com/q/48439619
score: 0

http://stackoverflow.com/comment/83871239
score: 0
comment on: http://stackoverflow.com/a/48431327
type: AnswerComment
has text: Indeed it seems the ``scrapy`` command works only in the ``\Scripts`` directory
type: Comment

http://stackoverflow.com/q/48443084
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/83878343
has title: Is this the correct way to write a SQLAlchemy many-to-many relationship?
score: 0
answer count: 0
tagged with: sqlalchemy
has body: Say I am creating a system where customers can order widgets. Each customer may order many widgets, and each widget may be ordered by many customers, so I need a link table to store the orders (where some additional information, like the quantity, can also be stored). So far, I have come up with the following implementation: from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Order(db.Model): customer_id = db.Column(db.ForeignKey("customer.id"), primary_key=True) widget_id = db.Column(db.ForeignKey("widget.id"), primary_key=True) customer = db.relationship("Customer", back_populates="orders") widget = db.relationship("Widget", back_populates="orders") quantity = db.Column(db.Integer) class Customer(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) orders = db.relationship("Order", back_populates="customer", cascade="all, delete-orphan", lazy="dynamic") class Widget(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text) orders = db.relationship("Order", back_populates="widget", cascade="all, delete-orphan", lazy="dynamic") Is this correct? Particularly, do I need the customer and widget attributes on Order, or could I do something with backref instead? (and if so, is there any advantage to using back_populates over backref or vice versa?)
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83878288

http://stackoverflow.com/comment/83916862
type: QuestionComment
comment on: http://stackoverflow.com/q/48461989
score: 0
type: Comment
has text: `A` is callable, but an `A` object (`a`, in your example) is not.

http://stackoverflow.com/a/48478537
answers question: http://stackoverflow.com/q/48478536
has body: Yes, you can just press run and have everything done using PyCharm. configuring flask: following this excellent link. Here are the steps: run > edit configuration Script: file/path/venv/bin/flask scrip parameters: run environment vars: FLASK_APP=run.py working directory: file/path/to/where/the/run.py/is unclick the PYTHONPATH options (1 &amp; 2) compiling scss before running automatically: file > settings/preferences tools > file watchers + scss ok
accepted answer of: http://stackoverflow.com/q/48478536
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83923891
type: AnswerComment
comment on: http://stackoverflow.com/a/48465028
score: 0
has text: Thank you! That's right what I wanted. I'm new in Python and it's really great that I can ask here for help. Thank you again! @Rachel, I cant upvote yet, sorry!
type: Comment

http://stackoverflow.com/q/48487401
tagged with: django
favorite count: 0
tagged with: postgresql
has title: Django migrate sqlite3 db to postgres Query invalid input syntax for integer: "none" error
type: Question
has answer: http://stackoverflow.com/a/48487716
tagged with: python
type: UnansweredQuestion
score: 2
upvote count: 2
has body: My project use Django 2.0 database from sqlite migrate to postgresql 9.6.3, Run normal in sqilet, migrate to postgresql and running error. models.py : Class WechatPay(models.Model): user = models.CharField('网点', max_length=20, default='None') user_group = models.CharField('渠道', max_length=20, default='None') total_fee = models.FloatField('订单金额', default=0, decimal_places=0, max_digits=7) card_sale = models.FloatField('售卡款', default=0, decimal_places=0, max_digits=7) card_recharge = models.FloatField('充值款', default=0, decimal_places=0, max_digits=7) trade_date = models.DateField('交易日期', auto_now_add=True) views.py : def group_list(request): start_time = request.GET.get('start_time', datetime.today().strftime("%Y-%m-%d")) end_time = request.GET.get('end_time', datetime.today().strftime("%Y-%m-%d")) object_list = WechatPay.objects.values('user', 'trade_date', 'user_group').filter( trade_date__gte=start_time).filter( trade_date__lte=end_time).filter( status='SUCCESS').annotate( card_sale=Cast(Sum('card_sale'), DecimalField(decimal_places=2)), total_fee=Cast(Sum('total_fee'), DecimalField(decimal_places=2)), card_recharge=Cast(Sum('card_recharge'), DecimalField(decimal_places=2)) ).order_by('-trade_date') summary = WechatPay.objects.filter( trade_date__gte=start_time).filter( trade_date__lte=end_time).filter( status='SUCCESS').aggregate(card_sale_sum=Cast(Sum('card_sale'), DecimalField(decimal_places=2)), total_fee_sum=Cast(Sum('total_fee'), DecimalField(decimal_places=2)), card_recharge_sum=Cast(Sum('card_recharge'), DecimalField(decimal_places=2))) return render(request, 'wechatpay/data-group.html', {'items': object_list, 'start_time': start_time, 'end_time': end_time, 'summary': summary}) error: Traceback (most recent call last): File "D:\workspace\venv\venv-django\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "none" LINE 1: ...LECT SUM("gft_wechat_pay_…
tagged with: sqlite
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83727527
type: QuestionComment
has text: You could show the error message.
comment on: http://stackoverflow.com/q/48370347
score: 0
type: Comment

http://stackoverflow.com/a/48370416
has body: You could use Bubble, and leave it hanging as long the input is wrong. You can even edit the lable to tell what is wrong. Or change the text color if validated or not. I made an example with both implemented. from kivy.app import App from kivy.uix.textinput import TextInput from kivy.uix.bubble import Bubble from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout from kivy.properties import BooleanProperty KV = """ &lt;ValidateLabel&gt;: size_hint: (None, None) size: (280, 60) Label: id: label text: "Must be a float" &lt;MyInput&gt;: foreground_color: (0,1,0,1) if root.validated else (1,0,0,1) FloatInput: """ class MyInput(TextInput): validated = BooleanProperty(False) class FloatInput(FloatLayout): bubble_showed = True def __init__(self, **kwargs): super(FloatInput, self).__init__(**kwargs) self.input = MyInput() self.input.bind(text=self.validate) self.add_widget(self.input) self.bubble = ValidateLabel() self.add_widget(self.bubble) def validate(self, input, value, min_value=15., max_value=25.): self.bubble.ids.label.text = "Number must be between {} and {}".format(min_value, max_value) try: print(min_value, max_value) status = float(min_value) &lt;= float(value) &lt;= float(max_value) except Exception as e: status = False self.bubble.ids.label.text = "Input must be a number" if not status: if not self.bubble_showed: self.input.validated = False self.add_widget(self.bubble) self.bubble_showed = True else: print("bubble removed") self.input.validated = True self.remove_widget(self.bubble) self.bubble_showed = False class ValidateLabel(Bubble): validated = False class TestApp(App): def build(self): return Builder.load_string(KV) TestApp().run() Output: Number to small or big: Number is okey: Input value is not a number:
answers question: http://stackoverflow.com/q/48347569
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83809881
type: Answer
has comment: http://stackoverflow.com/comment/83756975

http://stackoverflow.com/q/48440899
tagged with: django-2.0
has body: I'm trying to use django-modeltranslation in my project. For now, just for Tag model with one field - name. I've created and registered TranslationOptions, then makemigrations and migrate. Now I can't access the original name text. It seems to be replaced with '' (empty string) but it isn't: In [6]: Tag.objects.first() Out[6]: &lt;Tag: &gt; In [7]: Tag.objects.first().name Out[7]: u'' In [8]: Tag.objects.first().__dict__ Out[8]: {'_state': &lt;django.db.models.base.ModelState at 0x7fc96ad41710&gt;, 'id': 1, 'name': u'Sport', 'name_cs': None, 'name_de': None, 'name_en': None, 'name_es': None, 'name_fr': None, 'name_ru': None, 'name_sk': None} In [9]: Tag.objects.first().name Out[9]: u'' Do you know how to access the field/s? EDIT models.py class Tag(models.Model): name = models.CharField(max_length=50,verbose_name=u'Tag',unique=True) def __unicode__(self): return self.name translation.py from modeltranslation.translator import register, TranslationOptions from tags.models import Tag @register(Tag) class TagsTranslationOptions(TranslationOptions): fields = ('name',) settings.py USE_I18N = True USE_L10N = False gettext = lambda x: x LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', gettext('EN')), ('fr', gettext('FR')), ('es', gettext('ES')), ('de', gettext('DE')), ('ru', gettext('RU')), ('sk', gettext('SK')), ('cs', gettext('CZ')), ] The same problem is in Admin: Detail:
tagged with: python
favorite count: 0
type: Question
upvote count: 4
tagged with: django-modeltranslation
accepted answer: http://stackoverflow.com/a/48446638
answer count: 1
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/48446638
tagged with: django-database
score: 4
has title: Django modeltranslation - can't get and see original fields
type: AnsweredQuestion

http://stackoverflow.com/a/48357365
has comment: http://stackoverflow.com/comment/83701603
type: Answer
has comment: http://stackoverflow.com/comment/83701444
has comment: http://stackoverflow.com/comment/83703584
has body: Try: import os subprocess os.chdir("C:\\Users\\user\\") cmd= subprocess.Popen(["runas", "/noprofile", "/user:Administrator", "|", "echo", "Y", "|", "choco", "install", "dropbox"],stdin=sp.PIPE) cmd.stdin.write('password') cmd.communicate()
has comment: http://stackoverflow.com/comment/83701606
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104744246
has comment: http://stackoverflow.com/comment/83701569
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48357223
score: 0
accepted answer of: http://stackoverflow.com/q/48357223

http://stackoverflow.com/comment/83743288
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48378280
has text: `return` definitely does stop a function. But `number==[-1,-1]` doesn't do anything useful. Assignment is `=`, not `==`.
type: Comment

http://stackoverflow.com/comment/83798602
has text: after getting the top values, how can I change them to equal 1/3 and to set the rest of the values to be 0?
type: AnswerComment
comment on: http://stackoverflow.com/a/48399402
score: 0
type: Comment

http://stackoverflow.com/comment/83840924
type: Comment
has text: A sample of your data : all lines in your sample exists in your original dataset (and in fact comes from your data). A complete simulation : lines in your sample are just comming from simulation, and may be or may not exist in your original dataset.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48424044

http://stackoverflow.com/comment/84018860
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48511886
has text: the closest solution would be for me to use `TransactionTestCase` for all my tests.

http://stackoverflow.com/q/48353617
answer count: 2
upvote count: 2
has title: keras error: "AttributeError: can't set attribute" while defining a layer
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51549372
tagged with: python
has body: I'm trying t create my own layer in keras that I get error. my simple code is as below: class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim self.updates = [] super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # Create a trainable weight variable for this layer. self.kernel = self.add_weight(name='kernel', shape=(input_shape[1], self.output_dim), initializer='uniform', trainable=True) super(MyLayer, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): return K.dot(x, self.kernel) def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) and the error is: AttributeError Traceback (most recent call last) in () ----> 1 MyLayer(output_dim=10) in init(self, output_dim, **kwargs) 8 self.output_dim = output_dim 9 ---> 10 self.updates = [] 11 12 super(MyLayer, self).init(**kwargs) AttributeError: can't set attribute could you please help with this problem? Thanks
tagged with: keras
has answer: http://stackoverflow.com/a/59060980
score: 2

http://stackoverflow.com/a/48460544
has body: You could do something like this: df.loc['2012-04-08':'2012-04-10']['what_i_want']= \ df.loc['2012-04-08':'2012-04-10'].apply(lambda x:1, axis=1).cumsum() using a cumulative sum for the selected values after converting them to 1s.
answers question: http://stackoverflow.com/q/48458813
score: 0
type: Answer

http://stackoverflow.com/comment/83938075
comment on: http://stackoverflow.com/a/48471965
type: AnswerComment
has text: You don't really eliminate what to me is the main ugliness of `_`, which is that you create another attribute for the user to modify.
score: 0
type: Comment

http://stackoverflow.com/a/48423048
answers question: http://stackoverflow.com/q/48421703
has body: Try replacing df['Objectif(s)'] = df['Objectif(s)'].replace('\u00e9', 'é') to df['Objectif(s)'] = df['Objectif(s)'].str.replace('\u00e9', 'é')
type: Answer
score: 0

http://stackoverflow.com/comment/83830417
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48420091
score: 0
has text: Hi, the function that chack the availablity qty already exist in odoo10, serach in `stock/models/product.py` the function `_search_qty_available`

http://stackoverflow.com/comment/83875780
comment on: http://stackoverflow.com/a/48441824
score: 0
has text: @elarinya17 then you may want to edit your post to add the working solution so someone else having a similar problem can find it (don't remove the original code and question, _add_ the solution at the bottom).
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48475311
type: Answer
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/83944417
downvote count: 1
has body: If you run pip search turtle and read through the descriptions the PythonTurtle modual sounds like the one you are missing so just run pip3 install PythonTurtle
answers question: http://stackoverflow.com/q/48474398

http://stackoverflow.com/a/48352315
has comment: http://stackoverflow.com/comment/104786776
type: Answer
has body: The roots of that quadratic (34x^2 + 68x + 510) are complex. math.sqrt is real-valued -- it won't take a negative value. You'll need import cmath and cmath.sqrt to do a complex-valued square root.
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48352290
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48352290

http://stackoverflow.com/comment/83770329
type: AnswerComment
has text: @mdurant thanks I see it now, I did skim over that documentation page but missed it :(
comment on: http://stackoverflow.com/a/48389458
type: Comment
score: 0

http://stackoverflow.com/q/48445219
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: problem-steps-recorder
type: UnansweredQuestion
tagged with: python
has body: I'm using psr.exe in my python application and I'm trying to somehow get a signal from psr when it saves the recording file. I saw that there's an option in psr called stopevent which somehow sends an event after it stops recording and saves the recording file. But there's no documentation about how to use this parameter anywhere. So the question is, How can I use the stopevent parameter in my program to get an event after the psr successfully saves the recording file?
has title: Using "_Problem Steps Recorder" with the Stop Event
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/83755553
comment on: http://stackoverflow.com/a/48384208
score: 1
type: Comment
has text: I would have used `\nstatic` to check for start of line. Less changes to your code :) then slice with i+1
type: AnswerComment

http://stackoverflow.com/q/48438933
tagged with: python
tagged with: tweepy
score: 0
has answer: http://stackoverflow.com/a/48440639
answer count: 1
tagged with: twitter
type: Question
has body: I'm trying to use tweepy to retrieve tweets of a particular hashtag. This is my code: file = open('pc_week1.csv', 'a') writer = csv.writer(file) for tweet in tweepy.Cursor(extractor.search, q='#pyeongchang2018', count=100, lang='en', since='2017-12-01', until='2017-12-07').items(): writer.writerow([tweet.created_at, tweet.text.encode('utf-8')]) When I define the 'until' parameter, the code returns an empty dataframe. But when I DON'T define 'until', it retrieves all tweets since the date specified. The only thing is, I'm looking to get only a week's worth of data (2017-12-01~2017-12-07). Is there a way to do this? EDIT: I tried putting in a different date for 'until' parameter: for tweet in tweepy.Cursor(extractor.search, q='#pyeongchang2018', count=100, lang='en', since='2017-12-01', until='2017-12-15').items(): writer.writerow([tweet.created_at, tweet.text.encode('utf-8')]) And it DIDN'T return an empty df like before, but instead the results indicate that the until parameter was ignored. Here's a snippet of the results: Date Tweet 0 2018-01-25 08:35:21 b"RT @AFP: WATCH: A dozen North Korean female ... 1 2018-01-25 08:34:19 b"RT @AFP: WATCH: A dozen North Korean female ... 2 2018-01-25 08:33:29 b'Amazing @Aerialskier what an achievement! Go... 3 2018-01-25 08:32:29 b'RT @cnni: The new police force in charge of ... 4 2018-01-25 08:32:12 b'North Korean ice hockey teams arrives in Sou...
has title: using tweepy to retrieve data containing a particular hashtag
type: UnansweredQuestion

http://stackoverflow.com/a/48448679
answers question: http://stackoverflow.com/q/48448647
type: Answer
has comment: http://stackoverflow.com/comment/83889925
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48448647
has body: You can use a groupby, iterate over each group and build a list using a list comprehension. df_list = [g for _, g in df.groupby(['A', 'B'])] print(*df_list, sep='\n\n') A B C 0 1 2 10 1 1 2 1000 A B C 2 2 4 250 A B C 3 4 2 100 A B C 4 5 2 550 A B C 5 5 4 100 6 5 4 3000 A B C 7 5 5 250

http://stackoverflow.com/comment/83899722
type: Comment
has text: checker is a module given to intro to CS students. runTests is a wrapper so they don't get confused and too heavily involved in command line/shell etc, it's just something they can copy paste to see if their code works. I've fixed the indent, it copied pasted incorrectly.
score: 0
comment on: http://stackoverflow.com/q/48453054
type: QuestionComment

http://stackoverflow.com/q/48373506
has comment: http://stackoverflow.com/comment/83734181
has answer: http://stackoverflow.com/a/48373639
has comment: http://stackoverflow.com/comment/83734257
has comment: http://stackoverflow.com/comment/83734527
accepted answer: http://stackoverflow.com/a/48373628
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83734216
has comment: http://stackoverflow.com/comment/83734534
has comment: http://stackoverflow.com/comment/132645003
tagged with: python
has answer: http://stackoverflow.com/a/48373628
has body: Consider this example, with a deliberate typo: try: print("Hello!") raise ValueError("?") except ValueErro: print("Error!") finally: print("World!") The handling of the explicitly raised ValueError results in a NameError: Traceback (most recent call last): File "<stdin>", line 3, in <module> ValueError: ? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 4, in <module> NameError: name 'ValueErro' is not defined However, if a ValueError is not raised: try: print("Hello!") except ValueErro: print("Error!") finally: print("World!") then no exception occurs; Hello! and World! are simply printed. Why is there no NameError caused by the typo ValueErro (no such name exists)? Shouldn't this have been detected ahead of time? Can I use a different syntax to ensure that the problem is caught ahead of time?
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/83734270
has comment: http://stackoverflow.com/comment/83734218
has title: Why doesn't an invalid exception name in an "except" statement cause a NameError immediately?
downvote count: 0
has comment: http://stackoverflow.com/comment/83734198
has comment: http://stackoverflow.com/comment/83734160
possible better answer: http://stackoverflow.com/a/48373639
favorite count: 0
has comment: http://stackoverflow.com/comment/83734280
type: Question
has comment: http://stackoverflow.com/comment/83734296

http://stackoverflow.com/a/48349639
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48345305
upvote count: 2
type: AcceptedAnswer
has body: This is called Advanced Indexing: triggered when the selection object is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean. Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view). Your situation is integer advanced indexing, where you pass an array of indexes to be retrieved. As sascha noted in comments, this will create a copy of the data, so the new array will exist independently from the original one (i.e., writing to it will not modify the original array).
score: 2
answers question: http://stackoverflow.com/q/48345305

http://stackoverflow.com/comment/83752422
type: Comment
type: QuestionComment
has text: The error means that you should not use "+" between two classes. You could use "+" between two int variables.
comment on: http://stackoverflow.com/q/48382644
score: 0

http://stackoverflow.com/a/48435916
answers question: http://stackoverflow.com/q/48415862
has body: Why two loops , you can do in one loop : data=[['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']] year=[] contenst=[] for i in data: year.append(int(i[0])) contenst.append(int(i[1])) print(year) print(contenst) output: [1951, 1957, 1962, 1967, 1971, 1977] [1874, 1519, 1985, 2369, 2784, 2439]
accepted answer of: http://stackoverflow.com/q/48415862
type: AcceptedAnswer
type: Answer
downvote count: 0
upvote count: 1
score: 1

matplotlib
tags question: http://stackoverflow.com/q/48457951
tags question: http://stackoverflow.com/q/48428729
tags question: http://stackoverflow.com/q/48485538
tags question: http://stackoverflow.com/q/48391146
tags question: http://stackoverflow.com/q/48472011
tags question: http://stackoverflow.com/q/48366017
tags question: http://stackoverflow.com/q/48483527
tags question: http://stackoverflow.com/q/48382626
tags question: http://stackoverflow.com/q/48418534
tags question: http://stackoverflow.com/q/48452494
tags question: http://stackoverflow.com/q/48389470
tags question: http://stackoverflow.com/q/48392010
tags question: http://stackoverflow.com/q/48430358
tags question: http://stackoverflow.com/q/48350675
tags question: http://stackoverflow.com/q/48480985
tags question: http://stackoverflow.com/q/48468921
tags question: http://stackoverflow.com/q/48428562
tags question: http://stackoverflow.com/q/48376000
tags question: http://stackoverflow.com/q/48372905
tags question: http://stackoverflow.com/q/48456028
tags question: http://stackoverflow.com/q/48373743
tags question: http://stackoverflow.com/q/48477451
tags question: http://stackoverflow.com/q/48344745
tags question: http://stackoverflow.com/q/48397567
tags question: http://stackoverflow.com/q/48444312
tags question: http://stackoverflow.com/q/48435229
tags question: http://stackoverflow.com/q/48374580
tags question: http://stackoverflow.com/q/48402019
tags question: http://stackoverflow.com/q/48344566
tags question: http://stackoverflow.com/q/48446351
tags question: http://stackoverflow.com/q/48435538
tags question: http://stackoverflow.com/q/48375171
tags question: http://stackoverflow.com/q/48454263
tags question: http://stackoverflow.com/q/48331097
tags question: http://stackoverflow.com/q/48334315
tags question: http://stackoverflow.com/q/48466995
tags question: http://stackoverflow.com/q/48372758
tags question: http://stackoverflow.com/q/48333063
tags question: http://stackoverflow.com/q/48456298
tags question: http://stackoverflow.com/q/48407338
tags question: http://stackoverflow.com/q/48433772
tags question: http://stackoverflow.com/q/48361637
tags question: http://stackoverflow.com/q/48478956
tags question: http://stackoverflow.com/q/48443102
tags question: http://stackoverflow.com/q/48400932
tags question: http://stackoverflow.com/q/48408123
tags question: http://stackoverflow.com/q/48454525
tags question: http://stackoverflow.com/q/48393305
tags question: http://stackoverflow.com/q/48432978
tags question: http://stackoverflow.com/q/48403986
tags question: http://stackoverflow.com/q/48408670
tags question: http://stackoverflow.com/q/48395209
tags question: http://stackoverflow.com/q/48383266
tags question: http://stackoverflow.com/q/48471546
tags question: http://stackoverflow.com/q/48449106
tags question: http://stackoverflow.com/q/48380962
tags question: http://stackoverflow.com/q/48476117
tags question: http://stackoverflow.com/q/48332964
tags question: http://stackoverflow.com/q/48420864
tags question: http://stackoverflow.com/q/48393080
tags question: http://stackoverflow.com/q/48374092
tags question: http://stackoverflow.com/q/48436940
tag name: matplotlib
tags question: http://stackoverflow.com/q/48391019
tags question: http://stackoverflow.com/q/48348953
tags question: http://stackoverflow.com/q/48468463
tags question: http://stackoverflow.com/q/48442713
tags question: http://stackoverflow.com/q/48391568
tags question: http://stackoverflow.com/q/48480588
tags question: http://stackoverflow.com/q/48424622
tags question: http://stackoverflow.com/q/48399182
tags question: http://stackoverflow.com/q/48410579
tags question: http://stackoverflow.com/q/48360377
tags question: http://stackoverflow.com/q/48419163
tags question: http://stackoverflow.com/q/48358442
tags question: http://stackoverflow.com/q/48385200
tags question: http://stackoverflow.com/q/48430069
tags question: http://stackoverflow.com/q/48385336
tags question: http://stackoverflow.com/q/48457887
tags question: http://stackoverflow.com/q/48351853

http://stackoverflow.com/comment/83913746
has text: Can you add data sample?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48460466

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48368186
tags question: http://stackoverflow.com/q/48347569
tags question: http://stackoverflow.com/q/48342039
tags question: http://stackoverflow.com/q/48467917
tags question: http://stackoverflow.com/q/48485131
tags question: http://stackoverflow.com/q/48450867
tags question: http://stackoverflow.com/q/48382245
tag name: kivy-language
tags question: http://stackoverflow.com/q/48486807

http://stackoverflow.com/q/48416982
type: Question
has comment: http://stackoverflow.com/comment/83839103
has title: How implement 1d covolutional autoencoder for text data in Keras?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83827928
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/83825649
tagged with: keras
has comment: http://stackoverflow.com/comment/83827334
score: 0
has comment: http://stackoverflow.com/comment/83828276
has comment: http://stackoverflow.com/comment/83828083
answer count: 0
tagged with: deep-learning
upvote count: 1
has body: I have bio medical related text data and I want to apply clustering. Here is my code Sequence_len = 58 ebbed_size = 50 I use glove pre trained word vector inputs = Input(shape=(SEQUENCE_LEN, EMBED_SIZE), name="input") x = Conv1D(filters=NUM_FILTERS, kernel_size=NUM_WORDS, activation="relu")(inputs) x = MaxPooling1D(pool_size=pool_size)(x) x = Conv1D(filters=12, kernel_size=NUM_WORDS, activation="relu")(inputs) x = MaxPooling1D(pool_size=pool_size)(x) x = Conv1D(filters=8, kernel_size=NUM_WORDS, activation="relu")(x) encoded = MaxPooling1D(pool_size=pool_size)(x) x = Conv1D(filters=12, kernel_size=NUM_WORDS, activation="relu")(encoded) x = UpSampling1D(size=pool_size)(x) x = Conv1D(filters=16, kernel_size=NUM_WORDS, activation="relu")(x) x = UpSampling1D(size=pool_size)(x) decoded = Conv1D(inputs, kernel_size=NUM_WORDS, activation="sigmoid", data_format='channels_first')(x) autoencoder = Model(inputs, decoded) autoencoder.compile(optimizer="sgd", loss="mse") When I run this code I get this error ValueError: Negative dimension size caused by subtracting 3 from 1 for 'conv1d_37/convolution/Conv2D' (op: 'Conv2D') with input shapes: [?,1,1,8], [1,3,8,12].
downvote count: 1
has comment: http://stackoverflow.com/comment/83827475
favorite count: 0

http://stackoverflow.com/q/48466151
type: Question
has title: Python refactoring fails in Visual Studio Code
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/48480837
upvote count: 13
has body: I switched to Visual Studio Code for Python programming recently. Below is my Python configuration in Visual Studio Code settings: "python.pythonPath": "/Users/hzhang/.virtualenvs/env-2.7/bin/python", "python.autoComplete.extraPaths": [ "/Users/hzhang/Work/xxx/shared_modules" ], Basically, I just configure the Python interpreter and add one extra shared module path. When I try to refactor a variable name, it throws this error which says rope is not installed, and it doesn't work even I install it. Based on my understanding, refactor variables is a feature of Visual Studio Code, and it shouldn't rely on any specific language. How can I fix this problem? Once I installed rope, refactor was still not working. It popups this error: I am on Python 2.7 Visual Studio Code: Version 1.19.3 (1.19.3) Rope version: 0.10.7
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/83977039
has answer: http://stackoverflow.com/a/53686203
has answer: http://stackoverflow.com/a/61745388
possible better answer: http://stackoverflow.com/a/53686203
has comment: http://stackoverflow.com/comment/84005194
tagged with: automated-refactoring
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48480837
favorite count: 0

http://stackoverflow.com/comment/84456956
has text: It's completely unclear code, *Gradient is becoming larger and larger until python cannot process it anymore* , what do you even mean by that? Are you getting a MemoryError or something?
type: Comment
comment on: http://stackoverflow.com/q/48348275
type: QuestionComment
score: 0

http://stackoverflow.com/a/48393244
has body: This is one way: import pandas as pd df = pd.DataFrame([[1, 'ijk', 1, 2, 3, 3, 2, 0, 1], [2, 'mno', 2, 1, 1, 3, 1, 1, 1]], columns=['Day', 'Name', 'a', 'b', 1, 2, 3, 'x1', 'x2']) for i in range(1, 4): df['y'+str(i)] = df['a'] * df['b'] + df[i] #output #Day Name a b 1 2 3 x1 x2 y1 y2 y3 #1 ijk 1 2 3 3 2 0 1 5 5 4 #2 mno 2 1 1 3 1 1 1 3 5 3
answers question: http://stackoverflow.com/q/48387318
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48387318

http://stackoverflow.com/q/48460957
has title: Sending emails using outlook with Python - Overcoming Azure Information Protection Classifications
has comment: http://stackoverflow.com/comment/84895006
tagged with: outlook
answer count: 2
has answer: http://stackoverflow.com/a/78454428
upvote count: 2
type: UnansweredQuestion
tagged with: azure-information-protection
has body: I am using win32com to create emails, but with Azure Information Protection now enabled how do I select the classification from within python. I have 2 solutions so far: turn off AIP or manually select the classification, is there any way to automate it from the script? Thanks!
downvote count: 1
tagged with: azure
score: 1
tagged with: email
tagged with: python
has answer: http://stackoverflow.com/a/48559604
favorite count: 0
type: Question

http://stackoverflow.com/a/48439618
type: Answer
accepted answer of: http://stackoverflow.com/q/48410086
score: 0
answers question: http://stackoverflow.com/q/48410086
type: AcceptedAnswer
has body: first install this from python executable file:- import pip pip.main(["install","bs4"])
has comment: http://stackoverflow.com/comment/83913906

http://stackoverflow.com/comment/83736366
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48374608
type: QuestionComment
has text: First google result for "sitemap parser python": https://gist.github.com/chrisguitarguy/1305010

http://stackoverflow.com/comment/84186036
comment on: http://stackoverflow.com/a/48482993
score: 0
type: AnswerComment
type: Comment
has text: This answer worked for me, but not until I moved all the files into a subdirectory named "rpn" and adjusted the imports accordingly.

http://stackoverflow.com/q/48347661
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48347788
tagged with: python
has body: I used the Pillow library to show an image (called 'beach_sky.jpg'), but when I use the show() function, nothing happens! I read that a utility called 'xv' is necessary... I'm using an Android device by the way. Here's the code : from PIL import Image img = Image.open('beach_sky.jpg') img.show() Terminal output: """ WARNING: linker: _imaging.cpython-36m.so: unused DT entry: type 0x6ffffffe arg 0x45ec WARNING: linker: _imaging.cpython-36m.so: unused DT entry: type 0x6fffffff arg 0x1 [Program finished] """ Can you help me somehow showing the image?
type: Question
downvote count: 0
upvote count: 1
has title: How to successfully show an image with Pillow in Python?
answer count: 1
accepted answer: http://stackoverflow.com/a/48347788
favorite count: 0

http://stackoverflow.com/comment/83909673
type: QuestionComment
type: Comment
has text: `<class 'numpy.int32'>` is not `<class 'int'>`. So if you are working with `numpy` instead of checking for `isinstance(foo, int)`, check for `isinstance(foo, np.int32)`.
score: 0
comment on: http://stackoverflow.com/q/48458438

http://stackoverflow.com/q/48346572
duplicate of: http://stackoverflow.com/q/18281865
has answer: http://stackoverflow.com/a/48346602
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has body: I am trying to remove \n character from a sentence using strip() command, But it doesn't seem to work. str1 = "Hello World \n, I\n am \nhere" print(str1.strip()) Output Hello World , I am here
has title: How to remove \n character from a sentence using strip()
tagged with: strip
tagged with: newline
duplicate of: http://stackoverflow.com/q/31118332
tagged with: python
has comment: http://stackoverflow.com/comment/83678925
accepted answer: http://stackoverflow.com/a/48346602
type: Question
score: 2
upvote count: 3
answer count: 1

tensorflow
tags question: http://stackoverflow.com/q/48345006
tags question: http://stackoverflow.com/q/48392776
type: Tag
tags question: http://stackoverflow.com/q/48350117
tags question: http://stackoverflow.com/q/48482746
tags question: http://stackoverflow.com/q/48408062
tags question: http://stackoverflow.com/q/48384209
tags question: http://stackoverflow.com/q/48442117
tags question: http://stackoverflow.com/q/48346448
tags question: http://stackoverflow.com/q/48358941
tags question: http://stackoverflow.com/q/48479010
tags question: http://stackoverflow.com/q/48353821
tags question: http://stackoverflow.com/q/48453143
tags question: http://stackoverflow.com/q/48406763
tags question: http://stackoverflow.com/q/48357855
tags question: http://stackoverflow.com/q/48380547
tags question: http://stackoverflow.com/q/48378605
tags question: http://stackoverflow.com/q/48337489
tags question: http://stackoverflow.com/q/48369862
tags question: http://stackoverflow.com/q/48446306
tags question: http://stackoverflow.com/q/48463442
tags question: http://stackoverflow.com/q/48480238
tags question: http://stackoverflow.com/q/48340309
tags question: http://stackoverflow.com/q/48398229
tags question: http://stackoverflow.com/q/48344974
tags question: http://stackoverflow.com/q/48333097
tags question: http://stackoverflow.com/q/48361249
tags question: http://stackoverflow.com/q/48463250
tags question: http://stackoverflow.com/q/48386929
tags question: http://stackoverflow.com/q/48432622
tags question: http://stackoverflow.com/q/48437286
tags question: http://stackoverflow.com/q/48479517
tags question: http://stackoverflow.com/q/48374339
tags question: http://stackoverflow.com/q/48472331
tags question: http://stackoverflow.com/q/48447250
tags question: http://stackoverflow.com/q/48484985
tags question: http://stackoverflow.com/q/48429611
tags question: http://stackoverflow.com/q/48434407
tags question: http://stackoverflow.com/q/48414984
tags question: http://stackoverflow.com/q/48433796
tags question: http://stackoverflow.com/q/48483489
tags question: http://stackoverflow.com/q/48454195
tags question: http://stackoverflow.com/q/48357434
tags question: http://stackoverflow.com/q/48477909
tags question: http://stackoverflow.com/q/48349930
tags question: http://stackoverflow.com/q/48486304
tags question: http://stackoverflow.com/q/48419758
tags question: http://stackoverflow.com/q/48421061
tags question: http://stackoverflow.com/q/48416307
tags question: http://stackoverflow.com/q/48410530
tags question: http://stackoverflow.com/q/48385265
tags question: http://stackoverflow.com/q/48364263
tags question: http://stackoverflow.com/q/48454455
tags question: http://stackoverflow.com/q/48466192
tags question: http://stackoverflow.com/q/48447149
tags question: http://stackoverflow.com/q/48465649
tags question: http://stackoverflow.com/q/48484854
tags question: http://stackoverflow.com/q/48384245
tags question: http://stackoverflow.com/q/48393440
tags question: http://stackoverflow.com/q/48400600
tags question: http://stackoverflow.com/q/48460913
tags question: http://stackoverflow.com/q/48340960
tags question: http://stackoverflow.com/q/48373038
tags question: http://stackoverflow.com/q/48464597
tags question: http://stackoverflow.com/q/48438122
tags question: http://stackoverflow.com/q/48471794
tags question: http://stackoverflow.com/q/48423019
tags question: http://stackoverflow.com/q/48405386
tags question: http://stackoverflow.com/q/48369959
tags question: http://stackoverflow.com/q/48396554
tags question: http://stackoverflow.com/q/48431507
tags question: http://stackoverflow.com/q/48339129
tags question: http://stackoverflow.com/q/48393959
tags question: http://stackoverflow.com/q/48335132
tags question: http://stackoverflow.com/q/48431282
tags question: http://stackoverflow.com/q/48481873
tags question: http://stackoverflow.com/q/48486945
tags question: http://stackoverflow.com/q/48404153
tags question: http://stackoverflow.com/q/48334756
tags question: http://stackoverflow.com/q/48385868

http://stackoverflow.com/a/48412712
score: 1
answers question: http://stackoverflow.com/q/48412684
downvote count: 0
upvote count: 1
has body: in your code you keep setting posts equal to 0 in your loop. Move the post = 0 part to before the loop and what you tried before should work.
type: Answer

http://stackoverflow.com/comment/83899746
type: Comment
comment on: http://stackoverflow.com/q/48451806
type: QuestionComment
score: 0
has text: I don't, this is part of a project that I am working on to write tests with. I would access shadow-root that is marked as (open) with no problem, but with the (user-agent) ones they always come back as null, which makes me think they are closed shadow DOMs.

http://stackoverflow.com/comment/83682159
has text: Thanks, @MrSimple, I am new to ES but I think you are right, I think that there is no reasonable way to do this efficiently without going to the root of the problem and dealing with the duplication problem itself.
type: Comment
comment on: http://stackoverflow.com/q/48332479
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83926313
comment on: http://stackoverflow.com/q/48466416
score: 0
has text: Correction - your code needs a bit of formatting
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48347260
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83680796
answers question: http://stackoverflow.com/q/48347157
has body: You should do a single query to get the ticket with the related user for each one, then create the list of dicts from there. Assuming your Ticket model has an "owner" field which is a FK to User: queryset = Ticket.objects.filter(event=value).select_related('owner') result_list = [{'ticket_id': ticket.id, 'username': ticket.owner.username, 'user_id': ticket.owner.id} for ticket in queryset] (Note, this shouldn't be the action of a POST though; that is for changing data in the db, not querying.)
type: Answer
accepted answer of: http://stackoverflow.com/q/48347157
score: 1

http://stackoverflow.com/comment/83943050
has text: `def hello()` is from outside my code. I added redundancy to that fact to make the question more clear.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48474842

http://stackoverflow.com/comment/83862720
comment on: http://stackoverflow.com/a/48417007
score: 0
type: Comment
has text: Thank you Ove for your answer and giving me direction for where to look this up! I'll start reading up on this!
type: AnswerComment

http://stackoverflow.com/a/48450824
has comment: http://stackoverflow.com/comment/83930522
score: 0
has body: The issue is in y_sequence_ix[j] because your j range function is using SEQ_LENGTH+1. This is what you want since you're predicting the next value in the list but it also creates an issue in that y_sequence_ix is 1 sample too short on the last iteration of i when data splits evenly with SEQ_LENGTH. import string import random import numpy as np ix_to_char = list(string.ascii_lowercase) data = [random.choice(string.ascii_lowercase) for x in range(1000)] char_to_ix = {v:i for i,v in enumerate(ix_to_char)} VOCAB_SIZE = len(char_to_ix) SEQ_LENGTH = 5 usable_len = len(data)-1 #Note: don't try to use the last entry in data X = np.zeros((int(usable_len/SEQ_LENGTH), SEQ_LENGTH, VOCAB_SIZE)) y = np.zeros((int(usable_len/SEQ_LENGTH), SEQ_LENGTH, VOCAB_SIZE)) for i in range(0, int(usable_len/SEQ_LENGTH)): X_sequence = data[i*SEQ_LENGTH:(i+1)*SEQ_LENGTH] X_sequence_ix = [char_to_ix[value] for value in X_sequence] input_sequence = np.zeros((SEQ_LENGTH, VOCAB_SIZE)) for j in range(SEQ_LENGTH): input_sequence[j][X_sequence_ix[j]] = 1. X[i] = input_sequence y_sequence = data[i*SEQ_LENGTH+1:(i+1)*SEQ_LENGTH+1] y_sequence_ix = [char_to_ix[value] for value in y_sequence] target_sequence = np.zeros((SEQ_LENGTH, VOCAB_SIZE)) for j in range(SEQ_LENGTH): target_sequence[j][y_sequence_ix[j]] = 1 y[i] = target_sequence Other that the data creation at the top, the only thing modified here is use len(data)-1 in the data creation instead of len(data). By truncating a single value, you assure you won't get an index out of range type error. This is the easiest thing to do, however you could also set SEQ_LENGTH to be a value that isn't an even multiple of len(data), ie.. 6 would work for the above example.
answers question: http://stackoverflow.com/q/48450268
has comment: http://stackoverflow.com/comment/83928847
has comment: http://stackoverflow.com/comment/83928884
type: Answer

http://stackoverflow.com/comment/83829978
type: Comment
score: 0
type: AnswerComment
has text: do I need add new sock in uwsgi for upstream to use?
comment on: http://stackoverflow.com/a/48419709

http://stackoverflow.com/q/48336934
has comment: http://stackoverflow.com/comment/83661514
answer count: 0
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
tagged with: urllib
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to read and parse website content. I am using Python 3.5.2 But I have done it for like 300.000 entries. At some point, I got two errors; 1.TimeoutError: [WinError 10060] 2. AttributeError: type object 'URLError' has no attribute 'reason' I have searched for these errors and tried some of the solutions. But, I am still getting them. I dont know how to solve the first error. For the second errors, it tells me there is no attribute "reason" in URLError. But I have also tried "code" attribute. In addition to this, the webpage exist when I control it, why I am getting these errors. How can I solve two of the errors? Error in pdb no chain added. Obj is empty. 3dzd &lt;class 'urllib.error.URLError'&gt; Traceback (most recent call last): File "C:\...\AppData\Local\Programs\Python\Python35\lib\urllib\request.py", line 1254, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1106, in request self._send_request(method, url, body, headers) File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1151, in _send_request self.endheaders(body) File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1102, in endheaders self._send_output(message_body) File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 934, in _send_output self.send(msg) File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 877, in send self.connect() File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1252, in connect super().connect() File "C:\...\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 849, in connect (self.host,self.port), self.timeout, self.source_address) File "C:\...\AppData\Local\Programs\Python\Python35\lib\socket.py", line 711, in create_connection raise err File "C:\...\AppData\Local\Programs\Python\Python35\lib\socket.py", line 702, in create_connection s…
has comment: http://stackoverflow.com/comment/83663812
tagged with: timeout
tagged with: python
has title: TimeoutError: [WinError 10060] and URLError when using urllib in Python3

http://stackoverflow.com/q/48351994
has comment: http://stackoverflow.com/comment/83690811
has comment: http://stackoverflow.com/comment/83690762
has comment: http://stackoverflow.com/comment/83691000
has comment: http://stackoverflow.com/comment/83690778
has title: How to ensure IP camera compatibility for streaming with OpenCV in Python?
tagged with: url
has comment: http://stackoverflow.com/comment/83690879
type: Question
has body: Can anyone tell if this IP camera is capable of streaming in OpenCV. I tried this but still not working. I think the problem is to find the correct URL, I'm hoping you could find some solution on this problem. Rover System: MODEL - RND-813HBKSCD IP dome camera This sample code from python 2.7/3 works fine in my laptop camera but when I try my IP camera it doesn't respond to it. import cv2 import numpy as np faceDetect=cv2.CascadeClassifier('C:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml'); cam=cv2.VideoCapture(0); while(True): ret,img=cam.read(); gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces=faceDetect.detectMultiScale(gray,1.3,5); for(x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Face", img); if(cv2.waitKey(1)==ord('q')): break; cam.release() cv2.destroyAllWindows when I use this sample IP camera URL: cap = cv2.VideoCapture("http://admin:admin12345@192.168.0.0/mjpg/video.mjpg") It's get this. error: Traceback (most recent call last): File "C:\Users\Romel II G. Albia\Surveillance_IPC\IPCNB\Snap\192.168.1.13\stream1.py", line 17, in main() File "C:\Users\Romel II G. Albia\Surveillance_IPC\IPCNB\Snap\192.168.1.13\stream1.py", line 9, in main cv2.imshow('frame', frame) error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\highgui\src\window.cpp:331: error: (-215) size.width>0 &amp;&amp; size.height>0 in function cv::imshow
tagged with: opencv
has comment: http://stackoverflow.com/comment/83690960
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83690919
tagged with: ip-camera
tagged with: python
tagged with: rtsp
has comment: http://stackoverflow.com/comment/83690831
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83690729

http://stackoverflow.com/a/67749405
type: Answer
has body: See Pygame OpenGL init causes an X Error. The issue has nothing to do with your code. It is causes by your system or graphics driver. Possibly you have to update pygame.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48350671

http://stackoverflow.com/q/48435920
score: 4
type: AnsweredQuestion
has body: I am looking to iterate over a list with duplicate values. The 101 has 101.A and 101.B which is right but the 102 starts from 102.C instead of 102.A import string room_numbers = ['101','103','101','102','104','105','106','107','102','108'] door_numbers = [] num_count = 0 for el in room_numbers: if room_numbers.count(el) == 1: door_numbers.append("%s.%s" % (el, string.ascii_uppercase[0])) elif room_numbers.count(el) &gt; 1: door_numbers.append("%s.%s" % (el, string.ascii_uppercase[num_count])) num_count += 1 door_numbers = ['101.A','103.A','101.B','102.C','104.A', '105.A','106.A','107.A','102.D','108.A']
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48436585
possible better answer: http://stackoverflow.com/a/48436088
has answer: http://stackoverflow.com/a/48436585
has answer: http://stackoverflow.com/a/48436797
has answer: http://stackoverflow.com/a/48436088
has comment: http://stackoverflow.com/comment/83863177
has comment: http://stackoverflow.com/comment/83863350
has comment: http://stackoverflow.com/comment/83863401
tagged with: python
has title: iterating over list containing duplicate values
has comment: http://stackoverflow.com/comment/83863206
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/48436103
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83863458
downvote count: 0

http://stackoverflow.com/comment/83692319
has text: This is very helpful and exactly what I wanted. Thanks for taking the time to explain that to me. Much appreciated.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48352698

http://stackoverflow.com/a/48400264
type: Answer
has body: Based on Spearman's rank correlation coefficient definition, we have to order one list and give a position number to each instance. So as it can be seen in the second example it doesn't matter we use value list or rank list but its essential to take into account two instance lists as one pair of instances list and call each pair with a name. So on a nominal list, we fix one list and find the rank of each list member in the second list and put this rank in the same position. In this case, we have to find the ranking list of items for each person but with the same item order. It doesn't important we chose which order for items. [Item_0, Item_1, Item_2, Item_3] person_1: [3,1,4,2] or [2,0,3,1] person_2: [4,1,3,2] or [3,0,2,1] &gt;&gt;&gt; stats.spearmanr([3,1,4,2],[4,1,3,2]) SpearmanrResult(correlation=0.79999999999999993, pvalue=0.20000000000000007) or: [Item_1, Item_3, Item_0, Item_2] person_1: [1,2,3,4] or [0,1,2,3] person_2: [1,2,4,3] or [0,1,3,2] &gt;&gt;&gt; stats.spearmanr([1,2,3,4],[1,2,4,3]) SpearmanrResult(correlation=0.79999999999999993, pvalue=0.20000000000000007)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48398265
score: 1

http://stackoverflow.com/q/48366903
upvote count: 0
downvote count: 2
tagged with: arrays
tagged with: python
answer count: 1
has title: not able to store a csv file data into an array in python
type: Question
has answer: http://stackoverflow.com/a/48366940
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83720608
has body: Not able to store the data in an array &amp; plot the array data on scatterplot with open('Infosys.csv','r') as csv_file : csv_reader = csv.reader(csv_file) print(csv_reader) next(csv_reader) for line in csv_reader : x[i] = line[2] print(x) i=i+1 #X = array.array('i',x) with open('Infosys.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) print(csv_reader) next(csv_reader) for p in csv_reader : y = p[5] print(y) plt.scatter(x,y,label='pt.',color='red')
score: -2
favorite count: 0
accepted answer: http://stackoverflow.com/a/48366940
type: AnsweredQuestion

http://stackoverflow.com/comment/83729870
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48371363
type: Comment
has text: @彼得名姓, `i` is a start of the interval of length `len`, the end of this interval is `i+len-1`. But we also need to prevent going out of the array bounds, thus we need to limit `i` with `n-len`.

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/48454870
tag name: directed-acyclic-graphs

http://stackoverflow.com/comment/83754177
comment on: http://stackoverflow.com/q/48361281
type: Comment
type: QuestionComment
has text: Can you split your code into two separate executions? Something like this: `window.Highcharts.charts[0].xAxis[0].setExtremes(Date.UTC(2017, 0, 7)` to set extremes, then `return window.Highcharts.charts[0].series[0].options.data`.
score: 0

http://stackoverflow.com/q/48389234
tagged with: python
has comment: http://stackoverflow.com/comment/83766143
has comment: http://stackoverflow.com/comment/83766429
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83766215
has answer: http://stackoverflow.com/a/48389299
tagged with: while-loop
has comment: http://stackoverflow.com/comment/83766162
has title: While Loop doesn't break when enter (return) key is pressed
has body: The program below is a dice simulator using the random library written in Python3. It randomly selects 1 digit out of 6 numbers that are there on a dice. import random while True: pipe = input("Type y to roll the dice ") if pipe in ('y'): numbers = [1,2,3,4,5,6] x = random.choice(numbers) print (x) else: print ("GoodBye") break Problem: When I press the enter (return) key upon execution the program is using the 'y' case and giving out a random value and not ending (breaking the loop) the program. Why is that?
has comment: http://stackoverflow.com/comment/83766425
has comment: http://stackoverflow.com/comment/83766177
possible better answer: http://stackoverflow.com/a/48405445
type: Question
has answer: http://stackoverflow.com/a/48405445
accepted answer: http://stackoverflow.com/a/48389299
has comment: http://stackoverflow.com/comment/83766286
has comment: http://stackoverflow.com/comment/83766312
has comment: http://stackoverflow.com/comment/83766126

http://stackoverflow.com/q/48453231
score: -1
has body: import math as m a = 6378137.0 c = 6356752.314245 e = m.sqrt( 1 - ((c**2)/(a**2)) s = 2 * (m.pi) * ( a**2 ) * ( 1 + ( ( ( 1 - ( e**2 ) ) / e ) ) * (m.atanh( e )) ) print( s ) my code is throwing an invalid syntax error on line 6, when I try to define the s variable.
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48453374
upvote count: 1
has comment: http://stackoverflow.com/comment/83899798
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48453236
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83899990
type: UnansweredQuestion
has title: "invalid syntax" thrown upon defining a variable
tagged with: spyder
tagged with: python

http://stackoverflow.com/a/48392724
has body: Try this: import pandas as pd df = pd.read_csv("file.csv", sep='\t', header=[0, 1], index_col=0) df2 = df.xs('read_count', axis = 1, level = 1) Copied from here: pandas multiindex - how to select second level when using columns? I also tried using pd.melt, but didn't get a good solution. Note that if the file is an appreciable fraction of the machine's memory, reading it in may cause issues. You can try setting chunksize if performance is an issue. I believe, but am not sure, that pandas reads the entire file into memory when read_csv is called, even if only a portion of the file is then stored in the df.
accepted answer of: http://stackoverflow.com/q/48391867
type: Answer
has comment: http://stackoverflow.com/comment/83790448
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83775351
has comment: http://stackoverflow.com/comment/83774404
answers question: http://stackoverflow.com/q/48391867

http://stackoverflow.com/comment/83734486
has text: Does this function also work if there are no,or many leading zeros? I ask because i don't understand the " *'0' " when you define c. Thanks anyways
type: Comment
comment on: http://stackoverflow.com/a/48373645
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83690210
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48347269
type: Comment
has text: This means you have not configured aws account. please do pip install awscli & do aws configure as explained at https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html .Once this is done your code should work.

http://stackoverflow.com/q/48408946
tagged with: datetime
has title: Parsing Timestamp in Python
has comment: http://stackoverflow.com/comment/83807321
tagged with: python
tagged with: timestamp
has answer: http://stackoverflow.com/a/48409213
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48409213
has body: I have an application in which I need to parse timestamps of four different formats. HH:MM:SS HH:MM:SS.mm MM:SS MM:SS.mm How can I write a function to parse any of these formats into a timedelta object? I have tried iterating through the characters one by one and breaking when I see the :, but my code is a mess, so I would rather not have it here as a baseline.
downvote count: 0
linked to: http://stackoverflow.com/q/16138744
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/35241643

http://stackoverflow.com/a/48364395
answers question: http://stackoverflow.com/q/48364284
downvote count: 0
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48364284
has body: What is happening here is that the table loads through JS after the page loads. You have to wait until the table loads. To do that, you'll have to use any one of the Waits specified here. I'll recommend using Explicit Wait. You can do this: First, you'll need to add the following imports. from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException Then change main_table = driver.find_elements_by_tag_name('table') outer_table = main_table[3].find_element_by_tag_name('table') print outer_table.get_attribute('innerHTML') to try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'gvContractors'))) except TimeoutException: pass # Handle the exception here table = driver.find_element_by_id('gvContractors').get_attribute('innerHTML') print(table) It'll give you the required output. I'm not posting the output here since it is too large, but you can verify it by doing this print('Company/Address' in table) which prints True Note: Instead of finding the tables one by one using _by_tag_name you can directly use _by_id to find the table you want. (Here the table has id="gvContractors")

http://stackoverflow.com/a/48451129
has comment: http://stackoverflow.com/comment/83895420
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83898566
accepted answer of: http://stackoverflow.com/q/48450566
has body: 1: If user-acceleration-magnitude-mean is less or equal than 0.973, follow True. (This is continued downwards into the tree.) 2: I googled a bit, and found the "gini coefficient: a statistical measure of the degree of variation represented in a set of values, used especially in analysing income inequality". I think it has been taken out of the economic context, but I don't know for sure if this is the case. 3: There is a underlying structure in this. samples is the amount of samples that apply for that node. There are 3878 samples for the root, 2881 for the left child and 997 for the right child. Since 2881 + 997 = 3878 I believe that for 2881 samples user-acceleration-magnitude-mean &lt;= 0.973 was True. And respectively False for the other 997 samples. The values also have some sort of underlying structure going on. The sum of every value in the value list equals to the amount of samples in that node.
has comment: http://stackoverflow.com/comment/83895318
answers question: http://stackoverflow.com/q/48450566
has comment: http://stackoverflow.com/comment/84021947
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/48378106
has title: Running scrapy splash with rotating proxies
answer count: 1
tagged with: scrapy-splash
has answer: http://stackoverflow.com/a/70479135
has body: I'm trying to use scrapy with splash and rotating proxies. Here's my settings.py: ROBOTSTXT_OBEY = False BOT_NAME = 'mybot' SPIDER_MODULES = ['myproject.spiders'] NEWSPIDER_MODULE = 'myproject.spiders' LOG_LEVEL = 'INFO' USER_AGENT = 'Mozilla/5.0' # JSON file pretty formatting FEED_EXPORT_INDENT = 4 # Suppress dataloss warning messages of scrapy downloader DOWNLOAD_FAIL_ON_DATALOSS = False DOWNLOAD_DELAY = 1.25 # Enable or disable spider middlewares SPIDER_MIDDLEWARES = { 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, } # Enable or disable downloader middlewares DOWNLOADER_MIDDLEWARES = { 'rotating_proxies.middlewares.RotatingProxyMiddleware': 610, 'rotating_proxies.middlewares.BanDetectionMiddleware': 620, 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, } # Splash settings HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' SPLASH_URL = 'http://localhost:8050' I'm setting the ROTATING_PROXY_LIST in my spider: proxy_list = re.findall(r'(\d*\.\d*\.\d*\.\d*\:\d*)\b', requests.get("https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list.txt").text) custom_settings = {'ROTATING_PROXY_LIST': proxy_list} I started splash with docker run -p 8050:8050 scrapinghub/splash. Here's how the splash requests are initiated: def start_requests(self): urls = [ 'http://example-com/page_1.html', 'http://example-com/page_1.html'] for url in urls: yield SplashRequest(url, self.parse_url, headers={'User-Agent': self.user_agent }, args = {'render_all': 1, 'wait': 0.5} ) But, when running the crawler I don't see any requests going through Splash. How can I fix this? Thanks Zin
tagged with: scrapy
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: proxy
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48428717
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83849984
has comment: http://stackoverflow.com/comment/83849838
tagged with: python
has comment: http://stackoverflow.com/comment/83849946
has comment: http://stackoverflow.com/comment/83944859
score: 0
has comment: http://stackoverflow.com/comment/83847933
answer count: 0
has title: Shutil.move doesn't move files
has comment: http://stackoverflow.com/comment/83875874
has body: I am trying to move PDF files from one folder to another using shutil.move. After I execute the script, python doesn't see them anymore, while they are still visible in Windows explorer. If I run the script again, python tells me there are no files. I have to run reverse script in order for python to see them. I use 64-bit Python v3.6.4 on Windows 10. Command prompt with counts import os, sys import shutil from os.path import join Filez=0 PDFZ=0 filovi = os.listdir("C:/Users/Mirko1/pdfannots-master/NoGo") for file in filovi: Filez +=1 if file.endswith(".pdf"): newdr=join('C:\\', 'Users','Mirko1','pdfannots-master','NoGo', file) olddr=join('C:\\', 'Users','Mirko1','pdfannots-master', file) PDFZ +=1 shutil.move(newdr, olddr) print(Filez) print(PDFZ)
type: Question
has comment: http://stackoverflow.com/comment/83875515
has comment: http://stackoverflow.com/comment/83848132

http://stackoverflow.com/q/48434175
has answer: http://stackoverflow.com/a/48434207
upvote count: 2
type: AnsweredQuestion
has title: How to put python and pygame on a flash drive?
answer count: 2
has comment: http://stackoverflow.com/comment/83861934
score: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/48434207
accepted answer: http://stackoverflow.com/a/48434335
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83860338
has body: So I need to be able to bring python to and from my school, and I figured the easiest way would be to put all of it on one flash drive. I would download everything onto the laptop the school gave us but I don't think they would like me downloading things onto their computers. I'm not sure how to go about putting python on a flash drive so if anyone knows how, then it would help a lot.
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/48434335

http://stackoverflow.com/comment/83952324
type: QuestionComment
has text: thanks yes I spent several hours trying every other solution with no success then docker worked on my first try. Hope you can get it working
comment on: http://stackoverflow.com/q/48479571
score: 0
type: Comment

http://stackoverflow.com/comment/83894179
has text: Oh, I see. PyDev is an Eclipse customization. I'd start with the docs for PyDev, assuming that is what you are using. Note the comment above by @Joe
comment on: http://stackoverflow.com/q/48427514
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83928753
type: QuestionComment
comment on: http://stackoverflow.com/q/48467320
score: 0
type: Comment
has text: *Hopefully there is a way to extract and save the file* -- There is no "file". There is the whole string, and there are portions of the string, which apparently you are interested in. A portion of the string could be a file's name, which is a string, too.

http://stackoverflow.com/q/48445459
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/83882786
has answer: http://stackoverflow.com/a/58394634
tagged with: text
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48445588
has comment: http://stackoverflow.com/comment/83882896
answer count: 3
linked to: http://stackoverflow.com/q/517923
has answer: http://stackoverflow.com/a/48445588
linked to: http://stackoverflow.com/q/2400504
downvote count: 2
possible better answer: http://stackoverflow.com/a/48445750
tagged with: diacritics
favorite count: 0
has comment: http://stackoverflow.com/comment/83882842
has body: I have a couple of text files with characters which has diacritical marks, for example è, á, ô and so on. I'd like to replace these characters with e, a, o, etc How can I achieve this in Python? Grateful for help!
type: Question
has comment: http://stackoverflow.com/comment/83882776
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/48445750
linked to: http://stackoverflow.com/q/9491890
has title: Removing diacritical marks using Python

http://stackoverflow.com/comment/83858032
type: AnswerComment
has text: that was just a typo my bad, I know about indents. If there wasn't any indent the code wouldn't work at all and would return an error saying that the indent is not correct...
type: Comment
comment on: http://stackoverflow.com/a/48412391
score: 0

http://stackoverflow.com/q/48450284
tagged with: python
has title: Different ways of calling render() in Django
has answer: http://stackoverflow.com/a/48450599
has comment: http://stackoverflow.com/comment/83894990
score: 1
answer count: 1
downvote count: 0
tagged with: render
has body: I am having some difficulty understanding how render() works. I have read posts about the functionality of the function, however still have unanswered questions. Reading about it in the Django Docs, and looking at the source, it is not a method pertaining to any class. Instead, it is a function just like many others, and one that takes several arguments (request, template_name, etc). Though, in the Django Book, it is stated as a method you can call on a template object. That is, you can instantiate an object, and immediately call the render method on that object with some context. I have previously used it without specifying any template name, merely calling it on a template object with some context, as previously described. Why do the Docs describe it as a free-standing function, not belonging to a class, when it can be called on a template object like as if it was a method of a template class? Why don't I find a template class anywhere? What am I missing?
has comment: http://stackoverflow.com/comment/83893660
upvote count: 1
tagged with: templates
has comment: http://stackoverflow.com/comment/83895223
has comment: http://stackoverflow.com/comment/83900977
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83900965
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83893696
tagged with: django

http://stackoverflow.com/comment/83700144
score: 0
comment on: http://stackoverflow.com/q/48335872
has text: Yes. I can only select Python3 when I click "New" in a top page of Jupyter.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83959785
type: Comment
comment on: http://stackoverflow.com/a/48483289
type: AnswerComment
score: 0
has text: Then I'll have to agree with other comments here and suggest that I cannot reproduce your error. The interpreter only complained about your _unintended_ indentation error.

http://stackoverflow.com/q/48409525
has comment: http://stackoverflow.com/comment/83809536
has title: Crop different portions of image from 4D array for data augmentation
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48409574
tagged with: numpy
has body: I have the following batched RGB image array (4D array): In [55]: img_arr = np.random.randint(0, 255, (10000, 32, 32, 3)) Now, I want to crop only certain dimensions, say (12x12), from the top left corner across all 3 channels, and preferably along the batch dimension (i.e. axis 0) as well, all in one go. My idea was to produce a grid and just slice it. So, I have constructed this grid: In [56]: grid = np.c_[np.arange(12)]+ np.r_[np.arange(12)] In [57]: grid.shape Out[57]: (12, 12) But, when I slice the array, I get something which is unexpected: In [58]: img_arr[:, grid, :].shape Out[58]: (10000, 12, 12, 32, 3) I expected and need the result to be of shape (10000, 12, 12, 3) but I don't know where the 32 is coming from. This is just an example. Ideally, I want to do this cropping at 10 different positions on the image viz. top-left, top-right, bottom-left, bottom-right etc., But, by first doing top-left cropping, the rest should be intuitive. Additionally, as you can see I need to store more than 100K images along the batch dimension in a single 4D array, so it'd be very nice to have a view when doing such random croppings, since it will be memory efficient.
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/83809052
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/83809674
accepted answer: http://stackoverflow.com/a/48409574
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83809308
answer count: 1
has comment: http://stackoverflow.com/comment/83809641
tagged with: image-processing

http://stackoverflow.com/q/48484358
has body: how to get exact value when I use array? why the result is array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) but not 0.7? overlap= np.array([0]*10) tempi = np.zeros(10) for i in range(10): for j in range(10): tempi[j] = 0.7; overlap[i] = max(tempi) print(max(tempi)) overlap
downvote count: 0
tagged with: python
tagged with: type-coercion
score: 1
has answer: http://stackoverflow.com/a/48484429
answer count: 1
has title: Assigning values to a position in a numpy array not modifying the array
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
type: UnansweredQuestion
tagged with: arrays

http://stackoverflow.com/a/48371785
has comment: http://stackoverflow.com/comment/83731837
has comment: http://stackoverflow.com/comment/83731315
has body: As far as I know this is not possible. When handling input, mouse input and touch input are to be handled separately. So to answer the 2 questions you listed at the end: As far as I know there is no way to implement this functionality. You could use the pixel coordinates of the arrows. However you can use Rects for that and test if the place of mouse input/touch input is inside the arrow button Rect with the collidepoint method You can achieve that as follows: arrow_left.collidepoint(mouse_x, mouse_y) I hope this answer helped you!
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83731804
has comment: http://stackoverflow.com/comment/83772362
answers question: http://stackoverflow.com/q/48371137
accepted answer of: http://stackoverflow.com/q/48371137
type: Answer

http://stackoverflow.com/a/48474125
score: -2
has body: k parameter tell random.sample function that how many sample you need, you should write: print (random.sample([Jacks, a], 3)) which means you need 3 sample from your list. the output will be something like: [1, jacks, 0]
type: Answer
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/48474034

http://stackoverflow.com/comment/83666350
has text: `LectureCategory` shows up in the admin panel as 0 or 1 because that's how you defined `LectureCategory` instances to be printed (see `LectureCategory.__str__`)
comment on: http://stackoverflow.com/q/48340494
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83670500
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48339837
type: AnswerComment
has text: The last problem can be solved by having: ` def __copy__(self): \n keywordArgs = vars(self) \n return C(**keywordArgs)` instead.

http://stackoverflow.com/comment/83732788
type: Comment
score: 0
type: AnswerComment
has text: @ChristianDean Yes, I agree, though admittedly. I found the `docs` intimidating when I first started. Sometimes being walked though it in a youtube clip can be quite useful.
comment on: http://stackoverflow.com/a/48372737

http://stackoverflow.com/q/48367591
has comment: http://stackoverflow.com/comment/83743389
tagged with: python-multiprocessing
score: 0
answer count: 0
has body: I'm building a web server via django 1.11.5, that uses celery-3.1.23 &amp; rabbitmq as message queue manager, to send async-tasks to a number of different demon-processes (processes with infinite loop [long time running]). How can I dynamically create queues for each process separately, and receive messages from the process' queue inside the daemon-process, do something asynchronously, and then forward the result to another "aggregator queue", to collect &amp; validate the results, and sending a response to the user. (please see attached ilustracion) So far, I connected the processes via multiprocessing.connection Client and Server objects, and opened the processes by the Process object. code - consumer: from multiprocessing.connection import Listener from multiprocessing import Process def main_process_loop(path, port_id, auth_key): # Initialize the action1 intance to handle work stream: action_handler = ActionHandler(path) # Initialize the infinite loop that will run the process: pid, auth_key_bytes = int(port_id), bytes(auth_key) address = ('localhost', pid) # family is deduced to be 'AF_INET' while True: try: listener = Listener(address, authkey=auth_key_bytes) conn = listener.accept() input_values = conn.recv() listener.close() if input_values == None: raise Exception(ERR_MSG_INVALID_ARGV) else: #do something with input_values and ActionHandler # need to return success message to user except Exception as err: # need to return fail message to user if __name__ == '__main__': # worker_processes = [] for auth_key, port_id in PID_DICT.items(): path = TEMPLATE_FORMAT.format(auth_key) p = Process(target=main_process_loop, args=(path, port_id, auth_key)) # worker_processes.append(p) p.start() # for p in worker_processes: # p.join() # print "all processes have been initiated" code - celery task: from multiprocessing.connection import Client from celery import Celery app = Celery('tasks', broker='amqp://localhost:5672//') @app.task def run_backend_processes(a_lst, b_lst,…
tagged with: django
has title: celery - message queues for long time running processes
tagged with: celery
has comment: http://stackoverflow.com/comment/83839106
type: Question
has comment: http://stackoverflow.com/comment/83725267
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11964742
linked to: http://stackoverflow.com/q/23916413
tagged with: python
tagged with: rabbitmq

http://stackoverflow.com/comment/107601723
type: AnswerComment
has text: Glad it was useful!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48344268

http://stackoverflow.com/q/48362486
has title: Passing information to an imported Python module
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48362515
tagged with: module
score: 2
has body: I wish I could get my module to initialize two different ways, based on an option chosen in the main program. Wishful code: Main program: &lt;magic variable&gt; = True import mymodule mymodule.py: def start1(): ... def start2(): ... if &lt;magic variable&gt;: start1() else: start2() Is there any way to place magic variable where the imported module can find it? Without creating yet another module?
answer count: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48362534
tagged with: initialization
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83711863

http://stackoverflow.com/q/48399323
score: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: io
has title: file not write in current file position
tagged with: python
type: UnansweredQuestion
has body: with open('test.txt', 'w+') as f: f.write('foo') f.seek(0) f.read(1) print f.tell() # 1 f.write('bar') I want the result to be fbar but it returns foobar. Obviously, file does not write at the current file position. with open('test.txt', 'w+') as f: f.write('foo') f.seek(0) f.read(1) m = f.tell() # 1 f.seek(m) f.write('bar') It works as I expect. why do I need seek again while the current file position is already in 1 ?
answer count: 1
has answer: http://stackoverflow.com/a/48399584
tagged with: file

http://stackoverflow.com/comment/83931789
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48468919
type: AnswerComment
has text: ::thunder claps loudly::

http://stackoverflow.com/a/48345990
has body: One common way to share state between functions is to pass that state as an argument to those functions. For example, with tempfile.TemporaryDirectory() as tempdir: move_source_to_dest(tempdir, ...) df_to_csv(tempdir, ...) with move_source_to_dest and df_to_csv re-defined like: def move_source_to_dest(tempdir, key, src_session): # no additional tempdir created here # ... def df_to_csv(key, src_session): # no additional tempdir created here # ...
type: Answer
answers question: http://stackoverflow.com/q/48345943
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/83913986
type: QuestionComment
has text: Welcome to StackOverflow. You can edit your post to add that information, there is an `edit` button at the bottom of your post.
comment on: http://stackoverflow.com/q/48460560
score: 0
type: Comment

http://stackoverflow.com/q/48481958
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83957805
has comment: http://stackoverflow.com/comment/83957837
has title: I can not open Anaconda3
tagged with: python
has comment: http://stackoverflow.com/comment/83976410
score: 0
has comment: http://stackoverflow.com/comment/83957120
tagged with: anaconda
answer count: 0
has body: I downloaded and installed Anaconda3. But when I run it, nothing opens. The screen remains the same. It does not appear in the task manager either.
tagged with: spyder
has comment: http://stackoverflow.com/comment/83957397
has comment: http://stackoverflow.com/comment/83957291
has comment: http://stackoverflow.com/comment/83970008
type: Question
has comment: http://stackoverflow.com/comment/83957881

http://stackoverflow.com/q/48458047
type: Question
has body: I like the Monokai theme that Pycharm 2017.3 comes with, but I can't see what I'm highlighting. E.g.: Nothing highlighted: Highlighted the word delete_table: Question: How do I change the highlight color in PyCharm?
type: UnansweredQuestion
tagged with: python
score: 0
has title: Can not see Pycharm Monokai highlight color
tagged with: pycharm
has answer: http://stackoverflow.com/a/48458048
upvote count: 1
answer count: 1
tagged with: ide
downvote count: 1
favorite count: 0

image
tags question: http://stackoverflow.com/q/48431510
tags question: http://stackoverflow.com/q/48414823
tags question: http://stackoverflow.com/q/48428337
tags question: http://stackoverflow.com/q/48436468
tags question: http://stackoverflow.com/q/48369952
tags question: http://stackoverflow.com/q/48384516
tags question: http://stackoverflow.com/q/48454263
tags question: http://stackoverflow.com/q/48395209
tags question: http://stackoverflow.com/q/48476923
tags question: http://stackoverflow.com/q/48430597
tags question: http://stackoverflow.com/q/48425515
tags question: http://stackoverflow.com/q/48468536
tags question: http://stackoverflow.com/q/48380663
tags question: http://stackoverflow.com/q/48458377
tag name: image
tags question: http://stackoverflow.com/q/48478052
tags question: http://stackoverflow.com/q/48439040
tags question: http://stackoverflow.com/q/48337949
tags question: http://stackoverflow.com/q/48348116
tags question: http://stackoverflow.com/q/48482317
tags question: http://stackoverflow.com/q/48356398
type: Tag
tags question: http://stackoverflow.com/q/48378996
tags question: http://stackoverflow.com/q/48487945
tags question: http://stackoverflow.com/q/48369862
tags question: http://stackoverflow.com/q/48349678
tags question: http://stackoverflow.com/q/48379205
tags question: http://stackoverflow.com/q/48362837

http://stackoverflow.com/comment/83913009
type: Comment
has text: Thank you! I will check it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48445762

http://stackoverflow.com/a/48599443
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48448472
has body: If you want to add all of the downloaded files to a Jupyter notebook, you can use the code here

http://stackoverflow.com/comment/83672563
type: AnswerComment
comment on: http://stackoverflow.com/a/48341598
score: 0
has text: @wilson_smyth For that one would first need to know which pandas version you are using.
type: Comment

http://stackoverflow.com/comment/83884759
comment on: http://stackoverflow.com/q/48444294
score: 0
type: Comment
type: QuestionComment
has text: I'm using python 3.6 with pyramid, and currently just printing to the console to see what's there.

http://stackoverflow.com/q/48430711
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48430750
has title: How to append a third column in a dataframe using conditions from 2 other columns in a dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/48430750
has body: I have the following data frame, uuid variable value AAS Highly_Active False AAS Highly_Active True SAP Highly_Active False SAP Multiple_days True YAS Highly_Active False YAS Highly_Active False YAS Busi_weekday False And I need to use the values from the column variable and value to define third column Activity and I have following classic python code doing it but my primary data frame is 121Mb in size and so its taking long time. Any pandas solutions would be great def activity(row): if row['variable'] == "Highly_Active" and row['value'] ==True: val = "Highly_Active" else: val = "NO" if row['variable'] == "Multiple_days" and row['value']==True: val = "Multiple_days" else: val = "NO" if row['variable'] == "Busi_weekday" and row['value']==True: val = "Busi_weekday" else: val="NO" return val
possible better answer: http://stackoverflow.com/a/48430743
tagged with: data-science
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48430743
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/83904256
comment on: http://stackoverflow.com/q/48344974
type: Comment
score: 0
has text: You have a bug in your provided code; you're always calculating 0 in your setup: `square=tf.reduce_sum(x) # equals v` followed by `root=tf.sqrt(square-v)`
type: QuestionComment

http://stackoverflow.com/comment/83708864
type: QuestionComment
comment on: http://stackoverflow.com/q/48361026
has text: @ChristianDean I tried that but it doesn't work, maybe because my classes don't have a defined module.
type: Comment
score: 0

http://stackoverflow.com/comment/83904749
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48425473
type: Comment
has text: typecast the int to string

http://stackoverflow.com/a/48461964
upvote count: 1
answers question: http://stackoverflow.com/q/48461379
type: Answer
score: 1
has body: I think that there are two ways you could go about this. You could subclass dict to make a new class for which each addition or modification appends a modification time, or you could create function to modify an existing dict that also appends a modification time. Subclassing is probably a more robust method, but I think the later is probably easier / more readable, so having a quick try at that approach: import time def nested_dict_updater(dict, top_key, nested_key, value): dict[top_key][nested_key] = value dict[top_key]['modification_time'] = time.time() # Original dict now = time.time() d = {"top_key": {"nested_key": "value", "modification_time": now}} print(d) # Updated dict nested_dict_updater(d, "top_key", "nested_key", "new_value") print(d) # Add another nested key and value nested_dict_updater(d, "top_key", "another_key", "second_value") print(d) This simple function allows you to update any of your nested key's values, or add a new nested key with value, and records the modified time for that top level key.
downvote count: 0

web-scraping
tags question: http://stackoverflow.com/q/48364814
tags question: http://stackoverflow.com/q/48406930
tags question: http://stackoverflow.com/q/48388564
tags question: http://stackoverflow.com/q/48331820
tags question: http://stackoverflow.com/q/48446684
tags question: http://stackoverflow.com/q/48487876
tags question: http://stackoverflow.com/q/48388552
tags question: http://stackoverflow.com/q/48426624
tags question: http://stackoverflow.com/q/48362237
tags question: http://stackoverflow.com/q/48385165
tags question: http://stackoverflow.com/q/48467245
tags question: http://stackoverflow.com/q/48336828
tag name: web-scraping
tags question: http://stackoverflow.com/q/48375056
tags question: http://stackoverflow.com/q/48474108
tags question: http://stackoverflow.com/q/48363913
tags question: http://stackoverflow.com/q/48363722
tags question: http://stackoverflow.com/q/48421714
tags question: http://stackoverflow.com/q/48450696
tags question: http://stackoverflow.com/q/48444008
tags question: http://stackoverflow.com/q/48449578
tags question: http://stackoverflow.com/q/48364941
tags question: http://stackoverflow.com/q/48390005
tags question: http://stackoverflow.com/q/48461493
tags question: http://stackoverflow.com/q/48382750
tags question: http://stackoverflow.com/q/48399110
tags question: http://stackoverflow.com/q/48466784
tags question: http://stackoverflow.com/q/48470241
tags question: http://stackoverflow.com/q/48428689
tags question: http://stackoverflow.com/q/48480345
type: Tag
tags question: http://stackoverflow.com/q/48383869
tags question: http://stackoverflow.com/q/48361145
tags question: http://stackoverflow.com/q/48364284
tags question: http://stackoverflow.com/q/48395485
tags question: http://stackoverflow.com/q/48477666
tags question: http://stackoverflow.com/q/48375937
tags question: http://stackoverflow.com/q/48459104
tags question: http://stackoverflow.com/q/48435390
tags question: http://stackoverflow.com/q/48410479
tags question: http://stackoverflow.com/q/48401741
tags question: http://stackoverflow.com/q/48478337
tags question: http://stackoverflow.com/q/48376543
tags question: http://stackoverflow.com/q/48334948
tags question: http://stackoverflow.com/q/48438794
tags question: http://stackoverflow.com/q/48407037
tags question: http://stackoverflow.com/q/48482933
tags question: http://stackoverflow.com/q/48481246
tags question: http://stackoverflow.com/q/48352895
tags question: http://stackoverflow.com/q/48334865
tags question: http://stackoverflow.com/q/48454799
tags question: http://stackoverflow.com/q/48393021
tags question: http://stackoverflow.com/q/48343337
tags question: http://stackoverflow.com/q/48393941

http://stackoverflow.com/comment/83756028
type: QuestionComment
has text: That's it. I edited to make it more readable, but there is like 200 lines in total. So I can add more things but I wanted to keep it digest. Thanks for your comments tho, don't hesitate to ask more things
comment on: http://stackoverflow.com/q/48384267
type: Comment
score: 0

http://stackoverflow.com/a/48465787
type: Answer
has body: If you're using a recent version of Python (>= 3.5), you can take advantage of unpacking in mapping literals d1 = {'name':'tom', 'age':'14', 'sex':'m'} d2 = {'color':'w', 'weight':'58','style':'good'} d3 = {'sports':'cricket','music':'rock','dance':'disco'} new_dict = {**d1, **d2, **d3}
upvote count: 6
downvote count: 0
answers question: http://stackoverflow.com/q/48465576
score: 6

sonarqube
tags question: http://stackoverflow.com/q/48359923
tags question: http://stackoverflow.com/q/48410192
type: Tag
tag name: sonarqube

http://stackoverflow.com/comment/83829940
type: QuestionComment
comment on: http://stackoverflow.com/q/48419151
score: 0
has text: @joppich I think he kinda had a diffrent problem
type: Comment

http://stackoverflow.com/q/48443477
has title: use mkdir on python and call list items
tagged with: mkdir
has comment: http://stackoverflow.com/comment/83878559
has comment: http://stackoverflow.com/comment/83878618
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/42677066
has comment: http://stackoverflow.com/comment/83878386
accepted answer: http://stackoverflow.com/a/48443565
has comment: http://stackoverflow.com/comment/83878324
tagged with: os.system
has answer: http://stackoverflow.com/a/48443565
tagged with: python
has body: I would like to create new directories using the names of the subjects contained in the 'subjlist'. I call the bash function 'mkdir' for so, but the command '+subj+' seem not to recognize it as an item on the list. Do you know how to tackle this? Sorry for the silly question, I'm still crawling. #!/usr/bin/python import glob import os path ='/data2/kizilirm/Mooney_fMRI_v01/subject_data' subjlist = ['di21_1028', 'dn20_1072', 'ed17_1026', 'eo56_1016', 'ge51_1039', 'ha96_1069', 'hp84_1024', 'ht02_1049', 'hw44_1051', 'ij99_1073', 'ja58_1070', 'ju49_1036', 'km61_1064', 'kr25_1034', 'lw37_1062', 'lz02_1041', 'mj45_1037', 'nm54_1017', 'od90_1040', 'ol12_1063', 'os19_1038', 'ow93_1061', 'pk62_1074', 'qq31_1068', 'qq39_1060', 'tt42_1025', 'ut93_1048', 'ws81_1042','xi27_1050', 'zd63_1035'] #'series_2_t1_mpr_sag_1iso_p2', runlist = ['series_2_t1_mpr_sag_1iso_p2','series_3_BOLD- fMRI_2x2x(3+0.3)_p2_run1', 'series_4_BOLD-fMRI_2x2x(3+0.3)_p2_run2', 'series_5_BOLD-fMRI_2x2x(3+0.3)_p2_run3'] os.system("mkdir /home/mansur/Documents/mooney") counter = 0 for subj in subjlist: for run in runlist: if run == 'series_2_t1_mpr_sag_1iso_p2': print subj , run counter = counter + 1 os.system("mkdir -p '/home/mansur/Documents/mooney/'+subj+'/'anatomy/high_res") #Here is the problem!!! else: continue print counter
type: AnsweredQuestion
score: 0
tagged with: bash

http://stackoverflow.com/a/48357410
type: Answer
has body: Try this Replace outtweets = [[tweet.fullname_str, tweet.id, tweet.likes, tweet.replies, tweet.retweets, tweet.text.encode('utf-8'),tweet.timestamp,tweet.url,tweet.user] for tweet in all_tweets] with outtweets = [[tweet.fullname, tweet.id, tweet.likes, tweet.replies, tweet.retweets, tweet.text.encode('utf-8'),tweet.timestamp,tweet.url,tweet.user] for tweet in all_tweets['ladygaga']]
has comment: http://stackoverflow.com/comment/83701822
answers question: http://stackoverflow.com/q/48357177
score: 0
has comment: http://stackoverflow.com/comment/83701744
has comment: http://stackoverflow.com/comment/83731060
has comment: http://stackoverflow.com/comment/83701639
has comment: http://stackoverflow.com/comment/83702878
has comment: http://stackoverflow.com/comment/83702792
has comment: http://stackoverflow.com/comment/83701977
has comment: http://stackoverflow.com/comment/83702431

http://stackoverflow.com/comment/83897638
comment on: http://stackoverflow.com/q/48451492
type: Comment
has text: I have edited the question to include extra information.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48343886
score: 0
type: Answer
has body: Consider this: {line.strip().split('\t')[0]:line.split('\t')[1] for line in rdata.splitlines() if line.strip() == '\n'} Use "==" to test for equality and "=" to set value to the variable.
answers question: http://stackoverflow.com/q/48343734

http://stackoverflow.com/comment/83834499
score: 0
comment on: http://stackoverflow.com/q/48418843
has text: @Maarten Fabré The lists within the lists are ordered, but the list of lists are not.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83795417
type: QuestionComment
has text: It is interesting. I thought that it should simply execute the given function which should then create a generator. Thanks.
score: 0
comment on: http://stackoverflow.com/q/48403504
type: Comment

http://stackoverflow.com/comment/83728944
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the response. Are you talking about the PyCharm Terminal, though? I'm asking specifically about the embedded terminal (View > Tool Windows > Terminal), and I think you might be talking about the keymap of the PyCharm Editor.
comment on: http://stackoverflow.com/a/48344507

http://stackoverflow.com/comment/83648450
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48331209
has text: Have you got a `local_settings.py` ?

http://stackoverflow.com/comment/83754370
score: 0
has text: Isn't `pbr` already an "extra requirement"?
type: QuestionComment
comment on: http://stackoverflow.com/q/48383737
type: Comment

http://stackoverflow.com/q/48453412
score: 2
has answer: http://stackoverflow.com/a/48453450
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48455949
answer count: 3
has answer: http://stackoverflow.com/a/48455949
downvote count: 0
has body: Okay so this may be just googling wrong or not reading documentation correctly, but I couldn't find anything on this. Say I have: sample_str = "rose aaron robert moro" pat = 'ro' I want to find all instances of words (preferably using re.search()) which DON'T end OR begin in 'ro'. That is, I want one or more character to be before and after 'ro'. So I would want 'aaron' to match, but not at any of the other words in sample_str. How would I do this? I tried a bunch of things, including '+ro+', but it gave me an error. I am not new to Python but have some trouble with the Regex, so if anyone can please explain that would be great. Thanks
has comment: http://stackoverflow.com/comment/83904531
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83899924
has title: How to find a phrase that is NOT at a word boundary from a string in Regex?
upvote count: 2
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48453450
has answer: http://stackoverflow.com/a/48455606

http://stackoverflow.com/q/48399789
type: Question
has comment: http://stackoverflow.com/comment/83837087
has comment: http://stackoverflow.com/comment/83829549
has comment: http://stackoverflow.com/comment/83826024
score: 1
has title: pydrive upload a file 400 "Bad Request"
tagged with: python
has comment: http://stackoverflow.com/comment/83824530
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/48434510
has comment: http://stackoverflow.com/comment/83825943
tagged with: pydrive
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83819162
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm uploading a file from one GDrive account to another, using PyDrive. I can download the file fine, but then when I go to upload it, I get a 400. pydrive.files.ApiRequestError: &lt;HttpError 400 when requesting https://www.googleapis.com/upload/drive/v2/files?alt=json&amp;uploadType=resumable returned "Bad Request"&gt; This is the ListFolder code: def ListFolder(parent, drive1, drive2): filecount = 0 filelist=[] file_list = drive1.ListFile({'q': "'%s' in parents and trashed=false" % parent}).GetList() for f in file_list: filecount +=1 print("Still working %s" % filecount) if f['mimeType']!='application/vnd.google-apps.folder': # if regular file print("I've found a file - passing %s to download" % f['title']) download_file(drive1, f, drive2) # Download the file Here is the download file code: def download_file(drive1, f, drive2): """This function will download a file from the source drive1 to the local hard drive, just before uploading it to the destination drive- i.e. drive2""" dirpath = tempfile.mkdtemp() print ("Downloading a file %s" % f['title']) filesource = drive1.CreateFile({'id': f['id']}) filesource.GetContentFile(f['title'], f['mimeType']) upload_file(drive2, f) os.remove(f['title']) drive2 is a GoogleDrive instance (with auth passed). f is an item in a file_list that is not a folder. def upload_file(drive2, f): #Will copy files over until it detects a directory """"This function accepts the destination drive, filetitle (which has previously been downloaded from download_file function) and the file mimetype. This function uploads the local file to the destination drive""" filename = f['title'] print("file title: %s" % f['title']) #filetitle) file = drive2.CreateFile() file.SetContentFile(f['title']) file.Upload() I've tried using a string to upload the file, but still get the same results. What else should I be looking for?

http://stackoverflow.com/a/48427221
downvote count: 0
answers question: http://stackoverflow.com/q/48426401
upvote count: 1
has comment: http://stackoverflow.com/comment/83844724
type: Answer
has body: Simply delete the old User model from the previous app, and put the new one in the new app, so that in the end you only have one User class that extends the AbstractUser class. As for your second issue, try this. I hope this helps.
accepted answer of: http://stackoverflow.com/q/48426401
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48362398
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48366248
has title: Can't figure out how to configure email settings for cookiecutter-django
has comment: http://stackoverflow.com/comment/83713968
linked to: http://stackoverflow.com/q/15796530
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83713119
has comment: http://stackoverflow.com/comment/83713206
tagged with: smtp
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: python
has body: I've set up a cookiecutter-django project for testing and it worked just fine printing the confirmation email to the console. However, it's important to me to also test the actual sending of the emails and when I tried to adjust the settings for a local testing environment, it gave me a SMTP AUTH extension not supported by server. error after adding a new account. I changed EMAIL_BACKEND to EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' and added the relevant EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, and EMAIL_HOST_PASSWORD settings in the local.py settings file. I'm using a yahoo account that was set up for this purpose and worked just fine outside of Django. I can't find anything in the cookie-cutter documentation about how to configure this and the Django documentation has been less than helpful. Edit to add: email settings: EMAIL_PORT = 587 EMAIL_HOST = 'smtp.mail.yahoo.com' EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') Full traceback: Internal Server Error: /accounts/signup/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 53, in inner return func(*args, **kwds) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "…
tagged with: cookiecutter-django

http://stackoverflow.com/q/48445577
type: Question
tagged with: numpy
tagged with: view
has comment: http://stackoverflow.com/comment/83882934
answer count: 2
has body: After defining an arrray a with zeros, I can create a view to the leftmost column with the following function: a = np.zeros((5, 5)) a_left_col = a[:, 0] a_left_col[:] = 2. which prints for a: array([[2., 0., 0., 0., 0.], [2., 0., 0., 0., 0.], [2., 0., 0., 0., 0.], [2., 0., 0., 0., 0.], [2., 0., 0., 0., 0.]]) If I subsequently reinitialize a with a = np.zeros((5, 5)) then the view still exists, but it refers to nothing anymore. How does Python handle the situation if I do a_left_col[:] = 2 again? Is this undefined behavior like in C or C++, or does Python handle it properly, and if so, why doesn't it throw an error?
has title: Using a numpy view to a non-existing array
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48445858
favorite count: 0
has answer: http://stackoverflow.com/a/48445858
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/48445752
tagged with: python
has answer: http://stackoverflow.com/a/48445752

http://stackoverflow.com/comment/83891018
comment on: http://stackoverflow.com/a/48448141
type: Comment
score: 0
has text: @AkhilReddy see updated answer, some of the tags do have values
type: AnswerComment

http://stackoverflow.com/q/48378163
type: Question
score: 3
tagged with: django-class-based-views
has comment: http://stackoverflow.com/comment/83744551
has body: I am new to creating API endpoints using Django. Which is a better way to handle API requests and process JsonResponse? Should I do it in a Class-Based View? Or a Functional View? I would assumed CBV would be an overkill since people tend to use CBV for the generic-view inheritance. Since I am merely sending back a Json object, i would consider it unnecessary and thus a Functional view would suffice. However, I am not too sure what exactly are the other components of CBV and FV that would matter and make the difference. If there is one view better over another view, can you please tell me with reasons why one is preferred over another. Cheers.
type: UnansweredQuestion
has title: CBV or Functional View for JsonResponse
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83743532
tagged with: python
has comment: http://stackoverflow.com/comment/83745875
has comment: http://stackoverflow.com/comment/83744963
has comment: http://stackoverflow.com/comment/83743478
answer count: 0
tagged with: api
upvote count: 3
downvote count: 0
tagged with: django
favorite count: 0

http://stackoverflow.com/comment/83933821
has text: @MatthewH yes, the Python 2 input works differently, it is equivalent to `eval(raw_input())` which is just... dangerous. Use `raw_input` always, pretty much.
comment on: http://stackoverflow.com/q/48469884
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48471086
has comment: http://stackoverflow.com/comment/83936267
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83936160
has body: Do any popular Python style guides express a preference between: x = (f'One plus one is ' f'equal to {1+1}') and: x = ('One plus one is ' f'equal to {1+1}') Does it make sense to omit the f prefix for lines that don't involve interpolation? Should it be included for consistency?
tagged with: python
has comment: http://stackoverflow.com/comment/83936308
has answer: http://stackoverflow.com/a/48471223
has comment: http://stackoverflow.com/comment/83936446
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/83936330
has comment: http://stackoverflow.com/comment/83936205
has comment: http://stackoverflow.com/comment/83936149
has comment: http://stackoverflow.com/comment/83936133
upvote count: 14
score: 12
has comment: http://stackoverflow.com/comment/83936398
has comment: http://stackoverflow.com/comment/83936131
downvote count: 2
has comment: http://stackoverflow.com/comment/83936193
answer count: 1
has comment: http://stackoverflow.com/comment/83936379
has comment: http://stackoverflow.com/comment/83936634
has comment: http://stackoverflow.com/comment/83936166
has comment: http://stackoverflow.com/comment/83936208
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83936156
has title: Style for continued multi-line f-strings

http://stackoverflow.com/a/48483096
answers question: http://stackoverflow.com/q/48483041
score: 0
type: Answer
has body: Well, Python has a built-in function called "set()" and you could use it on your "Y" array so that the numbers in it won't get repeated. That of course, won't help you if the numbers are similar yet not the same (I.e. 4.4 and 4.5). In that case you might want to consider making your graph bigger and adding more space between each unit on the scale. The size of the plot can be changed by setting the dynamic rc settings of Matplotlib. These are stored in a dictionary named rcParams. The size of the plot figure is stored with the key figure.figsize. As an example, to get and set the size of a Matplotlib plot: import matplotlib.pyplot as plt # Get current size fig_size = plt.rcParams["figure.figsize"] # Prints: [8.0, 6.0] print "Current size:", fig_size # Set figure width to 12 and height to 9 fig_size[0] = 12 fig_size[1] = 9 plt.rcParams["figure.figsize"] = fig_size

http://stackoverflow.com/a/48465094
score: 1
answers question: http://stackoverflow.com/q/48464630
downvote count: 0
upvote count: 1
type: Answer
has body: I believe you are asking for two different things. PHP is generally running as a server side application thus has specific constructs for error logging. Python can run about any type of application and run multiple instances at once - so what you are asking doesn't really make sense in that context. However, you can still accomplish what you desire. Though you can pipe output to stderr directly from you cron job " > /path/to/log.txt", for more granular information, use pythons logging libarary - part of the standard libary. Personally, though, I prefer pygogo -- it provides a nice wrapper around the logging libary. So... Add some logging to your Python with either the standard library or pygogo Pipe the output from your cron job to a log file using " > " or " tee ". Watch your logs real time using "tail -f /path/to/my/log.txt" I do this regularly, works like a charm.

http://stackoverflow.com/q/48399497
has comment: http://stackoverflow.com/comment/95407602
has comment: http://stackoverflow.com/comment/105314422
has title: Can't run python scripts in Jenkins
has comment: http://stackoverflow.com/comment/84039782
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48560829
has comment: http://stackoverflow.com/comment/84015770
score: 17
has comment: http://stackoverflow.com/comment/84113876
upvote count: 17
tagged with: windows-10
has comment: http://stackoverflow.com/comment/84015108
has comment: http://stackoverflow.com/comment/84113902
has comment: http://stackoverflow.com/comment/83880987
has comment: http://stackoverflow.com/comment/83885534
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84037974
has comment: http://stackoverflow.com/comment/83885980
has comment: http://stackoverflow.com/comment/84070758
tagged with: jenkins
has comment: http://stackoverflow.com/comment/83897977
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83911536
has comment: http://stackoverflow.com/comment/95339997
has comment: http://stackoverflow.com/comment/84070593
has answer: http://stackoverflow.com/a/48559366
has answer: http://stackoverflow.com/a/48728127
tagged with: python
has body: I have been using Jenkins for a few years and recently bought a new Windows 10 PC. I installed Jenkins 2.89.2, Visual Studio 2017 and Python 3.6 and copied several Jenkins jobs from my previous Windows 7 PC. The problem that I encountered was that all the python scripts in the free-style Jenkins jobs now do nothing. I have similar command-line batch files which run these python scripts which work just fine in a command window on the new PC. I have also checked the file associations with ftype, and ended up changing it: ftype Python.File Python.File="D:\Python36_64\python.exe" "%L" %* My work-around is like this: Example line which worked under Windows 7: CreateBuildNumber.py &lt;= uses PATH to find this file, then file associations to run python Replacement line need to work under Windows 10: python .\Scripts\CreateBuildNumber.py &lt;= uses PATH to find python. How can I avoid explicit paths in my scripts? Update: D:\project&gt;assoc | findstr -i python .py=Python.File .pyc=Python.CompiledFile .pyd=Python.Extension .pyo=Python.CompiledFile .pyw=Python.NoConFile .pyz=Python.ArchiveFile .pyzw=Python.NoConArchiveFile echo %PATH% D:\Python36_64;D:\Python36_64\Scripts;.\Scripts;"C:\Program Files\CppCheck";C:\windows\system32 Further Info I removed .\Scripts from the %PATH% and re-ran the job, having also moved demo.py into .\Scripts, now instead of doing nothing there is the error: 'demo.py' is not recognized as an internal or external command, operable program or batch file. This means that Windows IS looking for and finding python scripts, but is failing to execute them. Why would windows not take the next step and use file associations to find an executable program to run, taking the file as a parameter? Update: Now everything works as it should and I don't know why. I recently started using a different job on Jenkins that I had neither run nor touched for over two years and that one just worked without modification. I have since gone back over the job in question and…
has comment: http://stackoverflow.com/comment/83881880

http://stackoverflow.com/q/48413479
has comment: http://stackoverflow.com/comment/83816967
has answer: http://stackoverflow.com/a/48417440
has comment: http://stackoverflow.com/comment/83816946
has comment: http://stackoverflow.com/comment/83816914
tagged with: python
has comment: http://stackoverflow.com/comment/83817024
has comment: http://stackoverflow.com/comment/83817290
has comment: http://stackoverflow.com/comment/83817053
has title: for loop within a list
possible better answer: http://stackoverflow.com/a/48413554
has body: I want to get a ordered list with ascending order, but leave out the first element in the original list. But the first for-loop only runs 4 times. After 4 times loop in first for-loop: lst=[6, 5, 4] I think the first for-loop should keep running, but it finishes. I don't know why? Source code below: #coding: utf-8 lst = [0, 1, 6, 2, 5, 3, 4] new_lst = [] # the ordered list, [0, 1, 2, 3, 4, 5, 6] p0 = lst[0] # the first element can be arbitrary lst.remove(p0) new_lst.append(p0) for temp in lst: lst.remove(temp) while 1: for pt in lst: if temp &lt; pt: continue else: lst.append(temp) temp = pt lst.remove(pt) break else: new_lst.append(temp) break print("the ordered list:", new_lst) At last, I only get: ('the ordered list:', [0, 1, 2, 3])
has comment: http://stackoverflow.com/comment/83824754
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/83817033
answer count: 3
has comment: http://stackoverflow.com/comment/83817386
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83816986
has comment: http://stackoverflow.com/comment/83817230
accepted answer: http://stackoverflow.com/a/48413507
has comment: http://stackoverflow.com/comment/83817438
has comment: http://stackoverflow.com/comment/83817429
upvote count: 1
has answer: http://stackoverflow.com/a/48413507
downvote count: 1
linked to: http://stackoverflow.com/q/1207406
favorite count: 0
has comment: http://stackoverflow.com/comment/83817167
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83816996
has answer: http://stackoverflow.com/a/48413554
has comment: http://stackoverflow.com/comment/83816951

gflags
tag name: gflags
tags question: http://stackoverflow.com/q/48390664
type: Tag

http://stackoverflow.com/comment/90259832
type: Comment
comment on: http://stackoverflow.com/a/51647762
type: AnswerComment
has text: @IvanKaloyanov I wanted to comment, but couldn't because of insufficient reputation. Thought I'd rather post an answer than nothing at all then.
score: 1

http://stackoverflow.com/comment/83901670
comment on: http://stackoverflow.com/a/48454080
has text: Thanks, very straightforward implementation
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48413760
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48413706
has body: def find_between( s, first, last ): try: start = s.index( first ) + len( first ) end = s.index( last, start ) return s[start:end] except ValueError: return "" and then do something like sorted(names, key=lambda x: int(find_between(x, 'Test-', '.model')))
type: Answer
upvote count: 1

cmd
tags question: http://stackoverflow.com/q/48355319
tags question: http://stackoverflow.com/q/48387397
tags question: http://stackoverflow.com/q/48337778
tags question: http://stackoverflow.com/q/48387241
type: Tag
tags question: http://stackoverflow.com/q/48468141
tags question: http://stackoverflow.com/q/48450527
tag name: cmd

http://stackoverflow.com/comment/83779423
type: AnswerComment
comment on: http://stackoverflow.com/a/48372877
score: 0
has text: @Jay Sorry, I assumed Python3. I edited my answer, so it works with both Python2 (returns str) and Python3 (returns bytes). However, the same as with int-example, the memory is copied behind the scenes.with `str`.
type: Comment

http://stackoverflow.com/comment/83658545
type: Comment
score: 0
has text: soiund like a bug. Which version of python 2.7 are you using? (minor revision I mean)
type: QuestionComment
comment on: http://stackoverflow.com/q/48335494

http://stackoverflow.com/a/65122787
has comment: http://stackoverflow.com/comment/115136423
has body: Is kivy installed on your machine? Have you added kivy in requirements of buildozer.spec file? If no then open the buildozer.spec file and in requirements add all the requirements
answers question: http://stackoverflow.com/q/48373755
type: Answer
score: 0

http://stackoverflow.com/q/48371449
score: 0
answer count: 0
has title: How to use "rest_framework" routers with Django 2
has comment: http://stackoverflow.com/comment/83767578
has comment: http://stackoverflow.com/comment/83767406
type: Question
type: UnansweredQuestion
has body: I am aware that "Django 2 with router url patterns has changed". I cant manage to work with Router because I am getting an error : 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I have written a basic model and after that I have created an api folder, I have prepared files "views.py": from rest_framework import generics from yogavidya.apps.articles.models import Article from .serializers import ArticleSerializer from rest_framework import routers, serializers, viewsets class ArticleUpdateView(generics.RetrieveUpdateAPIView): lookup_field = 'pk' serializer_class = ArticleSerializer queryset = Article.objects.all() router = routers.DefaultRouter() router.register(r'api/articles', ArticleUpdateView, base_name='api-articles') after I have urls.py : from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from .views import ArticleUpdateView from django.urls import re_path urlpatterns = [ re_path(r'articles/(?:page-(?P&lt;page_number&gt;\d+)/)?$', ArticleUpdateView.as_view(), name='article-update'), ] now I want to add the api to project urls.py from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static from yogavidya.apps.articles import views from .views import home,home_files, pricing from rest_framework import routers, serializers, viewsets urlpatterns += i18n_patterns( path('admin/', admin.site.urls), path('articles/', include('yogavidya.apps.articles.urls', namespace="articles")), ) urlpatterns += [ path('api/articles/', include('yogavidya.apps.articles.api.urls', namespace="api-arti…
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/83851539

http://stackoverflow.com/q/48475039
accepted answer: http://stackoverflow.com/a/48475142
has body: I want to let my student to update his profile after he logged in, but I don't seem to be able to code the profile update properly. This is my code: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) {% csrf_token %} {{ form.as_p }} Save q def profile_edit(request): user = request.student form = StudentForm(request.POST or None, initial={'name': user.name, 'surname': user.surname}) if request.method == 'POST': if form.is_valid(): user.student.name = request.POST['name'] user.student.surname = request.POST['surname'] user.save() return HttpResponseRedirect('index') context = { "form": form } return render(request, "registration/profile_edit.html", context)
has comment: http://stackoverflow.com/comment/83943621
has comment: http://stackoverflow.com/comment/83943565
downvote count: 0
has answer: http://stackoverflow.com/a/48475142
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/76465311
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48477041
score: 1
has answer: http://stackoverflow.com/a/48477041
has title: How to update user profile in Django
has comment: http://stackoverflow.com/comment/83943516
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/67750525

http://stackoverflow.com/q/48383963
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83755090
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83754954
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83755017
has title: Execute Multiple Python Script Files & Pass values for variables - Python 3.6
has body: I am using below 3 variables in python script file. sourcePath, knoxPath, redShiftKeyFolderPath I want pass the values for these variable &amp; execute them using below script. import sys, subprocess knoxPath = r"C:\sunil_plus\dataset\knoxFile.xlsx" redShiftKeyFolderPath = r"C:\sunil_plus\redShift" sourcePath = 'C:\sunil_plus\dataset\Source1' subprocess.call([sys.executable, r"D:\Sunil_Work\1_redShift.py", 'htmlfilename.htm']) # want to pass knoxPath, redShiftKeyFolderPath, sourcePath sourcePath = 'C:\sunil_plus\dataset\Source2' subprocess.call([sys.executable, r"D:\Sunil_Work\2_redShift.py", 'htmlfilename.htm']) # want to pass knoxPath, redShiftKeyFolderPath, sourcePath sourcePath = 'C:\sunil_plus\dataset\Source3' subprocess.call([sys.executable, r"D:\Sunil_Work\3_redShift.py", 'htmlfilename.htm']) # want to pass knoxPath, redShiftKeyFolderPath, sourcePath Also, I want to get the output of script file.
tagged with: subprocess
answer count: 0

http://stackoverflow.com/comment/83954837
type: QuestionComment
has text: ah.understood thanks
comment on: http://stackoverflow.com/q/48480954
score: 0
type: Comment

http://stackoverflow.com/comment/83885433
has text: please indent your code properly; it is vital in Python
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48446676

http://stackoverflow.com/comment/83951445
has text: https://docs.python.org/3/library/socket.html#socket.socket.sendto
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48479182
type: QuestionComment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/48470962
tag name: google-oauth
tags question: http://stackoverflow.com/q/48433331

image-segmentation
tags question: http://stackoverflow.com/q/48473417
tags question: http://stackoverflow.com/q/48455338
tag name: image-segmentation
type: Tag

http://stackoverflow.com/comment/83882391
type: Comment
type: AnswerComment
score: 0
has text: Perfect! Mersi!
comment on: http://stackoverflow.com/a/48444739

http://stackoverflow.com/comment/83892877
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48449849
has text: I tried with multithreading but even with 4 Threads it only uses 25% of CPU. Threading is not a strength of Python, it seems
type: Comment

http://stackoverflow.com/comment/83673695
score: 0
comment on: http://stackoverflow.com/q/48344027
type: Comment
type: QuestionComment
has text: What is your desired output for this dataframe?

http://stackoverflow.com/a/48426566
answers question: http://stackoverflow.com/q/48426462
downvote count: 0
score: 1
upvote count: 1
has body: As I said in the comments, the problem with your code is that you assumed that the replace works in-place. It does not, you have to assign the value it returns to the variable. But, there is a better way of doing it that involves dictionaries. Take a look: d = {'\n': '&lt;br&gt;', 'while:': '&lt;while&gt;', 'for:': '&lt;for&gt;'} s = 'line1\nline2\nwhile: nothing and for: something\n\nnothing special' for k, v in d.items(): s = s.replace(k, v) print(s) # line1&lt;br&gt;line2&lt;br&gt;&lt;while&gt; nothing and &lt;for&gt; something&lt;br&gt;&lt;br&gt;nothing special The advantage of using dictionaries in this case is that you make it very straightforward what you want to replace and what with. Playing with the indexes is not something you want to do if you can avoid it. Finally, if you are wondering how to convert your list to a dict you can use the following: d = {k: v for k, v in zip(l[::2], l[1::2])} which does not break even if your list has an odd number of elements.
type: Answer

http://stackoverflow.com/a/48345444
answers question: http://stackoverflow.com/q/48343941
downvote count: 0
has body: I was also having same issue as yours. If you are using Generic views then do this: Views: def perform_create(self, serializer): serializer.save(user=self.request.user) Serializer: You just have to add this in you serializer in order to save the user. PrimaryKeyRelatedField is used to represent the target of the relationship using its primary key. read_only=True to make this field read only. class WaitercallCreateSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Waitercall fields = ('order', 'user', 'done', 'type_of_call')
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/48347265
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48347494
possible better answer: http://stackoverflow.com/a/48347368
tagged with: dataframe
has answer: http://stackoverflow.com/a/48347494
has answer: http://stackoverflow.com/a/48347368
has title: Deleting half of dataframe rows which meet condition
type: Question
answer count: 2
upvote count: 3
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 3
has body: I'm looking to extract a subset of a dataframe based on a condition. Let's say df = pd.Dataframe({'Col1': [values1], 'Col2' = [values2], 'Col3' = [values3]}) I'd like to sort by Col2. Of the entries in Col2 that are negative (if any), I'd like to drop the largest half. So if values2 = [-5,10,13,-3,-1,-2], then I'd want to drop the rows corresponding to the values -5 and -3. If I wanted to simply drop half the entire dataframe after sorting, I (think) could do df = df.iloc[(df.shape[0]/2):] Not sure how to introduce the conditionality of dropping half of only the negative values. The vast majority of my experience is in numpy - still getting used to thinking in terms of dataframes. Thanks in advance.

ip-address
tags question: http://stackoverflow.com/q/48394741
tag name: ip-address
type: Tag
tags question: http://stackoverflow.com/q/48348910

http://stackoverflow.com/comment/83925055
type: QuestionComment
has text: Is this python 2 or 3? If it's 3 you don't need arg in your super().
score: 1
comment on: http://stackoverflow.com/q/48465797
type: Comment

http://stackoverflow.com/comment/83816070
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48401162
has text: Does the initial problem persist after testing on mobile?

http://stackoverflow.com/comment/83926069
has text: Can you please publish a _complete_ resulting dictionary?
score: 0
comment on: http://stackoverflow.com/q/48466298
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83896942
comment on: http://stackoverflow.com/a/48451536
type: AnswerComment
score: 0
type: Comment
has text: indeed... havent had to do that yet my self... but here is a good [answer](https://stackoverflow.com/questions/42113233/install-numba-0-30-1-on-ubuntu-16-04-lts)

http://stackoverflow.com/comment/83858684
has text: Ok, I purged apache and followed the example here: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 Now I am getting a "Forbidden" when I go to the IP Address.
comment on: http://stackoverflow.com/q/48432664
score: 0
type: Comment
type: QuestionComment

class
tags question: http://stackoverflow.com/q/48480786
tags question: http://stackoverflow.com/q/48428689
tags question: http://stackoverflow.com/q/48407822
tags question: http://stackoverflow.com/q/48361026
tags question: http://stackoverflow.com/q/48360650
tags question: http://stackoverflow.com/q/48387077
tags question: http://stackoverflow.com/q/48457356
tags question: http://stackoverflow.com/q/48406389
type: Tag
tags question: http://stackoverflow.com/q/48470059
tags question: http://stackoverflow.com/q/48482945
tags question: http://stackoverflow.com/q/48430297
tags question: http://stackoverflow.com/q/48445403
tags question: http://stackoverflow.com/q/48336655
tags question: http://stackoverflow.com/q/48407587
tags question: http://stackoverflow.com/q/48444021
tags question: http://stackoverflow.com/q/48470361
tags question: http://stackoverflow.com/q/48481492
tags question: http://stackoverflow.com/q/48394464
tags question: http://stackoverflow.com/q/48388982
tags question: http://stackoverflow.com/q/48455207
tags question: http://stackoverflow.com/q/48443753
tags question: http://stackoverflow.com/q/48368635
tags question: http://stackoverflow.com/q/48364044
tag name: class
tags question: http://stackoverflow.com/q/48472958
tags question: http://stackoverflow.com/q/48369351
tags question: http://stackoverflow.com/q/48338847
tags question: http://stackoverflow.com/q/48483210
tags question: http://stackoverflow.com/q/48426190
tags question: http://stackoverflow.com/q/48335791
tags question: http://stackoverflow.com/q/48390615
tags question: http://stackoverflow.com/q/48401428
tags question: http://stackoverflow.com/q/48481889
tags question: http://stackoverflow.com/q/48404262
tags question: http://stackoverflow.com/q/48362622
tags question: http://stackoverflow.com/q/48422875
tags question: http://stackoverflow.com/q/48370952
tags question: http://stackoverflow.com/q/48433207
tags question: http://stackoverflow.com/q/48408270
tags question: http://stackoverflow.com/q/48449997
tags question: http://stackoverflow.com/q/48465797
tags question: http://stackoverflow.com/q/48409078
tags question: http://stackoverflow.com/q/48350971
tags question: http://stackoverflow.com/q/48454034

http://stackoverflow.com/a/55621120
has body: A few issues: On the right side of the equation, the new field (emome)is not created yet. The lambda function is on x, not on df_transactions, which does not exist in this scope. You need to specify axis since you are applying to each row (default is to each column). From Doc: axis : {0 or ‘index’, 1 or ‘columns’}, default 0 Axis along which the function is applied: 0 or ‘index’: apply function to each column. 1 or ‘columns’: apply function to each row. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
answers question: http://stackoverflow.com/q/48460234
score: 0
type: Answer

http://stackoverflow.com/q/48372436
has title: How to Input multiple data types and Output multiple data types on one line in python3?
upvote count: 0
has answer: http://stackoverflow.com/a/48372515
score: -5
has comment: http://stackoverflow.com/comment/83731934
has comment: http://stackoverflow.com/comment/83732027
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has body: I am new to python and trying to solve the following problem, answer is appreciate : (python 3) Prompt the user to input an integer between 0 and 155, a float, a character, and a string, storing each into separate variables. Then, output those four values on a single line separated by a space.
downvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83732097
tagged with: python
has answer: http://stackoverflow.com/a/48372599

http://stackoverflow.com/comment/83677806
has text: If u r using `path` feature in Django 2.0 u don't need to supply `r'^account/',` just `path('account/', include('account.urls')),` is enough. same for login url.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48345957

http://stackoverflow.com/comment/83823070
type: Comment
comment on: http://stackoverflow.com/a/48416477
score: 0
type: AnswerComment
has text: Ah, my bad... It works. My point is still valid. This is similar to doing the comparison in a loop.

http://stackoverflow.com/a/48478556
score: 0
has body: You can try this one too: for i in inList: for j in inDict: if int(j.split('-')[0])==i[0]: inDict[j]=i[1] print(inDict) Output: {'45-49': 1, '0-4': 4, '96-100': 2, '81-85': 8, '51-55': 7, '25-29': 4, '56-60': 2, '20-24': 5, '35-39': 2, '10-14': 2, '50': 0, '76-80': 4, '66-70': 4, '30-34': 4, '40-44': 1, '86-90': 2, '15-19': 4, '91-95': 1, '5-9': 2, '61-65': 4, '71-75': 4}
type: Answer
answers question: http://stackoverflow.com/q/48478357

http://stackoverflow.com/q/48465368
tagged with: python
has answer: http://stackoverflow.com/a/77473187
downvote count: 6
upvote count: 2
tagged with: python-2.7
tagged with: string-search
tagged with: list
answer count: 3
score: -4
has title: Looking for single digits in my string in python
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48466220
has answer: http://stackoverflow.com/a/48465516
has body: I want to search my string for single digits, for every different single digit in python. If it contains 1 in want to add 1 to another list and same for other digits. //single-digit found ar.append(single-digit) example-string: ap126ks8 ar=[1,2,6,8]
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83924155

http://stackoverflow.com/a/48530928
has body: In other words, I need to run .recv in the same loop and thread with multiple consumers. In RxPy I could just stream.emit(recv_result) and consume items like thatstrem.subscribe(callback_fn), but this is callback way, I need async Your subscribe method can accept coroutine functions, i.e. functions created with async def. Once something is emitted, they can be instantiated and their coroutines spawned using create_task: def __init__(self, ...): self._subscribers = [] def subsribe(self, corofn): self._subscribers.append(corofn) def emit(self, obj): loop = asyncio.get_event_loop() for corofn in self._subscribers: coro = corofn(obj) loop.create_task(coro) async def main(self): while True: request_raw = await self.ws_server.recv() self.emit(request_raw)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48394405
type: Answer
score: 1

http://stackoverflow.com/comment/83949273
comment on: http://stackoverflow.com/a/48456280
type: Comment
type: AnswerComment
score: 2
has text: Thanks for the help and not being such a stick in the mud!!!

http://stackoverflow.com/comment/83928432
type: AnswerComment
type: Comment
has text: haha, was already trying, then I thought I could just add a method to the seg class like add(whatever) and let that function append the lists
comment on: http://stackoverflow.com/a/48467486
score: 0

http://stackoverflow.com/comment/83760052
comment on: http://stackoverflow.com/a/48386211
type: Comment
score: 0
type: AnswerComment
has text: The lack of activation functions was the problem. That said, if the hyper-parameters are so far off from what's typical, I'm rethinking using this book!

http://stackoverflow.com/comment/83957199
has text: I dunno why that happens, but why not just split the list in 2, and then concatenate? You could also try retrieving from google finance (I dunno if that has a similar limit or not)
score: 0
comment on: http://stackoverflow.com/q/48482053
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83905545
score: 1
type: Comment
type: AnswerComment
has text: @wwii Yes, more abstraction more distance from the Truth.
comment on: http://stackoverflow.com/a/48456238

http://stackoverflow.com/q/48469653
score: 5
has comment: http://stackoverflow.com/comment/83933206
has comment: http://stackoverflow.com/comment/83933242
has body: I have an executable written in C but don't have the source code. I can call in in python (in ubuntu linux): from subprocess import Popen, PIPE # variable 'output' is the string I need. p = Popen(["./excutable",par1,par2]], stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() rc = p.returncode This works fine for me except I need to do this millions of times. It takes a lot time to run. Is there a way to run this faster? Thanks!
type: UnansweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/83933153
tagged with: python
has comment: http://stackoverflow.com/comment/83933473
has comment: http://stackoverflow.com/comment/83933346
has comment: http://stackoverflow.com/comment/83933239
tagged with: subprocess
has title: Can anything be done to make subprocess invocations faster in Python?
answer count: 0
has comment: http://stackoverflow.com/comment/83933402
downvote count: 0
has comment: http://stackoverflow.com/comment/83933259
has comment: http://stackoverflow.com/comment/83933247
favorite count: 0
type: Question

http://stackoverflow.com/comment/83760407
type: AnswerComment
has text: I know but I would have to ask every question in separated topic and my questions are associated with RNN that I have described above.
comment on: http://stackoverflow.com/a/48385917
score: 0
type: Comment

http://stackoverflow.com/comment/83705127
comment on: http://stackoverflow.com/a/48359137
has text: Thank you. I definitely prefer the broadcasting method.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83837334
comment on: http://stackoverflow.com/q/48423759
score: 0
has text: Since you are using Python 2.x (where x=?): is there a good reason that you are not switching to **Python 3**? With its improved strings with full Unicode support, a lot of special character handling has ... disappeared. It did up an' gone away. It's no longer needed.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83715021
comment on: http://stackoverflow.com/q/48364077
has text: If you want to read all the lines of a file in a list you can also use `list(f)` or `f.readlines()`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48789367
downvote count: 0
has body: It is important that resampling is performed by first producing a raster which is a sequence of instants (not periods, intervals, durations), and it is done independent of the 'label' and 'closed' parameters. It uses only the 'freq' parameter and 'loffset'. In your case, the system will produce the following raster: 2000-01-01 00:00:00 2000-01-01 00:03:00 2000-01-01 00:06:00 2000-01-01 00:09:00 Note again that at this moment there is no interpretation in terms of intervals or periods. You can shift it using 'loffset'. Then the system will use the 'closed' parameter in ordre to choose among two options: (start, end] [start, end) Here start and end are two adjacent time stamps in the raster. The 'label' parameter is used to choose whether start or end are used as a representative of the interval. In your example, if you choose closed='right' then you will get the following intervals: ( previous_interval , 2000-01-01 00:00:00] - {0} (2000-01-01 00:00:00, 2000-01-01 00:03:00] - {1,2,3} (2000-01-01 00:03:00, 2000-01-01 00:06:00] - {1,2,3} (2000-01-01 00:06:00, 2000-01-01 00:09:00] - {4,5,6} (2000-01-01 00:09:00, next_interval ] - {7,8} Note that after you aggregate the values over these intervals, the result is displayed in two versions depending on the 'label' parameter, that is, whether one and the same interval is represented by its left or right time stamp.
answers question: http://stackoverflow.com/q/48340463
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/q/48350116
tagged with: python-docx
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/77704007
has body: I am using python-docx 0.8.6 and python 3.6 to preform a simple search/replace operation. I'm having a problem where not all of the document's text appears when iterating over the doc.paragraphs For debugging I have tried doc = Document(input_file) fullText = [] for para in doc.paragraphs: fullText.append(para.text) print('\n'.join(fullText)) Which only seems to print out about half of the file's contents. There are no tables or special formatting in the file. Is there any reason why so much of the document's contents cannot be read by python-docx? Edit: the missing text is contained within a mail merge field if that makes any difference
has answer: http://stackoverflow.com/a/77704007
has title: Missing document text when using python-docx
tagged with: python
accepted answer: http://stackoverflow.com/a/48360410
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48360410
answer count: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/48461830
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83916543
has answer: http://stackoverflow.com/a/48470650
upvote count: 1
has comment: http://stackoverflow.com/comment/83925108
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48462130
type: UnansweredQuestion
tagged with: physics
tagged with: math
tagged with: python
has answer: http://stackoverflow.com/a/48461888
tagged with: numerical-integration
has title: Writing code to integrate 1D Fresnel Diffraction in Python
has body: my task is to integrate the following equation for 1d Fresnel diffraction, in red in: The point is that you are fourier transforming the aperture to a pattern on the screen, but for now just focussing on integrating the horizontal strip in 1d (ignoring the height for now). yprime is thus ignored. You also have fixed z and k, and j is an imaginary number. I have written the following code for it: import math import numpy as np import cmath k=5 z=5 x=0 j=cmath.sqrt(-1) func=math.exp((j*k/2*z)(x-xp)*(x-xp)) def X(xp1,xp2,function,N): h=(xp2-xp1)/N y=0.0 xp=xp1 for x in np.arange(1, N/2 +1): #summing odd order y terms y+=4*f(xp) xp+=2*h xp=xp1+2*h for x in np.arange(0, N/2): #summing even order y terms y+=2*f(x) xp+=2*h integral= (h/3)*(y+f(xp1)+f(xp2)) return integral print(simpson(0,5,func,10)) however, it is saying that xp is not defined. but I clearly have defined xp in the function. Does anyone have an idea what could be wrong? Thanks EDIT: here is a neater version of my code. But it's still asking me to define xp.. import math import cmath lamda=0.2 k=(2*math.pi)/lamda z=0.1 def expfunc(x, xp): func = math.exp(((1j)*k/2*z)(x-(xp))*(x-(xp))) return(func) def X(xp1,xp2,x,f,N): h=(xp2-xp1)/N y=0.0 xp=xp1 for i in np.arange(1, N/2 +1): #summing odd order y terms y+=4*f(xp) xp+=2*h xp=xp1+2*h for i in np.arange(0, N/2): #summing even order y terms y+=2*f(xp) xp+=2*h integral= (h/3)*(y+f(xp1)+f(xp2)) return integral print(X(0,1,x,expfunc,10))

http://stackoverflow.com/a/48468622
score: 1
has comment: http://stackoverflow.com/comment/83931383
type: Answer
has body: @Mark Dickinson's comment is correct, you're using with where you want for. You probably also want to open the input files as read explicitly for clarity def get_json_file(content_type, proc_date): filenames = glob.glob('/home/*') with open('/home/tgfile', 'w') as outfile: for fname in filenames: print ('line 1..') with open(fname, 'r') as infile: print ('line 2..') for line in infile: print ('line 3..') outfile.write(line) get_json_file('dir', '20180122')
answers question: http://stackoverflow.com/q/48468524
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83857181
comment on: http://stackoverflow.com/a/48432267
type: AnswerComment
has text: Where the initial click, right click, occurred right?
type: Comment
score: 0

http://stackoverflow.com/q/48387389
type: Question
has title: save graphviz source to dot file using python
score: 10
upvote count: 10
has answer: http://stackoverflow.com/a/48387705
tagged with: python
accepted answer: http://stackoverflow.com/a/48387705
tagged with: graphviz
has body: I am writing a visualisation with graphviz in python. I imported graphviz and pylab. I figured out how to save the graphic representation import graphviz as gv import pylab g1 = gv.Graph(format='png') g1.node('A') g1.node('B') g1.edge('A', 'B') g1.view() print(g1.source) filename = g1.render(filename='img/g1') pylab.savefig('filename.png') How can i save the source to a .dot file?
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/48427903

http://stackoverflow.com/q/48356593
has answer: http://stackoverflow.com/a/48356865
favorite count: 0
type: Question
tagged with: interpolation
tagged with: numpy
has answer: http://stackoverflow.com/a/48356826
accepted answer: http://stackoverflow.com/a/48356826
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/83699935
has comment: http://stackoverflow.com/comment/83699892
tagged with: python
upvote count: 4
has title: Interpolate 2D matrix along columns using Python
has comment: http://stackoverflow.com/comment/83699767
has comment: http://stackoverflow.com/comment/83700263
score: 2
type: AnsweredQuestion
tagged with: matrix
has body: I am trying to interpolate a 2D numpy matrix with the dimensions (5, 3) to a matrix with the dimensions (7, 3) along the axis 1 (columns). Obviously, the wrong approach would be to randomly insert rows anywhere between the original matrix, see the following example: Source: [[0, 1, 1] [0, 2, 0] [0, 3, 1] [0, 4, 0] [0, 5, 1]] Target (terrible interpolation -&gt; not wanted!): [[0, 1, 1] [0, 1.5, 0.5] [0, 2, 0] [0, 3, 1] [0, 3.5, 0.5] [0, 4, 0] [0, 5, 1]] The correct approach would be to take every row into account and interpolate between all of them to expand the source matrix to a (7, 3) matrix. I am aware of the scipy.interpolate.interp1d or scipy.interpolate.interp2d methods, but could not get it to work with other Stack Overflow posts or websites. I hope to receive any type of tips or tricks. Update #1: The expected values should be equally spaced. Update #2: What I want to do is basically use the separate columns of the original matrix, expand the length of the column to 7 and interpolate between the values of the original column. See the following example: Source: [[0, 1, 1] [0, 2, 0] [0, 3, 1] [0, 4, 0] [0, 5, 1]] Split into 3 separate Columns: [0 [1 [1 0 2 0 0 3 1 0 4 0 0] 5] 1] Expand length to 7 and interpolate between them, example for second column: [1 1.66 2.33 3 3.66 4.33 5]
possible better answer: http://stackoverflow.com/a/48356865
has comment: http://stackoverflow.com/comment/83699809
has comment: http://stackoverflow.com/comment/83700066

http://stackoverflow.com/comment/83783645
comment on: http://stackoverflow.com/q/48397903
score: 1
has text: Why `0` in beginning ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83899975
comment on: http://stackoverflow.com/q/48453346
has text: The fact that they have used different letters, or capitalised version of the same letters, is misleading. The documentation here is just saying that imshow takes different shaped arrays which are interpreted and plotted differently
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48406987
favorite count: 0
type: Question
tagged with: python
has body: Y is a np array containing NA values and numeric values. I want to replace all non-NA values with a value Y_new calculated by the formula below: Y_min = np.nanmin(Y) Y_max = np.nanmax(Y) Y_new = (np.log(Y)-np.log(Y_min))/(np.log(Y_max)-np.log(Y_min)) How to do so, while leaving the NA values there and only changing the non-NA values?
has title: replace non NA values of numpy array with value calculated by formula
tagged with: numpy
type: AnsweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48407028
answer count: 1
downvote count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48407028

http://stackoverflow.com/comment/83731617
comment on: http://stackoverflow.com/a/48371736
type: Comment
type: AnswerComment
score: 0
has text: I want to make the text invisible when the button is shown up. This way is just to show or hide the button part I think.

http://stackoverflow.com/q/48385630
has comment: http://stackoverflow.com/comment/83758971
score: 1
possible better answer: http://stackoverflow.com/a/48385899
tagged with: linear-algebra
accepted answer: http://stackoverflow.com/a/48386889
has answer: http://stackoverflow.com/a/48385899
favorite count: 0
has answer: http://stackoverflow.com/a/48386889
type: Question
tagged with: numpy
answer count: 2
tagged with: numerical-methods
has title: Getting eigenvalues from 3x3 matrix in Python using Power method
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm trying to get all eigenvalues from a 3x3 matrix by using Power Method in Python. However my method returns diffrent eigenvalues from the correct ones for some reason. My matrix: A = [[1, 2, 3], [2, 4, 5], [3, 5,-1]] Correct eigenvalues: [ 8.54851285, -4.57408723, 0.02557437 ] Eigenvalues returned by my method: [ 8.5485128481521926, 4.5740872291939381, 9.148174458392436 ] So the first one is correct, second one has wrong sign and the third one is all wrong. I don't know what I'm doing wrong and I can't see where have I made mistake. Here's my code: import numpy as np import numpy.linalg as la eps = 1e-8 # Precision of eigenvalue def trans(v): # translates vector (v^T) v_1 = np.copy(v) return v_1.reshape((-1, 1)) def power(A): eig = [] Ac = np.copy(A) lamb = 0 for i in range(3): x = np.array([1, 1, 1]) while True: x_1 = Ac.dot(x) # y_n = A*x_(n-1) x_norm = la.norm(x_1) x_1 = x_1/x_norm # x_n = y_n/||y_n|| if(abs(lamb - x_norm) &lt;= eps): # If precision is reached, it returns eigenvalue break else: lamb = x_norm x = x_1 eig.append(lamb) # Matrix Deflaction: A - Lambda * norm[V]*norm[V]^T v = x_1/la.norm(x_1) R = v * trans(v) R = eig[i]*R Ac = Ac - R return eig def main(): A = np.array([1, 2, 3, 2, 4, 5, 3, 5, -1]).reshape((3, 3)) print(power(A)) if __name__ == '__main__': main() PS. Is there a simpler way to get the second and third eigenvalue from power method instead of matrix deflaction?
has comment: http://stackoverflow.com/comment/83758887
type: AnsweredQuestion

http://stackoverflow.com/comment/83670547
has text: Waht is expected output?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48342588

http://stackoverflow.com/comment/83892590
type: Comment
score: 0
has text: It is different from the original question. Since I inherit from `Serializer` not `ModelSerializer`
type: QuestionComment
comment on: http://stackoverflow.com/q/48441193

http://stackoverflow.com/q/48474108
has answer: http://stackoverflow.com/a/48474188
type: AnsweredQuestion
score: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/83941768
tagged with: web-scraping
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83941875
has title: Looping through rows of a table while clicking links in selenium (python)
tagged with: python
has body: The sample page source looks like this </table </table Explanation Hi, So let's get to it. As shown above the code snippet I'm interacting with is housed in a . The is clickable and once clicked it renders a page(the page of interest) so I would like to loop through getting each and click it. From my research I haven't found anything similar but I have found interesting stuff but nothing to help. I appreciate all help given. Thanks. my code import time import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.firefox.options import Options from BeautifulSoup import BeautifulSoup #some of the imports are for headless firefox so don't mind them #for.testing.purposes.only driver = webdriver.Firefox() url = 'here://code.above.com/' driver.get(url) #looping rows in selenium table = driver.find_elements_by_xpath("//table[@class='foot-market']") for row in table.find_element_by_xpath("//tbody[@data-live='false']"): row.find_element_by_xpath("//td[@class='today-name']").click() #try for one row first # driver.back() break Error The error returned is in line: for row in table.find_element_by_xpath("//td[@data-live='false']"): Exception: AttributeError: 'list' object has no attribute 'find_element_by_xpath' which makes sense and all, but how do I achieve this...
linked to: http://stackoverflow.com/q/47735375
accepted answer: http://stackoverflow.com/a/48474188

http://stackoverflow.com/comment/83969896
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48488361
score: 0
has text: A very good point, not sure why I didn't think about doing this in Python from the beginning. Thanks, I'll leave the question open in case anyone suggests alternative solutions.

http://stackoverflow.com/a/53091584
has comment: http://stackoverflow.com/comment/93144293
score: 1
type: Answer
has body: If you installed the package using setup.py, then you will most likely have to delete the package files manually. You'd find the Uninstalling setup.py install wiki useful. Unix instructions quoted below: sudo python setup.py install --record files.txt # inspect files.txt to make sure it looks ok. Then in bash: tr '\n' '\0' &lt; files.txt | xargs -0 sudo rm -f --
upvote count: 2
answers question: http://stackoverflow.com/q/48337016
has comment: http://stackoverflow.com/comment/93143593
downvote count: 1

http://stackoverflow.com/q/48419414
possible better answer: http://stackoverflow.com/a/48419527
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48419527
tagged with: python
has answer: http://stackoverflow.com/a/48419486
tagged with: inheritance
has comment: http://stackoverflow.com/comment/83828525
type: AnsweredQuestion
score: 3
tagged with: declaration
upvote count: 3
accepted answer: http://stackoverflow.com/a/48419486
downvote count: 0
has body: I have a file test.py class A(B): def display(self): print ("In A") class B: def display(self): print ("In B") I get the following error while run it Traceback (most recent call last): File "/Users/praveen/Documents/test.py", line 1, in &lt;module&gt; class A(B): NameError: name 'B' is not defined But if I change the order of declaration, It runs without any errors class B: def display(self): print ("In B") class A(B): def display(self): print ("In A") Can anyone explain in detail why this weird error happens?
has title: python class inheritance order
favorite count: 0

http://stackoverflow.com/comment/83975497
type: Comment
type: AnswerComment
score: 0
has text: What options are there? Feel free to edit if you know of a better way!
comment on: http://stackoverflow.com/a/48484081

bubble-sort
tags question: http://stackoverflow.com/q/48337195
type: Tag
tags question: http://stackoverflow.com/q/48373186
tag name: bubble-sort

http://stackoverflow.com/q/48394638
has comment: http://stackoverflow.com/comment/83776871
has comment: http://stackoverflow.com/comment/83839104
score: 0
linked to: http://stackoverflow.com/q/44967202
answer count: 0
has comment: http://stackoverflow.com/comment/83811813
has comment: http://stackoverflow.com/comment/83776828
tagged with: pip
tagged with: django
has title: I cannot get my PIP 9.0.1 to work properly
type: Question
has comment: http://stackoverflow.com/comment/83776956
type: UnansweredQuestion
tagged with: python
has body: I'm working with a Hostgator Shared package to install and run my Django projects, I followed all the steps from here http://support.hostgator.com/articles/django-with-fastcgi#shared-reseller (section: Setup Django Using Virtualenv) I get stuck in step 3 (Install Django): ~/mydjango/bin/pip install django I get this output: Exception: Traceback (most recent call last): File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 1050, in &lt;module&gt; _distro = LinuxDistribution() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info raise subprocess.CalledProcessError(code, cmd, stdout) CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 3 Traceback (most recent call last): File "/home2/belldentjc/mydjango/bin/pip", line 11, in &lt;module&gt; sys.exit(main()) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as s…
has comment: http://stackoverflow.com/comment/83811955
tagged with: hosting
has comment: http://stackoverflow.com/comment/83782189

http://stackoverflow.com/a/68676535
has body: i = "15:21" sp = i.split(":") minutes = 0.0 if len(sp) == 3: minutes = minutes + int(sp[0]) * 60 minutes = minutes + int(sp[1]) minutes = minutes + int(sp[2]) / 60 elif len(sp) == 2: minutes = minutes + int(sp[0]) minutes = minutes + int(sp[1]) / 60 elif len(sp) == 1: minutes = minutes + int(sp[0]) / 60 print(minutes) A Good solution :)
score: 0
answers question: http://stackoverflow.com/q/48447123
type: Answer

http://stackoverflow.com/comment/83706831
has text: note: there are lots of compelling reasons to use ipython, such as better tab completion and access to docstrings
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48360005
score: 4

http://stackoverflow.com/a/48362796
has comment: http://stackoverflow.com/comment/83712745
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83712514
has comment: http://stackoverflow.com/comment/83713205
accepted answer of: http://stackoverflow.com/q/48362768
type: AcceptedAnswer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/48362768
has body: This is an infinite generator. You can either take a slice of it (shown in the last line), or iterate over it directly: import itertools import random def one_string(): l = random.randint(1, 5) return "".join(random.choice("0123456789") for _ in range(l)) def string_pairs(): while True: yield one_string(), one_string() print(list(itertools.islice(string_pairs(), 10))) produces: [('840', '452'), ('20', '4651'), ('784', '589'), ('1', '08211'), ('809', '2103'), ('48975', '46884'), ('307', '83913'), ('88512', '212'), ('57', '11772'), ('38', '14')]

http://stackoverflow.com/a/48342655
answers question: http://stackoverflow.com/q/48342588
type: AcceptedAnswer
has body: You need custom function with apply and np.linalg.pinv: np.random.seed( 666 ) dt_lst = pd.date_range( start='2017-01-01', end='2017-06-30' )[:5] df = pd.DataFrame({'date':dt_lst,'river':1,'RAND1':np.random.random(size=5), 'RAND2':100.0*np.random.random(size=5)}) df2 = df.copy() df2['river'] = 2 df2['RAND1'] = 4.0 * df2['RAND1'] df2['RAND2'] = 3.0 * df2['RAND2'] df = df.set_index(['date','river']) df2 = df2.set_index(['date','river']) dforig = df.append(df2).sort_index(level='date') dforig['RAND3'] = dforig['RAND2'] / dforig['RAND1'] print (dforig) RAND1 RAND2 RAND3 date river 2017-01-01 1 0.700437 1.270320 1.813610 2 2.801748 3.810959 1.360207 2017-01-02 1 0.844187 41.358770 48.992448 2 3.376747 124.076310 36.744336 2017-01-03 1 0.676514 4.881279 7.215338 2 2.706057 14.643838 5.411503 2017-01-04 1 0.727858 9.992856 13.729128 2 2.911432 29.978568 10.296846 2017-01-05 1 0.951458 50.806631 53.398713 2 3.805832 152.419892 40.049035 def f(x): x = x.reset_index(drop=True, level=0) x = pd.DataFrame(np.linalg.pinv(x.values), x.columns, x.index) return (x) df_inv = dforig.groupby(level=0).apply(f) print (df_inv) river 1 2 date 2017-01-01 RAND1 -0.201457 0.192762 RAND2 -0.101951 0.196343 RAND3 0.700602 -0.211973 2017-01-02 RAND1 -0.000446 0.000386 RAND2 -0.008046 0.010735 RAND3 0.027212 -0.009069 2017-01-03 RAND1 -0.020513 0.019960 RAND2 -0.064182 0.087055 RAND3 0.183937 -0.060765 2017-01-04 RAND1 -0.005731 0.005380 RAND2 -0.032754 0.043910 RAND3 0.096982 -0.032246 2017-01-05 RAND1 -0.000375 0.000302 RAND2 -0.006551 0.008740 RAND3 0.024966 -0.008321
type: Answer
accepted answer of: http://stackoverflow.com/q/48342588
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83670790

http://stackoverflow.com/q/48480118
upvote count: 4
has body: I am a python hobbyist and installed pycharm to work on a number of projects. Every time I start a new project, pycharm community edition creates a new virtualenv without any packages. So for each small project, I have to install numpy, matplotlib, scikit etc again and again. This is irritating. How can this feature be disabled ? I tried to search for this question but did not find it. Sorry if it is a duplicate.
score: 4
downvote count: 0
has title: How do I prevent PyCharm from creating a virtualenv every time I start a new project?
has comment: http://stackoverflow.com/comment/96223250
answer count: 1
has answer: http://stackoverflow.com/a/48480149
tagged with: pycharm
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83953251
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83670277
score: 0
has text: If these are indeed (euclidean) distances, then I would compute my similarity measure in euclidean space, not in the space of pairwise distances. Aligning two sets of points is a much easier and better understood problem than aligning two sets of distance measures.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48336165

http://stackoverflow.com/comment/83896011
comment on: http://stackoverflow.com/a/48451345
type: Comment
has text: You are a magician! By putting root.state do I jump back to to the controller class?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83829911
type: QuestionComment
comment on: http://stackoverflow.com/q/48420022
type: Comment
has text: `filepath/filename` is unique.
score: 0

http://stackoverflow.com/a/53036155
answers question: http://stackoverflow.com/q/48449611
upvote count: 0
downvote count: 2
type: Answer
has body: Try this one profile.update_preferences() before webdriver.Firefox(profile) please may help you
score: -2

http://stackoverflow.com/comment/83806716
type: Comment
comment on: http://stackoverflow.com/q/48408695
score: 0
has text: Your single example of input and result is not enough to specify the problem you're trying to solve. Please be *clear* about your definition of "similar" for this program. Also, provide a *complete* example; the posted code hangs, waiting for input, and `list` (which is a bad variable name, being a built-in data type) is not defined.
type: QuestionComment

http://stackoverflow.com/q/48454918
tagged with: max
tagged with: datetime
tagged with: python
has title: pandas datetime not finding max time correctly
type: AnsweredQuestion
tagged with: sql-server
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48454948
has answer: http://stackoverflow.com/a/48454948
type: Question
has body: I have data from SQL server. I've converted these to pandas datetime like so: pd.to_datetime(max(df2[endTime]), format='%H:%M:%S %p') However it is not working correctly to get the maximum time of the series. Does anyone know why? As you can see, index 100 is the maximum time, but it is giving me index 763.

http://stackoverflow.com/comment/83809666
comment on: http://stackoverflow.com/q/48409610
has text: @9dogs Yes a solution for this would be very useful in many situations :) Note: I don't start all scripts from the same entry point / not using `multiprocessing`. I'm looking for a more lightweight solution than running redis in Docker, but I'll remember this option in last resort!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83890303
comment on: http://stackoverflow.com/a/48448360
type: Comment
score: 0
type: AnswerComment
has text: Alex, thanks, you have me the directions! I wrote: df.at[df["Type"]=="mean(+1)","ABC"] = 1.0 Thanks!

http://stackoverflow.com/comment/83772392
comment on: http://stackoverflow.com/a/48392101
score: 0
has text: @user3375448: thanks, excellent suggestion! I incorporated it in my answer
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48462491
has comment: http://stackoverflow.com/comment/83918508
answers question: http://stackoverflow.com/q/48461367
has body: Have you tried following the quick start def print_response(response): """Parses and prints the Analytics Reporting API V4 response. Args: response: An Analytics Reporting API V4 response. """ for report in response.get('reports', []): columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) for row in report.get('data', {}).get('rows', []): dimensions = row.get('dimensions', []) dateRangeValues = row.get('metrics', []) for header, dimension in zip(dimensionHeaders, dimensions): print header + ': ' + dimension for i, values in enumerate(dateRangeValues): print 'Date range: ' + str(i) for metricHeader, value in zip(metricHeaders, values.get('values')): print metricHeader.get('name') + ': ' + value
type: Answer
accepted answer of: http://stackoverflow.com/q/48461367
has comment: http://stackoverflow.com/comment/83919608
score: 0
has comment: http://stackoverflow.com/comment/83918341
type: AcceptedAnswer

http://stackoverflow.com/a/48427387
score: 2
upvote count: 2
downvote count: 0
type: Answer
has body: You could try setting up a thread pool and using multithreading to improve performance rates. The link below does a really good job of introducing you to the basics for python: http://chriskiehl.com/article/parallelism-in-one-line/ You could put the parallelism in multiple spots. You'll have to play with what works best for you. It might be more efficient to treat each file as a unique process, or it might be better to put it around the process of checking each line individually. However, one final way you could speed this up is to avoid going line by line. Instead, put the regular expression on the entire file and replace all matches at once. @Idlehands answer gives more detail into this.
answers question: http://stackoverflow.com/q/48425063

http://stackoverflow.com/comment/83826620
type: Comment
comment on: http://stackoverflow.com/a/48407315
has text: What I can say - works for me. If you don't agree. No problem - at least at my side.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83815244
has text: Like math.sin is a function of x, I want xintegral with constants x,k,z to be a function of xdot to use it in the simpson definition to insert values in it.
comment on: http://stackoverflow.com/q/48412422
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83886316
comment on: http://stackoverflow.com/a/48446782
has text: The question is about how to convert the existing list `data` to something like `processed_data`. Your 'answer' does not say anything about this.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/83888538
comment on: http://stackoverflow.com/a/48448077
score: 1
type: Comment
has text: Oh wow cool! For clarification, in this scenario could I just apply my `X` where you have `X_train`? Furthermore, would you be able to explain the equation a little? I understand that the code you've provided does essentially that, but I want to be able to read the equation too
type: AnswerComment

http://stackoverflow.com/comment/84097953
type: QuestionComment
has text: Possible duplicate of [Is file append atomic in UNIX?](https://stackoverflow.com/questions/1154446/is-file-append-atomic-in-unix)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48406572

http://stackoverflow.com/a/48373194
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48372461
answers question: http://stackoverflow.com/q/48372461
upvote count: 5
type: Answer
has body: You can use set_value: df1.set_value(0,0,df2) or: df1.iat[0,0]=df2 Since .set_value has been deprecated since version 0.21.0.
has comment: http://stackoverflow.com/comment/83755412

http://stackoverflow.com/comment/83936108
comment on: http://stackoverflow.com/q/48470671
type: Comment
score: 0
type: QuestionComment
has text: You're using a green range to generate a mask, then using the mask to erase entire pixels.

http://stackoverflow.com/q/48478947
has comment: http://stackoverflow.com/comment/83951177
tagged with: postgresql
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/83950972
has body: I'm scraping lots of pages and storing the source in a Postgres database, then determining bits of information to parse and either parsing it with Postgres' own regex, which is super fast, or with Python and BeautifulSoup, row by row, which is perhaps more "proper" but much, much slower. I'm wondering if I should convert the source to JSON and store in a JSONB field. Seems faster because all the JSON can be indexed...am I wrong? Or maybe switch to MongoDB? I just feel that there must be a faster way. Let's assume, for purposes of argument, that I cannot determine in advance all data that needs to be parsed. Suggestions?
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83951072
has comment: http://stackoverflow.com/comment/83951263
has comment: http://stackoverflow.com/comment/83951905
type: Question
has comment: http://stackoverflow.com/comment/83951113
has comment: http://stackoverflow.com/comment/83950952
has comment: http://stackoverflow.com/comment/83951064
has title: proper way to store scraped HTML for re-parsing?

http://stackoverflow.com/a/48426564
has comment: http://stackoverflow.com/comment/83844089
answers question: http://stackoverflow.com/q/48425278
has comment: http://stackoverflow.com/comment/83995141
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83990088
type: Answer
has comment: http://stackoverflow.com/comment/83844843
has comment: http://stackoverflow.com/comment/84088756
has comment: http://stackoverflow.com/comment/84090698
has body: This is not a easy question at all. It is a very good question and many people face the same problem in their daily work. Your question will help others as well! The error is because you are trying to read a so called Rich Text Format file (RTF). So, the real content of the file is not like what you see on screen, but coded strings. Instead of ['1 2', '3 4',...] f.readline() actually generate something like ['{\\rtf1\\adeflang1025\\ansi\\ansicpg1252\\uc1\\adeff31507\\deff0\\stshfdbch31505\\stshfloch31506\\stshfhich31506\\stshfbi31507\\...] Therefore, when you try to index the splited line, you get index out of range error. 3 ideas to solve this problem. First you may consider to convert the RTF to plain text and read the text file with readline() as what you did. Or, you can read the RTF with some third party parser. Or, you can parse the RTF yourself with regular expression. Here are some useful links convert RTF parse RTF Hope it is helpful. Update Though it is not very clear what you want to plot exactly, I guess what you really want is a scatter plot regarding the 1st and 2nd column in your data file. If that is true, you may need to modify a bit your code. Below is an example. Assume your a.txt file (not rtf) has content 1 2 3 4 5 6 7 8 You can do this to plot a x y scatter plot with the 1st column as x 2nd column as y. import matplotlib.pyplot as plt f = open(os.path.expanduser("a.txt")) lines = f.readlines() x, y = [], [] for line in lines: x.append(line.split()[0]) y.append(line.split()[1]) f.close() print(x, y) plt.plot(x,y) plt.show() Or with one-liner f = open(os.path.expanduser("a.txt")) lines = f.readlines() x, y = zip(*(line.split() for line in lines)) f.close() print(x, y) plt.plot(x,y) plt.show()
downvote count: 0
has comment: http://stackoverflow.com/comment/83993087

http://stackoverflow.com/a/75164537
has body: To avoid drag-data-received being called twice... You can drop from Nautilus, LibreOffice, gedit, a link fron Chrome import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk import sys, urllib class GUI: def __init__(self): window = Gtk.Window() window.connect('destroy', Gtk.main_quit) textview = Gtk.TextView() # 'enforce_target1' enforce_target1 = Gtk.TargetEntry.new('text/uri-list', 0, 50) # laisse passer les noms de fichiers avec pb d'accents (info = 50) # add the ability to receive URIs (e.g. file paths) textview.drag_dest_set_target_list([enforce_target1]) # add the ability to receive 'texts', 'link' textview.drag_dest_add_text_targets() # gère correctement les textes, les liens (info = 0) # connect the signal "drag-data-received" of the textview to the callback 'self.on_drag_data_received' textview.connect("drag-data-received", self.on_drag_data_received) window.add(textview) window.show_all() def on_drag_data_received(self, widget, drag_context, x,y, data,info, time): print(info) if info == 50: # 'text/uri-list' from Nautilus data = data.get_data() # Si on a glissé un fichier depuis Nautilus : # L'objet byte se termine par \r\n, il faut supprimer ces deux caractères # \r correspond à CR (Carriage Return) \n correspond à LF (Line Feed). if data[-2:] == b'\r\n': print(" ...se termine par \\r CR (Carriage Return) et \\n correspond à LF (Line Feed)") data = data[:-2] print(f"Data reçu : {data}") # Replacing '%20' with Space and '%C3%A9' with é .... etc.... data=urllib.parse.unquote(data.decode()) print(f"Data reçu (unquote) : {data}") # Insert data in the the textview widget.get_buffer().insert_at_cursor(data) if info == 0 : print(data.get_text()) print("The drop is done automatically on the textview") # Gtk.drag_finish(drag_context, True, False, time) # always call Gtk.drag_finish to receive as suggested by documentation def main(): GUI() Gtk.main() if __name__ == "__main__": sys.exit(main())
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48469655
score: 1
upvote count: 1

http://stackoverflow.com/q/48415447
tagged with: normalization
has answer: http://stackoverflow.com/a/48435913
type: UnansweredQuestion
has title: Layer Normalization, with average power constraints
tagged with: python
tagged with: deep-learning
score: 0
answer count: 1
upvote count: 1
tagged with: keras
downvote count: 1
tagged with: tensorflow
has body: I'm studying the paper "An Introduction to Deep Learning for the Physical Layer". While implementing the proposed network with python Keras, I should normalize some values, output of former layer. One way is simple L2 Normalization, ||X||^2 = 1, where X is a tensor of former layer output. as a code from keras import backend as K Lambda(lambda x: K.l2_normalize(x,axis=1)) The other way, what I want to know, is ||X||^2 ≤ 1. Is there any way that constrains the value of layer outputs?
favorite count: 0
type: Question

http://stackoverflow.com/comment/83786477
type: QuestionComment
has text: It would help tremendously if you provided a [mcve], instead of some datafile which we don't have. From that it would be more obvious what you are trying to achieve here. Also clearly explain what the colorbar should actually show - what is the mapping you want to display?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48398726

http://stackoverflow.com/a/48376308
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48375776
answers question: http://stackoverflow.com/q/48375776
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: Regarding the count plot, you can use sns.countplot on the original DataFrame without grouping: import seaborn as sns sns.countplot(x='originating_system_id', data=df) As for the scientific notation, you can use matplotlib.ticker.ScalarFormatter: import matplotlib.ticker as ticker import matplotlib.pyplot as plt tick = ticker.ScalarFormatter(useOffset=False, useMathText=True) ''' tick.set_powerlimits() represent the limits you want your label to show at so in this case the minimum is 10^0 and the maximum is set to 10^100 (It won't turn your labels to scientific notation if your max data point is less than 10^100) ''' tick.set_powerlimits((0,100)) fig, ax = plt.subplots() ax.yaxis.set_major_formatter(tick) sns.distplot(... , ax=ax)

http://stackoverflow.com/a/48431392
type: Answer
has comment: http://stackoverflow.com/comment/83854011
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48430380
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83854933
answers question: http://stackoverflow.com/q/48430380
has body: (Spyder developer here) This problem has been reported before but we haven't had time to solve it. Although it sounds simple, it's really hard to solve correctly in all situations because indentation spaces matters in Python (whereas in R they are irrelevant).
has comment: http://stackoverflow.com/comment/83855918
has comment: http://stackoverflow.com/comment/83854628

http://stackoverflow.com/comment/83904866
has text: When I type the equivalent command in the terminal on the HPC, a job is created successfully: `sbatch --job-name test_job --partition=short --time 00:60:00 --mem-per-cpu=2G --cpus-per-task=1 -o /projects/sanlab/shared/REV/REV_scripts/org/python/output.txt -e /projects/sanlab/shared/REV/REV_scripts/org/python/error.txt --wrap="/projects/sanlab/shared/dcm2niix/build/bin/dcm2niix -o -b y /projects/sanlab/shared/REV/archive/clean_nii /projects/sanlab/shared/DICOMS/REV/subject_directory"`
comment on: http://stackoverflow.com/a/48451302
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48485621
answers question: http://stackoverflow.com/q/48485434
type: Answer
has body: If a member tries to invoke a command that is currently on cooldown a CommandOnCooldown exception is thrown and triggers on_command_error. Although async does not document it there is an event on_command_completion on_command_completion(command, ctx) this is dispatched if a command has successfully completed its invocation.
accepted answer of: http://stackoverflow.com/q/48485434
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/48467369
has comment: http://stackoverflow.com/comment/83985936
score: 0
tagged with: azure
has comment: http://stackoverflow.com/comment/83985523
answer count: 1
has comment: http://stackoverflow.com/comment/83975440
has comment: http://stackoverflow.com/comment/83990492
has answer: http://stackoverflow.com/a/65658899
type: Question
tagged with: azure-sdk-python
tagged with: azureservicebus
type: UnansweredQuestion
has body: I am trying to pass a list of Messages to Service Bus via the Python SDK and I get a 400 response as JSON is not in required format. I am doing something like this and it fails: messages = [Message({'id':1,'name':'bob'}),Message({'id':2,'name':'bill'})] sb.send_queue_message_batch('queue_name', messages) If I do this it works: messages = [Message('bob'),Message('bill')] sb.send_queue_message_batch('queue_name', messages) Or if I call send_queue_message individually like this it works sb.send_queue_message('queue_name', Message({'id':1,'name':'bob'})) sb.send_queue_message('queue_name', Message({'id':2,'name':'bill'})) Looking at the source it calls a method on the message to create the format expected in a batch so not sure what I should be doing differently. Unfortunately all examples of batch I can find are the simple string approach. The consumer at the other end will be a .Net app so I need to ensure it can still be deserialised. I could call json.dump on the message content and pass it as a stringified version of the body but that does not sound like the ideal solution. Thanks SDK Source for batch: https://github.com/Azure/azure-sdk-for-python/blob/587bc9a2f955f43c67b02c537521f31aa4c27555/azure-servicebus/azure/servicebus/servicebusservice.py#L892
tagged with: python
has title: Issue using Python Azure ServiceBus SDK to send batch of messages with object body

http://stackoverflow.com/comment/83702819
score: 0
has text: Are the lines repeated (like the example above) or distinct? I think there isn't much to do if all pair of segments intersects.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48358037

http://stackoverflow.com/q/48413412
tagged with: django-testing
favorite count: 0
type: Question
has title: Django: import error in test
has body: I have a new project in django, without any test. I think that it should say that all is ok, because there are not tests when I try python manage.py test. Instead of that, I obtained this exit: shell screen Any one know why?
has comment: http://stackoverflow.com/comment/83816742
downvote count: 5
has answer: http://stackoverflow.com/a/48415431
tagged with: python
has comment: http://stackoverflow.com/comment/83816985
type: UnansweredQuestion
score: -4
answer count: 1
tagged with: django
upvote count: 1

longest-substring
tags question: http://stackoverflow.com/q/48442419
tag name: longest-substring
type: Tag

counter
tags question: http://stackoverflow.com/q/48484166
tag name: counter
tags question: http://stackoverflow.com/q/48349088
type: Tag

http://stackoverflow.com/q/48479346
score: 1
has title: Schedule task to running event loop from synchronous code
answer count: 1
tagged with: python
tagged with: coroutine
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48479665
has answer: http://stackoverflow.com/a/48479665
has body: Consider this program, where the mainloop and the coroutine to stop it are actually implemented by a library I'm using. import asyncio import signal running = True async def stop(): global running print("setting false") running = False await asyncio.sleep(3) print("reached end") async def mainloop(): while running: print("loop") await asyncio.sleep(1) def handle_signal(): loop.create_task(stop()) loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGINT, handle_signal) loop.run_until_complete(mainloop()) loop.close() I need to call the stop coroutine to stop the mainloop when the program recieves a signal. Although when scheduling the stop coroutine using asyncio.BaseEventLoop.create_task it first stops the mainloop which stops the event loop and the stop coroutine can't finish: $ ./test.py loop loop loop ^Csetting false Task was destroyed but it is pending! task: &lt;Task pending coro=&lt;stop() done, defined at ./test.py:7&gt; wait_for=&lt;Future pending cb=[Task._wakeup()]&gt;&gt; How to add the coroutine to the running event loop while making the event loop wait until it is complete?
downvote count: 0
upvote count: 1
type: AnsweredQuestion
tagged with: python-asyncio

http://stackoverflow.com/q/48486533
downvote count: 0
accepted answer: http://stackoverflow.com/a/48490296
has comment: http://stackoverflow.com/comment/83966507
has answer: http://stackoverflow.com/a/63318359
has answer: http://stackoverflow.com/a/48490296
favorite count: 0
type: Question
tagged with: turtle-graphics
has body: I'm using turtle graphics and I would like to clear only a part of the screen and keep the rest of the image/drawings intact. So far I've been drawing a white rectangle to clear a part of the image, but this is very slow and if the background isn't white then I can't use this method. This is the function I have been using : import turtle t = turtle.Turtle() def screen_clearer(coordinate_x, coordinate_y, length, width): t.up() t.goto(coordinate_x, coordinate_y) t.color("white") t.begin_fill() t.setheading(0) for i in range(2): t.fd(length) t.rt(90) t.fd(width) t.rt(90) t.end_fill() Is there a built-in function in turtle that clears only part of the screen? I have looked and haven't found anything so this is why I've been using this.
has comment: http://stackoverflow.com/comment/94222978
tagged with: python
has title: Clear only a part of the screen in turtle graphics
type: AnsweredQuestion
score: 3
answer count: 2
has comment: http://stackoverflow.com/comment/83966027
upvote count: 3
possible better answer: http://stackoverflow.com/a/63318359

http://stackoverflow.com/a/57843107
has comment: http://stackoverflow.com/comment/106690662
has body: On my system Pipe(duplex=False) is slower (twice the time, or half the rate) than Pipe(duplex=True). For anyone looking for performance here is a side-by-side comparison: from time import time from multiprocessing import Process, Queue, Pipe n = 1000 buffer = b'\0' * (1000*1000) # 1 megabyte def print_elapsed(name, start): elapsed = time() - start spi = elapsed / n ips = n / elapsed print(f'{name}: {spi*1000:.3f} ms/item, {ips:.0f} item/sec') def producer(q): start = time() for i in range(n): q.put(buffer) print_elapsed('producer', start) def consumer(q): start = time() for i in range(n): out = q.get() print_elapsed('consumer', start) class PipeQueue(): def __init__(self, **kwargs): self.out_pipe, self.in_pipe = Pipe(**kwargs) def put(self, item): self.in_pipe.send_bytes(item) def get(self): return self.out_pipe.recv_bytes() def close(self): self.out_pipe.close() self.in_pipe.close() print('duplex=True') q = PipeQueue(duplex=True) producer_process = Process(target=producer, args=(q,)) consumer_process = Process(target=consumer, args=(q,)) consumer_process.start() producer_process.start() consumer_process.join() producer_process.join() q.close() print('duplex=False') q = PipeQueue(duplex=False) producer_process = Process(target=producer, args=(q,)) consumer_process = Process(target=consumer, args=(q,)) consumer_process.start() producer_process.start() consumer_process.join() producer_process.join() q.close() Results: duplex=True consumer: 0.301 ms/item, 3317 item/sec producer: 0.298 ms/item, 3358 item/sec duplex=False consumer: 0.673 ms/item, 1486 item/sec producer: 0.669 ms/item, 1494 item/sec I think this must come down to CPython using os.pipe vs socket.socketpair, but I'm not sure.
type: Answer
has comment: http://stackoverflow.com/comment/106690706
answers question: http://stackoverflow.com/q/48353601
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83686132
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48349812
has text: Searching for the error message I come across this solution: https://apple.stackexchange.com/a/254381 Please check if that fixes the problem for you

http://stackoverflow.com/q/48471726
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Python C Extension: Py_DECREF for PyList
has answer: http://stackoverflow.com/a/48474076
favorite count: 0
type: Question
tagged with: swig
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has body: I have a question on how to properly use Py_DECREF() on PyList in C. So let say I have a function called build_list() which accepts a string linked list as its input argument and returns a Python list if everything goes well, or NULL if there is an error. Below is the minimalistic example: struct strlist { char *str; size_t len; struct strlist *next; }; PyObject *build_list (struct strlist *inlist) { struct strlist *node = NULL; PyObject *tmp_obj = NULL; int success; PyObject *ret_obj = PyList_New(0); if (ret_obj == NULL) { return NULL; } node = inlist; while (node != NULL) { tmp_obj = PyString_FromStringAndSize(node-&gt;str, node-&gt;len); if (tmp_obj == NULL) { Py_DECREF(ret_obj); return NULL; } else { success = PyList_Append(ret_obj, tmp_obj); Py_DECREF(tmp_obj); if (success != 0) { Py_DECREF(ret_obj); return NULL; } } node = node-&gt;next; } return ret_obj; } Have I used Py_DECREF() correctly in this case? My particular question is: If a few elements have been appended to the list before an error occur, my code will decrement the reference to the list directly (inside success != 0) while the elements inside the list technically still have refcount of 1. Should I instead decrement each element's reference first before I finally decrement the reference to the list? Thank you.
accepted answer: http://stackoverflow.com/a/48474076
has comment: http://stackoverflow.com/comment/83937597

http://stackoverflow.com/comment/83875174
type: Comment
comment on: http://stackoverflow.com/a/48441925
score: 0
type: AnswerComment
has text: Tried this, it removed the output of the adb command and still hasn't created a text file :(

http://stackoverflow.com/comment/83902874
type: AnswerComment
comment on: http://stackoverflow.com/a/48454866
has text: this is really good, thank you for your help here. I was going down the entirely wrong path but this is super helpful and informative. much appreciated!
score: 1
type: Comment

http://stackoverflow.com/a/48477221
has body: Check the type of key variable. Keys are NOT strings probably.
score: 0
answers question: http://stackoverflow.com/q/48477136
type: Answer

http://stackoverflow.com/comment/83969918
comment on: http://stackoverflow.com/q/48487482
score: 0
has text: First figure out how to do this mathematically, and then people may be able to help you implement the algorithm. Just some thoughts- the shortest distance between the points is a straight line. Starting from the initial point, you can draw this line and find where the it intersects the polygon, then follow it around to the other intersection (there are 2 ways, pick the shorter one), and continue on the original line to the end point.
type: QuestionComment
type: Comment

simplex-noise
type: Tag
tags question: http://stackoverflow.com/q/48415208
tag name: simplex-noise

http://stackoverflow.com/q/48412858
tagged with: artificial-intelligence
tagged with: nlp
has comment: http://stackoverflow.com/comment/83818447
has comment: http://stackoverflow.com/comment/83825626
has answer: http://stackoverflow.com/a/48424785
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: words related to a topic (another word) using NTLK
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83837861
has comment: http://stackoverflow.com/comment/83816928
has body: I'm working on building my own virtual assistant based on intent&lt;->action mechanism and want to run some NLP on sentences that my users write. I want to find out words related to a topic(another word) so that I can define an intent, for example: If a user asks: Will it rain tomorrow? What's the weather today? is it sunny? Is if going to be windy this afternoon? I want to be able to say that rain, weather, sunny, sun are related to the intent called weather so that I can communicate with the relevant API and retrieve the requested information. I'm currently working with Python 3 and NLTK but using synonyms, path to parent and similarity doesn't really do the trick: wordFromList1 = wn.synsets('weather')[0] wordFromList2 = wn.synsets('cold')[0] value = wn.wup_similarity(wordFromList1, wordFromList2) print(value) --------------------------- 0.1 You can see that the similarity here for cold and weather is really weak. Any suggestions? Thanks,
type: UnansweredQuestion
tagged with: nltk
tagged with: python

http://stackoverflow.com/comment/83825233
type: QuestionComment
comment on: http://stackoverflow.com/q/48344540
score: 0
has text: You are completely right, sleeping on it I understood what you meant :) I will correct it in the question. But this does not resolve the problem of infinite decimals / precise frequency.
type: Comment

http://stackoverflow.com/q/48362221
has answer: http://stackoverflow.com/a/48362276
has answer: http://stackoverflow.com/a/48362272
score: 1
has comment: http://stackoverflow.com/comment/83776486
has title: Searching Text Files - High Scores (using Python)
answer count: 4
has answer: http://stackoverflow.com/a/48362289
tagged with: text-files
favorite count: 0
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48362273
has body: Here is my code: results = username, score if (topic == 'history') and (difficulty == 'easy'): with open("hisEasyR.txt", "a") as hisEasyRFile: writer = csv.writer(hisEasyRFile, delimiter='|') writer.writerows(results) This is what the text file looks like: mary|4 john|5 lisa|3 I want to read from the file this file and find the highest score. Perhaps using the max function? I'm not sure how to even go about this though. Is there a way to search a file like you can search a list?
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48362276
has comment: http://stackoverflow.com/comment/83711350
accepted answer: http://stackoverflow.com/a/48362272
has comment: http://stackoverflow.com/comment/83711318
type: AnsweredQuestion

http://stackoverflow.com/q/48431366
has comment: http://stackoverflow.com/comment/83853933
upvote count: 0
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/83853919
has title: Run Lengths (python )
tagged with: python
has body: I'm supposed to create a list where it takes account if heads or tails is consecutive... ie. [H,H,H,T,T,H,H,T,T,H,T] = [ 3,2,2,2,1,1] why isn't this working? from __future__ import print_function import numpy as np import matplotlib.pyplot as plt def run_lengths(n,p): tosses= np.random.choice(([True, False ]),p=[p,1-p], size=n) heads= True tails= False heads_counter = 0 tails_counter=0 runlist=[] rl=runlist for i in tosses: if True: heads_counter+=1 if tosses[i+1]== False: rl.append(heads_counter) heads_counter=0 elif False: tails_counter +=1 if tosses[i+1]== True: rl.append(tails_counter) tails_counter=0 print(runlist) print(tosses) ##print(run_lengths(10,.5))
has comment: http://stackoverflow.com/comment/83853895
has comment: http://stackoverflow.com/comment/83853776
tagged with: matplotlib
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48432878
favorite count: 0
type: Question

http://stackoverflow.com/q/48400177
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Python mysqldb stops working after trying to connect to DB
has comment: http://stackoverflow.com/comment/83800320
score: 0
has comment: http://stackoverflow.com/comment/83801972
tagged with: mysql-python
has body: I'm trying to connect to a external database but after trying to connect to the database, the whole script stops running. i'm trying to run it on a Raspberry PI 3. So after the attempt to connect to the database, it stops working. the test print does show up but the second one does not. Script: import MySQLdb HOST = "host" PORT = 3306 USER = "user" PASS = "pass" DATABASE = "databasename" print("test") db = MySQLdb.connect(HOST, USER, PASS, DATABASE) print("test2") cursor = db.cursor() cursor.execute("SELECT * FROM Persoon") data = cursor.fetchone() print "database version :%s"% data db.close()
has comment: http://stackoverflow.com/comment/83793017
tagged with: raspberry-pi
type: Question
has comment: http://stackoverflow.com/comment/83800185

http://stackoverflow.com/comment/83907982
comment on: http://stackoverflow.com/a/48444535
type: Comment
score: 1
type: AnswerComment
has text: @JeffC A big _Thanks_ to you for all your time and effort to edit/prettify the Answers. However I would request you to look back the [meta post](https://meta.stackoverflow.com/questions/362515/is-this-formatting-overuse) as you are clearly _violating_ the rules by _downvoting_ . None of the Answers points towards downvoting for _formatting overuse_ as such.

http://stackoverflow.com/a/48395032
has body: The SU.TO.csv file contains rows with 'null' values. For example on line 68: 1995-04-13,2.383130,2.383130,2.359380,2.359380,0.963797,3283200 1995-04-14,null,null,null,null,null,null 1995-04-17,2.390620,2.390620,2.359380,2.359380,0.963797,600000 So you will have to take care of that in your code. Maybe you can use na_values=['null'] instead of na_values=['nan']?
type: Answer
answers question: http://stackoverflow.com/q/48394954
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48394954
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83817464

http://stackoverflow.com/comment/83696504
score: 0
has text: @jonrsharpe of course, thank you
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48354491

http://stackoverflow.com/q/48429439
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a dataset made up of 4 columns, a numerator denominator, country, and month. I am pivoting it to get months as columns, country as index, and values as sum(numerator)/sum(denominator). The only problem I get is that my columns are all out of order. How can I sort the columns so earlier months appear first? I tried table = table.sort_index(1) with no luck. table = pd.pivot_table(df, values=['Numerator', 'Denominator'], index='Country', columns=['Month'], aggfunc=np.sum) table = table['Numerator'] / table['Denominator'] Edit with full example and data: Data: Denominator,Numerator,Country,Month 10,4,USA,1-Jan 6,2,USA,1-Jan 10,1,Canada,1-Jan 9,2,Canada,1-Jan 6,4,Canada,1-Feb 4,3,Canada,1-Feb Code: import pandas as pd import numpy as np df = pd.read_csv('data.csv') table = pd.pivot_table(df, values=['Numerator', 'Denominator'], index='Country', columns=['Month'], aggfunc=np.sum) table = table['Numerator'] / table['Denominator'] print table Output: Month 1-Feb 1-Jan Country Canada 0.7 0.157895 USA NaN 0.37500 Desired Output: Month 1-Jan 1-Feb Country Canada 0.157895 0.7 USA 0.37500 NaN
favorite count: 0
accepted answer: http://stackoverflow.com/a/48429857
type: Question
has comment: http://stackoverflow.com/comment/83850375
has comment: http://stackoverflow.com/comment/83849738
has comment: http://stackoverflow.com/comment/83850637
has comment: http://stackoverflow.com/comment/83850192
has comment: http://stackoverflow.com/comment/83849660
tagged with: python
has comment: http://stackoverflow.com/comment/83850326
has answer: http://stackoverflow.com/a/48429857
has comment: http://stackoverflow.com/comment/83850249
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83850070
has title: Sorting month columns in pandas pivot_table
tagged with: pandas
linked to: http://stackoverflow.com/q/47152691
score: 1

http://stackoverflow.com/q/48443629
answer count: 1
has comment: http://stackoverflow.com/comment/83880673
has body: I want to pass self.user = QtGui.QLineEdit(MainWindow) variable from Login.py to officer = str(self.tocomb.currentText()) in ingooi.py My 3 GUI windows My program consists of various files where I import the classes from other files as needed. The 3 main files consists of : Login.py ( My Login window where user logs in ) page22.py ( User selects to enter/view data ) ingooi.py ( User enters data then adds the data to access database via Submit Button Please see the code for these 3 main files below. Login.py from PyQt4 import QtCore, QtGui from ingooi import Ui_NextPage from page22 import Ui_Page1 import pypyodbc try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Logged(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(389, 235) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.Login_button = QtGui.QPushButton(self.centralwidget) self.Login_button.setGeometry(QtCore.QRect(90, 150, 75, 23)) self.Login_button.setObjectName(_fromUtf8("Login_button")) self.user = QtGui.QLineEdit(MainWindow) self.user.setGeometry(QtCore.QRect(100, 30, 113, 20)) self.user.setObjectName(_fromUtf8("user")) self.password = QtGui.QLineEdit(MainWindow) self.password.setGeometry(QtCore.QRect(100, 70, 113, 20)) self.password.setObjectName(_fromUtf8("password")) self.password.setEchoMode(QtGui.QLineEdit.Password) self.user_label = QtGui.QLabel(self.centralwidget) self.user_label.setGeometry(QtCore.QRect(30, 30, 46, 13)) self.user_label.setObjectName(_fromUtf8("user_label")) self.Password_label = QtGui.QLabel(self.centralwidget) self.Password_label.se…
type: Question
has comment: http://stackoverflow.com/comment/83879101
has comment: http://stackoverflow.com/comment/83891805
has comment: http://stackoverflow.com/comment/83880474
has comment: http://stackoverflow.com/comment/83879135
has title: PyQt4 sharing QLineEdit variable across .py files
tagged with: pyqt4
accepted answer: http://stackoverflow.com/a/48451679
has comment: http://stackoverflow.com/comment/83894334
tagged with: python
linked to: http://stackoverflow.com/q/11812000
has comment: http://stackoverflow.com/comment/83895192
has answer: http://stackoverflow.com/a/48451679
has comment: http://stackoverflow.com/comment/83894422
type: AnsweredQuestion
tagged with: pyqt
score: 0

http://stackoverflow.com/comment/83839947
type: AnswerComment
comment on: http://stackoverflow.com/a/48425021
has text: Thanks a lot for this. It is working :) +1 @dirkgroten
type: Comment
score: 0

http://stackoverflow.com/comment/83720409
score: 1
type: Comment
has text: @ChaseTaylor by convention on SO, Python users do not generally include the `print` statement for reasons of code length.
type: AnswerComment
comment on: http://stackoverflow.com/a/48363487

http://stackoverflow.com/a/48452377
has comment: http://stackoverflow.com/comment/83898045
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/135002962
has comment: http://stackoverflow.com/comment/83898009
has body: The g object is only global to the current request context. That means when the same user sends a new request, the new request has its own g object. One solution to have a global connection object: just use normal global object and some bookkeeping if you want to make sure there's only one connection object. conn = None def get_db(): global conn if conn is None: conn = connect_db() return conn
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48452240
type: Answer
score: 5
answers question: http://stackoverflow.com/q/48452240

http://stackoverflow.com/comment/139153152
comment on: http://stackoverflow.com/a/78923357
type: AnswerComment
has text: This answer would be clearer if you could put the command-lines into code blocks using single or triple back-ticks. It looks like "Source" is a relative directory, could be more precise that it is a directory. Also, _Windows_ is a proper noun ending with S.
score: 0
type: Comment

http://stackoverflow.com/a/48414150
has body: Just do it in Python: with open("file1.txt", "rb") as fin: with open("file2.txt", "wb") as fout: while True: data = fin.read(100000) if not data: break data = data.replace(b"\r", b"") fout.write(data)
has comment: http://stackoverflow.com/comment/83834257
answers question: http://stackoverflow.com/q/48414112
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83818930
type: Answer

http://stackoverflow.com/q/48484152
tagged with: subprocess
downvote count: 0
has body: I am using the following system command in Python 2.7. I am able to execute the same command in terminal successfully whereas I am not able to run it in python(getting return code = 32512). The command basically converts a mp3 file into a wave file along with stereo to mono conversion. I am able to run the same command in terminal successfully. Below is the command I'm trying out: os.system("ffmpeg -i /Users/krish/audio.mp3 -acodec pcm_s16le -ar 16000 -ac 1 /Users/krish/converted_audio.wav") I also tried using the subprocess command but it gave the same 32512 return code. Could anyone help me out on what's wrong with this?
tagged with: os.system
accepted answer: http://stackoverflow.com/a/58856294
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83964138
has title: os.system() returns error code 32512 - Python
tagged with: python
has answer: http://stackoverflow.com/a/58856294
has answer: http://stackoverflow.com/a/48484217
possible better answer: http://stackoverflow.com/a/48484217
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2

django-import-export
tags question: http://stackoverflow.com/q/48435549
tag name: django-import-export
type: Tag

http://stackoverflow.com/q/48363477
upvote count: 0
has answer: http://stackoverflow.com/a/48363490
has answer: http://stackoverflow.com/a/48363498
score: -3
tagged with: string
has answer: http://stackoverflow.com/a/48363520
possible better answer: http://stackoverflow.com/a/48363520
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17151405
downvote count: 3
answer count: 5
has title: Python regular expression quoted string
has answer: http://stackoverflow.com/a/48385169
duplicate of: http://stackoverflow.com/q/17151405
has answer: http://stackoverflow.com/a/48363487
tagged with: python
has body: I have the following string: str1 = "I am doing 'very well' for your info" and I want to extract the part between the single quotes i.e. very well How am I supposed to set my regular expression? I tried the following but obviously it will give wrong result import re pt = re.compile(r'\'*\'') m = pt.findall(str1) Thanks
accepted answer: http://stackoverflow.com/a/48363487
tagged with: regex
type: Question

http://stackoverflow.com/comment/83768275
comment on: http://stackoverflow.com/q/48390030
type: QuestionComment
has text: @juanpa.arrivillaga "the implementation details are irrelevant, there are no pointers in the Python" so you said, but http://scottlobdell.me/2013/08/understanding-python-variables-as-pointers/ explicitly states "All python references are, in effect, C pointers under the hood." I don't understand why you contradicted me calling them pointers, when in fact they are so? :D
type: Comment
score: 0

http://stackoverflow.com/comment/83855912
type: QuestionComment
comment on: http://stackoverflow.com/q/48432316
has text: There are no private attributes in Python. double-underscore name-mangling does *name-mangling*, it doesn't restrict access.
score: 1
type: Comment

http://stackoverflow.com/comment/83768362
score: 0
comment on: http://stackoverflow.com/a/48389178
has text: How bulky is it to bundle python? `libpython` is not a full-fledged interpreter, so these compiled versions should still be lighter and faster, right? Just not as light and fast as actually reimplementing things in C.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48403708
has body: There is a third iframe underneath your frame2, select that before requesting for in-game-stats. All together, frame1 = browser.find_element_by_xpath('//iframe[contains(@class, "player")]') browser.switch_to.frame(frame1) frame2 = browser.find_element_by_xpath('//iframe[contains(@id, "playerFrame")]') browser.switch_to.frame(frame2) You can try to get a better way of identifying this last iframe, here I am going to index it as the first iframe under iframe2. frame3 = browser.find_element_by_xpath('//iframe[1]') browser.switch_to.frame(frame3) Now you can get the node that you were looking for: browser.find_element_by_xpath("//div[contains(@id, 'in-game-stats')]")
type: Answer
answers question: http://stackoverflow.com/q/48402242
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48402242
has comment: http://stackoverflow.com/comment/83823598

http://stackoverflow.com/a/48341598
answers question: http://stackoverflow.com/q/48341233
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83677207
type: Answer
has comment: http://stackoverflow.com/comment/83672563
has comment: http://stackoverflow.com/comment/83671246
downvote count: 1
has comment: http://stackoverflow.com/comment/84144507
has comment: http://stackoverflow.com/comment/84147156
has comment: http://stackoverflow.com/comment/84144465
accepted answer of: http://stackoverflow.com/q/48341233
score: 3
has body: You can get this working if you snap your time series to a daily frequency before plotting, using pd.Series.asfreq: ts.asfreq('D').plot(); plt.show()

http://stackoverflow.com/a/48713132
has body: Each pair of samples has a matching string (SN=sample N) A solution to this question in bash could be: #!/bin/bash #apply loop function to samples 1-12 for SAMPLE in {1..12} do #set input file 1 to "FL1", input file 2 to "FL2" FL1=$(ls ~path/to/input/files/_S${SAMPLE}_*_R1_*.gz) FL2=$(ls ~path/to/input/files/_S${SAMPLE}_*_R2_*.gz) #invoke java ,send FL1 and FL2 to appropriate output folders java -jar ~/path/to/trimming/apps/Trimmomatic-0.36/trimmomatic-0.36.jar PE -threads 12 -phred33 -trimlog ~/path/to/output/folders/${FL1}.trimlog ~/path/to/input/file1/${FL1} ~/path/to/input/file2/${FL2} ~/path/to/paired/output/folder/${FL1}.pair.fq.gz ~/path/to/unpaired/output/folder/${FL1}.unpair.fq.gz ~/path/to/paired/output/folder/${FL2}.pair.fq.gz ~/path/to/unpaired/output/folder/${FL2}.unpair.fq.gz ILLUMINACLIP:/path/to/trimming/apps/Trimmomatic-0.36/TruSeq3-PE.fa:2:30:10 LEADING:5 TRAILING:5 SLIDINGWINDOW:4:15 MINLEN:28 #add verbose option to track progress echo "Sample ${SAMPLE} done" done This is an inelegant solution, because it requires the format I'm using. A better method would be to grep each filename and assign them to FL1, FL2 accordingly, because this would generalize the method. Still, this is what worked for me, and I can easily control which samples are subjected to the for loop, as long as I always have the _S * _ format in the filename strings.
answers question: http://stackoverflow.com/q/48429991
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48429991

http://stackoverflow.com/comment/83697766
comment on: http://stackoverflow.com/q/48355267
type: Comment
type: QuestionComment
has text: have a look at volumetric rendering/reconstruction. Maybe you can use something like marching cubes algorithm. In general this is more a computer graphics than a computer vision problem. Maybe there are functions in the point cloud library.
score: 0

http://stackoverflow.com/comment/83777597
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48394596
score: 0
has text: For instance if there is no 'children' attribute, you could get a `KeyError`. Or the `id` for a particular object is labeled `something_id`. Or the nesting is greater than the recursion limit. Or one of your objects is a subclass of `dict` or `list`. There could be loads to go wrong...

http://stackoverflow.com/comment/83854327
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48430523
type: Comment
has text: wow, that's way more than I would imagine. It still pains me that it is so difficult to read, but definitely a great improvement Thanks for the help!

http://stackoverflow.com/comment/83919506
type: QuestionComment
score: 0
has text: @IharobAlAsimi when I simply import "bz2" everything works fine since the python executable is (statically) linked to libpython and the module consequently get access to the symbols directly from the executable. As to "why python from C?" The C library is designed for portability between (scientific) applications and we use python to perform typically dynamic tasks. Think of the data in C mapping itself into a Python object whenever it wants to do something "fancy".
type: Comment
comment on: http://stackoverflow.com/q/48462792

http://stackoverflow.com/comment/83704225
type: AnswerComment
comment on: http://stackoverflow.com/a/48358698
has text: I am not familiar with a better way to do seeding, but the reason I selected a particular float is because I want to make sure I can reproduce my result. But then when I tried another number, they happened to fall in the same interval which I described above and generated the same result. Hence my confusion.
type: Comment
score: 0

http://stackoverflow.com/q/48441648
duplicate of: http://stackoverflow.com/q/23394476
score: 0
tagged with: pandas
answer count: 0
has title: How to return rows of a pandas dataframe based on conditions that are dependent on subsets of the dataframe
has body: Suppose I have a pandas dataframe like this: id val 0 1 1.0 1 1 2.0 2 2 1.5 3 2 1.3 4 3 1.4 5 3 1.0 6 3 2.1 7 1 0.8 8 2 1.2 9 3 1.0 In this example, I would like to get the rows with the minimum 'val' for each id. So I would like to get something like this: id val 0 1 0.8 1 2 1.2 2 3 1.0 How can I do that? In this case, the condition to select a row is dependent on a subset of the dataframe (minimum val for the subset with certain id). So the more general question is: how to select rows based on conditions that are dependent on subsets of the dataframe?
type: Question
linked to: http://stackoverflow.com/q/23394476
has comment: http://stackoverflow.com/comment/83874477
has comment: http://stackoverflow.com/comment/83875088
type: UnansweredQuestion
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/83686066
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48348875
score: 0
has text: What are you passing to `preprocess_data`?

http://stackoverflow.com/comment/83917511
comment on: http://stackoverflow.com/q/48334158
score: 0
has text: I am also facing the same issue.
type: Comment
type: QuestionComment

join
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/48484324
tags question: http://stackoverflow.com/q/48403619

http://stackoverflow.com/q/48460549
has title: retry requests with time interval
has answer: http://stackoverflow.com/a/48461072
answer count: 2
has body: I'm following this tutorial With session.mount I can ask requests to do as many retries as I want. But it seems like I can't control the interval between each request. For now I had to use codes like this for retry in range(1, 5): logging.warning('[fetch] try=%d, url=%s' % (retry, url)) try: resp = requests.get(url, timeout = 3) data = resp.text except Exception as e: logging.warning('[try=%d] fetch_list_html: %s' % (retry, e)) pass if data is False: time.sleep(retry * 2 + 1) else: break Is there any better solutions?
has comment: http://stackoverflow.com/comment/83914708
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
score: 0
has answer: http://stackoverflow.com/a/48461044
type: Question

http://stackoverflow.com/q/48410064
downvote count: 0
tagged with: python-requests
answer count: 1
has comment: http://stackoverflow.com/comment/83810065
has comment: http://stackoverflow.com/comment/83811491
favorite count: 0
has comment: http://stackoverflow.com/comment/83809835
has comment: http://stackoverflow.com/comment/83810206
type: Question
has comment: http://stackoverflow.com/comment/83823863
tagged with: lxml
has body: I'm trying to login to a webpage using python 3 using requests and lxml. However, after sending a post request to the login page, I can't enter pages that are available after login. What am I missing? import requests from lxml import html session_requests = requests.session() login_URL = 'https://www.voetbal.nl/inloggen' r = session_requests.get(login_URL) tree = html.fromstring(r.text) form_build_id = list(set(tree.xpath("//input[@name='form_build_id']/@value")))[0] payload = { 'email':'mom.soccer@mail.com', 'password':'testaccount', 'form_build_id':form_build_id } headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding':'gzip, deflate, br', 'Accept-Language':'nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control':'max-age=0', 'Connection':'keep-alive', 'Content-Type':'multipart/form-data; boundary=----WebKitFormBoundarymGk1EraI6yqTHktz', 'Host':'www.voetbal.nl', 'Origin':'https://www.voetbal.nl', 'Referer':'https://www.voetbal.nl/inloggen', 'Upgrade-Insecure-Requests':'1', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' } result = session_requests.post( login_URL, data = payload, headers = headers ) pvc_url = 'https://www.voetbal.nl/club/BBCB10Z/overzicht' result_pvc = session_requests.get( pvc_url, headers = headers ) print(result_pvc.text) The account in this sample is activated, but it is just a test-account which I created to put my question up here. Feel free to try it out.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48418149
tagged with: python
has comment: http://stackoverflow.com/comment/83824781
has title: Login website with python requests
has comment: http://stackoverflow.com/comment/83810314
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/83880174

http://stackoverflow.com/q/48366187
upvote count: 0
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/83718966
has answer: http://stackoverflow.com/a/48366459
accepted answer: http://stackoverflow.com/a/48366459
type: AnsweredQuestion
has body: How can I count all characters='Guest' and all characters='Stranger' for each year,and if number of guest is greater then number of strangers define a year 'strange year' or 'guest year' respectively g=titles.head() name type character n Homo actor Guests 22.0 Ramon actor Owner NaN 'El Guisa' actor Bailaor 25.0 'El Viti' actor Cantaor 20.0 Murray actor Himself NaN
tagged with: pandas
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83718978
has title: counting values within groups
favorite count: 0
type: Question

http://stackoverflow.com/a/48374690
type: Answer
answers question: http://stackoverflow.com/q/48374437
has body: If it's not json format, here's my answer: import ast def find(s, ch): # returns all indexes of occurrences of char ch in string s return [i for i, ltr in enumerate(s) if ltr == ch] # 1. Load your txt file as string with open('file.txt') as f: txt = f.read() # 2. Find occurrences of chars { and } start = find(txt, '{') end = find(txt, '}') # 3. Evaluate the string between corresponding occurrences of { and } for s, e in zip(start, end): a_python_dict = ast.literal_eval(txt[s:e+1]) print(a_python_dict) I took the find method here.
score: 0

http://stackoverflow.com/comment/83663680
has text: For my example, groups started with `C1`, but thanks
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48339157

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/48465846
type: Tag

http://stackoverflow.com/q/48480071
type: Question
tagged with: python
tagged with: mysql
score: 1
accepted answer: http://stackoverflow.com/a/48480213
favorite count: 0
has answer: http://stackoverflow.com/a/48480213
has body: My console shows this problem when trying to push data into my db invalid literal for int() with base 10: My views.py class: def routineInput(request): if request.method == 'POST': form = CreateRoutine(request.POST) query = request.POST["name_of_routine"] newEntry = Todolist(str(query)) #newEntry.name = () if form.is_valid(): newEntry.save() return HttpResponseRedirect('/todo/saved/') else: form = CreateRoutine() This is my models.py class: class Todolist(models.Model): id = models.AutoField(primary_key=True) name = models.TextField() created_at = models.DateTimeField(default = datetime.now, blank = True) updated_at = models.DateTimeField(default = datetime.now, blank = True) The newEntry = Todolist(str(query)) is my problem. If I change it to newEntry = Todolist(1, str(query)) my code works. But in the last case my code pushes the integer into the "id" field although it should be my auto increment primary key. Without the integer in my function my browser throws me this message: invalid literal for int() with base 10:...
type: AnsweredQuestion
downvote count: 0
has title: Django problems with primary keys and data inserts
tagged with: django
upvote count: 1
answer count: 1

http://stackoverflow.com/a/48488819
accepted answer of: http://stackoverflow.com/q/48487788
has comment: http://stackoverflow.com/comment/83993345
type: Answer
answers question: http://stackoverflow.com/q/48487788
has body: This is very simple as the function key can have list of dictionaries, so follow the following steps: post = { "file_name" : file_name, "function" : [{ "func_name" : func_name, "start_line" : start_line, "end_line" : end_line }] } #Define new function new_function = { "func_name" : new_func_name, "start_line" : new_start_line, "end_line" : new_end_line } #Append the new_function into post post["function"].append(new_function) print post Hope this helps.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48352001
score: 0
has comment: http://stackoverflow.com/comment/83691722
has body: You can use print() function. If you use print() function inside your view then when that view function is executed it prints on Command line or terminal. in views.py def indexView(request): productCat = Product_Cat.objects.order_by('name') upcoming = Upcoming_Product.objects.all() print(upcoming) return render(request,'website/index.html',{'productCat':productCat}) in terminal: &lt;QuerySet []&gt;
type: Answer
answers question: http://stackoverflow.com/q/48351756

http://stackoverflow.com/comment/83796326
type: QuestionComment
comment on: http://stackoverflow.com/q/48402009
type: Comment
score: 0
has text: I tried printing the size but it throws the error before it runs that part of the code

http://stackoverflow.com/comment/83803818
score: 0
has text: You want to add a `datilist` key, with `[]` as value ? It is unclear to me, could you post some little code ?
type: Comment
comment on: http://stackoverflow.com/q/48407360
type: QuestionComment

http://stackoverflow.com/comment/83901055
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48453835
type: Comment
has text: @NathanVērzemnieks Technically the OP is only asking to fix their syntax errors, rather than their logical errors. As such this answer is entirely valid.

http://stackoverflow.com/q/48405225
upvote count: 1
has comment: http://stackoverflow.com/comment/83802636
favorite count: 0
has comment: http://stackoverflow.com/comment/83806237
type: Question
score: 1
tagged with: database
has comment: http://stackoverflow.com/comment/83805539
tagged with: python
has title: How to store large feature vectors for a huge dataset for image retrieval application (CBIR)?
has body: I am building a CBIR application . I am using the features extracted from a deep convnet. The feature vectors are quite big ( about 100,000 in size) . And the dataset has more than 10k images. I have already gone through the answer to this problem, and I don't want to use the libraries mentioned in the same. I tried cPickle and hdf5 for storing the feature vectors. I am running it on a PC having 4GB of RAM and a 2Ghz Intel Core i3 processor. The following piece of code builds the index : h = h5py.File(index_file, 'w') for imagePath in glob.glob(args["dataset"] + "/*.*"): # extract our unique image ID (i.e. the filename) k = imagePath[imagePath.rfind('/') + 1:] features = get_features(imagePath, args["layer"]) h.create_dataset(k, data=features) Whenever I run the program to build the index for my dataset of images, I get the error "Python.exe has stopped working"after around 16MB of index file has been created. I am new to hdf5 and the answer maybe trivial, but any help would be deeply appreciated.
tagged with: deep-learning
answer count: 0
type: UnansweredQuestion
tagged with: hdf5
downvote count: 0
tagged with: cbir

http://stackoverflow.com/comment/83880916
has text: @ImportanceOfBeingErnest I know, but I also tried plotting directly (as I did in the first example) and it didn't work either. Because of what I'm plotting, I need a GroupBy Dataframe plot.
comment on: http://stackoverflow.com/q/48444312
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83760135
comment on: http://stackoverflow.com/q/48335823
score: 0
has text: Have you tried tensorflow's eager execution? Numpy-style code should easily translate there.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83659345
has text: Wow... well, map isn't going to do it. It only maps one key to one value. By the way, these details are important, and they should be in your question.
comment on: http://stackoverflow.com/q/48336937
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83927810
has text: Thanks for the explanation! Sorry for being stupid though, why can 2^-100 be represented if the precision is only 52-bit?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48466839
type: Comment

http://stackoverflow.com/q/48480279
has answer: http://stackoverflow.com/a/48480306
favorite count: 0
type: Question
tagged with: python-3.x
has body: hey I have this file in py, it is called Numbers.py: Numbers=[1,3,5,7] for i in Numbers: if i%2==0: print(i) else: i%2==1 print(i) for l in Numbers: if l&gt;1 &amp; i%l==1: print(l) how can I import it in another one?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83953559
score: -2
linked to: http://stackoverflow.com/q/2349991
has comment: http://stackoverflow.com/comment/83953567
tagged with: python
has title: How to import in py
has comment: http://stackoverflow.com/comment/83953553
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/q/48339129
has comment: http://stackoverflow.com/comment/83668283
answer count: 0
has comment: http://stackoverflow.com/comment/83669878
score: 0
tagged with: tensorflow
type: Question
has title: `binary_crossentropy` definitions not the same?
has comment: http://stackoverflow.com/comment/83669635
type: UnansweredQuestion
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/83663592
has body: In my neural network if I compile it with: D.compile(loss="binary_crossentropy", optimizer=opt_D) it works great but if I do: def make_loss_D(c): def loss_D(y_true, y_pred): #return c * K.binary_crossentropy(y_pred, y_true) return c * K.mean (K.binary_crossentropy(y_pred, y_true)) return loss_D D.compile(loss=[make_loss_D(c=1.0)], optimizer=opt_D) The losses are totally different, and the neural network makes very strong predictions close to 1 or 0 always. I like the behaviour seen in the first example, but after digging into https://github.com/keras-team/keras/blob/master/keras/losses.py code I don't see why the two would be so different. Adjusting the value of c in my code to make the two losses match after the first epoch doesn't help at all. What is the difference in the losses defined, and why is the second one so badly behaved? Edit: After fixing the order of y_pred, y_true, and axis for mean, the custom function also works. def make_loss_D(c): def loss_D(y_true, y_pred): return c * K.mean (K.binary_crossentropy(y_true, y_pred), axis=-1) return loss_D The losses are still not the same, what could be the reason for that?

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/48406749
tags question: http://stackoverflow.com/q/48332216
tags question: http://stackoverflow.com/q/48372296

http://stackoverflow.com/a/48466480
has comment: http://stackoverflow.com/comment/83927125
has comment: http://stackoverflow.com/comment/83927313
has comment: http://stackoverflow.com/comment/83926510
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83926689
upvote count: 1
has comment: http://stackoverflow.com/comment/83926962
has body: If what you want is to convert minutes to an hour what you can do is this: def toHour(minutes): return str(timedelta(minutes=minutes%1440))[:-3] Now to do that for every element : df['new_min'] = list(map(lambda x: toHour(int(x)), df['minutes'])) EDIT 1 If you prefer "01:30" instead of "1:30" you can do def toHour(minutes): hour = str(timedelta(minutes=minutes%1440))[:-3] return "{0:0&gt;5}".format(hour)
has comment: http://stackoverflow.com/comment/83926705
answers question: http://stackoverflow.com/q/48466263
has comment: http://stackoverflow.com/comment/83926857
score: 1
accepted answer of: http://stackoverflow.com/q/48466263
type: Answer

http://stackoverflow.com/a/48360223
downvote count: 0
has comment: http://stackoverflow.com/comment/83707211
upvote count: 1
has body: You may have to do it like this: data = np.array([[[ 6, 12, 108]], [[122, 112, 38]], [[ 57, 101, 62]], [[119, 76, 177]], [[ 46, 62, 2]], [[127, 61, 155]], [[ 5, 6, 151]], [[ 5, 8, 185]], [[109, 167, 33]]]) np.argmax(data[:,0][:,2]) 7
answers question: http://stackoverflow.com/q/48360189
type: Answer
has comment: http://stackoverflow.com/comment/83707294
accepted answer of: http://stackoverflow.com/q/48360189
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48369125
answers question: http://stackoverflow.com/q/48368879
type: Answer
has body: Python solution: s = '11+Samsung-Galaxy-S8+-4469+a2:cc:2b:8d:xx:xx' if s.count('+') &gt; 2: parts = s.split('+') s = '{}+{}+{}'.format(parts[0], ''.join(parts[1:-1]), parts[-1]) print(s) The output: 11+Samsung-Galaxy-S8-4469+a2:cc:2b:8d:xx:xx
score: 0

http://stackoverflow.com/comment/83884966
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48431023
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163884/discussion-between-pault-and-andrew-r).
type: Comment

http://stackoverflow.com/q/48373768
has answer: http://stackoverflow.com/a/48394083
favorite count: 0
tagged with: aws-lambda
tagged with: urllib
has title: Connection Reset by Peer Occuring on Lambda
type: Question
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83771426
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/83774921
tagged with: alexa-skills-kit
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48394083
has body: I wrote a simple script in Python 2.7 that compiles my homework off of my school website using urllib(2), cookielib, and bs4. When I ran it off of my IDE it worked perfectly without any errors. However when compile it for Alexa and I run it on AWS Lambda, I receive the following error: [Errno 104] Connection reset by peer: error Traceback (most recent call last): File "/var/task/lambda_function.py", line 136, in lambda_handler return on_launch(event['request'], event['session']) File "/var/task/lambda_function.py", line 80, in on_launch return scraper(session) File "/var/task/lambda_function.py", line 98, in scraper open(URL) File "/var/task/lambda_function.py", line 16, in open return browser.open(url, postdata).read() File "/usr/lib64/python2.7/urllib2.py", line 429, in open response = self._open(req, data) File "/usr/lib64/python2.7/urllib2.py", line 447, in _open '_open', req) File "/usr/lib64/python2.7/urllib2.py", line 407, in _call_chain result = func(*args) File "/usr/lib64/python2.7/urllib2.py", line 1243, in https_open context=self._context) File "/usr/lib64/python2.7/urllib2.py", line 1203, in do_open r = h.getresponse(buffering=True) File "/usr/lib64/python2.7/httplib.py", line 1136, in getresponse response.begin() File "/usr/lib64/python2.7/httplib.py", line 453, in begin version, status, reason = self._read_status() File "/usr/lib64/python2.7/httplib.py", line 409, in _read_status line = self.fp.readline(_MAXLINE + 1) File "/usr/lib64/python2.7/socket.py", line 480, in readline data = self._sock.recv(self._rbufsize) File "/usr/lib64/python2.7/ssl.py", line 756, in recv return self.read(buflen) File "/usr/lib64/python2.7/ssl.py", line 643, in read v = self._sslobj.read(len) error: [Errno 104] Connection reset by peer I know that usually this is because the server I'm attempting to access is dropping the connection, but I can't figure out why it works in my IDE and not in my lambda. Here is my original code I use in the IDE: import urllib import urllib2 …

ckan
tags question: http://stackoverflow.com/q/48453382
tag name: ckan
type: Tag

http://stackoverflow.com/a/48455925
score: 2
accepted answer of: http://stackoverflow.com/q/48455749
type: Answer
answers question: http://stackoverflow.com/q/48455749
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: One way to do this is to flatten the multiindex columns, merge and expand flatten column names back to multiindex: df1.columns = df1.columns.map('|'.join) df2.columns= df2.columns.map('|'.join) df_out = df1.merge(df2, on='info|P') df_out.columns = df_out.columns.str.split('|',expand=True) df_out Output: info 2002 2003 2002 P E DT02_x DT03 DT02_y DTH 0 1 4 20020111 20121222 20020111 1 1 2 5 20021111 20141222 20021111 1 2 3 4 20021112 20151222 20021113 0

http://stackoverflow.com/comment/83722919
score: 0
has text: I am sorry.Just now i updated it.Thanks :-)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48366939

http://stackoverflow.com/q/48484705
tagged with: function
answer count: 1
tagged with: variables
tagged with: multiprocessing
type: Question
tagged with: while-loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48485128
tagged with: python
has title: How using the current contents of the list in a function running in the loop?
score: 0
has body: I try to use multiprocessing in this way: from multiprocessing import Pool added = [] def foo(i): added = [] # do something added.append(x[i]) return added if __name__ == '__main__': h = 0 while len(added)&lt;len(c): pool = Pool(4) result = pool.imap_unordered(foo, c) added.append(result[-1]) pool.close() pool.join() h = h + 1 Multiprocessing takes place in the while-loop, and in the foo function, the added list is created. In each subsequent step h in the loop, the listadded should be incremented by subsequent values, and the current list added should be used in the functionfoo. Is it possible to pass the current contents of the list to the function in each subsequent step of the loop? Because in the above code, the foo function creates the new contents of the added list from scratch each time. How can this be solved?

http://stackoverflow.com/a/48451302
type: Answer
accepted answer of: http://stackoverflow.com/q/48449744
has comment: http://stackoverflow.com/comment/83904866
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83904230
answers question: http://stackoverflow.com/q/48449744
has body: This is a possible solution for your code. It has not been tested. with open(subjectlist) as file: lines = file.readlines() for line in lines: subject=line.strip() subjectpath=sourcedir+"/"+subject if os.path.isdir(subjectpath): with open(outputlog, 'a') as logfile: logfile.write(subject+os.linesep) # Submit a job to the HPC with sbatch. This next line was not in the # original script that works, and it isn't correct, but it captures # the gist of what I am trying to do (written in bash). cmd = 'sbatch --job-name dcm2nii_{subject} --partition=short --time 00:60:00\ --mem-per-cpu=2G --cpus-per-task=1 -o {niidir}/{subject}_dcm2nii_output.txt\ -e {niidir}/{subject}_dcm2nii_error.txt\ --wrap="dcm2niix -o -b y {niidir} {subjectpath}"'.format(subject=subject,niidir=,subjectpath=subjectpath) # This is what I want the job to do for the files in each directory: subprocess.call([cmd], shell=True) else: with open(errorlog, 'a') as logfile: logfile.write(subject+os.linesep)
has comment: http://stackoverflow.com/comment/83928811
has comment: http://stackoverflow.com/comment/83943182

http://stackoverflow.com/q/48438790
type: Question
tagged with: numpy
has body: I want to create a dataset B by processing a dataset A. Therefore, every column in A (~ 2 Mio.) has to be processed in a batch-fashion (putting through a neural network), resulting in 3 outputs which are stacked together and then e.g. stored in a numpy array. My code looks like the following, which seems to be not the best solution. # Load data data = get_data() # Storage for B B = np.empty(shape=data.shape) # Process data for idx, data_B in enumerate(data): # Process data a, b, c = model(data_B) # Reshape and feed in B B[idx * batch_size:batch_size * (idx + 1)] = np.squeeze(np.concatenate((a, b, c), axis=1)) I am looking for ideas to speed up the stacking or assigning process. I do not know if it is possible for parallel processing since everything should be stored in the same array finally (the ordering is not important). Is there any python framework I can use? Loading the data takes 29s (only done once), stacking and assigning takes 20s for a batch size of only 2. The model command takes &lt; 1s, allocating the array takes 5s and all other part &lt;1s.
has title: Idea to speed up array processing
has comment: http://stackoverflow.com/comment/83870809
score: 0
answer count: 1
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/83877367
type: AnsweredQuestion
tagged with: performance
accepted answer: http://stackoverflow.com/a/48449320
has comment: http://stackoverflow.com/comment/83868716
tagged with: database-performance
has answer: http://stackoverflow.com/a/48449320

http://stackoverflow.com/q/48475110
tagged with: python
tagged with: list-comprehension
has body: Trying to read a txt file and filter irrelevant lines. Some lines are random strings, some being with '#' hashtag character. base_txt = open(path, 'rU') txt = base_txt.readlines() txt = [x for x in base_txt if x.startswith('#')] print txt print len(txt) The output is an empty list. If I print txt before the list comprehension then it prints out all the strings in the file. Is there a syntax error I'm doing?
tagged with: startswith
tagged with: readlines
has comment: http://stackoverflow.com/comment/83943639
has title: python empty list output for list comprehension from txt
answer count: 1
has answer: http://stackoverflow.com/a/48475182
accepted answer: http://stackoverflow.com/a/48475182
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83943623
has comment: http://stackoverflow.com/comment/83943635

http://stackoverflow.com/q/48461081
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83915707
has body: i was annoyed by the fact that timedelta has no __format__ method. so i wanted to inherit from timedelta (monkey-patching is no option for built-in/extension type 'datetime.timedelta') so i tired inheritance (my_dict is just here for reference; this one works!). from datetime import timedelta class my_dict(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class my_timedelta(timedelta): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print(my_dict.__mro__) # (&lt;class '__main__.my_dict'&gt;, &lt;class 'dict'&gt;, &lt;class 'object'&gt;) print(my_timedelta.__mro__) # (&lt;class '__main__.my_timedelta'&gt;, # &lt;class 'datetime.timedelta'&gt;, &lt;class 'object'&gt;) d0 = my_dict(); d1 = my_dict(a=3) print(d0, d1) # -&gt; {} {'a': 3} # no arguments: this works! t0 = my_timedelta() print(t0) # -&gt; 0:00:00 # one argument: TypeError # t1 = my_timedelta(5) # -&gt; TypeError: object.__init__() takes no parameters # print(t1) # a key-word argument: TypeError # t2 = my_timedelta(seconds=5) # -&gt; TypeError: object.__init__() # takes no parameters # print(t2) the method resolution order of both looks similar; but it seems that __init__ in the timedelta case is skipping timedelta.__init__ and jumping directoy to object.__init__. am i doing something very wrong? how can i inherit from timedelta? what goes wrong here?
has comment: http://stackoverflow.com/comment/83915658
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48461450
linked to: http://stackoverflow.com/q/40743739
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48461450
has title: can't inherit from timedelta

http://stackoverflow.com/a/48429509
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48429361
accepted answer of: http://stackoverflow.com/q/48429361
type: Answer
has body: Iterate from 1 to the length-1 for i in range(1, trex.shape[0]-1): # MOST ROWS for j in range(1, trex.shape[1]-1): # MOST COLUMNS ...

http://stackoverflow.com/q/48371880
tagged with: macos
has comment: http://stackoverflow.com/comment/83730850
has comment: http://stackoverflow.com/comment/83730846
has title: Beautifull soup install mac error
score: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48371962
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I am getting the following error message when i try to install Beautifullsoup via mac terminal. [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-40423.pth' Please help.
type: UnansweredQuestion
tagged with: java
has comment: http://stackoverflow.com/comment/83730756
tagged with: python

http://stackoverflow.com/comment/103711967
comment on: http://stackoverflow.com/a/48367402
type: Comment
score: 0
type: AnswerComment
has text: i have edited answer to make it better. hope i did it correctly!

http://stackoverflow.com/q/48338062
score: 1
tagged with: terminate
has title: How to stop a script within a script
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48401963
answer count: 2
has answer: http://stackoverflow.com/a/48397389
type: UnansweredQuestion
has body: I'm looking to control a script via Zigbee/XBee using X-CTU. I've created a script named zb_control.py. Now I'm trying to start and stop another script within this script. A script adxl345test.py is used to collect data from an attached accelerometer on my Raspberry Pi. The idea behind the zb_control.py script is that I run it and then if I type "run" in X-CTU the script will start running adxl345test.py and collect data. I'm trying to create a script within a script that can also be stopped again and then still have the zb_control.py running ready to recieve new input from X-CTU. As you can tell I've tried different things: import serial, time, sys, os, subprocess from subprocess import check_call from subprocess import call while True: ser=serial.Serial('/dev/ttyUSB0',9600,timeout=2) inc=ser.readline().strip() if inc=='run': print("---------------") print("Collecting data") print("---------------") p = subprocess.Popen("/home/pi/adxl345test.py", stdout=subprocess.PIPE, shell=True) elif inc=='stop': # check_call(["pkill", "-9", "-f", adxl345test.py]) # serial.write('\x03') # os.system("pkill –f adxl345test.py") # call(["killall", "adxl345test.py"]) p.kill() print("-----------------------") print("Script has been stopped") print("-----------------------") I got it to run and it's now collecting data properly. However now the problem is stopping the adxl345test.py again. As you can tell from the script from above I'm using p.kill() but the script doesn't stop collecting data. When I type "stop" in XCTU my zb_control.py does print the print-commands but the p.kill() isn't being executed. Any suggestions? I've tried using p.terminate() alone and together with p.kill() aswell as the commands by themselves however it doesn't stop the adxl345test.py script. I can tell that the .csv-file is still increasing in size and therefore the script must still be collecting data.
tagged with: kill
downvote count: 0
has comment: http://stackoverflow.com/comment/83782016
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83662591
linked to: http://stackoverflow.com/q/18499497
has comment: http://stackoverflow.com/comment/83661738

http://stackoverflow.com/comment/83860335
type: QuestionComment
score: 4
has text: UDP doesn't make any guarantees about ordering of packets, or even that all packets are delivered. If you need these properties you need to either build them youself, use a library which provides them on top of UDP (e.g., QUIC), or use a different protocol (e.g., TCP). As for timing issues, there is probably some buffering going on (see https://en.wikipedia.org/wiki/Bufferbloat).
type: Comment
comment on: http://stackoverflow.com/q/48433985

http://stackoverflow.com/q/48371754
favorite count: 0
tagged with: testing
has title: Testing error: No module named 'app.post'
score: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48374148
upvote count: 2
type: UnansweredQuestion
has body: I'm trying to use Django's unit test feature. I've added a blank test.py under app/post/tests (along with __init__.py). However when I run python manage.py test post it returns ImportError: No module named 'app.post'. Any idea why it says this and how I can fix it?
answer count: 1
tagged with: django
downvote count: 1

http://stackoverflow.com/comment/83658674
type: QuestionComment
comment on: http://stackoverflow.com/q/48333793
score: 2
type: Comment
has text: As usr1234567 said, Stack Overflow is not bug-reporting site. If you think the problem could be in your code, you need to provide that code in the question post itself, not as an off-site project. This is a usual rule of Stack Overflow.

http://stackoverflow.com/comment/83974301
comment on: http://stackoverflow.com/a/48467533
type: AnswerComment
has text: _Is there a way to avoid the above casting to timestamp and back_ - not built in. You can check the expression and implement the same logic yourself. _is there a way to retrieve just the first value in the window range_ - `$"window.start"`.
type: Comment
score: 0

http://stackoverflow.com/comment/83667289
comment on: http://stackoverflow.com/q/48339263
type: QuestionComment
has text: @COLDSPEED This helped out. Thankyou!
score: 0
type: Comment

http://stackoverflow.com/comment/84073016
has text: I don't think so @georgexsh, I see `Writers merely append new content to the end of the WAL file. Because writers do nothing that would interfere with the actions of readers, writers and readers can run at the same time. However, **since there is only one WAL file, there can only be one writer at a time**.`
comment on: http://stackoverflow.com/a/48473953
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48476629
downvote count: 0
has answer: http://stackoverflow.com/a/48476749
favorite count: 0
type: Question
upvote count: 4
tagged with: split
has body: I have the following dataframe: Date 2017-12-05 2017-12-06 2017-12-15 2017-12-19 2017-12-20 2017-12-21 .... time 00:00:00 19.94 21.19 21.88 20.76 21.26 21.26 00:15:00 20.29 21.07 21.71 21.79 21.95 21.52 00:30:00 21.03 21.25 21.80 22.15 22.26 21.62 00:45:00 22.20 21.56 22.77 22.20 22.33 21.91 01:00:00 23.25 22.15 23.71 22.31 22.69 21.99 01:15:00 23.78 23.33 24.53 22.29 22.82 22.58 Columns are dates, and I want to split the dataframe by every 3 date columns. How can I do this? Illustration of the final result with one of the resultant dataframes following the split: Date 2017-12-05 2017-12-06 2017-12-15 2 time 00:00:00 19.94 21.19 21.88 00:15:00 20.29 21.07 21.71 00:30:00 21.03 21.25 21.80 00:45:00 22.20 21.56 22.77 01:00:00 23.25 22.15 23.71 01:15:00 23.78 23.33 24.53
accepted answer: http://stackoverflow.com/a/48476787
has title: how to split dataframe vertically, having N columns in each resulting DF
has answer: http://stackoverflow.com/a/48476787
tagged with: python
tagged with: date
score: 4
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48476749

http://stackoverflow.com/q/48472029
has comment: http://stackoverflow.com/comment/83938112
tagged with: python
duplicate of: http://stackoverflow.com/q/11887762
has comment: http://stackoverflow.com/comment/83938071
has comment: http://stackoverflow.com/comment/83938077
has comment: http://stackoverflow.com/comment/83938072
has comment: http://stackoverflow.com/comment/83938047
score: 0
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/83938045
has title: Find biggest number in a list using Python
has comment: http://stackoverflow.com/comment/83938174
has comment: http://stackoverflow.com/comment/83938062
type: Question
has body: What is the correct way to print out the biggest number from a list in Python? lst = ["1.1.3.9", "1.1.3.11", "1.1.3.30", "1.1.3.8", "1.1.2.7"] print max(lst) gives me 1.1.3.9 This value is wrong. The max value must be 1.1.3.30. Please help. Many thanks in advance.
linked to: http://stackoverflow.com/q/11887762
type: UnansweredQuestion

http://stackoverflow.com/q/48358675
upvote count: 1
linked to: http://stackoverflow.com/q/13421767
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48358796
score: 1
tagged with: io
has comment: http://stackoverflow.com/comment/83704176
tagged with: python
has title: Number of threads not affecting disk read rate?
has body: I am dumbfounded by the results of reading 4 very large CSV files into a dataframe in Python: I performed the read with a single thread in series, i.e. read the first CSV, then the second etc. It took 230s. With 4 threads, one thread reading one CSV, in "parallel" it takes 220s, and with 2 threads it takes 220s. I can't explain this because this suggests no integer number of disk read heads which makes sense; if there is a single head then both the 2 and 4-threaded version of the program would take significantly longer due to the read head constantly moving between addresses as threads are switched. If it was 2 or 4 read heads then surely both of the multi-threaded versions would outperform the single threaded version?
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83778921
comment on: http://stackoverflow.com/q/48390353
score: 0
type: Comment
type: QuestionComment
has text: Maybe, hence any suggestion on the xpath string?

http://stackoverflow.com/q/48407058
score: 0
tagged with: python-imaging-library
has title: ValueError: too many values to unpack PIL
has answer: http://stackoverflow.com/a/48408578
type: Question
has body: I am a beginner, here is my code. from PIL import Image UPLOAD_FOLDER = '/home/name/Desktop/Project/Image/' img = ["lighthouse.jpg", "mountain.jpg", "image.jpg"] pil_img = [Image.open(UPLOAD_FOLDER + x) for x in img] ratio, height = [y.size for y in pil_img] I've seen a few questions similar to this, but I can't seem to figure out how to fix this code. Any help?
has comment: http://stackoverflow.com/comment/83803202
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83803682
answer count: 1
tagged with: python

http://stackoverflow.com/comment/83893902
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48449045
type: Comment
has text: Thanks @BryanOakley! I've updated my post above to show the changes that are needed. I'm still not sure about the menu page or color change - I'm using `bg_label.place(anchor='nw',x=-2,y=-2)` in the IDLE; is there an extra default I'm missing that might be being altered between the two instances?

http://stackoverflow.com/q/48455466
has comment: http://stackoverflow.com/comment/83904366
has comment: http://stackoverflow.com/comment/83904658
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83904386
upvote count: 1
has comment: http://stackoverflow.com/comment/83904140
tagged with: tensorflow
favorite count: 0
has title: Tensorflow - AttributeError: 'dict' object has no attribute 'index'
type: Question
has body: I am new to Tensorflow, please help to fix this error. I used the Tensorflow Tutorial code to convert the pandas dataframe inputs to tensors using get_input_fn, but i am stuck with this error. Little help would be grateful. --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-4-8ac4f79a2981&gt; in &lt;module&gt;() 114 115 if __name__ == '__main__': --&gt; 116 main() &lt;ipython-input-4-8ac4f79a2981&gt; in main() 105 Xtrain = pd.concat([Xtrain, ytrain], axis = 1) 106 Xtest = pd.concat([Xtest, ytest], axis = 1) --&gt; 107 Tensors(Xtrain, Xtest) &lt;ipython-input-4-8ac4f79a2981&gt; in Tensors(Xtrain, Xtest) 30 print(feature_cols) 31 nnreg = tf.contrib.learn.DNNRegressor(feature_columns = feature_cols, hidden_units = [10, 10]) ---&gt; 32 nnreg.fit(input_fn = get_input_fn(Xtrain), steps = 5000) 33 ev = nnreg.evaluate(input_fn = get_input_fn(Xtest, num_epochs = 1, shuffle = False)) 34 loss_score = ev['loss'] &lt;ipython-input-4-8ac4f79a2981&gt; in get_input_fn(data, num_epochs, shuffle) 22 y = tf.constant(data[label].values), 23 num_epochs = num_epochs, ---&gt; 24 shuffle = shuffle) 25 26 def Tensors(Xtrain, Xtest): C:\Users\user\Anaconda3\lib\site- packages\tensorflow\python\estimator\inputs\pandas_io.py in pandas_input_fn(x, y, batch_size, num_epochs, shuffle, queue_capacity, num_threads, target_column) 83 'Cannot use name %s for target column: DataFrame already has a ' 84 'column with that name: %s' % (target_column, x.columns)) ---&gt; 85 if not np.array_equal(x.index, y.index): 86 raise ValueError('Index for x and y are mismatched.\nIndex for x: %s\n' 87 'Index for y: %s\n' % (x.index, y.index)) AttributeError: 'dict' object has no attribute 'index' This is my get_input_fn() for pandas dataframe. def get_input_fn(data, num_epochs = None, shuffle = True): features = ['name', 'ship', 'GC', 'SC1_Enc', 'SC2_Enc', 'rating', 'condition', 'pol'] label = ['target'] return tf.estimator.i…
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83913321
tagged with: python

http://stackoverflow.com/comment/83913693
comment on: http://stackoverflow.com/q/48460332
type: QuestionComment
has text: and it is no dup.
type: Comment
score: 0

http://stackoverflow.com/q/48359234
score: 1
favorite count: 0
tagged with: turtle-graphics
type: Question
upvote count: 2
has title: Python Turtles , what am i doing wrong here?
tagged with: python
type: UnansweredQuestion
answer count: 1
downvote count: 1
has body: So... i'm pretty much a beginner in the turtle module and i want to move all the turtles at the same time, but probably because they never stop moving, i can't move more than two, what can i do to improve that? Here's the code: (i do plan to make more "colors" after the problem is solved) from turtle import Turtle, Screen wn = Screen() wn.bgcolor('black') speed = 4 def game(): def red(coordred): redg = Turtle() redg.hideturtle() redg.shape('circle') redg.color('red') redg.penup() redg.shapesize(2.5, 2.5, 2.5) redg.setheading(270) redg.goto(-280, 320 + coordred * 50) redg.showturtle() def movred(): redg.forward(speed) wn.ontimer(movred, 1) movred() def green(coordgreen): greeng = Turtle() greeng.hideturtle() greeng.shape('circle') greeng.color('green') greeng.penup() greeng.shapesize(2.5, 2.5, 2.5) greeng.setheading(270) greeng.goto(-100, 320 + coordgreen * 50) greeng.showturtle() def movgreen(): greeng.forward(speed) wn.ontimer(movgreen, 1) movgreen() red(0) green(1) green(2) game() wn.mainloop()
has answer: http://stackoverflow.com/a/48360657

http://stackoverflow.com/comment/83843026
type: QuestionComment
has text: For starters, your `Meta` class should be indented inside of the parent class
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48426401

http://stackoverflow.com/q/48389157
has title: Python typing for module type
tagged with: python
has answer: http://stackoverflow.com/a/48389207
type: AnsweredQuestion
downvote count: 2
upvote count: 91
answer count: 1
score: 89
accepted answer: http://stackoverflow.com/a/48389207
tagged with: python-typing
favorite count: 0
type: Question
has body: I am dynamically loading a Python module using importlib.import_module as follows def load_module(mod_name: str) -&gt; ???: return importlib.import_module(mod_name) Can somebody tell me what is the correct type annotation for a module type. The typing module does not contain one and I could not find an answer elsewhere.

http://stackoverflow.com/comment/84032447
type: Comment
score: 0
type: AnswerComment
has text: The namespace in which `x+y` are searched does not depend on the content of the dictionaries, but on a "static" notion of which lexical scope has the relevant binding. So syntactic binding occurrences (e.g. the _code_ `x = 5` somewhere in a function scope) works very much like a declaration `int x` in Java, as far as lookup goes. That's why I claim the are variables and variable declarations in Python.
comment on: http://stackoverflow.com/a/48453709

http://stackoverflow.com/comment/83811155
has text: @JohnRawls: Exactly, Because each iteration you are starting out with an empty list, then you append that one letter to it.
comment on: http://stackoverflow.com/q/48410563
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/75780174
answers question: http://stackoverflow.com/q/48343669
score: 2
upvote count: 2
downvote count: 0
has body: I would recommend using a reverse dynamic proxy. In your case, try: On your local machine ssh -R 9999 username@remotehostname On the remote host pip install packageName --proxy socks5:127.0.0.1:9999 For your reference: https://unix.stackexchange.com/questions/179270/how-to-create-reverse-dynamic-ssh-port-forwarding
type: Answer

http://stackoverflow.com/a/48484571
has body: Try this: pd.DataFrame([(k, ", ".join([x["best"] for x in v])) for k, v in data.items()], columns=["name", "ethnicity"]) Explanation: items and k,v is the way to allow some operations to be done. See for example the output of [(k, v) for k,v in data.items()] You can see now that they are aligned, but the second column is not how you want it pd.DataFrame([(k,v) for k, v in d.items()]) You want to select the best for each ethnicity column, and you can do that by [x["best"] for x in v] to make the result: name ethnicity 0 t creavalle GreaterEuropean, British 1 uyŏng yi Asian, GreaterEastAsian, EastAsian 2 temple orme GreaterEuropean, British
accepted answer of: http://stackoverflow.com/q/48484475
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48484475
type: Answer

http://stackoverflow.com/a/60238371
score: 7
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/48373812
type: Answer
has body: The simplest way is to cast soup to a string and then pickle it: import pickle from bs4 import BeautifulSoup # ... now we have soup # dump with open('my_soup.pkl', 'wb') as f: pickle.dump(str(soup), f) # load with open('my_soup.pkl', 'rb') as f: str_soup = pickle.load(f) re_soup = BeautifulSoup(str_soup, 'lxml') # check if they are the same assert soup == re_soup, 'Houston we have a problem' # we should not see anything if they are the same.

http://stackoverflow.com/comment/83902805
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48454749
type: AnswerComment
has text: Sure. `lst_expanded` gives a list like [['project', 'task1'], ['project', 'task1']]. `zip` iterates `lst_expanded` piecewise to give [('project', 'project'), ('task1', 'task1')]. `enumerate` adds a counter `i`. `set` makes the collection unique. `len` counter number of items.

http://stackoverflow.com/q/48399287
has title: PHP Curl vs Python Requests
has body: I am currently writing a piece of code to interface with an API in Python. Supplied by the company that hosts the API is a PHP script that logs into the API given the correct username and password, retrieved the current event ID (JSON format), and then logs out. This works perfectly. Currently, I am in the process of writing a script in Python to do the very same thing, the current code is shown below. It logs in and out successfully, however, when it tries to retrieve the current event ID I get the status code 404, suggesting that the URL doesn't exist, despite this same URL working with the PHP code. PHP Code: define('BASE_URL', 'https://website.api.com/'); define('API_USER', 'username'); define('API_PASS', 'password'); $cookiefile = tempnam(__DIR__, "cookies"); $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); $loginParams = array( 'username' =&gt; API_USER, 'password' =&gt; API_PASS ); $obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams); if( $obj-&gt;success ) { echo 'API login successful.' . PHP_EOL; } $obj = CurlGet($ch, BASE_URL . '/api/current-event-id'); echo 'API current event ID: ' . $obj-&gt;currentEventId . PHP_EOL; // logout of the API $obj = CurlGet($ch, BASE_URL . '/api/logout' ); if( $obj-&gt;success ) { echo 'Logged out successfully.' . PHP_EOL; } curl_close($ch); exit(0); // ------------------------------------------------------------------------- // Functions // ------------------------------------------------------------------------- // Run cURL post and decode the returned JSON object. function CurlPost($ch, $url, $params) { $query = http_build_query($params); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, count($query)); curl_setopt($ch, CURLOPT_POSTFIELDS, $query); $output=curl_exec($ch); $obj = json_decode($output); return $obj; } // Run cURL get and decode the returned JSON object. function CurlG…
tagged with: curl
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48401138
answer count: 2
tagged with: python-requests
has answer: http://stackoverflow.com/a/48399534
possible better answer: http://stackoverflow.com/a/48399534
type: Question
has answer: http://stackoverflow.com/a/48401138
tagged with: python
tagged with: php

http://stackoverflow.com/comment/83696408
comment on: http://stackoverflow.com/q/48354939
type: Comment
type: QuestionComment
score: 4
has text: Fascinating - do you have a question?

http://stackoverflow.com/q/48331501
answer count: 2
has answer: http://stackoverflow.com/a/48331582
upvote count: 1
has title: numpy arrays: fast element wise compare and set?
downvote count: 1
possible better answer: http://stackoverflow.com/a/48331587
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48331587
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/48331582
has body: Is there a function which allows me to quickly compare and set values in a numpy array against a fixed value? E.g., assume I have an array with numerical values like this: 0 0 0 3 7 3 0 0 0 I'd like to say: from index position [3 to index position [7, set the value to 5 if it is lower than 5. The result would be this: 0 0 0 5 7 5 5 0 0 The reason I'm asking is because when doing this operation "by hand" in a loop, things seem to be superslow. E.g., the following code takes ~90s to perform 1 million times such an operation on 64 consecutive elements in a 1 million element array: import numpy as np import random tsize = 1000000 arr = np.zeros(tsize, dtype=np.uint32) for rounds in range(tsize): num = random.randint(1, 123456) # generate a random number apos = random.randint(0, tsize - 64) # a random position for kpos in range(apos, apos + 64): # loop to compare and set 64 elements if arr[kpos] &lt; num: arr[kpos] = num If there is not such a function: are there any obvious NumPy newbie mistakes in the code above which slow it down?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48435348
tagged with: python-multithreading
tagged with: python
accepted answer: http://stackoverflow.com/a/48477752
has body: OS: debian9. A simple multi-processes program named mprocesses.py. import os import multiprocessing def run_task(name): print("task %s (pid = %s) is running" %(name,os.getpid())) while True: pass if __name__ == "__main__": print("current process %s ." %os.getpid()) pool = multiprocessing.Pool(processes = 2) for i in range(2): pool.apply_async(run_task,args=(i,)) pool.close() pool.join() Run python3 mprocesses.py and get below output. python3 mprocesses.py current process 6145 . task 0 (pid = 6146) is running task 1 (pid = 6147) is running Get processes info. ps lax |grep 'python3 mprocesses.py' |grep -v grep 0 1000 6145 5615 20 0 275428 14600 - Sl+ pts/1 0:00 python3 mprocesses.py 1 1000 6146 6145 20 0 54232 10340 - R+ pts/1 1:01 python3 mprocesses.py 1 1000 6147 6145 20 0 54232 10348 - R+ pts/1 1:01 python3 mprocesses.py Check processes tree view. pstree -p 5615 bash(5615)───python3(6145)─┬─python3(6146) ├─python3(6147) ├─{python3}(6148) ├─{python3}(6149) └─{python3}(6150) What confused me is the three threads 6148,6149,6150. Does that mean every process contain one process ? Maybe my logical graph is better to express relationships between processes and threads here. bash(5615)───python3(6145)─┬─────────────────python3(6146) | └─{python3}(6149) | ├──────────────────python3(6147) ├─{python3}(6148) └─{python3}(6150) 1.bash(5615) is the python3 mprocesses.py(6145) 's father process. 2.python3 mprocesses.py(6145) contains two processes 6146 and 6147 created by pool = multiprocessing.Pool(processes = 2). 3.Process(6145) contain thread(6148),Process(6146) contain thread(6149),Process(6147) contain thread(6150). It does no matter which exact process id contain which thread id. Is my understanding right?
score: 12
upvote count: 12
tagged with: multithreading
answer count: 1
downvote count: 0
has title: The relationship between thread and process in multi-process program
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48477752
type: AnsweredQuestion

http://stackoverflow.com/a/48357864
has comment: http://stackoverflow.com/comment/83702508
answers question: http://stackoverflow.com/q/48357618
downvote count: 0
upvote count: 1
score: 1
has body: You should not call create_account() again if 1) you don't want the function to be entirely reset, 2) you don't want evaluation to return back to the point at which you called the function (such as in the except block) Also, koniec = 'nie' will make that always be set before the if statements, so checking it against anything else doesn't make sense. Instead, change your code to follow this pattern def create_account(): registered = False while not registered: # do work try: captcha_text = captcha('captcha_img/'+nazwa) except: continue # repeat the loop if "Your registration was successful" in text: registered = True return elif "The supplied Captcha is wrong." in text: # just let the while loop repeat the function on its own continue # or call continue
type: Answer

http://stackoverflow.com/q/48440226
has title: Unable to get the full match in Regex
type: Question
has comment: http://stackoverflow.com/comment/83895932
has comment: http://stackoverflow.com/comment/83905470
has comment: http://stackoverflow.com/comment/83871588
duplicate of: http://stackoverflow.com/q/31915018
has comment: http://stackoverflow.com/comment/83872630
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83879821
has comment: http://stackoverflow.com/comment/83893916
score: 0
has comment: http://stackoverflow.com/comment/83879957
answer count: 0
linked to: http://stackoverflow.com/q/31915018
has body: I am trying to find the complete Github url from text. But it returns only the first match and not the complete URL. I tested my regex on https://pythex.org/ and its shows the correct match result. test = 'https://www.github.com/whoisthere' GITHUB_PATTERN = r"(http(s?):\/\/|[a-zA-Z0-9\-]+\.|[github])[github\/~\-]+\.[a-zA-Z0-9\/~\-_,&amp;=\?\.;]+[^\.,\s&lt;]" GITHUB_REGEX = re.compile(GITHUB_PATTERN,re.IGNORECASE) github_regex_result = re.findall(GITHUB_REGEX,test) if len(github_regex_result) &gt; 0: print("GITHUB : {}".format(github_regex_result[0])) else: print(None) It returns me the following GITHUB : ('https://', 's') While I am trying to get the complete url like GITHUB : ('https://www.github.com/whoisthere') New screenshot of issue

http://stackoverflow.com/q/48353886
has body: In this problem,I used Search Function in Re Module of Python but I'm Able to get the Span ID of the First Word Only string2="Jhon is a good boy,Jhon is brilliant,Jhon is a data scientist,Jhon is Jhon" m=re.search("Jhon",string2) print(m) I'm Getting Output Like This &lt;_sre.SRE_Match object; span=(0, 4), match='Jhon'&gt; This output(Span ID) is only for the first word,Please Tell Me Is there any way to find Span ID for All "Jhon"
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83694320
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/4697882
favorite count: 0
has comment: http://stackoverflow.com/comment/83694317
duplicate of: http://stackoverflow.com/q/4697882
score: 1
has comment: http://stackoverflow.com/comment/83694342
has title: How to Get Span Id of Same Words in one String?
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/83793728
comment on: http://stackoverflow.com/q/48400514
type: Comment
has text: Is the aim to capture `Error code` entries with all lines back to the previous `--- xxxxxxx ---` line?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83730327
comment on: http://stackoverflow.com/q/48371615
score: 0
has text: I only get overshot when I try to run your code.
type: Comment
type: QuestionComment

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/48379421

http://stackoverflow.com/a/48449342
answers question: http://stackoverflow.com/q/48449264
upvote count: 5
downvote count: 0
type: Answer
has body: You can snap your dataframe to hourly recordings using asfreq, and then use diff? df.asfreq('1H').diff(periods=24, axis=0).dropna() Or, use shift and then subtract (instead of diff), v = df.asfreq('1h') (v - v.shift(periods=24)).dropna() A B 2017-01-02 00:00:00 -3.0 3.0 2017-01-02 01:00:00 -28.0 -23.0 2017-01-02 02:00:00 -4.0 -7.0 2017-01-02 03:00:00 3.0 -29.0 2017-01-02 04:00:00 -4.0 3.0 2017-01-02 05:00:00 -17.0 -6.0 2017-01-02 06:00:00 -20.0 35.0 2017-01-02 07:00:00 -2.0 -40.0 2017-01-02 08:00:00 13.0 -21.0 2017-01-02 09:00:00 -9.0 -13.0 2017-01-02 10:00:00 0.0 3.0 2017-01-02 11:00:00 -21.0 -9.0
score: 5

http://stackoverflow.com/comment/83835698
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48422380
has text: @ayhan just re-post it, I think its also great !

http://stackoverflow.com/comment/83773453
score: 0
type: AnswerComment
has text: thank you, actually np.savetxt works for me but i got an error ValueError: cannot reshape array of size 504273 into shape (407,413) do you know how to fix it ?
type: Comment
comment on: http://stackoverflow.com/a/48392501

http://stackoverflow.com/q/48335240
tagged with: python
has answer: http://stackoverflow.com/a/48337628
tagged with: ipython
has comment: http://stackoverflow.com/comment/83659458
has comment: http://stackoverflow.com/comment/83659765
tagged with: jupyter-notebook
type: AnsweredQuestion
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83660315
has title: Change content of image interactively using slider widgets
accepted answer: http://stackoverflow.com/a/48337628
has body: I am trying to change content of an image interactively using a slider (e.g. for applying a median operation with different kernel sizes). While this works well if I only show one resulting image (cf commented lines), I run into trouble when using the subplot function, since the image will not get updated. What am I missing? %matplotlib inline from ipywidgets import interact, widgets import matplotlib.pyplot as plt import warnings from skimage.morphology import disk from skimage.filters import rank from skimage.color import rgb2gray import skimage.data def f(Median_Size): selem = disk(int(Median_Size)) with warnings.catch_warnings(): warnings.simplefilter("ignore") img_median = rank.median(img_gray, selem=selem) ax_neu.imshow(img_median, cmap="gray") fig.canvas.draw() #plt.imshow(img_median, cmap="gray") #This would work #plt.show() image = skimage.data.camera() #plt.imread("Test.png") img_gray = rgb2gray(image) fig = plt.figure(figsize=(6, 4)) ax_orig = fig.add_subplot(121) ax_neu = fig.add_subplot(122) ax_orig.imshow(img_gray, cmap="gray") ax_neu.imshow(img_gray, cmap="gray") interact(f, Median_Size=widgets.IntSlider(min=1,max=21,step=2,value=1))
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83658724
possible better answer: http://stackoverflow.com/a/77692375
has answer: http://stackoverflow.com/a/77692375
upvote count: 10
tagged with: matplotlib
score: 10
has comment: http://stackoverflow.com/comment/83659692

http://stackoverflow.com/q/48366883
tagged with: python
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/83730300
has title: Fast method for PyMongo Cursor to array/DataFrame
type: Question
tagged with: numpy
tagged with: mongodb
has comment: http://stackoverflow.com/comment/83729766
has body: I am fetching 43k records with just 2 datetime fields from my mongoDB server. It takes me around 10 seconds to 20 seconds to convert the cursor to array to dataframe. I have tried variety of ways to do this: Attempt-1 docs=pd.DataFrame(list(collection.find({"dId":4},{"ts":1,"cd":1,"_id":0}).sort("ts",-1).limit(43200))) Attempt-2 docs=collection.find({"dId":4},{"ts":1,"cd":1,"_id":0}).sort("ts",-1).limit(43200) ts = np.empty([2,43200], dtype='datetime64[us]') for i, doc in enumerate(docs): ts[0][i] = doc["ts"] ts[1][i] = doc["cd"] df = pd.DataFrame() df['ts']=ts[0] df['cd']=ts[1] Attempt-3 docs=collection.find({"dId":4},{"ts":1,"cd":1,"_id":0}).sort("ts",-1).limit(43200) arr= [x for x in docs] Attempt-4 my_data = list(map(lambda x: list(x.values()), collection.find({"dId":4},{"ts":1,"cd":1,"_id":0}).sort("ts",-1).limit(43200))) result=np.array(my_data) How to reduce this time to less than 2 seconds?
type: UnansweredQuestion

http://stackoverflow.com/a/48356358
downvote count: 0
has comment: http://stackoverflow.com/comment/83700401
type: AcceptedAnswer
has body: You could try creating a udev rule that would create a symbolic link to that USB device and then you would be able to use something like /dev/myUSB that would always stay the same for that specific USB device. First, you will need to find some identifying information for the USB drive. Typing in lsusb should display some information that looks like: Bus 001 Device 004: ID 0403:6001 Future Technology Devices International In this example 0403 is the Vendor Id and 6001 is the Product Id. Create a file named 99_usbdevice.rules (I don't think the name matters, just the directory): sudo nano /etc/udev/rules.d/99_usbdevices.rules Note that the directory above may be specific to Raspbian. Copy/paste the line below into the file and save it: SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", SYMLINK+="myUSB" Restart your Raspberry Pi or unplug the USB and reinsert it. There should now be a /dev/myUSB entry that you can use the same way you would the ttyUSB# entry.
answers question: http://stackoverflow.com/q/48356223
accepted answer of: http://stackoverflow.com/q/48356223
type: Answer
score: 12
upvote count: 12

http://stackoverflow.com/q/48433682
has comment: http://stackoverflow.com/comment/83859691
possible better answer: http://stackoverflow.com/a/71630228
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/83860885
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/83859588
has comment: http://stackoverflow.com/comment/83860077
type: AnsweredQuestion
tagged with: foreign-keys
answer count: 2
has body: I have the below in my models.py file: class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') class Comment(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) When I logged into Django admin I added some films, and then added some comments, selecting which film object the comment related to. I then created a couple of users via the admin panel also. I would like my relationships to be: Film can have many comments / Comments belong to film User can have many comments / Comments belong to user I think, like with comments and films, I just need to define user as a foreign key to comment. I am struggling to do this. I am working through the Django tutorials but I can't see the tutorials covering how I can link other tables to the user. I thought I would be able to do something like this: user = models.ForeignKey(User, on_delete=models.CASCADE) While importing User like this: from django.contrib.auth.models import User The result at the moment is if I keep user = models.ForeignKey(User, on_delete=models.CASCADE) I get err_connection_refused
has comment: http://stackoverflow.com/comment/83859936
has comment: http://stackoverflow.com/comment/83861126
has comment: http://stackoverflow.com/comment/83859892
has comment: http://stackoverflow.com/comment/83860156
downvote count: 0
has answer: http://stackoverflow.com/a/71630228
has title: Users as foreign key in Django
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48434845
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34305805
has answer: http://stackoverflow.com/a/48434845
has comment: http://stackoverflow.com/comment/83859602

http://stackoverflow.com/comment/83685239
comment on: http://stackoverflow.com/q/48349367
has text: I saw that post before. it's to set font family via rcParams. not really using a whole different font (not exist from matplotlib's own font dir). Or is there a way to register new font? I tried fm.FontProperties = fm.FontProperties(fname='/Library/Fonts/Phosphate.ttc') seems matplotlib doesn't like it
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83882786
type: QuestionComment
score: 0
has text: Put your replacements in a dictionary, open the text files and use an answer from https://stackoverflow.com/questions/2400504/easiest-way-to-replace-a-string-using-a-dictionary-of-replacements
comment on: http://stackoverflow.com/q/48445459
type: Comment

http://stackoverflow.com/q/48464753
upvote count: 0
downvote count: 3
answer count: 1
has body: Goal: Make my turtle go to a point, selected by the user. Something like that: ranpoint = input() turtle(go, randpoint)
favorite count: 0
type: Question
has title: How can I make the turtle go to a variable point?
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/48465868
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/83923106
has comment: http://stackoverflow.com/comment/83922908

http://stackoverflow.com/comment/83844940
has text: The main problem with this (besides lack of entropy), is that it still requires somehow building a string from allowed characters, quickly. Martijn and myself got around this with the `base64` library, which takes bytes, and returns ASCII, and once you're doing that, you may as well hand it `urandom()` bytes. The uniqueness is not a slowness factor, thanks to sets. The difference in time between my solution without checking for uniqueness is so small that one is faster than the other at random due to system load.
type: AnswerComment
comment on: http://stackoverflow.com/a/48426820
score: 1
type: Comment

http://stackoverflow.com/a/48359622
downvote count: 0
type: Answer
upvote count: 2
has body: The Wikipedia API quickstart document has a suggestion: catch the exception and extract the text you need: try: mercury = wikipedia.summary("Mercury") except wikipedia.exceptions.DisambiguationError as e: print e.options [u'Mercury (mythology)', u'Mercury (planet)', u'Mercury (element)', u'Mercury, Nevada', ...]
answers question: http://stackoverflow.com/q/48359531
has comment: http://stackoverflow.com/comment/83811191
score: 2

http://stackoverflow.com/comment/83725742
has text: What's your expected output?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48369104

http://stackoverflow.com/q/48391636
has answer: http://stackoverflow.com/a/48391722
has answer: http://stackoverflow.com/a/48391807
has body: I'm looking for solution of this problem: I have two functions: def foo1(): while True: print("x") def foo2(): while True: print("y") I would like to run them alternately, like: run foo1() stop foo1() run foo2() stop foo2() run foo1() Functions can't work simultaneously, at the moment only one of them can work.
favorite count: 0
type: Question
tagged with: python-3.x
has title: Two infinite loops alternately?
has comment: http://stackoverflow.com/comment/83771714
tagged with: python-multithreading
has answer: http://stackoverflow.com/a/48391783
answer count: 5
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/83771325
tagged with: python
has answer: http://stackoverflow.com/a/48391719
has comment: http://stackoverflow.com/comment/83771360
has comment: http://stackoverflow.com/comment/83771522
upvote count: 2
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83771378
has answer: http://stackoverflow.com/a/48391806
has comment: http://stackoverflow.com/comment/83771392
has comment: http://stackoverflow.com/comment/83771271
has comment: http://stackoverflow.com/comment/83771652
has comment: http://stackoverflow.com/comment/83771934

http://stackoverflow.com/comment/83705801
score: 0
type: Comment
type: QuestionComment
has text: Could you give an example code and not just the error?
comment on: http://stackoverflow.com/q/48359531

http://stackoverflow.com/q/48425658
tagged with: gcc
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has body: Context I'm trying to build bindings for Python 3 to a program originally written in Go. Below is what I was able to do so far: Write Go code that exposes functionality to C code. Write glue C code that uses functions exposed by Go code. Write Cython code that calls into C code, which calls into Go code. I can compile my code by hand-crafting the GCC command. Problem The way setuptools wants to generate the command, ld isn't "able" to find the library. No amount of hinting doesn't help, and ld doesn't produce any parseable output. The command generated by setuptools looks like this: gcc -pthread -shared build/temp.linux-x86_64-3.6/pykubectl/lib/bindings.o \ build/temp.linux-x86_64-3.6/pykubectl/wrapped.o \ -lpykubectl.so \ -o build/lib.linux-x86_64-3.6/pykubectl/wrapped.cpython-36m-x86_64-linux-gnu.so \ -L/home/.../pykubectl/pykubectl/lib This fails with: /usr/bin/ld: cannot find -lpykubectl.so But, if I do it like this: gcc -pthread -shared build/temp.linux-x86_64-3.6/pykubectl/lib/bindings.o \ build/temp.linux-x86_64-3.6/pykubectl/wrapped.o \ /home/.../pykubectl/pykubectl/lib/libpykubectl.so \ -o build/lib.linux-x86_64-3.6/pykubectl/wrapped.cpython-36m-x86_64-linux-gnu.so It does compile. Here's some info about libpykubectl.so: ldd /home/.../pykubectl/pykubectl/lib/libpykubectl.so linux-vdso.so.1 => (0x00007ffd7cccd000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f69662d2000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6965f0b000) /lib64/ld-linux-x86-64.so.2 (0x000055e410408000) file /home/.../pykubectl/pykubectl/lib/libpykubectl.so /home/.../pykubectl/pykubectl/lib/libpykubectl.so: \ ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=d4225259207743ceaecda8d90368c13732d0f310, not stripped (formatted for readability).
score: 0
has title: What can be wrong with shared object (library) produced by Go?
answer count: 0
has comment: http://stackoverflow.com/comment/83841107
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83841259
tagged with: cython
type: Question

http://stackoverflow.com/q/48435107
answer count: 1
has answer: http://stackoverflow.com/a/48456124
tagged with: excel
has title: Implement Bloomberg BChain function in Python using blpapi
type: Question
tagged with: python
has body: I am trying to implement Excel's BChain() function in Python. Unfortunately I have no idea how and if this can be achieved. Here is the function I want to achieve: =BChain("COL US Equity", "LOANS", "LOAN_TYP == TERM") Any idea how this can be done?
tagged with: bloomberg
tagged with: blpapi
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48456124

http://stackoverflow.com/q/48386645
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83761374
has body: Hi to everybody and thanks for your help. I'm trying to show people a real-time seismogram with Python for educational purposes. I get the data through serial port connected to an arduino, but the problem is that there is a big delay (8-20 seconds) between the signal and the graph on screen seismogram plot. I have checked the code, but I can't see anything wrong, at least as far as I understand the code. Can anybody help me? Thanks in advance. import time import serial import sys import numpy as np from matplotlib import pyplot as plt from matplotlib import animation arduino = serial.Serial('COM4', baudrate=115200, timeout=1.0) start = time.time() ad = [] ed = [] ec = [] es = [] delta=0 duracion=120 # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure(figsize=(16,8)) ax = plt.axes(xlim=(0, duracion), ylim=(-1000, 1000)) ax.set_xlabel('segundos') ax.set_ylabel('cuentas') plt.title('Haz tu propio sismograma') fig.canvas.set_window_title("Sismograma") line, = ax.plot([], [], lw=0.5) line2, = ax.plot([],[],lw=0.5) line3, = ax.plot([],[],lw=0.5) # initialization function: plot the background of each frame def init(): arduino.readline() ad = [] ed = [] ec = [] es = [] start = time.time() delta=0 line.set_data([],[]) line2.set_data([],[]) line3.set_data([],[]) return line, line2, line3 # animation function. This is called sequentially def animate(i): global start global ad,ed,ec,es global delta delta = time.time() - start linea = arduino.readline() texto=linea.decode('ascii', errors='replace') valora=texto.split(',') try: valor=int(valora[0])+400 valor2=int(valora[1]) valor3=int(valora[2])-400 #print(valor) ad.append(delta) ed.append(valor) ec.append(valor2) es.append(valor3) line.set_data(ad, ed) line2.set_data(ad, ec) line3.set_data(ad, es) except ValueError: ed.append(ed[-1]) ec.append(ec[-1]) es.append(es[-1]) ad.append(delta) except RuntimeError: ed.append(ed[-1]) ec.append(ec[-1]) es.append(es[-1]) ad.append(delta) except Inde…
has title: Real-time plotting with delay
tagged with: real-time
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83761111
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83761004
type: Question
answer count: 0

http://stackoverflow.com/q/48469708
has comment: http://stackoverflow.com/comment/83933336
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83933480
score: 2
has comment: http://stackoverflow.com/comment/83933292
has comment: http://stackoverflow.com/comment/83933235
has comment: http://stackoverflow.com/comment/83933214
has comment: http://stackoverflow.com/comment/83933596
has comment: http://stackoverflow.com/comment/83933522
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83933579
tagged with: lowercase
has comment: http://stackoverflow.com/comment/83933322
has title: .lower() and a regular expression in the same line?
has comment: http://stackoverflow.com/comment/83933435
has comment: http://stackoverflow.com/comment/83933743
favorite count: 0
type: Question
has body: I have a regular expression that eliminates all non-alpha characters def genLetters(string): regex = re.compile('[^a-zA-Z]') newString = regex.sub("", string) If I want to make this string lowercase, I have to define a new string (since they are immutable) like lowerString = newString.lower() It seems dumb to me that I would have to make a second string just to do the to lower, but if I remove the A-Z from the regex, I lose any characters that are uppercase which I don't want. I just want a final product of everything lower case. Can this be done without the lowerString, or even cooler, can it be done in one line?
accepted answer: http://stackoverflow.com/a/48469811
has comment: http://stackoverflow.com/comment/83933260
has answer: http://stackoverflow.com/a/48469811
has comment: http://stackoverflow.com/comment/83933290
upvote count: 2
has comment: http://stackoverflow.com/comment/83933341
has comment: http://stackoverflow.com/comment/83933780
has comment: http://stackoverflow.com/comment/83933646
tagged with: python

http://stackoverflow.com/q/48437429
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83867853
has comment: http://stackoverflow.com/comment/83868161
tagged with: python-multiprocessing
linked to: http://stackoverflow.com/q/14124588
has comment: http://stackoverflow.com/comment/83881661
has comment: http://stackoverflow.com/comment/83879817
has comment: http://stackoverflow.com/comment/83868093
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83880749
has comment: http://stackoverflow.com/comment/83880723
has comment: http://stackoverflow.com/comment/83867180
favorite count: 0
has comment: http://stackoverflow.com/comment/83881771
has body: In the following code, I time how long it takes to pass a large array (8 MB) to a child process using the args key word when forking the process verses passing using a pipe. Does anyone have any insight into why it is so much faster to pass data using an argument than using a pipe? Below, each code block is a cell in a Jupyter notebook. import multiprocessing as mp import random N = 2**20 x = list(map(lambda x : random.random(),range(N))) Time the call to sum in the parent process (for comparison only): %%timeit -n 5 -r 10 -p 8 -o -q pass y = sum(x)/N t_sum = _ Time the result of calling sum from a child process, using the args keyword to pass list x to child process. def mean(x,q): q.put(sum(x)) %%timeit -n 5 -r 10 -p 8 -o -q pass q = mp.Queue() p = mp.Process(target=mean,args=(x,q)) p.start() p.join() s = q.get() m = s/N t_mean = _ Time using a pipe to pass data to child process def mean_pipe(cp,q): x = cp.recv() q.put(sum(x)) %%timeit -n 5 -r 10 -p 8 -o -q pass q = mp.Queue() pipe0,pipe1 = mp.Pipe() p = mp.Process(target=mean_pipe,args=[pipe0,q]) p.start() pipe1.send(x) p.join() s = q.get() m = s/N t_mean_pipe = _ (ADDED in response to comment) Use mp.Array shared memory feature (very slow!) def mean_pipe_shared(xs,q): q.put(sum(xs)) %%timeit -n 5 -r 10 -p 8 -o -q xs = mp.Array('d',x) q = mp.Queue() p = mp.Process(target=mean_pipe_shared,args=[xs,q]) p.start() p.join() s = q.get() m = s/N t_mean_shared = _ Print out results (ms) print("{:&gt;20s} {:12.4f}".format("MB",8*N/1024**2)) print("{:&gt;20s} {:12.4f}".format("mean (main)",1000*t_sum.best)) print("{:&gt;20s} {:12.4f}".format("mean (args)",1000*t_mean.best)) print("{:&gt;20s} {:12.4f}".format("mean (pipe)",1000*t_mean_pipe.best)) print("{:&gt;20s} {:12.4f}".format("mean (shared)",1000*t_mean_shared.best)) MB 8.0000 mean (main) 7.1931 mean (args) 38.5217 mean (pipe) 136.5020 mean (shared) 4195.0568 Using the pipe is over 3 times slower than passing arguments to the child process. And unless I am doing someth…
has title: Passing arguments vs. using pipes to communicate with child processes
has comment: http://stackoverflow.com/comment/83879953
type: Question
linked to: http://stackoverflow.com/q/11710552
tagged with: python

http://stackoverflow.com/comment/83969070
comment on: http://stackoverflow.com/a/48487716
type: AnswerComment
score: 0
has text: if passed in value < 100, then save 0; if passed in value > 100 then save value // 100 .
type: Comment

http://stackoverflow.com/a/48335701
score: 1
has comment: http://stackoverflow.com/comment/83657474
type: AcceptedAnswer
has body: If it is a list of elements: a = "2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex" print [i for i in a.split(" ")] Result: ['2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'] or if it is a list of tuple: a = "2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex" print [tuple(i for i in a.split(" "))] Result: [('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex')] And if you have multiple line of the string: a = """2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex""" print [tuple(j.split(" ")) for j in a.split("\n")] Result: [('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex'), ('2012-01-01 09:00', 'San Jose', "Men's Clothing", '214.05', 'Amex')]
accepted answer of: http://stackoverflow.com/q/48335590
has comment: http://stackoverflow.com/comment/83675212
has comment: http://stackoverflow.com/comment/83672491
type: Answer
has comment: http://stackoverflow.com/comment/83657450
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48335590

azure
tags question: http://stackoverflow.com/q/48430428
type: Tag
tags question: http://stackoverflow.com/q/48469709
tags question: http://stackoverflow.com/q/48428669
tags question: http://stackoverflow.com/q/48467369
tags question: http://stackoverflow.com/q/48460957
tags question: http://stackoverflow.com/q/48433641
tags question: http://stackoverflow.com/q/48469614
tags question: http://stackoverflow.com/q/48477042
tag name: azure
tags question: http://stackoverflow.com/q/48377413
tags question: http://stackoverflow.com/q/48454906
tags question: http://stackoverflow.com/q/48387711
tags question: http://stackoverflow.com/q/48390529
tags question: http://stackoverflow.com/q/48355055

http://stackoverflow.com/a/48454102
type: Answer
answers question: http://stackoverflow.com/q/48453769
has body: This, in my opinion, is a more pythonic solution. op_map = {'+': add, '-': sub, '*': mul, '/': dev} if op in op_map: print(op_map[op](num1, num2)) elif op == 'stop': rng = 'f' else: print('Please enter a valid operation!')
score: 0

http://stackoverflow.com/comment/87059689
has text: I have the same problem. If it helps, I have figured that the problem is that even if you delete the session['profile'] data, there are a lot more data stored in session. You can view those using session.get_items() I have no idea how to delete those though
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48475180
score: 0

http://stackoverflow.com/a/51396618
answers question: http://stackoverflow.com/q/48480972
has body: class UserSerializer(serializers.ModelSerializer): class Meta: model = User def to_representation(self, obj): rep = super(UserSerializer, self).to_representation(obj) rep.pop('password', None) return rep
score: 6
upvote count: 6
downvote count: 0
type: Answer

http://stackoverflow.com/q/48370603
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has body: I have a dataframe with various number of values in each columns. I created a mask that tells me how many values in each column with the following code from another post > I get the following results count_year_mask = df_mth_return.notnull().sum() results in series like this AAPL US Equity 312 GOOGL US Equity 161 GOOG US Equity 45 MSFT US Equity 312 AMZN US Equity 248 FB US Equity 68 I then want to delete all the columns in df_mth_return that are LESS THAN 180 from the above series. I want the DF to only have columns with > 180 numbers. So GOOGL, GOOG and FB would be eliminated. I tried this code and got the following error df_mth_return.drop(np.where(count_year_mask&lt;180)) ValueError: Buffer has wrong number of dimensions (expected 1, got 3) This seems like a simple mask so not sure what I am doing wrong. Please help if you can
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48370613
has title: drop columns in pandas dataframe based on mask
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48370613

http://stackoverflow.com/comment/83693832
type: Comment
comment on: http://stackoverflow.com/q/48353603
score: 0
type: QuestionComment
has text: yes, once you run makemigrations for the apps, the migration folder will be auto generated in all the apps folder

http://stackoverflow.com/q/48454034
tagged with: python
tagged with: class
score: 0
accepted answer: http://stackoverflow.com/a/48454107
has body: First: does it matter if i define an update function in a class or can i just do the following: class foo(object): def __init__(self): self.a = 1 def f(self,): self.a = self.a**2 - self.a - 6 return self.a Second: is it more beneficial (save memory, runtime etc) to create a dummy variable, perform operations and use this to update my class variable, or does it not actually matter? class foo(object): def __init__(self): self.a = 1 def f(self): a = self.a a = a**2-a-6 self.a = a return self.a In this trivial of an example, I know it doesn't matter, but as functions perform more operations, will it have any effect?
has title: Updating variables in a python class
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/20923411
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48454107
tagged with: class-variables

http://stackoverflow.com/a/48357384
accepted answer of: http://stackoverflow.com/q/48350948
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48350948
has body: Given a datetime.datetime object such as: dt_obj = datetime.datetime(2017, 12, 15, 18, 0) which can be extracted e.g. from another dataframe such as avg_30min in the example reported, a lookup into a dataframe which uses a dtype='datetime64[ns]' as index can be performed using get_loc on the index column: &gt;&gt;&gt; df_lookup.index.get_loc(dt_obj) 2 Then the position can be used to retrieve the requested row, with df_lookup.iloc[].
score: 0

http://stackoverflow.com/comment/83717443
type: AnswerComment
has text: So, as I understand, this database would allow the changes in db to be made automatically for users?
comment on: http://stackoverflow.com/a/48363024
score: 0
type: Comment

http://stackoverflow.com/q/48473691
upvote count: 0
has body: I'm trying to get course name out of a university website, but Scrapy won't crawl the data. I would appreciate if someone can tell me what I'm doing wrong. Item.py: Course_spider.py Output:
downvote count: 3
tagged with: scrapy
answer count: 1
favorite count: 0
has title: Scrapy will not scrawl(Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
type: Question
has answer: http://stackoverflow.com/a/48476825
type: UnansweredQuestion
tagged with: python
score: -3
tagged with: pycharm

http://stackoverflow.com/q/48355353
downvote count: 0
accepted answer: http://stackoverflow.com/a/48365796
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48365796
has title: Multiclient Streaming Websocket endpoint (Python)
possible better answer: http://stackoverflow.com/a/48357148
has answer: http://stackoverflow.com/a/48357148
tagged with: sanic
tagged with: python
has comment: http://stackoverflow.com/comment/83700717
score: 2
has body: Recently I've gotten into the "crypto mania" and have started writing my own wrappers around the API's on some exchanges. Binance in particular has an a streaming websocket endpoint. where you can stream data but via a websocket endpoint. I thought I'd try this out on my own using sanic. here is my websocket route @ws_routes.websocket("/hello") async def hello(request, ws): while True: await ws.send("hello") now I have 2 clients on 2 different machines connecting to it async def main(): async with aiohttp.ClientSession() as session: ws = await session.ws_connect("ws://192.168.86.31:8000/hello") while True: data = await ws.receive() print(data) however only one of the clients will be able to connect and receive the sent data from the server. I'm assuming that because of the while loop its blocking and preventing the other connection from connecting because it doesn't yield? how do we make it stream to multiple clients without blocking the other connections? I looked into adding more workers and it seems to do the trick but what I don't understand is thats not a very scalable solution. because each client would be its own worker and if you have thousands or even just 10 clients that would be 10 workers 1 per client. so how does Binance do their websocket streaming? or hell how does the twitter stream endpoint work? how is it able to serve an infinite stream to multiple concurrent clients? because ultimately thats what I'm trying to do
type: AnsweredQuestion
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/83835833
type: QuestionComment
comment on: http://stackoverflow.com/q/48423098
has text: Ah, now I understand. Works fine for python 2.7.13 and matplotlib 2.0.2, too.. can you post your versions?
type: Comment
score: 0

http://stackoverflow.com/comment/83952232
has text: your question heading says **square**, and the start of question says **square root** and your example belongs to something else. What exactly do you want?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48479647
score: 3

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/48370499
type: Tag

http://stackoverflow.com/q/48397522
favorite count: 0
has answer: http://stackoverflow.com/a/48543576
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48543576
tagged with: linux
tagged with: pandas
has body: I have the below code which updates the mysql database batchwise. count = pd.read_sql_query("SELECT count(*) FROM table",con=db) count = count.iat[0,0] batchsize = 1000 for offset in range(0,count,batchsize): df = pd.read_sql(('SELECT id,col2,col3 FROM table LIMIT %s OFFSET %s' % (batchsize,offset)), con=db) ## code ## cursor = db.cursor() cursor.executemany("UPDATE table SET col2=%s, col3=%s WHERE id=%s",d) db.commit() db.close() After updating, later if new records got added in mysql database, those has to be updated by running the same script. The code is ran on linux environment as python script.
tagged with: python
score: -1
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/83784119
has title: How to update newly added rows in mysql database excluding already updated rows using python pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/83782807
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/83913551
has text: I tried using and, it still return the same error
score: 0
comment on: http://stackoverflow.com/q/48460234
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83696184
has text: Thanks, this solved the problem! One more question, when I save a Lecture, it says "Lecture 0 has been saved!". I think its due the choices field. How do I change that ?
type: Comment
comment on: http://stackoverflow.com/a/48354116
score: 0
type: AnswerComment

http://stackoverflow.com/q/48353281
tagged with: python
has answer: http://stackoverflow.com/a/48353349
possible better answer: http://stackoverflow.com/a/48353349
has title: Find all integers in list of strings and output it in form of a list
linked to: http://stackoverflow.com/q/4289331
type: AnsweredQuestion
tagged with: list
answer count: 2
score: 1
duplicate of: http://stackoverflow.com/q/4289331
has body: How can I find and extract integers (without using the re module) from a list of strings and integers. ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69'] How do I extract all the integers (2,42,69) in form of a list? Desired output: [2, 42, 69]
downvote count: 0
has answer: http://stackoverflow.com/a/48353323
has comment: http://stackoverflow.com/comment/83693241
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48353323

http://stackoverflow.com/q/48369613
favorite count: 0
type: Question
has body: What is best way to store pearson correlation values as a pandas dataframe. Correlation is calculated as below Correlation = df.corr() But I want to store the output as dataframe.
has title: Python Pandas - what is best way to store pearson correlation values stored in as pandas dataframe
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48369662
tagged with: pandas
upvote count: 0
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/83898253
comment on: http://stackoverflow.com/a/48452440
score: 1
type: Comment
type: AnswerComment
has text: @NickA: Yes. The `and` operator will call `bool` on its first argument as necessary to asses its truth value. The `&` operator will not, since it expects to be working on numbers. `1 and 2` is truthy (it will be `2`, due to `and`'s short-circuiting behavior), but `1 & 2` is `0`, which is falsey.

rhel
tags question: http://stackoverflow.com/q/48386714
tag name: rhel
type: Tag

http://stackoverflow.com/comment/83902504
score: 0
has text: If you'll be working more with these kind of data, and since you already mention dataframe (though you didn't tag your question with `pandas`), have a read through the [merge, join and concatenate section](https://pandas.pydata.org/pandas-docs/stable/merging.html) of the Pandas documentation.
type: QuestionComment
comment on: http://stackoverflow.com/q/48454720
type: Comment

http://stackoverflow.com/comment/83807081
score: 0
type: Comment
type: QuestionComment
has text: what about just the years?
comment on: http://stackoverflow.com/q/48408866

http://stackoverflow.com/q/48429787
score: 0
answer count: 2
has body: I am trying to produce a subplot, plotting 3 time series over 2 different axes. My time series go from Jan-2007 till Sep-2017 (one data point per month). My problem is that I cannot change the limits of the x axis. I have tried both xlim and set_xlim, but they have no effect whatsoever. What am I doing wrong? An example of my code is below. import numpy as np import pandas as pd import datetime as dt import dateutil import matplotlib.pyplot as plt import matplotlib import matplotlib.ticker as mtick mystart = dt.date(2007,1,1) mydates =[mystart] for i in np.arange(1,130): mydates.append( mystart +dateutil.relativedelta.relativedelta(months=i)) df=pd.DataFrame() df['month']=mydates df['a']= np.arange(1,131) df['b']=df['a']/2 df['c']=0.25 fig,ax=plt.subplots(2) ax[0].set_title('My title') l1 = ax[0].plot_date( df['month'],df['a'], label= 'a (left axis)', color='blue', ls='solid', marker ='') l2 = ax[0].plot_date( df['month'],df['b'], label= 'b (left axis)',color='red', ls='solid', marker ='') # THESE BELOW ARE THE TWO LINES I CANNOT GET TO WORK!!! #plt.xlim(xmin= dt.date(2012,1,31),xmax=dt.date(2017,9,30)) ax[0].set_xlim([dt.date(2012,1,31),dt.date(2017,9,30)], auto=True) ax[0].grid() ax2=ax[0].twinx() l3 = ax2.plot_date( df['month'],df['c']*100 , label= 'some % (right axis)', color='green', ls='solid', marker ='') fmt = '%.2f%%' # Format you want the ticks, e.g. '40%' yticks = mtick.FormatStrFormatter(fmt) ax2.yaxis.set_major_formatter(yticks) ls=l1+l2+l3 labs=[l.get_label() for l in ls] ax[0].legend(ls, labs, loc='upper left') ax[1].set_title('Something else will go here...') plt.show()
linked to: http://stackoverflow.com/q/32100912
has answer: http://stackoverflow.com/a/48430134
possible better answer: http://stackoverflow.com/a/48430134
has comment: http://stackoverflow.com/comment/83850723
type: Question
has comment: http://stackoverflow.com/comment/83850434
tagged with: matplotlib
tagged with: python
has title: matplotlib subplot with dates: cannot change xlim
has answer: http://stackoverflow.com/a/48432604
accepted answer: http://stackoverflow.com/a/48432604
type: AnsweredQuestion

http://stackoverflow.com/q/48335265
type: Question
has comment: http://stackoverflow.com/comment/83656062
has comment: http://stackoverflow.com/comment/83656275
upvote count: 2
tagged with: group-by
has title: how to perform drop_duplicates with multiple condition in a pandas dataframe
has comment: http://stackoverflow.com/comment/83655883
tagged with: duplicates
tagged with: dataframe
tagged with: python
has body: I have a df, Sr.No Name Class Data 0 1 Sri 1 sri is a good player 1 '' Sri 2 sri is good in cricket 2 '' Sri 3 sri went out 3 2 Ram 1 Ram is a good player 4 '' Ram 2 sri is good in cricket 5 '' Ram 3 Ram went out 6 3 Sri 1 sri is a good player 7 '' Sri 2 sri is good in cricket 8 '' Sri 3 sri went out 9 4 Sri 1 sri is a good player 10 '' Sri 2 sri is good in cricket 11 '' Sri 3 sri went out 12 '' Sri 4 sri came back I am trying to drop duplicates based on ["Name","Class","Data"]. The goal is to drop duplicates based on all sentences per Sr No. My expected output is, out_df Sr.No Name Class Data 0 1 Sri 1 sri is a good player 1 Sri 2 sri is good in cricket 2 Sri 3 sri went out 3 2 Ram 1 Ram is a good player 4 Ram 2 sri is good in cricket 5 Ram 3 Ram went out 9 4 Sri 1 sri is a good player 10 Sri 2 sri is good in cricket 11 Sri 3 sri went out 12 Sri 4 sri came back
accepted answer: http://stackoverflow.com/a/48335627
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48335627
has comment: http://stackoverflow.com/comment/83656288
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83655565
favorite count: 0

http://stackoverflow.com/comment/83945733
has text: That's not `request.POST`, it's `request.GET`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48475357
type: QuestionComment

http://stackoverflow.com/comment/105549547
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48447477
has text: No need to use set() since dict.keys() returns a set-like object that supports set operations, including equality comparison.
type: Comment

http://stackoverflow.com/q/48448453
favorite count: 0
has answer: http://stackoverflow.com/a/48448591
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/48448941
tagged with: python
has title: For X seconds do some action every Y seconds
accepted answer: http://stackoverflow.com/a/48448591
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/1133857
has answer: http://stackoverflow.com/a/48448941
has body: So I stumbled upon an answer that almost satisfies my question. In my case I want to fetch the status of my limit buy order in market for 5 seconds every 0.8 seconds or so. The code that I found looks like this: import threading def printit(): threading.Timer(0.8, printit).start() print("Hello, World!") and to run something for 5 seconds, one can do the following: import time t_end = time.time() + 5 while time.time() &lt; t_end: print('Hello World') but combining those two like so, is not gonna work: while time.time() &lt; t_end: printit() So I am just wondering how I can make printit() run every 0.8 seconds for 5 seconds?

http://stackoverflow.com/comment/83903468
type: AnswerComment
comment on: http://stackoverflow.com/a/48455137
has text: @Amy My advice, don't use builtin names for variables, e.g. `sum`. Consider `total` or `sum_`
score: 1
type: Comment

http://stackoverflow.com/comment/83704871
comment on: http://stackoverflow.com/q/48358723
type: QuestionComment
type: Comment
has text: Possibly missing a quote somewhere.
score: 0

http://stackoverflow.com/comment/83828540
has text: You could check if `--with-cov` was passed via command line or config.
type: Comment
comment on: http://stackoverflow.com/q/48409157
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83960622
comment on: http://stackoverflow.com/a/48483859
score: 0
type: Comment
has text: It seems you did not read my whole question (I want that automated)
type: AnswerComment

http://stackoverflow.com/comment/83709011
score: 0
comment on: http://stackoverflow.com/q/48349556
has text: A very example of the function f: if users define the arguments as a, b, c, then def f(data, a, b, c): return a * data - b - c but if users define the argument as b, c, d, then def f(data, b, c, d): return data / b + c * d And so on...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/120590493
has text: How to get stdout?!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48377951

http://stackoverflow.com/comment/83892750
score: 0
comment on: http://stackoverflow.com/q/48443107
has text: @BoboDarph i just tried that (the simple_salesforce approach) and still get the same HTML response. Will update the question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83759808
type: QuestionComment
has text: @quamrana that's exactly my question! :) Is there such a functionality that would actually make sense?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48386100

http://stackoverflow.com/comment/83699085
type: QuestionComment
comment on: http://stackoverflow.com/q/48355942
has text: Using drop_duplicates of DataFrame is much easier, if you have no problem in converting your list to a dataframe.
score: 1
type: Comment

http://stackoverflow.com/comment/83931284
has text: Cheers , thats fixed it :)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48468526
type: Comment

http://stackoverflow.com/comment/83710510
type: Comment
comment on: http://stackoverflow.com/q/48361755
score: 1
has text: Maybe look into the BeautifulSoup module (`bs4`), it's a great html parser.
type: QuestionComment

http://stackoverflow.com/a/48392546
accepted answer of: http://stackoverflow.com/q/48392492
has comment: http://stackoverflow.com/comment/83773303
has comment: http://stackoverflow.com/comment/83773106
type: Answer
has comment: http://stackoverflow.com/comment/83797193
answers question: http://stackoverflow.com/q/48392492
has comment: http://stackoverflow.com/comment/83797242
has comment: http://stackoverflow.com/comment/83773247
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83772959
has body: (1) The system-bundled one is : /usr/bin/python (2) If pip is install on each version of Python, you can do (for example) : /Users/yangtong/anaconda2/bin/python pip freeze or (for /usr/bin/python) /usr/bin/python then help("modules") (3) You can still remove them, but I highly recommend you to create only virtual environment from now :)
has comment: http://stackoverflow.com/comment/83801345

http://stackoverflow.com/comment/83805259
type: Comment
type: QuestionComment
has text: @GerardvanHelden i have a server api which enables a client to define a collection in mongo than generates CRUD for it. now after client is done it can request to dispose of that collection. i'm creating this collection with inheritance to a pre-define object to get a specific behaviour. now i have different features which are enabled for all subclasses of my object. i relay in my implementation on that the subclasses list. is the context clearer now?
score: 0
comment on: http://stackoverflow.com/q/48407880

http://stackoverflow.com/comment/83834992
has text: Good to know, must be something with my setup, then! Strange...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48422744

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/48474142
type: Tag
tags question: http://stackoverflow.com/q/48481864

http://stackoverflow.com/q/48467961
type: UnansweredQuestion
tagged with: browser-automation
tagged with: selenium
has comment: http://stackoverflow.com/comment/83930400
has title: Possible to open/display/render a headless Selenium session?
linked to: http://stackoverflow.com/q/48369043
has comment: http://stackoverflow.com/comment/83930627
linked to: http://stackoverflow.com/q/47861813
answer count: 3
has body: I know this is sort of counter to the purpose of headless automation, but... I've got an automation test running using Selenium and Chromedriver in headless mode. I'd prefer to keep it running headless, but occasionally, it runs into an error that really needs to be looked at and interacted with. Is it possible to render and interact with a headless session? Maybe by duplicating the headless browser in a non-headless one? I can connect through remote-debugging, but the Dev Tools doesn't seem to do allow me to view the rendered page or interact with anything. I am able to take screenshots, which sort of helps. But I'm really looking for the ability to interact--there's some drag-and-drop elements that aren't working well with Selenium that are causing issues occasionally.
downvote count: 0
has answer: http://stackoverflow.com/a/48468760
has comment: http://stackoverflow.com/comment/83930245
tagged with: headless
has answer: http://stackoverflow.com/a/58045991
has comment: http://stackoverflow.com/comment/83930246
tagged with: python
has comment: http://stackoverflow.com/comment/83929616
has answer: http://stackoverflow.com/a/48476804
favorite count: 0
type: Question
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/83930134
has comment: http://stackoverflow.com/comment/83930936

http://stackoverflow.com/a/48423038
type: Answer
score: 1
downvote count: 0
has body: If you do this for large amounts of data, you should absolutely check out numpy and pandas, which both have more effective and natural methods of handling tables than native python. In case you only need a solution right now, accumulations can be done straight forwardly in pure python with collections.defaultdict: from collections import defaultdict con = defaultdict(int) for count, line in enumerate(connections): if count == 0: continue in_gate, out_gate, number = line.split(',') con[f"{in_gate}-&gt;{out_gate}"] += int(number) Now you can access the entries the following way: print(con['a-&gt;b']) &gt;&gt; 4 print(con['a-&gt;c']) &gt;&gt; 0
upvote count: 1
answers question: http://stackoverflow.com/q/48422730

http://stackoverflow.com/comment/96306491
comment on: http://stackoverflow.com/q/48421974
score: 0
type: Comment
has text: Link to AWS help request ... https://forums.aws.amazon.com/thread.jspa?messageID=826599
type: QuestionComment

http://stackoverflow.com/comment/139795147
type: AnswerComment
score: 0
type: Comment
has text: Great answer ! Another alternative, provided that `len(a)` is known a priori, it is to add it to the f-string format. For instance, in this case, `print(f'{c:06b}')`
comment on: http://stackoverflow.com/a/48373568

http://stackoverflow.com/q/48431626
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83855700
has body: I created batch delayed http (async) client which allows to trigger multiple async http requests and most importantly it allows to delay the start of requests so for example 100 requests are not triggered at a time. But it has an issue. The http .fetch() method has a handleMethod parameter which handles the response, but I found out that if the delay (sleep) after the fetch isn't long enough the handle method is not even triggered. (maybe the request is killed or what meanwhile). It is probably related to .run_sync method. How to fix that? I want to put delays but dont want this issue happen. I need to parse the response regardless how long the request takes, regardless the following sleep call (that call has another reason as i said, and should not be related to response handling at all) class BatchDelayedHttpClient: def __init__(self, requestList): # class members self.httpClient = httpclient.AsyncHTTPClient() self.requestList = requestList ioloop.IOLoop.current().run_sync(self.execute) @gen.coroutine def execute(self): print("exec start") for request in self.requestList: print("requesting " + request["url"]) self.httpClient.fetch(request["url"], request["handleMethod"], method=request["method"], headers=request["headers"], body=request["body"]) yield gen.sleep(request["sleep"]) print("exec end")
has comment: http://stackoverflow.com/comment/83855471
answer count: 0
has title: python tornado async client
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83855133
has comment: http://stackoverflow.com/comment/83856017
tagged with: python
has comment: http://stackoverflow.com/comment/83855601
has comment: http://stackoverflow.com/comment/83855215
linked to: http://stackoverflow.com/q/37565024
downvote count: 0
has comment: http://stackoverflow.com/comment/83855304
score: 1
tagged with: asynchronous
tagged with: tornado

http://stackoverflow.com/q/48365925
answer count: 1
downvote count: 0
upvote count: 1
tagged with: imaplib
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48366085
tagged with: email
tagged with: python
favorite count: 0
type: Question
tagged with: google-drive-api
accepted answer: http://stackoverflow.com/a/48366085
has body: I have mail messages which contain attachments. I need to upload the attachments from mail to google drive. For mail I'm using imaplib and for google drive I'm using pyDrive I'm using the below code to get attachment: if mail.get_content_maintype() == 'multipart': for part in mail.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: attachment = part.get_payload(decode=True) I have payload my attachment in mail. Now I can't understand how upload payload to google drive using pyDrive. I've tried this, but it did not work attachment = part.get_payload(decode=True) gd_file = self.gd_box.g_drive.CreateFile({'title': 'Hello.jpg', "parents": [{"kind": "drive#fileLink", "id": folder['id']}]}) gd_file.GetContentFile(attachment) gd_file.Upload() UPD: This code is work, but i think its bad solution(we save image localy, then upload this image in google drive) attachment = part.get_payload(decode=True) att_path = os.path.join("", part.get_filename()) if not os.path.isfile(att_path): fp = open(att_path, 'wb') fp.write(attachment) fp.close() gd_file = self.gd_box.g_drive.CreateFile({'title': part.get_filename(), "parents": [{"kind": "drive#fileLink", "id": folder['id']}]}) gd_file.SetContentFile(part.get_filename()) gd_file.Upload()
has title: PyDrive download image python
tagged with: pydrive

http://stackoverflow.com/comment/83885948
type: Comment
type: QuestionComment
has text: This probably varies by OS. I'm on Windows and multiplying by 10e6 seems to be sufficient to get a whole number (or something that looks like it; you never can tell with floats :-P).
score: 0
comment on: http://stackoverflow.com/q/48446875

http://stackoverflow.com/q/48339893
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48387897
possible better answer: http://stackoverflow.com/a/48340734
tagged with: python
has answer: http://stackoverflow.com/a/48387897
tagged with: optimization
type: AnsweredQuestion
has body: In the original paper, introducing the Idea 2 eliminates the learning rate. So what is the meaning of learning rate in tensorflow implementation? Class AdadeltaOptimizer: __init__( learning_rate=0.001, rho=0.95, epsilon=1e-08, use_locking=False, name='Adadelta' )
score: 0
answer count: 2
upvote count: 1
has title: Learning rate in tensorflow Adadelta
has answer: http://stackoverflow.com/a/48340734

http://stackoverflow.com/a/48419225
type: Answer
has comment: http://stackoverflow.com/comment/83829194
has body: You need to first convert them all into the same format, then sort. So, convert into date format with something like the following: from dateutil import parser SEASONS = {"Win" : "Feb", "Spr" : "May", "Sum" : "Aug", "Aut" : "Nov"} def convert_to_date(date_string): if date_string.startswith("Q"): quarter = int(date_string[1]) month = str(quarter * 3) return parser.parse("{}-{}".format(month, date_string[2:])) elif date_string.startswith(tuple(SEASONS.keys())): month = SEASONS[date_string[:3]] return parser.parse("{}-{}".format(month, date_string.split(" ")[1])) else: return parser.parse(date_string) Note that this puts the seasons at the last month as per comment. You may need to pip install python-dateutil. Then it should be trivial to sort: sorted_list = sorted(temp2, key=convert_to_date)
answers question: http://stackoverflow.com/q/48418556
score: 0

http://stackoverflow.com/comment/83694132
score: 0
type: AnswerComment
has text: The tutorial went from [a-z] and \w+ does this to write a expression that does that with no explanation on how to combine the fundamentals so I found the one in my original post through searches. Unfortunately, what I thought the question wanted as output, which your answer accomplishes, isn't the desired outcome for the tutorial. I totally forgot about the sentence starting with I, I'll see if I can understand a way to capture it aslo.
type: Comment
comment on: http://stackoverflow.com/a/48352748

http://stackoverflow.com/comment/83859026
type: Comment
has text: @delrocco Exactly, if you want to handle speed, the most common thing that libraries do is not exchange values, but memory positions, it is less expensive to move a variable than hundreds or thousands of them.
comment on: http://stackoverflow.com/a/48433480
type: AnswerComment
score: 0

http://stackoverflow.com/q/48430380
has answer: http://stackoverflow.com/a/48431392
tagged with: spyder
answer count: 1
has comment: http://stackoverflow.com/comment/83851684
downvote count: 0
has title: How to run python code line by line in Spyder and include loop/if statement contents
linked to: http://stackoverflow.com/q/39031796
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83851591
has comment: http://stackoverflow.com/comment/83851649
tagged with: python
has comment: http://stackoverflow.com/comment/83853465
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/83853701
has body: I usually use RStudio to code in R, and when running code line by line, if running the first line of a loop, the content of the loop runs with it. It is very convenient for debugging code, to be able to run code line by line without manually selecting the whole loop for example. In Spyder, if I run the first line of a loop, it runs just that, as if I was trying to run an empty loop, and gives an error. How can a run a code line by line properly in Spyder? I have researched the question but did not find an answer. Thank you for your help!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48431392
has comment: http://stackoverflow.com/comment/83851857
has comment: http://stackoverflow.com/comment/83851834

http://stackoverflow.com/q/48383199
has title: Splitting names that include "de", "da", etc. into first, middle, last, etc
has answer: http://stackoverflow.com/a/48389673
downvote count: 2
has answer: http://stackoverflow.com/a/48383580
score: 16
has answer: http://stackoverflow.com/a/48384447
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48383560
answer count: 9
has comment: http://stackoverflow.com/comment/83753776
tagged with: python
has answer: http://stackoverflow.com/a/48383773
has answer: http://stackoverflow.com/a/48383305
tagged with: regex
upvote count: 18
has comment: http://stackoverflow.com/comment/83754657
has answer: http://stackoverflow.com/a/48383699
has answer: http://stackoverflow.com/a/48383727
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48383345
has comment: http://stackoverflow.com/comment/83753909
has comment: http://stackoverflow.com/comment/83763756
has answer: http://stackoverflow.com/a/48383560
has answer: http://stackoverflow.com/a/48383345
has body: I want to split Brazilian names into parts. However there are names like below where "de", "da" (and others) that are not separate parts and they always go with the following word. So normal split doesn't work. test1 = "Francisco da Sousa Rodrigues" #special split test2 = "Emiliano Rodrigo Carrasco" #normal split test3 = "Alberto de Francia" #special split test4 = "Bruno Rezende" #normal split My expected output would be: [Francisco, da Sousa, Rodrigues] #1 [Emiliano, Rodrigo, Carrasco] #2 [Alberto, de Francia] #3 [Bruno, Rezende] #4 For the special cases I tried this pattern: PATTERN = re.compile(r"\s(?=[da, de, do, dos, das])") re.split(PATTERN, test1) (...) but the output is not what I expected: ['Francisco', 'da Sousa Rodrigues'] #1 ['Alberto', 'de Francia'] #3 Any idea how to fix it? Is there a way to just use one pattern for both "normal" and "special" case?

http://stackoverflow.com/comment/83728275
type: Comment
type: QuestionComment
has text: If the trouble is keeping the web driver process open, you can do that by moving the init out of the function itself and into the top level of the module. Then it will run once for each pool worker.
comment on: http://stackoverflow.com/q/48363237
score: 0

openmdao
tag name: openmdao
tags question: http://stackoverflow.com/q/48382662
type: Tag

http://stackoverflow.com/a/48374153
answers question: http://stackoverflow.com/q/48374039
score: 2
has body: You can do this: a = ["cats",4,"n",2,"the",3,"house"] data_types = [] total = 0 for i in a: if type(i) not in data_types: data_types.append(type(i)) if isinstance(i, int): total += i if len(data_types) &gt; 1: print("List has a mix data type of: {0}".format(', '.join([str(i) for i in data_types]))) if total &gt; 0: print("The total of integer in the list is: {0}".format(total)) Output: List has a mix data type of: &lt;class 'str'&gt;, &lt;class 'int'&gt; The total of integer in the list is: 9
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83863065
type: AnswerComment
has text: Even though I didn't provide a sample output, this is exactly was I was looking for. The approach provided by Ali and the one you provided worked perfectly. Thanks for your help!
score: 0
comment on: http://stackoverflow.com/a/48435693
type: Comment

http://stackoverflow.com/a/48373502
has comment: http://stackoverflow.com/comment/83769298
has comment: http://stackoverflow.com/comment/83773829
score: 1
has body: Your placeholder x is overridden by the integer x in the for loop. So the variable x in feed_dict is the one comes from range(trainingtimes), which is definitely not a TF tensor. Rename the variable x to avoid the problem: for i in range(trainingtimes): sess.run(train_step, feed_dict={x: regroup, ytt:labels}) if i % 100 == 0: print(sess.run(mse, feed_dict={x:regroup, ytt:labels}))
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48373038
has comment: http://stackoverflow.com/comment/83815464
type: Answer
has comment: http://stackoverflow.com/comment/83774103

http://stackoverflow.com/a/48431900
answers question: http://stackoverflow.com/q/48431871
score: 4
downvote count: 0
type: Answer
upvote count: 4
has body: You can use the parameter flat=True e.g.: vol = v.foo_set.values_list('Volume', flat=True) For reference docs are at https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values-list
accepted answer of: http://stackoverflow.com/q/48431871
type: AcceptedAnswer

http://stackoverflow.com/q/48431456
upvote count: 1
has comment: http://stackoverflow.com/comment/83928182
has comment: http://stackoverflow.com/comment/83854060
has comment: http://stackoverflow.com/comment/83937421
has comment: http://stackoverflow.com/comment/83855084
downvote count: 1
has title: Unable to execute python script from command-line
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/16945908
has comment: http://stackoverflow.com/comment/83937476
has comment: http://stackoverflow.com/comment/83854188
type: UnansweredQuestion
has body: I have sublime text 3 and python 3.6 on my windows 10 os. I written the basic "Hello World!" program in sublime text 3 and saved it as "siri.py" on desktop. I am trying to execute this on command line and it says, python: can't open file 'siri.py': [Error 2] no such file or directory What am I doing wrong here?
tagged with: python
has comment: http://stackoverflow.com/comment/83937535
has comment: http://stackoverflow.com/comment/83853994
linked to: http://stackoverflow.com/q/419163
has comment: http://stackoverflow.com/comment/83859379
score: 0
has comment: http://stackoverflow.com/comment/83855071
answer count: 0

http://stackoverflow.com/comment/83903590
has text: I think i was missing ... in there. for i in range
comment on: http://stackoverflow.com/q/48455290
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48394740
answers question: http://stackoverflow.com/q/48394649
type: Answer
accepted answer of: http://stackoverflow.com/q/48394649
has body: def get_list_fields(self): list_fields = { 'id' : self.id, 'name' : self.alias, 'description' : self.name, 'extra_fields' : "[{}][{}]".format( self.email, self.get_actor_type_display() ) } return list_fields try this
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83818346
has text: Well, I am not sure how to proceed. How would you relate `b` and `c`? In your sample code you provide a dict in the form of `{'a': ['b', 'c'], 'b': ['c']}` which clearly makes `b` related to `c` but the one you provide in the question is different.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48412616
type: Comment

http://stackoverflow.com/q/48404153
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48405366
tagged with: tensorflow
has body: I have the following problem where I would like to code W_hidden = tf.Variable(tf.random_normal(shape = [hidden_size1, hidden_size2], stddev = 0.1), name = "weights_hidden", trainable = True) b = tf.Variable(tf.zeros([1, hidden_size2]), name="bias", trainable = True) hidden_relu_0 = tf.nn.relu(tf.matmul(BN1[0], W_hidden)+b) hidden_relu_1 = tf.nn.relu(tf.matmul(BN1[1], W_hidden)+b) and so on where BN1 has some size, say n. I tried to use numpy array, list, Tensorarray and tf.concat but I did not manage to make it work. Ideally it would be something equivalent to tensor_list = [] for index in range(0,window_size): hidden_relu = tf.nn.relu(tf.matmul(BN1[index], W_hidden)+b) tensor_list.append(hidden_relu) Thanks a lot for your help
has comment: http://stackoverflow.com/comment/83804383
has title: How to store operations in tensorflow using a loop?
tagged with: python

http://stackoverflow.com/comment/83898280
comment on: http://stackoverflow.com/q/48452294
score: 0
has text: Are you asking how to do this from Python, or how to do this from shell?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48542090
answers question: http://stackoverflow.com/q/48484812
type: Answer
score: 0
has body: I can't understand what's wrong with my code. There I defined the list from certain folder, so that I could work at the strings in each file, right? Then I applied the conditions for filtering and further choice of the one file to delete. import os dir_name = "/Python/Test_folder/Schems" filenames = os.listdir(dir_name) for names in filenames: filenames.setdefault(names[0:7],[]).append(names) # create key=[] or/and append names for k,v in filenames.items(): filesToDelete = [] #ther's a syntax mistake. But I can't get it - there's the list or not? for k,v in filenames.items(): if len(v) == 1: continue v.sort(key = lambda x: int(x[7:9])) filesToDelete.extend(v[:-1])

http://stackoverflow.com/comment/83681012
comment on: http://stackoverflow.com/q/48345742
type: Comment
type: QuestionComment
score: 0
has text: df2.info(): `<class 'pandas.core.frame.DataFrame'> RangeIndex: 604558 entries, 0 to 604557 Data columns (total 22 columns): ZIP 445885 non-null float64 TIME_NOTED 604558 non-null object NAME 604558 non-null object OCCUPIED 604558 non-null object STATE 604558 non-null object`

http://stackoverflow.com/q/48371205
score: 1
favorite count: 0
has title: How to utilize sys.callstats?
tagged with: python-3.x
type: Question
possible better answer: http://stackoverflow.com/a/48371414
has body: I just stumbled over callstats in the sys module after PyCharm's autocomplete suggested it. Else I probably would never have discovered it because it doesn't get even mentioned in the docs help(sys.callstats) gives this: Help on built-in function callstats in module sys: callstats(...) callstats() -> tuple of integers Return a tuple of function call statistics, if CALL_PROFILE was defined when Python was built. Otherwise, return None. When enabled, this function returns detailed, implementation-specific details about the number of function calls executed. The return value is a 11-tuple where the entries in the tuple are counts of: 0. all function calls 1. calls to PyFunction_Type objects 2. PyFunction calls that do not create an argument tuple 3. PyFunction calls that do not create an argument tuple and bypass PyEval_EvalCodeEx() 4. PyMethod calls 5. PyMethod calls on bound methods 6. PyType calls 7. PyCFunction calls 8. generator calls 9. All other calls 10. Number of stack pops performed by call_function() Now I'm curious why it doesn't get mentioned anywhere and if there is a possibility to use it in an Anaconda build for Python. It returns None when I call sys.callstats() so I assume the answer for the latter will be no. However I'd still be interested in seeing how an actual output of this would look like for Python builds where this works. Edit: In the Issue28799 linked from the comments below the accepted answer we find the reason why callstats will be removed with Python 3.7. The stats probably wouldn't be right after an upcoming feature will be implemented: My problem is that with my work on FASTCALL, it became harder to track where the functions are called in practice. It maybe out of the Python/ceval.c file. I'm not sure that statistics are still computed correctly after my FASTCALL changes, and I don't know how to check it. Python has already sys.setprofile(), cProfile and profile modules. There is also sys.settrace(). Do we still need CALL_PROFILE? Atta…
answer count: 2
tagged with: sys
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48371414
tagged with: python
accepted answer: http://stackoverflow.com/a/48371530
has answer: http://stackoverflow.com/a/48371530
tagged with: anaconda
type: AnsweredQuestion

http://stackoverflow.com/a/48391700
has body: It would greatly help debug this if you include examples of such filenames that give you trouble. However, I have a good idea on what is probably happening here. This problems seem to appear on folders that start with r or t on their names. Also, as they are folders, on their full path name they are preceded by a \ character (for example "\thisFolder", or similar). This is true in the case of a Windows environment, as they use \ for separating paths contrary to *nix systems that use the regular slash /. Considering these things, seems that perhaps you are experiencing this as \r and \t are both special characters that mean Carriage Return and Tabulation, respectively. If this is the case many file openers will have trouble processing such file name. Even more, I would not be surprised if you got the same errors on folders that begin with n or other letters that when concatenated to a backslash give special characters (\n is new line, \s is a white space, etc.). To overcome this seems that you will need to escape your backslash character before passing it as a filename. In python, an escaped backslash is "\\" . In addition, you can also opt to pass a Raw string instead, by adding the r prefix to your string, something like r"\a\raw\string". More information on escaping and raw string can be found on this question and answers. I want to know if there are some specified rules on the filenames which should be avoided and otherwise would lead to such reading error in python, As mentioned, you should avoid this with characters that have a special meaning with a backslash. I suggest you check here to see the characters Python accepts like this, so you can refrain from using such characters (or well use raw strings and forget about this problem).
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48389764
score: 3
type: Answer

http://stackoverflow.com/q/48480345
answer count: 1
has body: Trying to make a python script that can scrape from pastebin's RAW Paste Data section of the page on saved pastebin outputs. But I'm running into an issue with Python Attribute Error about NoneType has no object attribute 'text', I'm using the libraries from BeautifulSoup in my project. I tried to install spider-egg with pip install so I could use that also, but there was issues downloading the package from the server. I need to be able to grab different multiple lines from the RAW Paste Data section and the print them back out to me. first_string = raw_box.text.strip() second_string = raw_box2.text.strip() from the pastebin page I have the class element names for the RAW Paste Data section which is; &lt;textarea id="paste_code" class="paste_code" name="paste_code" onkeydown="return catchTab(this,event)"&gt; taking the class name paste_code I then have this raw_box = soup.find('first_string ', attrs={'class': 'paste_code'}) raw_box2 = soup.find('second_string ', attrs={'class': 'paste_code'}) I thought that should of been it, but apparently not, because I get the error I mentioned before. After parsing the data that has been stripped I need to be able to redirect that into a file after printing what it got. I also want to try make this python3 compatible, but that would take a little more work I think, since there's a lot of differences between python 2.7.12 and 3.5.2.
tagged with: web-scraping
tagged with: scrapy
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48548567
score: 0
has title: Python AttributeError NoneType 'text'
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83953748
type: UnansweredQuestion

http://stackoverflow.com/a/48407108
has body: Python's r"" literal syntax escapes all your slashes automatically, which is why it's preferred for things like file paths. Try using chrome_path = r"\Users\prateek\Desktop\MSc\MWA\chromedriver.exe"
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/83803465
downvote count: 1
answers question: http://stackoverflow.com/q/48407037
has comment: http://stackoverflow.com/comment/83803160
score: 1

http://stackoverflow.com/comment/83679845
comment on: http://stackoverflow.com/q/48346877
type: Comment
type: QuestionComment
has text: i've tried just " and i've tried executing inserting this curs.execute("INSERT INTO zzz(tem,dat) VALUES (%s, %s)" ,(i, datetime.datetime.now())) not working
score: 0

http://stackoverflow.com/q/48371016
has answer: http://stackoverflow.com/a/48371352
possible better answer: http://stackoverflow.com/a/60197355
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48371352
has answer: http://stackoverflow.com/a/60197355
tagged with: pymongo
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/15257146
tagged with: mongodb
has body: I am looking to implement full text search in my python application using pymongo. I have been looking at this question but for some reason I am unable to implement this in my project as I am getting an error no such cmd: text. Can anyone direct me on what I am doing wrong? Here is my code: db = client.test collection = db.videos def search_for_videos(self, search_text) self.db.command("text", "videos", search=search_text, limit=10) The collection I am trying to search is called videos however I am not sure if I am putting this in the correct parameter, and I also am not sure if I need the line project={"name": 1, "_id": 0}. The documentation here I believe is using the mongo shell to execute commands, however I wish to perform this action in my code. I have looked at using the db.videos.find() function, but cannot seem to implement it correctly either. How to I use PyMongo Full Text Search from my Python Code?
score: 9
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/97233968
has title: Pymongo how to use full text search
answer count: 2
tagged with: python

http://stackoverflow.com/comment/83836192
type: QuestionComment
has text: What flags is `ll` using?
comment on: http://stackoverflow.com/q/48422744
score: 0
type: Comment

http://stackoverflow.com/comment/83826729
type: QuestionComment
has text: Yes, I need add the field values (facility_id , facility type etc in between fields{}) from the data which i fetched using getvalues() function
comment on: http://stackoverflow.com/q/48418396
score: 0
type: Comment

http://stackoverflow.com/a/48455502
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48455460
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/137749216
has body: You're on Windows, and your file presumably contains 204 (11264-11060) carriage return-linefeed pairs, which when read in text mode are normalized to a single linefeed (\n) character. Use binary mode ('rb') to avoid this conversion.
upvote count: 4
answers question: http://stackoverflow.com/q/48455460

http://stackoverflow.com/q/48349415
has title: Why PyCharm does not load file/module from specified directory?
has body: I want to load a module/file called lr_utils inside folder "Deep Learning". I am relatively new to Python and PyCharm. In my other languages, I just change the directory, and load the package. But, that does not work in PyCharm. import os &gt; os.chdir("/Users/Desktop/Deep Learning") &gt; os.getcwd() '/Users/Desktop/Deep Learning' The directory is changed. Let's import. from lr_utils import load_dataset Now, I get this error message: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'lr_utils' I've been reading that you can go to PyCharm interpreter and manually add the path. But that's too tedious! What If I have multiple paths? What if I want to send me a code? What if I switch to different computer? Bottom line: I just want to change directory on the fly.
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48349530
has answer: http://stackoverflow.com/a/48349530
type: AnsweredQuestion
score: 0
tagged with: pycharm
answer count: 1
tagged with: directory

http://stackoverflow.com/a/64632846
upvote count: 0
has comment: http://stackoverflow.com/comment/114280744
type: Answer
score: -1
has body: I am sharing idea and then you can extend it more : There is no limit to how long an integer value can be but depends on amount of memory your system has, but beyond that an integer can be as long as you need it to be. Strings can be prepended to an integer Code : print(0x10) Output : 16 Code : print(0b10) Output : 2
answers question: http://stackoverflow.com/q/48411539
downvote count: 1

http://stackoverflow.com/comment/83776414
comment on: http://stackoverflow.com/q/48394344
has text: use any text editor and you will see that the .ui is an .xml
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48355182
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48353359
has body: The problem is the additional dumb dimension. You can remove it using: arr = np.squeeze(arr)
type: Answer
answers question: http://stackoverflow.com/q/48353359
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83697315

http://stackoverflow.com/comment/83871588
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48440226
has text: Change all capturing groups to non-capturing.

http://stackoverflow.com/comment/83784384
type: Comment
has text: Hii. Welcome to SO. Better to write your approach first.
comment on: http://stackoverflow.com/q/48398253
type: QuestionComment
score: 0

http://stackoverflow.com/a/48393727
downvote count: 0
answers question: http://stackoverflow.com/q/48393431
type: Answer
upvote count: 1
score: 1
has body: List comprehension solution. np.array([np.amax(a * (1 - np.eye(3)[j]), axis=1) for j in range(a.shape[1])]).T

http://stackoverflow.com/comment/83924862
comment on: http://stackoverflow.com/q/48465576
has text: how is it different? can you clarify your question?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83962194
score: 0
comment on: http://stackoverflow.com/a/48484534
type: Comment
has text: i posted my current code up there. how do i get the program to retrieve the """11,560.00 USD"""
type: AnswerComment

http://stackoverflow.com/a/48345619
has body: Pandas read_csv should do the trick. You'll want to wrap your uploaded bytes in an io.StringIO since read_csv expects a file-like object. Here's a full example: https://colab.research.google.com/notebook#fileId=1JmwtF5OmSghC-y3-BkvxLan0zYXqCJJf The key snippet is: import pandas as pd import io df = pd.read_csv(io.StringIO(uploaded['train.csv'].decode('utf-8'))) df
downvote count: 1
has comment: http://stackoverflow.com/comment/85327480
has comment: http://stackoverflow.com/comment/91639557
accepted answer of: http://stackoverflow.com/q/48340341
score: 58
type: Answer
answers question: http://stackoverflow.com/q/48340341
has comment: http://stackoverflow.com/comment/124215135
upvote count: 59
type: AcceptedAnswer

http://stackoverflow.com/comment/83922582
type: AnswerComment
has text: exactly, in a shell script a condition is just a command, and the condition is true when the exit code of the command is 0, the condition is false when the exit code is anything but 0
comment on: http://stackoverflow.com/a/48463730
score: 0
type: Comment

http://stackoverflow.com/a/48398256
has body: I would just create a single for-loop, with the help of Calendar API: import calendar M = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] print(M[0], end=" ") # For whatever reason you are printing this value for i in range(1,len(M)): print(calendar.month_name[i],"=",(i - (i // 7) - ((i + 1) // 7)),end=" ")
upvote count: 1
answers question: http://stackoverflow.com/q/48397903
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/48470257
answers question: http://stackoverflow.com/q/48350692
type: AcceptedAnswer
downvote count: 0
score: 9
has comment: http://stackoverflow.com/comment/108102834
accepted answer of: http://stackoverflow.com/q/48350692
upvote count: 9
has body: Because pip uses the legacy Python 2. Use pip3 to install: pip3 install --upgrade pip pip3 install jupyter jupyter notebook #to start jupyter notebook I highly recommend installing Anaconda. Download Anaconda here. Then use : bash to install it. Good Luck.
type: Answer

http://stackoverflow.com/comment/83856024
score: 0
type: Comment
type: QuestionComment
has text: A brand new environment works just fine! Don't know what happened...but anyway that's the solution so let's go! Cheers buddy.
comment on: http://stackoverflow.com/q/48432038

http://stackoverflow.com/comment/83889931
score: 0
comment on: http://stackoverflow.com/q/48447369
type: Comment
type: QuestionComment
has text: are you sure that your query is working?. You should use datetime.datetime.now() instead of datetime.date.today() because your fields are datetimefield instead of DateField

http://stackoverflow.com/q/48448995
accepted answer: http://stackoverflow.com/a/48477177
linked to: http://stackoverflow.com/q/11779143
has answer: http://stackoverflow.com/a/48477177
tagged with: python
tagged with: uwp
has body: I am setting up a Raspberry PI 3 to work with a distance sensor and display to a UWP app. Specifically this model: https://www.tindie.com/products/upgradeindustries/hc-sr05--hy-srf05-precision-ultrasonic-sensor/. I am looking for a way to run the distance calculation/GPIO in the background in Python, and then display the distance to a UWP app. Does anyone know if this is possible, or could point me in the right direction? Currently the UWP app I have is working, however it does seem unreliable. Thanks!
type: AnsweredQuestion
tagged with: windowsiot
has title: Windows IOT Python/UWP interaction on Raspberry pi
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83893170
has comment: http://stackoverflow.com/comment/83891490
has comment: http://stackoverflow.com/comment/83892640
type: Question
has comment: http://stackoverflow.com/comment/83906728
tagged with: raspberry-pi

dataset
tags question: http://stackoverflow.com/q/48359899
tags question: http://stackoverflow.com/q/48455037
tags question: http://stackoverflow.com/q/48343257
tags question: http://stackoverflow.com/q/48351883
tags question: http://stackoverflow.com/q/48477848
tags question: http://stackoverflow.com/q/48385256
tag name: dataset
tags question: http://stackoverflow.com/q/48356733
type: Tag
tags question: http://stackoverflow.com/q/48349409

http://stackoverflow.com/comment/83964480
comment on: http://stackoverflow.com/a/48485585
score: 0
type: Comment
has text: Thank you! This helped me a lot!
type: AnswerComment

http://stackoverflow.com/a/48483582
type: Answer
has body: According to the tensorflow implementation: BasicLSTMCell source code. The shape of kernel is [input_depth + h_depth, 4 * num_units], which input_depth is your input vector dimension, and h_depth is your hidden units count. So your kernel shape is [1 + 80, 4 * 80].
score: 0
answers question: http://stackoverflow.com/q/48483489

http://stackoverflow.com/comment/83960336
score: 0
has text: You're welcome! Still don't quite understand what you're actually doing here so... ;)
comment on: http://stackoverflow.com/q/48483032
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48365992
type: Answer
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83723766
answers question: http://stackoverflow.com/q/48364817
has body: Update : Found the solution, instead of filter the queryset from form.py, just query it in view.py with this line : form.fields['project_manager'].queryset = Employee.objects.filter(department__in=[18, 19, 20]).exclude(employment_status=6)
score: -2

http://stackoverflow.com/comment/83685669
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48348714
score: 0
has text: _"I'm aware the exact code above wouldn't work."_ should never be the case unless above code not working is _the issue_ to be resolved.

http://stackoverflow.com/comment/83959512
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48483289
has text: I wasn't having issues with the break, it just indented weird when I posted it here.

http://stackoverflow.com/q/48391927
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has body: I want to have the amount under Rent to increment on the amount under Accounts. When a user types in the amount in Rent it should deduct or add in the amount in Account and should reset if paid or stay the same when not paid. class Account(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=250) number = models.PositiveIntegerField(help_text="Account number", unique=True, blank=True, null=False) currency = models.CharField(max_length=3, choices=ALLOWED_CURRENCIES) creation_date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES, help_text="Latest" "balance", default=0, blank=False, null=True) class Rent(models.Model): source = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account holder.") amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES) date = models.DateTimeField(auto_now_add=True)
has title: How do I make a Django model instance to relate to another model instance
has answer: http://stackoverflow.com/a/48392101
score: 1
answer count: 1

http://stackoverflow.com/q/48373845
has answer: http://stackoverflow.com/a/48373959
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67010429
has answer: http://stackoverflow.com/a/69791056
score: 49
has title: Loading model with custom loss + keras
has body: In Keras, if you need to have a custom loss with additional parameters, we can use it like mentioned on https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-keras def penalized_loss(noise): def loss(y_true, y_pred): return K.mean(K.square(y_pred - y_true) - K.square(y_true - noise), axis=-1) return loss The above method works when I am training the model. However, once the model is trained I am having difficulty in loading the model. When I try to use the custom_objects parameter in load_model like below model = load_model(modelFile, custom_objects={'penalized_loss': penalized_loss} ) it complains ValueError: Unknown loss function:loss Is there any way to pass in the loss function as one of the custom losses in custom_objects ? From what I can gather, the inner function is not in the namespace during load_model call. Is there any easier way to load the model or use a custom loss with additional parameters
tagged with: python
accepted answer: http://stackoverflow.com/a/48373959
possible better answer: http://stackoverflow.com/a/67010429
favorite count: 0
type: Question
answer count: 5
has answer: http://stackoverflow.com/a/54574212
downvote count: 0
upvote count: 49
tagged with: keras
has answer: http://stackoverflow.com/a/70708296

del
tag name: del
tags question: http://stackoverflow.com/q/48407153
type: Tag

valueerror
tags question: http://stackoverflow.com/q/48339315
tags question: http://stackoverflow.com/q/48471329
tags question: http://stackoverflow.com/q/48373710
tags question: http://stackoverflow.com/q/48468827
tags question: http://stackoverflow.com/q/48343387
tag name: valueerror
tags question: http://stackoverflow.com/q/48481223
type: Tag
tags question: http://stackoverflow.com/q/48332977
tags question: http://stackoverflow.com/q/48373228

http://stackoverflow.com/q/48356280
tagged with: java
downvote count: 0
has answer: http://stackoverflow.com/a/62927340
tagged with: jvm
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/53160271
tagged with: ibm-cloud
upvote count: 2
has answer: http://stackoverflow.com/a/53160271
possible better answer: http://stackoverflow.com/a/62927340
tagged with: dashdb
tagged with: python
has body: I am running a python flask application in a Cloud Foundry/IBM Cloud-environment. In my application I try to connect to DB2 Warehouse on Cloud with the IBMDBPY-package. This packages needs a package called jaydebeapi to be able to run. For the jaydebeapi to work I think I need JRE/JVM somehow installed on the server. I tried adding the Server JRE for Linux based OS, but it didn't work either. My error I got before I tried to upload the Sever JRE was this: idadb = IdaDataBase(dsn=jdbc) #Establish a connection to our DB2-service 1/20/2018 12:05:45 PM ERR undefined File "/home/vcap/deps/0/python./lib/python2.7/site-packages/ibmdbpy/base.py", line 282, in __init__ 1/20/2018 12:05:45 PM ERR undefined jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path=%s' % jarpath) 1/20/2018 12:05:45 PM ERR undefined File "/home/vcap/deps/0/python/lib/python2.7/site-packages/jpype/_core.py", line 114, in get_default_jvm_path 1/20/2018 12:05:45 PM ERR undefined return finder.get_jvm_path() 1/20/2018 12:05:45 PM ERR undefined File "/home/vcap/deps/0/python/lib/python2.7/site-packages/jpype/_jvmfinder.py", line 121, in get_jvm_path 1/20/2018 12:05:45 PM ERR undefined jvm = method() 1/20/2018 12:05:45 PM ERR undefined File "/home/vcap/deps/0/python/lib/python2.7/site-packages/jpype/_jvmfinder.py", line 164, in _get_from_known_locations 1/20/2018 12:05:45 PM ERR undefined for home in self.find_possible_homes(self._locations): 1/20/2018 12:05:45 PM ERR undefined File "/home/vcap/deps/0/python/lib/python2.7/site-packages/jpype/_jvmfinder.py", line 95, in find_possible_homes 1/20/2018 12:05:45 PM ERR undefined for childname in sorted(os.listdir(parent)): 1/20/2018 12:05:45 PM ERR undefined OSError: [Errno 2] No such file or directory: '/usr/lib/jvm' 1/20/2018 12:05:46 PM OUT undefined Exit status 1 Does anyone know how I can solve this?
score: 2
type: AnsweredQuestion
has title: Add Java/JRE/JVM in Python Flask Cloud Foundry/IBM Cloud application

http://stackoverflow.com/comment/83715118
score: 0
type: Comment
type: AnswerComment
has text: @VaibhavSharma ok
comment on: http://stackoverflow.com/a/48359842

http://stackoverflow.com/comment/83757001
score: 0
comment on: http://stackoverflow.com/q/48384681
type: QuestionComment
type: Comment
has text: yes, it is just extract the data with particular id, if I use ` data["body"][0]["id"] ` it is listing value of index 0, is there a way I can mention index value which contains the id value as b1234

http://stackoverflow.com/q/48403793
score: 3
has answer: http://stackoverflow.com/a/48403872
has comment: http://stackoverflow.com/comment/83795866
has body: I have dictionary a = {'age': '12\xa0', 'name': 'pks\xa0\xa0'} I wanted to remove all Non ASCII characters and replace with spaces. For Removing Non ASCII character in non-dict we are using ''.join([i if 32 &lt; ord(i) &lt; 126 else " " for i in a]) But how to use for dictionary. Any help would be appreciated.
upvote count: 3
accepted answer: http://stackoverflow.com/a/48403884
downvote count: 0
has answer: http://stackoverflow.com/a/48403884
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48404322
has title: How to remove from Python Dictionary Non ASCII characters and replacing with spaces
tagged with: dictionary
has answer: http://stackoverflow.com/a/48403928
answer count: 4
possible better answer: http://stackoverflow.com/a/48403872
has comment: http://stackoverflow.com/comment/83796008
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20078816

http://stackoverflow.com/a/48466539
has body: For the purely academic challenge of squeezing it into one line, you could use the singleton list/iterator trick: name, d, j = next((x, *map(int, y)) for x, *y in ['john 3 4'.split()]) But pls never do this in production code ;)
answers question: http://stackoverflow.com/q/48466267
score: 0
type: Answer

http://stackoverflow.com/comment/83703363
comment on: http://stackoverflow.com/a/48351121
type: Comment
has text: @Omortis re: *"assuming ... pyodbc [is] passing the value through untouched"* - Yes, it is. Wireshark shows that for your original test date/time which the Output Converter function received as `'e\xa8\x00\x00\xa0\x14\xc3\x00'`, [this](https://i.sstatic.net/NDhju.png) is the packet that SQL Server is sending back over the network.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/83879082
comment on: http://stackoverflow.com/a/48368736
score: 0
type: AnswerComment
has text: Thanks, this is a great digest on how to make the sender stop folding!
type: Comment

http://stackoverflow.com/a/53855606
downvote count: 0
answers question: http://stackoverflow.com/q/48383797
has body: You can use pytest-harvest for this. Simply install it, and you can directly use the pre-defined fixtures: import pytest import time @pytest.mark.parametrize('p', ['world', 'self'], ids=str) def test_foo(p): """ A dummy test, parametrized so that it is executed twice """ print('\n hello, ' + p + ' !') time.sleep(len(p) / 10) def test_synthesis(module_results_df): """ Shows that the `module_results_df` fixture already contains what you need """ # drop the 'pytest_obj' column module_results_df.drop('pytest_obj', axis=1, inplace=True) print("\n `module_results_df` dataframe:\n") print(module_results_df) Yields &gt;&gt;&gt; pytest -s -v ============================= test session starts ============================= ... collecting ... collected 3 items test_basic.py::test_foo[world] hello, world ! PASSED test_basic.py::test_foo[self] hello, self ! PASSED test_basic.py::test_synthesis `module_results_df` dataframe: status duration_ms p test_id test_foo[world] passed 500.028610 world test_foo[self] passed 400.022745 self PASSED ========================== 3 passed in 0.05 seconds =========================== You can also start from the 'dict' fixture, which contains more details about setup/teardown times, and convert it to a dataframe using the provided helper methods. See documentation for details. Finally, if you wish to also use parameters, fixtures, steps... you might wish to look at this datascience benchmark example I'm the author by the way ;)
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/83938435
has text: Why not just format the whole thing?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48472121

http://stackoverflow.com/comment/83896298
has text: @Jean-FrançoisFabre `save_virtual_workbook` it form `from openpyxl.writer.excel import save_virtual_workbook` . `xmls` it `GoogleDriveFile` it doesnt have attribute 'SetContent'
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48451317

http://stackoverflow.com/q/48355644
has body: I have a large numpy 2D array with a number of missing values (e.g. NaN), such that some rows and some columns may have multiple missing elements. I wish to remove (or mask out) rows and/or columns to create a subset of the array, while keeping as much data as possible. The difficulty is that if I remove e.g. a row with multiple NaNs, it may negate the need to remove several columns, and vice versa. My guess is that the optimal solution is best done iteratively, by removing e.g. the 1st row or column with at least one missing element that has the fewest non-missing values, removing it, then looking again for the next row or column with that property, etc until there are no missing values. I suspect this is a known problem, and there may be a one-pass solution. If so, is there a name for it? Also is there a Python / numpy implementation, rather than having to roll my own? Edit - added bonus question: I can imaging cases where it is slightly preferable to delete rows, or slightly preferable to delete columns. But of course, if (say) we prefer deleting rows, yet there is a column with all but one value missing, it would be a no-brainer to delete the column, rather than all but one of the rows. So can anyone provide a parameterised function such that for the parameter r, if r=1 we always delete rows, if r=0, we always delete columns, but for in-between values we weight row deletion and column deletion by differing relative amounts (e.g. perhaps if r=0.5 then neither column nor row deletion is preferred, and we end up maximising the amount of data retained)
favorite count: 0
has comment: http://stackoverflow.com/comment/83704616
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83769601
has comment: http://stackoverflow.com/comment/83698105
has comment: http://stackoverflow.com/comment/83704488
upvote count: 2
has comment: http://stackoverflow.com/comment/83697958
type: UnansweredQuestion
tagged with: arrays
tagged with: missing-data
tagged with: python
has comment: http://stackoverflow.com/comment/83730245
score: 2
has comment: http://stackoverflow.com/comment/83697957
answer count: 0
has comment: http://stackoverflow.com/comment/83720703
linked to: http://stackoverflow.com/q/43162526
has comment: http://stackoverflow.com/comment/83720652
has comment: http://stackoverflow.com/comment/83811526
downvote count: 0
has title: Optimally remove rows or columns in numpy to remove missing data

http://stackoverflow.com/comment/83964790
has text: Possible duplicate of [Getting a list of all subdirectories in the current directory](https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory)
comment on: http://stackoverflow.com/q/48486071
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/comment/83726369
comment on: http://stackoverflow.com/q/48369700
has text: Just discovering parallelism. Thanks a lot, using Thread instead of multiprocess do the job !
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48456465
accepted answer of: http://stackoverflow.com/q/48456028
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48456028
score: 0
has body: When calling scripts or python from directory, and importing matplotlib, it will check if any directory named matplolib is there in your current working directory first, rather than the install of matplotlib. Assuming that you have matplotlib directory in your working directory with a blank init file, when you do the following: import matplotlib print matplotlib.__version__ It shows you that 'module' object has no attribute '__version__'. And print matplotlib.__file__ gives you matplotlib/__init__.pyc. There is no pyplot in this directory. Hence, you got your error. Solution: Rename or delete this directory or if you don't want to rename or delete, move it to any other directory from the current working directory.
type: Answer

http://stackoverflow.com/comment/83802964
has text: @StefanPochmann I tried that, that just gives me the 100th binary number and displays a square in my terminal after printing, like [00\\12] (sorry, no better way to make this visible). How do I get this in a number?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48406906

http://stackoverflow.com/comment/84412461
type: Comment
has text: There was another discussion, rather effective way is to use the difference of cumsums about that, something like this: N=6, Xadd = np.ones((N-1))*X[0], X = np.concatenate((Xadd, X)), Xsum = np.cumsum(X, axis=0), Xfilt = Xsum[N:] - Xsum[:-N]. Same idea works for multidimensional arrays. Sorry that all are in one paragraph...
type: AnswerComment
comment on: http://stackoverflow.com/a/48367468
score: 0

http://stackoverflow.com/comment/83878618
score: 0
type: Comment
type: QuestionComment
has text: @PM2Ring, I'll try it
comment on: http://stackoverflow.com/q/48443477

http://stackoverflow.com/q/48484670
favorite count: 0
has answer: http://stackoverflow.com/a/48484846
type: AnsweredQuestion
has body: I am plotting a bar chart on the left axis and a line chart on the right axis. How can I show the legend for both in the same legend box? With the code below, I get two separate legend boxes; also, I need to specify the location of the second legend manually, with lots of trial-and-error, otherwise it overlaps the first one. import pandas as pd import matplotlib.pyplot as plt import matplotlib df=pd.DataFrame() df["bar"]=[40,35,50,45] df["line"]=[.5,.3,.2,.6] fig,ax=plt.subplots(2) l1 = ax[0].bar(df.index, df["bar"], label='my bar chart (left axis)', color='royalblue', width = 0.55) ax0b=ax[0].twinx() l2 = ax0b.plot(df.index, df['line'], label='my line (right axis)',color='tomato',marker='.', ls='dashed') ax[0].legend(loc='upper left', fancybox=True, title='My title') ax0b.legend(bbox_to_anchor=(0.155,0.8), loc=1) plt.show() If I had two lines on two different axes, instead of a bar chart and a line chart, I'd do: myl=l1+l2 labs=[l.get_label() for l in myl] ax[0].legend(myl, labs, loc='upper left') But this doesn't work in my case. I get: myl=l1+l2 TypeError: can only concatenate tuple (not "list") to tuple which I imagine must be because bar() and plot() return two different objects which cannot be concatenated.
tagged with: matplotlib
tagged with: legend
accepted answer: http://stackoverflow.com/a/48484846
tagged with: python
has title: Matplotlib: how to show legend for bar chart and line on 2 separate axes?
type: Question
upvote count: 4
tagged with: multiple-axes
answer count: 2
possible better answer: http://stackoverflow.com/a/77125977
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/77125977

http://stackoverflow.com/a/48486557
downvote count: 1
has comment: http://stackoverflow.com/comment/112507295
answers question: http://stackoverflow.com/q/48483348
score: 213
has comment: http://stackoverflow.com/comment/83994753
has comment: http://stackoverflow.com/comment/133799348
has comment: http://stackoverflow.com/comment/135467157
has comment: http://stackoverflow.com/comment/112503214
upvote count: 214
has comment: http://stackoverflow.com/comment/135469748
has comment: http://stackoverflow.com/comment/134444136
type: Answer
has body: If I'm not mistaken you're searching for asyncio.Semaphore. Example of usage: import asyncio from random import randint async def download(code): wait_time = randint(1, 3) print('downloading {} will take {} second(s)'.format(code, wait_time)) await asyncio.sleep(wait_time) # I/O, context will switch to main function print('downloaded {}'.format(code)) sem = asyncio.Semaphore(3) async def safe_download(i): async with sem: # semaphore limits num of simultaneous downloads return await download(i) async def main(): tasks = [ asyncio.ensure_future(safe_download(i)) # creating task starts coroutine for i in range(9) ] await asyncio.gather(*tasks) # await moment all downloads done if __name__ == '__main__': loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() Output: downloading 0 will take 3 second(s) downloading 1 will take 3 second(s) downloading 2 will take 1 second(s) downloaded 2 downloading 3 will take 3 second(s) downloaded 1 downloaded 0 downloading 4 will take 2 second(s) downloading 5 will take 1 second(s) downloaded 5 downloaded 3 downloading 6 will take 3 second(s) downloading 7 will take 1 second(s) downloaded 4 downloading 8 will take 2 second(s) downloaded 7 downloaded 8 downloaded 6 An example of async downloading with aiohttp can be found here. Note that aiohttp has a Semaphore equivalent built in, which you can see an example of here. It has a default limit of 100 connections.
has comment: http://stackoverflow.com/comment/97216698
has comment: http://stackoverflow.com/comment/83991539

http://stackoverflow.com/a/48388461
score: 8
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48372537
downvote count: 0
answers question: http://stackoverflow.com/q/48372537
upvote count: 8
has body: I've got a basic implementation of your code to run, using the inner struct as per your design. For brevity I've only included the relevant details for MarkerDetector and Params but it should match what you've done. The c++ code: #include &lt;pybind11/pybind11.h&gt; namespace py = pybind11; enum MarkerType { chessboard, tag }; class MarkerDetector { public: MarkerDetector() { } struct Params { int rows; int cols; static Params create(MarkerType markerType) { static Params markerTypes[] = { { 1, 2 }, { 3, 4 } }; return markerTypes[markerType]; } }; }; PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example"; // optional module docstring py::enum_&lt;MarkerType&gt;(m, "MarkerType") .value("chessboard", MarkerType::chessboard) .value("tag", MarkerType::tag) .export_values(); py::class_&lt;MarkerDetector&gt;(m, "MarkerDetector") .def(py::init&lt;&gt;()) ; py::class_&lt;MarkerDetector::Params&gt;(m, "MarkerDetectorParams") .def(py::init&lt;&gt;()) .def_readwrite("rows", &amp;MarkerDetector::Params::rows) .def_readwrite("cols", &amp;MarkerDetector::Params::cols) .def("create", (MarkerDetector::Params (*)(MarkerType)) &amp;MarkerDetector::Params::create) ; } (If you're interested, the command line to compile the above:) c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` -L /usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/ -lpython3.6 The python code: import sys sys.path.append('/Volumes/Programs/workspaces/workspace 1/Project CPP 2') import example mtype = example.MarkerType.chessboard print (mtype) x = example.MarkerDetectorParams.create(example.MarkerType.chessboard) print (x) print (x.rows) print (x.cols) y = example.MarkerDetectorParams.create(example.MarkerType.tag) print (y) print (y.rows) print (y.cols) This gives the following output, which appears correct as per the design: MarkerType.chessboard &lt;example.MarkerDetectorParams object at 0x1043e35a8&gt; 1 2…
type: Answer

http://stackoverflow.com/comment/84664188
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48811014
has text: Thanks Eric, I will test this and will reply you

http://stackoverflow.com/comment/83833260
has text: Sure, what are inputs of function?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48421664
type: Comment

http://stackoverflow.com/q/48480259
accepted answer: http://stackoverflow.com/a/48480415
has body: I have a numpy array of shape (6,5) and i am trying to index it with Boolean arrays. I slice the boolean array along the columns and then use that slice to index the original array, everything is fine, however as soon as i do the same thing along the rows i get the below error. Below is my code, array([[73, 20, 49, 56, 64], [18, 66, 64, 45, 67], [27, 83, 71, 85, 61], [78, 74, 38, 42, 17], [26, 18, 71, 27, 29], [41, 16, 17, 24, 75]]) bool = a &gt; 50 bool array([[ True, False, False, True, True], [False, True, True, False, True], [False, True, True, True, True], [ True, True, False, False, False], [False, False, True, False, False], [False, False, False, False, True]], dtype=bool) cols = bool[:,3] # returns values from 3rd column for every row cols array([ True, False, True, False, False, False], dtype=bool) a[cols] array([[73, 20, 49, 56, 64], [27, 83, 71, 85, 61]]) rows = bool[3,] # returns 3rd row for every column rows array([ True, True, False, False, False], dtype=bool) a[rows] IndexError Traceback (most recent call last) &lt;ipython-input-24-5a0658ebcfdb&gt; in &lt;module&gt;() ----&gt; 1 a[rows] IndexError: boolean index did not match indexed array along dimension 0; dimension is 6 but corresponding boolean dimension is 5
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48480415
type: Question
upvote count: 2
tagged with: numpy
has title: Numpy - Indexing with Boolean array
answer count: 1
has comment: http://stackoverflow.com/comment/83953491
downvote count: 1

http://stackoverflow.com/comment/83817060
type: AnswerComment
comment on: http://stackoverflow.com/a/48413437
type: Comment
has text: Its not running because you are using `float`s as arguments instead of `int`s. You either have to turn those floats into ints, or use a custom class with your own `.line()` method that accepts floats.
score: 0

eval
tag name: eval
tags question: http://stackoverflow.com/q/48343268
type: Tag
tags question: http://stackoverflow.com/q/48358723

http://stackoverflow.com/comment/83767043
comment on: http://stackoverflow.com/q/48377577
score: 0
has text: Please provide a [mcve]. It is hard to understand your question without it, and makes it unlikely to be helpful anyone but you.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83671704
comment on: http://stackoverflow.com/q/48342671
has text: @Kevin The accepted answer from your link does not work here. The reported length for the strings match the result of len()
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48345573
tagged with: sql
has comment: http://stackoverflow.com/comment/83680606
has body: I have a sqlalchamy query and an SQL query which I think are identical but return different results. Is there something I am missing about sqlalchemy? sqlalchemy code: session.query(Table1)\ .join(Table2)\ .join(Table3)\ .filter(Table3.data == X)\ .filter(Table1.other_data == Y)\ .all() SQL query: select Table1.* from Table1 join Table2 on Table2.table1_id = Table1.id join Table3 on Table2.id = Table3.table2_id where Table3.data = X and Table1.other_data = Y; Table2 has foreign key in Table1 and Table3 has foreign in table Table2 so sqlalchemy should be able to join them nicely. Table3 has no foreign key from Table1. The sqlalchemy code returns 1 result while the SQL returns 3 duplicates so my question is: Is sqlalchemy doing something I don't know?
has comment: http://stackoverflow.com/comment/83681648
tagged with: sqlalchemy
has title: Is sqlalchemy filtering duplicates?
has comment: http://stackoverflow.com/comment/83681432
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0

http://stackoverflow.com/q/48382873
tagged with: filtering
tagged with: algorithm
tagged with: perceptron
accepted answer: http://stackoverflow.com/a/48451376
has body: I am trying to implement an adaptive filter for noise cancellation, in particular a RLS filter to remove motion artifacts from a signal. To do this I am reading some literature, there is one thing I don't understand and every book or article I found just asumes I already now this. I have a reference signal represented as a list in Python of about 8000 elements, or samples. I need to input this to the RLS filter, but every algorithm I find always talks about the input vector as X[n] = [x1[n], x2[n], x3[n], ........, xM[n]]T Where X is the input vector, and n is a time instant. And here is where I get lost. If n is a time instant, it would mean x[n] is an element in the list, a salmple. But if that is the case, what are x1, x2, ...., xM???. I realise this is not strictly a coding problem, but I hope someone can help! Thanks...
has comment: http://stackoverflow.com/comment/83759338
has answer: http://stackoverflow.com/a/48451376
tagged with: python
has title: Adaptive Filter input vectors and iteration
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/83875863
type: Question

http://stackoverflow.com/q/48333798
upvote count: 1
has body: I have been working on an assignment for a Computer Science 30 course. In this assignment I have been asked to access a API and return a specific value that is not just the whole dictionary. My problem is that I can't seem to print the value I want because it is a string and not a integer or a slice. Here is my full code for you if you decide to offer me assistance. Thank You for your time. import requests import urllib.parse # set up a temporary copy of the google api temp = "https://maps.googleapis.com/maps/api/directions/json? origin=Disneyland&amp;destination=Universal+Studios+Hollywood4" # set up the main API and the origin and destination inputs from the user main_api = "https://maps.googleapis.com/maps/api/directions/json?" origin = str(input("Enter in the place that is you are going away from: ")) destination = str(input("Enter the destination that you would like to reach: ")) # set up the url from the main api, the origin, and the destination url = main_api + urllib.parse.urlencode({"origin": origin, "destination": destination}) # print the url back to the user print(url) # show the user the distance between the origin and the destination json_data = requests.get(url).json() print(json_data['routes']['legs']['distance']['text'])
has answer: http://stackoverflow.com/a/48333840
favorite count: 0
type: Question
has title: How do I access a value from a dictionary within a dictionary that is a string
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: api
score: 1
has comment: http://stackoverflow.com/comment/83653046
accepted answer: http://stackoverflow.com/a/48333840
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/10399614

http://stackoverflow.com/comment/83723724
has text: Why no `zip` .. ?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48368430
type: Comment

http://stackoverflow.com/q/48436769
type: UnansweredQuestion
score: 0
linked to: http://stackoverflow.com/q/16720541
has title: Zapier Python or Javascript Code for Twitter HTML
type: Question
has body: I'm using Zapier to run a search on Twitter, create a daily digest of results (Zapier Digest), and send the digest to a mailing list (Mailgun). I seek to format the Tweets similar to Twitter's own emails where the tweet isn't text but HTML where any user mention (@name, corresponding URL is https://twitter.com/[NAME]) and URL in the tweet are actual links. (I don't want the conversion for any hashtags.) This search, extract, and replace (with added HTML) isn't that hard. But it's too much for Zapier's simple Formatter text functions. So I turned to the Zapier Code action, thinking I could borrow code as I'm not a hardcore coder. I found Python code as below (and others at that site). After a couple hours of testing I've given up on being able to successfully adapt it for use in Zapier Code. Zapier has limitations on how it uses Python. Their documentation on it is primitive. Could someone here familiar with Zapier help me with converting that (or similar) code so I could run it on Zapier Python or Javascript? I truly would appreciate it. Thank you, Marc https://coderwall.com/p/wdtkhw/convert-links-username-mentions-and-hashtags-in-a-tweet function twitterify($ret) { $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1\\2", $ret); $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1\\2", $ret); $ret = preg_replace("/@(\w+)/", "@\\1", $ret); $ret = preg_replace("/#(\w+)/", "#\\1", $ret); return $ret; }
linked to: http://stackoverflow.com/q/3070655
has answer: http://stackoverflow.com/a/48471831
tagged with: javascript
tagged with: python
tagged with: twitter
tagged with: zapier
has answer: http://stackoverflow.com/a/48474251
answer count: 2

http://stackoverflow.com/q/48481041
has body: So I have a couple classes that share common attributes class Person(object): def __init__(self, name, age, income): self.name = name self.age = age self.income = income class Pet(object): def __init__(self, name, age): self.name = name self.age = age I want to make a superclass for these objects class Animal(object): ... So that I can refer to this type in functions and get type hints from my IDE def f(x: Animal): x.name&lt;tab&gt; # I expect to see that this thing is a string type Or have nice static analysis from projects like mypy. What is the best way for me to write my classes to achieve this behavior?
score: 0
has comment: http://stackoverflow.com/comment/83955097
upvote count: 1
tagged with: type-hinting
answer count: 1
downvote count: 1
has title: Build type information about attributes into superclass for type hinting
has answer: http://stackoverflow.com/a/48481359
favorite count: 0
type: Question
tagged with: mypy
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83955333

http://stackoverflow.com/comment/83803605
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48393242
score: 0
has text: I found examples here are more comprehensive http://blog.vero4ka.info/blog/2016/10/26/how-to-send-an-email-with-attachment-via-amazon-ses-in-python/

http://stackoverflow.com/comment/83810971
score: 0
type: Comment
type: QuestionComment
has text: @StevenRumbalski but when you append a character it adds that character into a list right?
comment on: http://stackoverflow.com/q/48410563

http://stackoverflow.com/a/48349761
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48348714
upvote count: 1
type: AcceptedAnswer
has body: The issue is that endtextand againbutton are not declared on the first call of homeScreen() Add this function below endscreen() to delete the attributes. def clearEnd(): global endtext, againbutton endtext.destroy() againbutton.destroy() homescreen() To give: from tkinter import * def homeScreen() successlogin=label(window, text=("You are logged in as: " + Username) global startquiz startquiz=Button(window, text="Start Quiz", command=quiz) startquiz.grid(column=1, row=4) def quiz(): global startquiz startquiz.destroy() #Display questions and check answers etc. etc. endscreen() #On completion of quiz def endScreen() global endtext, againbutton endtext=Label(window, text="quiz complete") endtext.grid(column=1, row=1) againbutton=Button(window, text="again", command=homescreen) againbutton.grid(column=1, row=2) def clearEnd(): global endtext, againbutton endtext.destroy() againbutton.destroy() homescreen()
answers question: http://stackoverflow.com/q/48348714
score: 1

http://stackoverflow.com/a/48375626
type: AcceptedAnswer
downvote count: 0
has body: You might want to check out the in keyword, since it seems like what youre going for. Here's a quick example: &gt;&gt;&gt; word = "some" &gt;&gt;&gt; sentence = "This is a sentence with some words." &gt;&gt;&gt; word in sentence True Since you don't want it to match partial words, you could remove all non-alphabetic characters, then split your string: &gt;&gt;&gt; sentence = ''.join(char for char in sentence if char.isalpha() or char.isspace()).split() &gt;&gt;&gt; "words" in sentence True &gt;&gt;&gt; "word" in sentence False Honestly though, I would just use regex for this.
accepted answer of: http://stackoverflow.com/q/48375511
has comment: http://stackoverflow.com/comment/83738371
score: 5
has comment: http://stackoverflow.com/comment/83738884
upvote count: 5
answers question: http://stackoverflow.com/q/48375511
type: Answer
has comment: http://stackoverflow.com/comment/83738298

http://stackoverflow.com/comment/83915010
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48451459
type: QuestionComment
has text: I've deleted my previous message about cmds.attrControlGrp(), cmds.attrFieldGrp() because it is beginning to make lots of posts xd. It could work fine but instead of updating attr value on selection, you would have rebuild the ui on selection change. It's a different approach.

http://stackoverflow.com/comment/84061895
comment on: http://stackoverflow.com/q/48454604
type: QuestionComment
has text: I want to do the same thing except my curve should be strictly beneath the original, and track it as closely as possible when not smoothing. The concept I have in mind is to roll a virtual circle along the curve and keep only the maximum points that the circle touches, so on slowly-changing curves it will hug them closely, but at tight notches it will force a minimum radius to the corner.
type: Comment
score: 0

http://stackoverflow.com/comment/96998009
type: AnswerComment
comment on: http://stackoverflow.com/a/48348006
score: 6
type: Comment
has text: For whatever reason, the line above kept throwing errors like `TypeError: diff() got an unexpected keyword argument 'axis'`. However this worked: `df.groupby(['site', 'country'])['score'].transform(pd.Series.diff).fillna(0)`.

http://stackoverflow.com/comment/84170403
comment on: http://stackoverflow.com/q/48464565
type: QuestionComment
has text: @Darkonaut, MAC OS and linux
score: 0
type: Comment

http://stackoverflow.com/a/48421523
upvote count: 1
type: Answer
score: 1
has body: You can do like this: P = [] for i in range(1, processes + 1): hup = MyURLParser() //A class I made p = Process(target = hup.run) p.start() P.append(p) for p in P: p.join() To only check if the process is alive, use .is_alive() Read more here: https://docs.python.org/3/library/multiprocessing.html
answers question: http://stackoverflow.com/q/48421426
downvote count: 0

librosa
tags question: http://stackoverflow.com/q/48388641
tag name: librosa
tags question: http://stackoverflow.com/q/48333516
type: Tag

http://stackoverflow.com/a/55778411
score: 3
type: Answer
has body: One Solution is: import os os.environ['NUMBAPRO_NVVM'] = r'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\bin\nvvm64_31_0.dll' os.environ['NUMBAPRO_LIBDEVICE'] = r'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\nvvm\libdevice' Or if you are using PyCharm GO TO RUN > Edit Configuration export NUMBAPRO_NVVM=/usr/local/cuda-{cuda version}/nvvm/lib64/libnvvm.so export NUMBAPRO_LIBDEVICE=/usr/local/cuda-{cuda version}/nvvm/libdevice/
upvote count: 4
answers question: http://stackoverflow.com/q/48385686
downvote count: 1

http://stackoverflow.com/comment/83791975
comment on: http://stackoverflow.com/a/48401542
score: 0
type: Comment
has text: Have you tried this: https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Mac-OSX
type: AnswerComment

http://stackoverflow.com/comment/83657004
comment on: http://stackoverflow.com/a/48335627
has text: @pyd But with `df["Data"]` you're still hardcoding the column name?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48458411
type: Answer
answers question: http://stackoverflow.com/q/48458322
has comment: http://stackoverflow.com/comment/83909780
downvote count: 0
has comment: http://stackoverflow.com/comment/83910415
upvote count: 10
has comment: http://stackoverflow.com/comment/83909876
has body: The linked answer appears to be completely wrong. The g object is for storing global data from one function to another within the same request, and is not at all for sharing data between requests. For that you need sessions: from flask import Flask, session @home.route('/save', methods=['GET']) def save_ressource(): an_object = {'key': 'value'} session['an_object'] = an_object return 'sucees' @home.route('/read', methods=['GET']) def read_ressource(): an_object = session.get('an_object') if an_object: return 'sucess' else: return 'failure'
has comment: http://stackoverflow.com/comment/97061498
type: AcceptedAnswer
score: 10
has comment: http://stackoverflow.com/comment/95483118
accepted answer of: http://stackoverflow.com/q/48458322

http://stackoverflow.com/a/48447512
score: 0
has comment: http://stackoverflow.com/comment/83909655
answers question: http://stackoverflow.com/q/48410192
type: Answer
has body: I finally found out what was going on. It seems that the scanner confuses two files of the same name in different django apps because each app was configured as "cover-package" in django settings for django-nose. Apparently django-nose treats all packet root files as a single module ". /" and if there is a repeated file (example: admin.py) only reads one but when you pass the data to the python scanner, it tries to read another one and if they both have different lines it throws the conflict, and I imagine that if they happen to have the same lines, the representation in sonar covered code vs. lines, would also be wrong. Coverage file generated by django-nose before change: <?xml version="1.0" ?> <coverage branch-rate="0" branches-covered="0" branches-valid="0" complexity="0" line-rate="0.5905" lines-covered="1142" lines-valid="1934" timestamp="1516895775536" version="4.4.2"> /home/jvallina/PycharmProjects/nana_project/app_administrador /home/jvallina/PycharmProjects/nana_project/app_cliente /home/jvallina/PycharmProjects/nana_project/app_gestor_de_citas /home/jvallina/PycharmProjects/nana_project/app_nana /home/jvallina/PycharmProjects/nana_project/app_test /home/jvallina/PycharmProjects/nana_project/nucleo <packages> <methods/> <methods/> <line hits="0" number="1"/> ... <line hits="0" number="238"/> Then we have to replace it (django settings): NOSE_ARGS = [ '--with-coverage', '--cover-package=app_administrador,app_cliente,app_nana,app_test,app_gestor_de_citas,nucleo', '--cover-erase', '--cover-xml', '--with-xunit', '--xunit-file=xmlrunner/nosetests.xml', '--cover-xml-file=xmlrunner/coverage.xml' ] with that: NOSE_ARGS = [ '--with-coverage', '--cover-package=.', '--cover-erase', '--cover-xml', '--with-xunit', '--xunit-file=xmlrunner/nosetests.xml', '--cover-xml-file=xmlrunner/coverage.xml' ] Coverage file after the change: We can see that each file repeated in the modules is already differentiated by its source app. <?xml version="1.0" ?> <coverage branch-rate="0"…

http://stackoverflow.com/q/48441382
has comment: http://stackoverflow.com/comment/83874371
tagged with: python
has answer: http://stackoverflow.com/a/48441455
has comment: http://stackoverflow.com/comment/83873905
tagged with: int
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83873878
score: 0
has title: python converting strings in list to ints and floats
tagged with: list
answer count: 2
upvote count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/48467258
possible better answer: http://stackoverflow.com/a/48467258
accepted answer: http://stackoverflow.com/a/48441455
tagged with: string
favorite count: 0
type: Question
has body: If I were to have the following list: lst = ['3', '7', 'foo', '2.6', 'bar', '8.9'] how would I convert all possible items into either ints or floats accordingly, to get lst = [3, 7, 'foo', 2.6, 'bar', 8.9] thanks in advance.

http://stackoverflow.com/q/48407377
has answer: http://stackoverflow.com/a/48408236
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/83885635
has body: I wanted to ask if there was an easy way to visualize a Keras model built from the Functional API? Right now, the best ways to debug at a high level a sequential model for me is: model = Sequential() model.add(... ... print(model.summary()) SVG(model_to_dot(model).create(prog='dot', format='svg')) However, I am having a hard time finding a good way to visualize the Keras API if we build a more complex, non-sequential model.
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/48408865
accepted answer: http://stackoverflow.com/a/48408236
has answer: http://stackoverflow.com/a/48408865
has answer: http://stackoverflow.com/a/61817167
tagged with: python
tagged with: graph-visualization
score: 4
type: AnsweredQuestion
answer count: 3
has title: Keras Visualization of Model Built from Functional API

http://stackoverflow.com/q/48456348
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48457473
has answer: http://stackoverflow.com/a/48457473
tagged with: pandas
type: AnsweredQuestion
score: 0
answer count: 1
has body: I have a Pandas data frame with some categorical variables. Something like this - &gt;&gt;df 'a', 'x' 'a', 'y' Now, I want to return a matrix with the conditional probabilities of each level appearing with every other level. For the data frame above, it would look like - [1, 0.5, 0.5], [1, 1, 0], [1, 0, 1] The three entries correspond to the levels 'a', 'x' and 'y'. This is because conditional on the first column being 'a', the probabilities of 'x' and 'y' appearing are 0.5 each and so on. I have some code that does this (below). However, the problem is that it is excruciatingly slow. So slow that the application I want to use it in times out. Does anyone have any tips to make it faster? df = pd.read_csv('pathToData.csv') df = df.fillna("null") cols = 0 col_levels = [] columns = {} num = 0 for i in df.columns: cols += len(set(df[i])) col_levels.append(np.sort(list(set(df[i])))) for j in np.sort(list(set(df[i]))): columns[i + '_' + str(j)] = num num += 1 res = np.eye(cols) for i in range(len(df.columns)): for j in range(len(df.columns)): if i != j: row_feature = df.columns[i] col_feature = df.columns[j] rowLevels = col_levels[i] colLevels = col_levels[j] for ii in rowLevels: for jj in colLevels: frst = (df[row_feature] == ii) * 1 scnd = (df[col_feature] == jj) * 1 prob = sum(frst*scnd)/(sum(frst) + 1e-9) frst_ind = columns[row_feature + '_' + ii] scnd_ind = columns[col_feature + '_' + jj] res[frst_ind, scnd_ind] = prob EDIT: Here is a bigger example: &gt;&gt;df 'a', 'x', 'l' 'a', 'y', 'l' 'b', 'x', 'l' The number of distinct categories here are 'a', 'b', 'x', 'y' and 'l'. Since these are 5 categories, the output matrix should be 5x5. The first row and first column would be how often does 'a' appear conditional on 'a'. This is of course, 1 (as are all the diagonals). The first row and second column is conditional on 'a', what is the probability of 'b'. Since 'a' and 'b' are parts of the same column, this is zero. The first row and third column is the probability of 'x…
tagged with: statistics
tagged with: performance
type: Question
has comment: http://stackoverflow.com/comment/83905871
tagged with: python
has title: Python getting conditional probabilities of all feature combinations in pandas dataframe
has comment: http://stackoverflow.com/comment/83906052

http://stackoverflow.com/q/48450936
answer count: 2
has body: I'd like to create a REST API for an object which can be partially updated. On http://www.django-rest-framework.org/api-guide/serializers/#partial-updates and example is given in which partial=True is passed when instantiating the serializer: # Update `comment` with partial data serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) In my case, however, the model (which is called SessionType) has the following viewset: class SessionTypeViewSet(viewsets.ModelViewSet): queryset = SessionType.objects.all() serializer_class = SessionTypeSerializer where the serializer is defined as class SessionTypeSerializer(serializers.ModelSerializer): class Meta: model = SessionType fields = ('title',) How can I adapt the serializer in this use case so that partial is always True?
downvote count: 0
score: 6
tagged with: django
tagged with: python
tagged with: django-rest-framework
upvote count: 6
possible better answer: http://stackoverflow.com/a/48451922
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48451922
has title: In the Django REST framework, how to allow partial updates when using a ModeViewSet?
accepted answer: http://stackoverflow.com/a/48452039
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48452039

http://stackoverflow.com/comment/83936443
has text: Move base_analysis.py up a level or use the full path
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48471252
score: 0

variable-assignment
tags question: http://stackoverflow.com/q/48353415
tags question: http://stackoverflow.com/q/48465510
type: Tag
tags question: http://stackoverflow.com/q/48426093
tag name: variable-assignment
tags question: http://stackoverflow.com/q/48347547
tags question: http://stackoverflow.com/q/48374664

http://stackoverflow.com/comment/83750008
has text: Read the first line of my answer: `At least for this image ...`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48356640

http://stackoverflow.com/comment/83963860
type: Comment
has text: @ayhan: The docs say `agg()` accepts "dict of column names -> functions (or list of functions)" but does not say that a list of 2-tuples is an acceptable substitute. Nor does it say that using a dict now results in a deprecation warning. But I know that many things in NumPy/Pandas which could use a dict can also use a list of (name, value) tuples. So I tried it and it worked. So no, it's not documented. :)
type: AnswerComment
score: 5
comment on: http://stackoverflow.com/a/48485284

http://stackoverflow.com/comment/83768594
comment on: http://stackoverflow.com/a/48389946
type: AnswerComment
has text: You may use `ax.invert_yaxis()` to invert the axis, instead of plotting the reversed lists (`[::-1]`), this might make it easier to change e.g. between `barh` and `bar`.
score: 0
type: Comment

http://stackoverflow.com/comment/83774588
type: AnswerComment
comment on: http://stackoverflow.com/a/48393385
score: 1
has text: @sfjac Sorry, forgot to add the important bit in ;)
type: Comment

http://stackoverflow.com/q/48404971
has answer: http://stackoverflow.com/a/48405534
possible better answer: http://stackoverflow.com/a/48405135
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/83798865
has body: I've been following this answer: Python sort a JSON list by two key values I want to adapt this to my case: [ {'score': 0.1, 'id': 1, 'flag': true}, {'score': 0.234, 'id': 2, 'flag': false}, {'score': 0.4, 'id': 3, 'flag': false} ] I need a sorting by flag(boolean) and score(float) kind of like the ones you do in SQL. In this case the result would be: [ {'score': 0.1, 'id': 1, 'flag': true}, // first because the flag is true {'score': 0.4, 'id': 3, 'flag': false} //second because the score is higher {'score': 0.234, 'id': 2, 'flag': false}, ] I am trying to use sorted_result = sorted(json, key=lambda k: (bool(k['flag']), -float(k['score']))) but it doesn't sort as expected
linked to: http://stackoverflow.com/q/28491289
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83799022
has title: Python sorting json list by 2 key values of different types
has comment: http://stackoverflow.com/comment/83798617
has answer: http://stackoverflow.com/a/48405135
has answer: http://stackoverflow.com/a/65346144
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83798563
tagged with: python
accepted answer: http://stackoverflow.com/a/48405534
has comment: http://stackoverflow.com/comment/83798636
score: -1

http://stackoverflow.com/q/48362611
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83712448
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48362700
accepted answer: http://stackoverflow.com/a/48362700
has answer: http://stackoverflow.com/a/48362632
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48362664
possible better answer: http://stackoverflow.com/a/48362664
has body: If I run file = open("BAL.txt","w") I = '200' file.write(I) file.close from a script, it outputs nothing in the file. (It literally overwrites the file with nothing) Furthermore, running cat BAL.txt just goes to the next line like nothing is in the file. But if I run it line by line in a python console it works perfectly fine. Why does this happen. ( I am a begginner learning python the mistake may be super obvious. I have thrown about 2 hours into trying to figure this out) Thanks in advance
has title: Python writing data to file only works when run from console
has comment: http://stackoverflow.com/comment/83712122
has comment: http://stackoverflow.com/comment/83713318

http://stackoverflow.com/comment/83887917
type: Comment
type: QuestionComment
has text: have look at this [answer](https://stackoverflow.com/a/7366731/5949840), i think this is similar to your query.
comment on: http://stackoverflow.com/q/48447369
score: 0

http://stackoverflow.com/q/48446513
has answer: http://stackoverflow.com/a/48446602
type: Question
has title: Update value of variable in a list - Python
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48446686
has comment: http://stackoverflow.com/comment/83885302
linked to: http://stackoverflow.com/q/11222440
has comment: http://stackoverflow.com/comment/83885172
has comment: http://stackoverflow.com/comment/83885378
has comment: http://stackoverflow.com/comment/83885072
score: 0
has comment: http://stackoverflow.com/comment/83885585
answer count: 2
upvote count: 1
downvote count: 1
has body: Developing a project I found a curious bug in Python. For example : #Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32 variable = "Hello_1" list = ["This is a variable -&gt; ",variable] print list #-&gt; ["This is a variable -&gt; " , "Hello_1"] Now, I modify variable to a new value. So, I think when change the value of variable, I will see the new value in the list variable = "Hello_2" print list #-&gt; ["This is a variable -&gt; " , "Hello_1"] But, the output is the same that first time? Does anybody know how to solve it?
linked to: http://stackoverflow.com/q/24804453
linked to: http://stackoverflow.com/q/2123925
has comment: http://stackoverflow.com/comment/83885075
favorite count: 0

http://stackoverflow.com/comment/83771511
type: Comment
has text: Do you know the answers to the questions asked in chat?
comment on: http://stackoverflow.com/a/48385917
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83691693
has text: It works in my console, but I inherit from `object`... it might be because `wx.Frame` is an old-style class
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48352342
type: Comment

http://stackoverflow.com/comment/83736218
comment on: http://stackoverflow.com/q/48373118
has text: I will check that! Thank you!
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83952583
score: 0
type: AnswerComment
type: Comment
has text: Thanks I don't know how I miss this.
comment on: http://stackoverflow.com/a/48479820

http://stackoverflow.com/a/57576078
answers question: http://stackoverflow.com/q/48416385
score: 2
type: Answer
has body: I had the same problem as you and the solution was nowhere to be found. Then I read this and I have figured out a way. Change the initialization of both your SparkSession objects, to: from os.path import abspath warehouse_location = abspath('spark-warehouse') spark = SparkSession.builder \ .config("spark.sql.warehouse.dir", warehouse_location) \ .enableHiveSupport() \ .getOrCreate() This initialization, explicitly instructs Spark where to look for the Hive tables and also enables Hive support. You can change the location of the Hive tables (i.e spark-warehouse) if you want to, by changing the argument inside the abspath() function. P.S: I don't know why one needs to explicitly enable Hive support since by default, saveAsTable() saves the dataframe to Hive table nor do I know why does someone need to explicitly define spark-warehouse location since the default location is the current directory. Nevertheless, the above solution just works :) (is it a bug?)
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83839696
type: Comment
score: 0
has text: what is your question here? Is it to find a `x,y` pair where the sum of `x+y<23`?
type: QuestionComment
comment on: http://stackoverflow.com/q/48424428

http://stackoverflow.com/q/48373550
has answer: http://stackoverflow.com/a/48373899
has title: Pandas/Numpy Changed File Type Read in Now Get Calculation Error
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: I was reading in an Excel file with Pandas, extracting a Numpy array from 2 sets of 9 columns, and creating a complex number array for doing complex number matrix multiplication. The original data is just decimal values, but depending on the column the values come from decides whether they are real or imaginary. I originally wrote the code reading from and Excel file as an xlsx. Then I changed it to a csv file source, I get the same individual 3X3 matrix in both cases which I am combining into a complex matrix. When I run the code, I get the following error. TypeError Traceback (most recent call last) &lt;ipython-input-107-e87255037c7f&gt; in &lt;module&gt;() 11 while counter &lt; count_net_r: 12 n = counter # int ---&gt; 13 net = (net_r[n] + 1.0j * net_x[n]) 14 counter = counter + 1 15 net_seq.append(net) TypeError: can't multiply sequence by non-int of type 'complex' My code for readin in the file: df = pd.read_csv('Report.csv') # uses Pandas .loc to extract and create the network equivalent R per phase components into an array # for multiplication to calculate the sequence matrix - REAL Part r = df.loc[df['Code\n'] == 'Network Equivalent', 'NetEq Z R AA':'NetEq Z R CC'] rr = r.shape[0] net_r = r.values.reshape(rr,3,3) # uses Pandas .loc to extract and create the network equivalent X per phase components into an array # for multiplication to calculate the sequence matrix - COMPLEX Part x = df.loc[df['Code\n'] == 'Network Equivalent', 'NetEq Z X AA':'NetEq Z X CC'] xx = x.shape[0] net_x = x.values.reshape(xx,3,3) # loop to concatenate the R &amp; X into one array of complex numbers # if the R and X matrices are of unequal lengths then prints unequal length so it can be solved and attempted again count_net_r = len(net_r) # int count_net_x = len(net_x) # int net = [] # list net_seq = [] # list counter = 0 if count_net_r != count_net_x: print('Network Equivalent matrices are not equivalent') else: while counter &lt; count_net_r: n = counter # int net = (net_r[n] + 1.0…
tagged with: arrays
tagged with: python
score: 0
tagged with: matrix
answer count: 1
tagged with: complex-numbers

http://stackoverflow.com/q/48452274
has answer: http://stackoverflow.com/a/48742150
accepted answer: http://stackoverflow.com/a/48742150
has title: How to create a pandas dataframe from a file with no common separator?
type: Question
tagged with: numpy
answer count: 2
has body: I have routing table data that looks something like this: Valid Network Next-Hop Path Protocol 0 1.0.128.0/17 80.249.208.85 3257 38040 9737 i 0 80.249.209.150 6939 4766 38040 9737 i 1 80.249.209.37 3491 38040 9737 i 0 80.249.211.42 6762 38040 9737 i 0 80.249.208.85 3257 38040 9737 i 1 80.249.209.37 3491 38040 9737 i 0 80.249.211.42 6762 38040 9737 i I want to create DataFrame with those same column names as the header and the prefix in the network column. The problem here is that not all lines have a prefix so I need to add the latest prefix (most recently seen). This is what I did: f = open('initial_data') current_prefix = None for index,line in enumerate(f): if index != 0 and index != 1058274: #ignoring first and last line if line.split(' ')[2].startswith(str(1)) or line.split(' ')[2].startswith(str(2)): current_prefix = np.asarray(line.split(' ')[2]) #storing the most recent prefix #print(current_prefix)#.shape,type(current_prefix)) df2 = pd.DataFrame(current_prefix, columns=list('Network')) df.append(df2,ignore_index = True)#current_prefix) else: pass#df['Network'].append(current_prefix) df2 = pd.DataFrame(current_prefix, columns=list('Network')) df.append(df2,ignore_index = True)#current_prefix But the prefix (eg 1.0.128.0/17) is interpreted as having 7 columns and I get this error: --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-100-f2ee3d75b5c4&gt; in &lt;module&gt;() 6 current_prefix = np.asarray(line.split(' ')[2]) 7 #print(current_prefix)#.shape,type(current_prefix)) ----&gt; 8 df2 = pd.DataFrame(current_prefix, columns=list('Network')) 9 df.append(df2,ignore_index = True)#current_prefix) AssertionError: 7 columns passed, passed data had 1 columns So is there any better/cleaner way to deal with this? To be more precise, I would like the DataFrame to look something like this: Valid | Network | Next-Hop | Path | Protocol 0 | 1.0.128.0/17 | 80.249.208.85…
downvote count: 0
upvote count: 1
tagged with: python
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48894713
possible better answer: http://stackoverflow.com/a/48894713
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/83677191
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48345740
has text: you have to return something either way. So just do `f=lambda x: x % 2 == 0`

http://stackoverflow.com/a/48494651
score: 0
answers question: http://stackoverflow.com/q/48455182
type: Answer
has body: Are the elements in each column bounded the depth of the column? If so just iterate through each column of your multi dimensional array and place the elements in their corresponding row. It is simple to do this if you allocate more memory or you can do it in place with swaps (still O(n)). You can apply more complicated grouping after the fact.

http://stackoverflow.com/q/48483652
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83970977
tagged with: charts
has body: I been working on a Pie Chart to display data based on year wise.I have tried for quite a while I am successful at achieving at slicing rows: df = pd.DataFrame(dict( Year = dates[:3], robbery = robbery[:3], fraud = fraud[:3], sexual = sexual[:3] )) fig, axes = plt.subplots(1,3, figsize=(12,8)) for ax, idx in zip(axes, df.index): ax.pie(df.loc[idx],explode=explode,shadow=True, labels=df.columns, autopct='%.2f%%') ax.set(ylabel='', title=idx, aspect='equal') axes[0].legend(bbox_to_anchor=(0, 0.5)) plt.show() but I have checked this link to display pie chart but they have worked on numpy array to achieve charts. In my scenario, I stuck on displaying all the data on pie chart with a year wise at once here is my code: import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.DataFrame(dict( robbery = robbery, fraud = fraud, assualt = sexual ), index=dates) print(df) plt.style.use('ggplot') colors = plt.rcParams['axes.color_cycle'] fig, axes = plt.subplots(nrows=2, ncols=2) for ax, col in zip(axes.flat, df.columns): ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors) ax.set(ylabel='', title=col, aspect='equal') axes[0, 0].legend(bbox_to_anchor=(0, 0.5)) fig.savefig('your_file.png') # Or whichever format you'd like plt.show() DataFrame: assualt fraud robbery 1997-1998 2988 11897 1212 1998-1999 6033 27660 2482 1999-2000 5924 28421 2418 2000-2001 5631 29539 2298 2001-2002 5875 30295 2481 2002-2003 7434 27141 1940 2003-2004 5673 27986 2053 2004-2005 5695 30070 1879 2005-2006 6099 26031 1903 2006-2007 7038 25845 1889 2007-2008 6671 21009 1736 2008-2009 6046 17768 1791 2009-2010 5496 18974 1934 2010-2011 5666 18458 1726 2011-2012 4933 14157 1748 2012-2013 4972 16849 1962 2013-2014 5328 18819 1762 2014-2015 5909 21915 1341 2015-2016 6067 21891 1354 2016-2017 6448 27390 1608 2017-2018 6355 25438 1822 1997-1998 2988 11897 1212 1998-1999 6033 27660 2482 1999-2000 5924 28421 2418 2000-2001 5631 29539 2298 2001-2002 5875 30295 2481 2002-2003 7434 2714…
tagged with: python
linked to: http://stackoverflow.com/q/34034457
has comment: http://stackoverflow.com/comment/83971015
has answer: http://stackoverflow.com/a/48493063
has title: How to Display Pie Chart Year wise in Pandas
accepted answer: http://stackoverflow.com/a/48493063
tagged with: numpy
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/a/48356407
score: 0
answers question: http://stackoverflow.com/q/48355713
has body: If you want a list, you can use list comprehension html = ''' 2002 (02 reg) Hatchback 115,000 miles Manual 1.8L 123 bhp Petrol ''' soup = BeautifulSoup(html, 'html.parser') vehicle_details = [x.text for x in soup.find('ul', {'class': 'listing-key-specs'}).find_all('li')] print(vehicle_details) Output: ['2002 (02 reg)', 'Hatchback', '115,000 miles', 'Manual', '1.8L', '123 bhp', 'Petrol'] If you want the details in a single string, you can add this vehicle_details_string = ', '.join(vehicle_details) print(vehicle_details_string) Output: 2002 (02 reg), Hatchback, 115,000 miles, Manual, 1.8L, 123 bhp, Petrol
type: Answer

http://stackoverflow.com/a/48417945
accepted answer of: http://stackoverflow.com/q/48417818
has body: On my PC: $ cat /usr/bin/pip3.6 #!/usr/bin/python ... So, I think your pip has shebang like #!/usr/local/bin/python3.6. Try rewrite or: /drive/username/Python3.6.4/bin/python3 -m ensurepip it will make correct pip in /drive/username/Python3.6.4/bin directory.
answers question: http://stackoverflow.com/q/48417818
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/48415430
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48415210
has comment: http://stackoverflow.com/comment/83821339
has body: Write an integration test: using requests or an equivalent library to call your API. If you plan to test it once, just deploy the app in another host and run the test. If you want automated testing, consider using a CI/CD pipeline. Put your API in a container, put the test code in another container, then trigger these tests when needed.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83865017
comment on: http://stackoverflow.com/q/48436019
has text: What is the problem that happens if you try your commented-out version using `read_table`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48426518
type: UnansweredQuestion
answer count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83846430
has answer: http://stackoverflow.com/a/48427931
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83846517
tagged with: python
tagged with: parsing
has body: I have this large text file that keeps on repeating like this [Event "Rated Crazyhouse game"] [Site "https://lichess.org/NsNeyqv1"] [Date "2018.01.23"] [Round "-"] [White "nikoskaterini"] [Black "Ominous"] [Result "0-1"] [UTCDate "2018.01.23"] [UTCTime "18:22:39"] [WhiteElo "1611"] [BlackElo "2118"] [WhiteRatingDiff "-10"] [BlackRatingDiff "+2"] [Variant "Crazyhouse"] [TimeControl "30+0"] [ECO "?"] [Opening "?"] [Termination "Normal"] 1. d4 { [%clk 0:00:30] } d5 { [%clk 0:00:30] } 2. Bf4 { [%clk 0:00:27] } Nc6 { [%clk 0:00:30] } 3. e3 { [%clk 0:00:26] } Nf6 { [%clk 0:00:30] } 4. Bd3 { [%clk 0:00:25] } Bg4 { [%clk 0:00:30] } 5. c3 { [%clk 0:00:25] } Bxd1 { [%clk 0:00:29] } 6. Kxd1 { [%clk 0:00:24] } e6 { [%clk 0:00:28] } 7. Nd2 { [%clk 0:00:23] } Bd6 { [%clk 0:00:28] } 8. Bxd6 { [%clk 0:00:21] } cxd6 { [%clk 0:00:28] } 9. Ngf3 { [%clk 0:00:19] } O-O { [%clk 0:00:27] } 10. Ng5 { [%clk 0:00:17] } B@e4 { [%clk 0:00:27] } 11. Bxe4 { [%clk 0:00:14] } dxe4 { [%clk 0:00:27] } 12. B@e2 { [%clk 0:00:11] } B@f5 { [%clk 0:00:27] } 13. Nh3 { [%clk 0:00:08] } Bxh3 { [%clk 0:00:24] } 14. gxh3 { [%clk 0:00:08] } N@d3 { [%clk 0:00:23] } 15. Rg1 { [%clk 0:00:08] } Nxf2+ { [%clk 0:00:22] } 16. Ke1 { [%clk 0:00:06] } Nd3+ { [%clk 0:00:22] } 17. Bxd3 { [%clk 0:00:05] } exd3 { [%clk 0:00:20] } 18. B@h6 { [%clk 0:00:04] } Q@e2# { [%clk 0:00:18] } 0-1 [Event "Rated Crazyhouse game"] [Site "https://lichess.org/0r8jJe5d"] [Date "2018.01.23"] [Round "-"] [White "RefuteMeThisWaste"] [Black "Ominous"] [Result "0-1"] [UTCDate "2018.01.23"] [UTCTime "15:51:19"] [WhiteElo "1718"] [BlackElo "2115"] [WhiteRatingDiff "-23"] [BlackRatingDiff "+3"] [Variant "Crazyhouse"] [TimeControl "300+0"] [ECO "?"] [Opening "?"] [Termination "Time forfeit"] 1. e4 { [%clk 0:05:00] } e5 { [%clk 0:05:00] } 2. Bc4 { [%clk 0:04:58] } Bc5 { [%clk 0:04:58] } 3. Nf3 { [%clk 0:04:50] } Nc6 { [%clk 0:04:56] } 4. Bxf7+ { [%clk 0:04:42] } Kxf7 { [%clk 0:04:55] } 5. d4 { [%clk 0:04:37] } Bxd4 { [%clk 0:04:53] } 6. Ng5+ { [%clk …
has title: Parse a txt file into a csv

http://stackoverflow.com/comment/84058429
comment on: http://stackoverflow.com/a/48504114
has text: @camel_case I made a few changes to make the code a little bit more readable
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83719799
type: AnswerComment
has text: Thanks a lot you for your answer. I have implemented your approach, but this unfortunately does not yield the correct equation. Please see updated post.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48362774

http://stackoverflow.com/q/48392926
type: Question
has body: I am quite a new user in python. I am making a script to calculate some quantity like below A = sum([( f * Rphi[i,i] + Rt[i,i]) * NN[i,i] for i range(0,2)]) + 2*sum([sum([(f * Rphi[i,j] + Rt[i,j]) * NN[i,j] for j in range(i+1,2)]) for i in range(0,1)]) f is defined as scalar value and all two indices quantities are defined as 3x3 matrix in previously. This is just summing over indices. When I try to compile it, I got: Error message The error indicates that there is a syntax problem in the usage of for I in range(0,1) But I cannot find the problem in there. Any comments or advice is really appreciated!
score: 1
has comment: http://stackoverflow.com/comment/83773921
tagged with: python
has title: Python3 Syntax error
has comment: http://stackoverflow.com/comment/83773750
has answer: http://stackoverflow.com/a/48393000
upvote count: 2
has comment: http://stackoverflow.com/comment/83773771
has comment: http://stackoverflow.com/comment/83773845
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83840812
type: QuestionComment
has text: look at icalendar package
comment on: http://stackoverflow.com/q/48424673
type: Comment
score: 0

http://stackoverflow.com/a/48553015
downvote count: 0
has comment: http://stackoverflow.com/comment/84118760
has comment: http://stackoverflow.com/comment/84115485
answers question: http://stackoverflow.com/q/48334315
has body: One option to draw arrows inside bars is indeed hatching. This is however a little involved. One needs to create some custom hatch, as shown in this answer: How to fill a polygon with a custom hatch in matplotlib? Here we can be use a path of an arrow. In the following we therefore subclass matplotlib.hatch.Shapes and create some path of an arrow. The problem is now that we need some parameter to plug into the hatching, to be able to define the angle. We can then define a custom hatching pattern which I chose to look like this hatch="arr{angle}{size}{density}" where angle: integer number between 0 and 360 size: some integer between 2 and 20 density: some integer >= 1 This is similar to my previous answer on this question. Depeding on the angle the path gets rotated and size and density determine basically how many arrows of what size are shown. Note that not all parameters look good, some lead to overlaps in the hatch. import numpy as np import matplotlib.pyplot as plt import matplotlib.offsetbox import matplotlib.hatch from matplotlib.patches import Polygon class ArrowHatch(matplotlib.hatch.Shapes): """ Arrow hatch. Use with hatch="arr{angle}{size}{density}" angle: integer number between 0 and 360 size: some integer between 2 and 20 density: some integer &gt;= 1 """ filled = True size = 1 def __init__(self, hatch, density): v1 = [[.355,0], [.098, .1], [.151,.018], [-.355,.018]] v2 = np.copy(v1)[::-1] v2[:,1] *= -1 v = np.concatenate((v1,v2)) self.path = Polygon(v, closed=True, fill=False).get_path() self.num_lines = 0 if len(hatch) &gt;= 5: if hatch[:3] == "arr": h = hatch[3:].strip("{}").split("}{") angle = np.deg2rad(float(h[0])) self.size = float(h[1])/10. d = int(h[2]) self.num_rows = 2*(int(density)//6*d) self.num_vertices = (self.num_lines + 1) * 2 R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) self.shape_vertices = np.dot(R,self.path.vertices.T).T self.shape_codes = self.path.codes matplotlib.hatch.Shapes.__init__(self, hatch…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84108572
upvote count: 2

http://stackoverflow.com/comment/83774769
type: QuestionComment
has text: You'd be much better off using Avro or Parquet, or at the very least JSON. Plaintext is just bad to query against... If you use Confluent's Kafka HDFS Connector, you get Hive Integration out of the box. https://docs.confluent.io/current/connect/connect-hdfs/docs/index.html
score: 0
comment on: http://stackoverflow.com/q/48387221
type: Comment

http://stackoverflow.com/comment/83864463
type: AnswerComment
has text: OK, and still some problem? Solution failed? Are data confidental?
comment on: http://stackoverflow.com/a/48396555
type: Comment
score: 0

http://stackoverflow.com/q/48410479
tagged with: beautifulsoup
type: Question
has body: new to SO and having some difficulty with scraping a table from a website using beautifulsoup. The source html of the table goes something like this (repeated ad-nauseum for every artist/song/album): song artist|album And I'm trying to create an output file with all of that information. The code I'm using is: with open('output.txt', 'w', encoding='utf-8') as f: for tr in soup.find_all('tr')[1:]: tds = tr.find_all('td') f.write("Information: %s" % tds[3].text) which gets me an output like so: Information: song singer | album How do I change this to have it all on one line, and to also separate it properly? Ideally my output should be like this: Song Title: song Artist: singer Album Name: album
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/48410833
upvote count: 2
accepted answer: http://stackoverflow.com/a/48410791
has answer: http://stackoverflow.com/a/48410833
downvote count: 0
tagged with: web-scraping
has title: Scraping table values in python
has answer: http://stackoverflow.com/a/48410791
favorite count: 0

http://stackoverflow.com/comment/83858025
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48433250
type: Comment
has text: Perfect! Thank you so much!

http://stackoverflow.com/a/48414789
type: Answer
has body: You can use Python's csv module similarly to how you're writing them. Define an empty list to hold the urls and read the url csv: all_urls = [] with open('&lt;urls&gt;.csv') as csv_file: reader = csv.reader(csv_file) for row in reader: all_urls.append(row[&lt;column of url&gt;])
score: 2
answers question: http://stackoverflow.com/q/48414657
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83821648

http://stackoverflow.com/comment/83857212
type: QuestionComment
has text: Hmmm, after fiddling around with it it seems that the y-axis is indeed logarithmic, it's just that there isn't enough spread in the values to look substantially different from the linear scale. If you set the y-axis limits manually you can see the difference. Not actually a bug just a visual oddity.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48430069

http://stackoverflow.com/comment/83873461
score: 4
has text: Possible duplicate of [Seeding random number generators in parallel programs](https://stackoverflow.com/questions/29854398/seeding-random-number-generators-in-parallel-programs)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48440541

http://stackoverflow.com/q/48350748
type: Question
has body: I have already installed mysql-devel, it didn't solve the problem. I am trying to executed the following commands: sudo easy_install-2.7 MySQL-python sudo pip2.7 install MySQL-python in the first one I see: error: Setup script exited with error: command 'gcc' failed with exit status 1 In the second one: Command "/usr/local/bin/python2.7 -u -c "import setuptools, tokenize;file='/tmp/pip-build-nySVuQ/MySQL-python/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-eC4DGP-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-nySVuQ/MySQL-python/ Is there any possibility to solve it? Thanks in advance,
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83688236
has comment: http://stackoverflow.com/comment/83688182
has title: How to install MySQL-python - CentOS
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83688239
tagged with: mysql

http://stackoverflow.com/comment/84002788
comment on: http://stackoverflow.com/a/48482993
has text: You're right. Git is extremely intelligent software, and I've found I can usually give it the benefit of the doubt.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48402680
answers question: http://stackoverflow.com/q/48402513
accepted answer of: http://stackoverflow.com/q/48402513
type: AcceptedAnswer
type: Answer
has body: You can set the destination path to a dictionary and then use this logic. import os import shutil path = "C:\\Users\\USERNAME\\Desktop\\A\\" path1 = 'C:\\Users\\USERNAME\\Desktop\\01-Folder' path2 = 'C:\\Users\\USERNAME\\Desktop\\02-Folder' path3 = 'C:\\Users\\USERNAME\\Desktop\\03-Folder' d = {1: path1, 2: path2, 3: path3} c = 1 for root, dirnames, filenames in os.walk(path): for filename in filenames: filePathVal = os.path.join(root, filename) shutil.move(filePathVal, d[c]) c += 1 if c &gt; 3: c = 1 Note: Tested in python2.7
has comment: http://stackoverflow.com/comment/83794267
score: 0
has comment: http://stackoverflow.com/comment/84004759

http://stackoverflow.com/comment/83925982
score: 1
type: Comment
type: QuestionComment
has text: `z` is not a regular-typed Numpy array. It's an `object` type which means that it contains uneven sub arrays. You can fill the missing items with a proper type (`np.inf`, `np.nan`, etc.) and perform the `argsort`.
comment on: http://stackoverflow.com/q/48466131

http://stackoverflow.com/q/48364837
has comment: http://stackoverflow.com/comment/92302602
tagged with: sqlalchemy
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83724077
has body: When my Database service restarts: Postgres throws terminating connection due to administrator command SSL connection has been closed unexpectedly Above error comes when i am using QueuePool as the poolClass in create_engine function,like this: conn_engine = create_engine(connect_db, poolclass=QueuePool) But when i use pollClass as "NullPool", even i restart the DB multiple times above error doesn't comes, conn_engine = create_engine(connect_db, poolclass=NullPool) So can i Use NullPool for production and what are the advantages of NullPool over QueuePool in Sqlalchemy?
type: UnansweredQuestion
has title: NullPool or QueuePool for remote Postgres SQLalchemy connections?
tagged with: python
has comment: http://stackoverflow.com/comment/83719747
tagged with: postgresql
tagged with: connection-pooling
score: 0
has comment: http://stackoverflow.com/comment/83720325

http://stackoverflow.com/a/48358461
has body: to remove all text in ( and ) you can use findall() method from re and remove them using replace(): import re test_string = 'This is a string (here is a text to remove), and here is a (second one) text not to remove' remove = re.findall(r" \(.*?\)",test_string) for r in remove: test_string = test_string.replace(r,'') print(test_string) #result: This is a string , and here is a text not to remove
type: Answer
answers question: http://stackoverflow.com/q/48357619
score: 0

http://stackoverflow.com/comment/83764336
has text: Which part of the matplotlib documentation are you refering to here?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48387480
type: QuestionComment

http://stackoverflow.com/q/48335963
tagged with: xlwt
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-testing
score: 1
downvote count: 0
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/83736053
favorite count: 0
type: Question
has body: I have used xlwt for export some data to the client in django. Now i am testing the function and hence i want to verify that the data in response are matching with expected result. How to read the excel data from the response object. The excel data is added to response something like w.save(response) and how to retrieve this data with the response in response=self.client.get(reverse("create"))?
has title: How to access excel data in django response for testing?
has comment: http://stackoverflow.com/comment/83700218

http://stackoverflow.com/comment/83934058
comment on: http://stackoverflow.com/q/48469916
score: 0
type: QuestionComment
has text: That said, you're saying you want to exit when the password prompt is printed. If that's the case, why are you also saying that you "don't want to disable password authentication"? If you don't want to enter a password, why do you insist that you want ssh to emit a password prompt?
type: Comment

http://stackoverflow.com/a/59731229
downvote count: 0
upvote count: 1
score: 1
has body: Maybe it's a bit too late. But one work around is installing the python package matlab engine: this allows you to call any matlab function from python. Here it is described how it works.
type: Answer
answers question: http://stackoverflow.com/q/48407384

http://stackoverflow.com/comment/83685066
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48348714
has text: What do you mean not declared? If you mean not positioned (endtext.grid(...)) I have done that but for the purpose of simplifying the question, I left it out
type: Comment

http://stackoverflow.com/q/48371247
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/42184792
has comment: http://stackoverflow.com/comment/83742911
linked to: http://stackoverflow.com/q/43124732
linked to: http://stackoverflow.com/q/7446187
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48372224
has body: I have been installing a series of basic packages for python 3 (numpy, etc.) with pip 3 and everything was fine. Then I tried to install tensorflow-gpu and I got user@computer:~$ pip3 install --upgrade tensorflow-gpu Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 33, in vendored __import__(vendored_name, globals(), locals(), level=0) ImportError: No module named 'pip._vendor.pkg_resources' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; from pip import main File "/usr/lib/python3/dist-packages/pip/__init__.py", line 13, in &lt;module&gt; from pip.exceptions import InstallationError, CommandError, PipError File "/usr/lib/python3/dist-packages/pip/exceptions.py", line 6, in &lt;module&gt; from pip._vendor.six import iteritems File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 75, in &lt;module&gt; vendored("pkg_resources") File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored __import__(modulename, globals(), locals(), level=0) File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 664, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 634, in _load_backward_compatible File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2927, in &lt;module&gt; File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2913, in _call_aside File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 956, in subscribe File "/usr/share/python…
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83729524
tagged with: pip
has comment: http://stackoverflow.com/comment/83734683
downvote count: 1
accepted answer: http://stackoverflow.com/a/48372224
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83729649
has comment: http://stackoverflow.com/comment/83747275
has comment: http://stackoverflow.com/comment/83729383
has title: pip3 throws an error when trying to install tensorflow

http://stackoverflow.com/comment/83843853
comment on: http://stackoverflow.com/a/48426198
has text: Labels work with the `annotate` function, added an example to the answer above
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83691526
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48352342
score: 0
has text: yes, you need to declare a variable as global in every scope. So, even if you access the same global from two methods of the same class you need to declare the variable as global in both methods

http://stackoverflow.com/comment/83760963
type: Comment
score: 0
has text: I've written some code with a larger version of the example dataframe to time it, and your solution is indeed about 100 times faster (code and output may be interesting to edit into your answer: https://pastebin.com/KRFTXjVy). However, for my actual project, it does not provide a speedup. Could it be because I have to do the same thing as in the question in four slightly different variations (4 columns), which may be more efficient on a row-by-row basis? Or do you expect that should not make a significant difference?
type: AnswerComment
comment on: http://stackoverflow.com/a/48385128

http://stackoverflow.com/q/48333690
has comment: http://stackoverflow.com/comment/83653083
type: UnansweredQuestion
tagged with: python
has body: So I am currently dealing with a slight problem with Python 3 and PySerial. I have a Raspberry Pi along with a Control Box linked up via the UART ports on the RPI. The controlbox sends data to the raspberry pi every 50ms and I want to read that data so I can use a parser to grab some needed data from it. The only issue is when I try to read data, the starting hex value is incorrect because I am starting to read data halfway the feedback being sent back by the controlbox. For example: b'\x21\x21\x22\x98\x98\x24\x23\x21\x21\x22\x22\x98 I need the x98 (0x98) to be the starting hex value for that byte so it looks like this x98\x98\x24\x23\x21\x21\x22\x22\ I need to have it like this so I can grab a certain hex code (from the byte) such as x21 and use that for my program. I have done research and haven't been able to come up with a single thing. What should I do to make this possible?
answer count: 1
has answer: http://stackoverflow.com/a/48445742
has comment: http://stackoverflow.com/comment/83709601
tagged with: uart
has title: How to prevent Python + PySerial from reading the wrong starting byte
tagged with: hex
type: Question
tagged with: pyserial
score: 0

http://stackoverflow.com/comment/83903402
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48455137
type: Comment
has text: I just set my valLeft controller to a number I assumed it would be bigger than 100. Just to make sure it would enter the loop the first time. It work just fine if you put it `valLeft = 101` instead

http://stackoverflow.com/comment/83776103
type: QuestionComment
has text: The demo(sess,net,f) function ends and returns with the part below. plt.axis('off'); plt.tight_layout(); plt.draw(); How to obtain cv2.imshow from this?
score: 0
comment on: http://stackoverflow.com/q/48374982
type: Comment

http://stackoverflow.com/comment/83834799
has text: Thanks. I am using ffmpeg version 3.4 and I get "Unrecognized option 'frame_pts'." while running your command and get no output. Any clue?
comment on: http://stackoverflow.com/a/48421258
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48349860
score: 4
answers question: http://stackoverflow.com/q/48348952
type: Answer
upvote count: 4
has body: You need to commit the INSERT transaction before closing, or it will not be persisted: import sqlite3 conn = sqlite3.connect("amigo_local_db.db") c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)") action = int(input("Insert an action: (1: Add row | 2: Close)")) if(action == 1): url = input("URL: ") bash = input("BASH: ") values = (url,bash) c.execute("INSERT INTO images VALUES(null,?,?)",values) conn.commit() else: conn.close() quit() for row in c.execute("SELECT * FROM images"): print(row) conn.close()
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48348952

http://stackoverflow.com/comment/83835448
type: AnswerComment
comment on: http://stackoverflow.com/a/48419706
has text: @darrrn Yes, it should work for lists of lists of strings. The plain string `"buses"` would be converted to `{'b', 'u', 's', 'e'}`, but the list `["buses"]` becomes the set `{"buses"}`.
score: 0
type: Comment

http://stackoverflow.com/q/48383520
type: Question
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/48383664
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48383582
has answer: http://stackoverflow.com/a/48383664
has title: Python pandas, .apply, use multiple returned values
has body: in[1]: import pandas as pd def somefunc(input1, input2): output1 = 1 output2 = 2 return [output1, output2] d = {'col1': ['A1', 'B1'], 'col2': ['A2', 'B2']} df = pd.DataFrame(data=d) df'col3', 'col4' = df.apply(lambda x: somefunc(x['col1'], x['col2']), axis=1) print df out[1]: col1 col2 col3 col4 0 A1 A2 1 2 1 B1 B2 1 2 somefunc: - Gets data from json in url with arguments input1 and input2 and puts it into a new dataframe df2 - Creates output1, output2 with values from df2 - Deletes dataframe when output vaiables is calulated to save RAM This executes perfectly, but I want to return 3 values which return an error in[2]: import pandas as pd def somefunc(input1, input2): output1 = 1 output2 = 2 output3 = 3 return [output1, output2, output3] d = {'col1': ['A1', 'B1'], 'col2': ['A2', 'B2']} df = pd.DataFrame(data=d) df'col3', 'col4', 'col5' = df.apply(lambda x: somefunc(x['col1'], x['col2']), axis=1) print df out[2]: "ValueError: Columns must be same length as key" The error is different from my actual program, but I guess it correlates; KeyError: "['col3' 'col4' 'col5'] not in index" Why does this work with one and two outputs but not three? Python 2.7.14
has answer: http://stackoverflow.com/a/48383582
type: AnsweredQuestion
tagged with: pandas
upvote count: 5
favorite count: 0

http://stackoverflow.com/q/48394635
tagged with: sqlalchemy
favorite count: 0
type: Question
answer count: 0
downvote count: 0
has title: Blaze does not understand a SQLAlchemy type
type: UnansweredQuestion
tagged with: blaze
has body: I am getting errors trying to use blaze import pandas as pd import numpy as np from sqlalchemy import create_engine from blaze import * database_con = create_engine("mssql+pyodbc://server/database?driver=SQL Server Native Client 11.0", echo=False) bzdata = data(database_con) Blaze does not understand a SQLAlchemy type. Blaze provided the following error: No SQL-datashape match for type TIMESTAMP Skipping. is there a way to fix this?
upvote count: 1
score: 1
tagged with: python

http://stackoverflow.com/q/48358992
tagged with: aws-cli
accepted answer: http://stackoverflow.com/a/48359172
has title: AWS sync parameters not specified when AWS-CLI is run as a subprocess in Python
favorite count: 0
has answer: http://stackoverflow.com/a/48359172
type: Question
has body: I have an AWS S3 bucket filled with data parameterized by date. I'd like to extract that data one date at a time using the AWS CLI (reference), specifically the aws s3 sync command. The following command does what I expect it to do: aws s3 sync s3://my-bucket-1 . --exclude "*" --include "*2018-01-17*" --dryrun Running this command from my command line generates a (dryrun) download for every file in my bucket containing the substring 2018-01-17. Great! To simplify the necessary file operations, I've written a small CLI wrapper around this executor. This wrapper is in Python, and uses the subprocess.run facility to do its work. The entire operation boils down to the following call: subprocess.run(['aws', 's3', 'sync', 's3://my-bucket-1', '.', '--exclude', '"*"', '--include', '"*2018-01-17*"', '--dryrun']) The problem is that when I run this statement, I get a (dryrun) download back for every file in the bucket. That is, data is returned that corresponds with bucket entries from 01-18, 01-19, and so on. The --exclude/--include rules fail to apply, and the result is the same as if I had simply run aws s3 sync s3://my-bucket-1 . Why does this occur?
has comment: http://stackoverflow.com/comment/83704868
upvote count: 2
has comment: http://stackoverflow.com/comment/83704942
answer count: 1
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/14928860
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83704806
tagged with: subprocess
tagged with: amazon-s3

http://stackoverflow.com/comment/83719293
type: Comment
comment on: http://stackoverflow.com/a/48366112
score: 0
type: AnswerComment
has text: Got `ValueError: ('malformed string', u'occurred at index ms2_Y3')` which is the column name where it has data as `nan`

http://stackoverflow.com/comment/87493738
score: 0
has text: You make it sound like patching is something extreme and to be avoided, but languages like Python give you a lot of room to do this in your own code (subclasses, magic "dunder" methods, wrappers, etc.). And of course you can always do the simple but effective workaround of writing your own function to use instead of the built-in syntax.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48347515

http://stackoverflow.com/comment/83956808
type: QuestionComment
has text: Thank you Nicolay. I will try that now. I did ask the same thing, but I didn't know what was causing the infinite loop at that time. Once I had more information, I asked a new question but thought I deleted the old question before posting this one.
comment on: http://stackoverflow.com/q/48479032
type: Comment
score: 0

http://stackoverflow.com/q/48385721
has answer: http://stackoverflow.com/a/48389429
score: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: Suppose that I have 10 separate datasets and I want to build a predictive model. I need to evaluate the model so, I use cross validation. How can I use each dataset as a fold or specific part in CV? For example, how can I use the first 9 datasets as training set and the 10th dataset as test set and then iterate over all datasets? This way, the training and test datasets will not be randomly selected. Is there any python function to perform it?
type: UnansweredQuestion
tagged with: cross-validation
upvote count: 1
tagged with: python
has title: non-random selection of training and test datasets for cross validation by python

http://stackoverflow.com/q/48414118
type: UnansweredQuestion
tagged with: python
tagged with: py2neo
score: 0
has body: From the example of py2neo site: http://py2neo.org/v3/ogm.html class Movie(GraphObject): __primarykey__ = "title" title = Property() tag_line = Property("tagline") released = Property() actors = RelatedFrom("Person", "ACTED_IN") directors = RelatedFrom("Person", "DIRECTED") producers = RelatedFrom("Person", "PRODUCED") class Person(GraphObject): __primarykey__ = "name" name = Property() born = Property() acted_in = RelatedTo(Movie) directed = RelatedTo(Movie) produced = RelatedTo(Movie) Is there a way to specify properties for the relationship ? eg. i want to add weighting for the relationship. Thanks
answer count: 1
has answer: http://stackoverflow.com/a/48510950
tagged with: neo4j
has title: Py2neo OGM create relationship with properties
type: Question

http://stackoverflow.com/comment/83734420
type: Comment
type: AnswerComment
has text: @DYZ - if you'd like to post an answer, I'd be happy to accept it.
comment on: http://stackoverflow.com/a/48373628
score: 0

http://stackoverflow.com/comment/83735469
comment on: http://stackoverflow.com/q/48373962
score: 0
type: Comment
type: QuestionComment
has text: It is work on my side ///

http://stackoverflow.com/comment/83869211
comment on: http://stackoverflow.com/a/48431295
score: 0
type: Comment
has text: @martineau: I am expecting an itertools specialized library to provide the iteration tools to simplify some specialized iterative stuff (iterate and select the `k`th `n` elements out of every `m` elements). It is such a simple task even natural language does the work in one sentence. I don't want to bring down the discussion to sarcasm, I mean it's just what it's expected from a whole library dedicated to facilitate the iteration over elements.
type: AnswerComment

http://stackoverflow.com/q/48351274
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: group-by
tagged with: datetime
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/48351353
has body: Given a DataFrame like below: dfx = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["01/01/2014","01/31/2014","01/23/2014","01/01/2014","01/20/2014"]}) I want to remove "duplicates". "duplicates" are defined as those rows where the ID of the rows are the same, but the "date" between them is Less Than 30 days. The resulting DataFrame upon removal of the "duplicates" is expected appear as: ID date A 01/01/2014 A 01/31/2014 C 01/23/2014 B 01/01/2014
has title: Drop rows from each group if dates are within a given range
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/83707006
type: Comment
type: QuestionComment
score: 0
has text: And please never post a screenshot of a window, always try to paste the output here from your window. Refer to [this](https://stackoverflow.com/help/how-to-ask) for more help about asking questions.
comment on: http://stackoverflow.com/q/48358941

http://stackoverflow.com/a/48452780
type: Answer
has body: This is my approach: (hope it helps :) ) Firstly, we need to store the files starting with "301": import os files = [] directory = os.fsencode(directory of files) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.startswith("301"): files.append(filename) The directory of files is the directory of where your files go. Now we need to fetch the data from the files: data = [] for f in files: with open(f) as file: for i,row in enumerate(file): data.append(row) Finally we need to write the "301.txt" file: with open("301.txt",'w') as newfile: for row in data: newfile.write(row)
answers question: http://stackoverflow.com/q/48452364
score: 0

http://stackoverflow.com/q/48336544
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83658195
has title: BeautifulSoup HTML except Tag
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
answer count: 2
has body: ... ... class="no">... sampletext class="title">... ... This sample code has 3 class 'abc bg1','bg1','bg2' I want only 'bg1','bg2' tag so I used soup.select('tbody > tr.bg1 > td') This code results in 'abc bg1','bg1' tag children 'td' How do I get the results I want? And to 'bg1', I want to extract only text except for other Tags ex): sampletext <- only
has answer: http://stackoverflow.com/a/48336606
has answer: http://stackoverflow.com/a/48336787

http://stackoverflow.com/q/48484854
has title: Tensorflow terminate called after throwing an instance of 'std::system_error' what(): Resource temporarily unavailable
downvote count: 0
answer count: 0
upvote count: 1
tagged with: ubuntu
tagged with: tensorflow
type: Question
favorite count: 0
tagged with: python
type: UnansweredQuestion
has body: it seems that after loading a saved model and then opening a session, tf.Session() will cause terminate called after throwing an instance of 'std::system_error' what(): Resource temporarily unavailable. but, using tf.Session() without loading a model works fine. i was wondering is there a minimum a mount or RAM needed. i'm working with ubuntu 16.04 server. 1GB RAM. python 3.6.3 tensorflow 1.4.1 trained model size 53MB. the model has been tested locally and it's working perfectly. does increasing the RAM will solve this problem?? and if so what is the amount of RAM needed??
score: 1

http://stackoverflow.com/comment/83973842
comment on: http://stackoverflow.com/q/48486988
score: 1
type: Comment
type: QuestionComment
has text: For me, when I replicate and run with a 3.4 venv, some errors appear the first time `Run All Unit Tests` is run but subsequent runs work. Problem must be more specific to your configuration.

http://stackoverflow.com/comment/83715580
type: QuestionComment
comment on: http://stackoverflow.com/q/48364134
score: 0
has text: @Tai - dataset posted
type: Comment

http://stackoverflow.com/q/48467250
type: Question
tagged with: python-3.x
has body: I've been going through the DataQuest "Introduction to Python" program, and in the "Modules" section of the course, there's a section on defining functions. I got through that section but then decided I wanted to try to extend it. The original code, which works, is: #!/usr/bin/env python3 import csv f = open("nfl.csv", 'r') nfl = list(csv.reader(f)) # Define your function here. def nfl_wins(team): count = 0 for row in nfl: if row[2] == team: count += 1 return count cowboys_wins = nfl_wins("Dallas Cowboys") falcons_wins = nfl_wins("Atlanta Falcons") print(cowboys_wins) print(falcons_wins) My code, which is intended to iterate over a list containing all the teams and give the number of wins for each team, is as follows: #!/usr/bin/env python3 import csv f = open('nfl.csv', 'r') nfl = list(csv.reader(f)) # Define your function here. def nfl_wins(team): print(team) count = 0 for row in nfl: if row[2] == team: count = count + 1 return count nfl_teams = ['Denver Broncos', 'Detroit Lions', 'Green Bay Packers', 'Houston Texans', 'Indianapolis Colts', 'Jacksonville Jaguars', 'Kansas City Chiefs', 'Miami Dolphins', 'Minnesota Vikings', 'New England Patriots', 'New Orleans Saints', 'New York Giants', 'New York Jets', 'Oakland Raiders', 'Philadelphia Eagles', 'Pittsburgh Steelers', 'San Diego Chargers', 'San Francisco 49ers', 'Seattle Seahawks', 'St. Louis Rams', 'Tampa Bay Buccaneers', 'Tennessee Titans', 'Washington Redskins'] for squad in nfl_teams: print(squad, nfl_wins(squad)) When I just iterate over the "nfl_teams" list and print the names, it works fine. When I try to pass the team names to the "nfl_wins" function, I get the following error: $ python3 nfl_wins.py Denver Broncos Traceback (most recent call last): File "nfl_wins.py", line 20, in &lt;module&gt; print(squad, nfl_wins(squad)) File "nfl_wins.py", line 13, in nfl_wins if row[2] == team: IndexError: list index out of range My environment is Python 3.4.3 on Cygwin running under Windows 7 Enterprise.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83928016
tagged with: python
has title: Python - iterating over a list and passing each element as a parameter to a function
upvote count: 2
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83931467
has comment: http://stackoverflow.com/comment/83927970
favorite count: 0

http://stackoverflow.com/q/48349025
has comment: http://stackoverflow.com/comment/99000360
has body: I have an aplication in Django 2.0 where one user can upload many images of their diplomas at the same time but also, I need to make this with ajax so the page will not reload. This is my models.py class diploma(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE, null=True) diploma=models.ImageField(default='nopic.png', null=True) def __str__(self): return self.diploma And this is my file input in my template upload.html &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="file" id="images" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif"&gt; &lt;a onclick="uploadWithAjax()"&gt; Upload Images &lt;/a&gt; If you notice, there's no Form html tag. Just an 'a' link that calls the function uploadWithAjax(). This is my script with the uploadWithAjax() function function uploadWithAjax() { var files = $('#images')[0].files; $.ajax( { type: "POST", url: "/UploadImages/", data: "", //I DON'T KNOW WHAT DATA I HAVE TO PUT HERE success: function(result) { alert('IMAGES UPLOADED'); } }); } I Think I have to send the 'files' variable in the 'data' atribute of ajax, but I'm not sure becouse there are files and dont normal inputs. Please help. This is my ajax.py file, where I recive the images def UploadImages(request): diplomas = request.FILES['images'] #I don't know if this is correct I didn't finish the view becouse I don't know how to continue or how to make a register in my bd table for each image I uploaded. Please Help!
score: 1
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/48829089
favorite count: 0
type: Question
tagged with: ajax
tagged with: image-uploading
accepted answer: http://stackoverflow.com/a/54823222
has answer: http://stackoverflow.com/a/54823222
has title: Django Multiple Files Upload Using Ajax without forms
tagged with: django
tagged with: javascript
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48442141
has title: Python gracefully stop a script from Laravel/Php
tagged with: python
linked to: http://stackoverflow.com/q/18499497
tagged with: php
score: -1
has answer: http://stackoverflow.com/a/48445653
type: AnsweredQuestion
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48445653
downvote count: 1
favorite count: 0
type: Question
has body: I'm looking for a way to gracefully exit from a long running python script which I launch from my Laravel app. My actual process to do so is: From Laravel set a 'script_state' to 1 in a MySql table database Launch the python script via shell_exec The python scripts periodically check the 'script_state' by a MySql query. If it is changed to 0 (intentionally from my Laravel app) then it gracefully exit the script Retrieving the pid from the shell_exec and then kill could have been an option but I actually wan't the script to stop and exit gracefully. My actual config works but I'm looking for a better approach.

http://stackoverflow.com/comment/83884481
type: AnswerComment
has text: So,indeed, should have taken it literally, will make an edit.
comment on: http://stackoverflow.com/a/48446108
type: Comment
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/48402634
tags question: http://stackoverflow.com/q/48475180
tags question: http://stackoverflow.com/q/48433331
tags question: http://stackoverflow.com/q/48482420

http://stackoverflow.com/comment/83649933
has text: @BrianRodriguez Perfect, thanks. I wish I can give more than 1 checkmark for all the great answers.
type: Comment
comment on: http://stackoverflow.com/a/48331947
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83694497
has text: You're also not using `z` at all in that loop...
score: 1
comment on: http://stackoverflow.com/q/48353624
type: QuestionComment
type: Comment

relationship
tag name: relationship
type: Tag
tags question: http://stackoverflow.com/q/48424704
tags question: http://stackoverflow.com/q/48340411

http://stackoverflow.com/comment/83887783
type: QuestionComment
has text: IF the ban is based on your IP address, then yes changing IP address might resolve that, but that's not something python has control over.
comment on: http://stackoverflow.com/q/48447709
type: Comment
score: 0

http://stackoverflow.com/comment/83816837
comment on: http://stackoverflow.com/a/48413422
type: AnswerComment
has text: Thanks a bunch. I truly appreciate it :)
score: 1
type: Comment

http://stackoverflow.com/q/48459574
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/48459624
answer count: 1
favorite count: 0
has title: How can I stringify a dictionary having a string with cyrillic symbols into a pretty JSON?
has body: Desired output: '{"a": "йцукен"}' I tried this: &gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps({'a': 'йцукен'}) '{"a": "\\u0439\\u0446\\u0443\\u043a\\u0435\\u043d"}' How can I avoid these U-codes and print normal symbols? I am using Python 3.
type: Question
has comment: http://stackoverflow.com/comment/83911964
linked to: http://stackoverflow.com/q/18337407
tagged with: python-3.x
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/18337407
accepted answer: http://stackoverflow.com/a/48459624

http://stackoverflow.com/q/48388624
favorite count: 0
type: Question
has body: The SQLite docs for in-memory databases (https://www.sqlite.org/inmemorydb.html) indicate that to share :memory: across connections, you should use URI naming and set cache=shared, like so (C API): rc = sqlite3_open("file::memory:?cache=shared", &amp;db); I tried this from Python 2.7.14, with these attributes: &gt;&gt;&gt; sqlite3.version '2.6.0' &gt;&gt;&gt; sqlite3.apilevel '2.0' &gt;&gt;&gt; sqlite3.sqlite_version '3.20.1' What I discovered was that the database isn't quite as transient as I would have expected. Here's a session. First, create a database and insert a row... % python Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; conn = sqlite3.Connection("file::memory:?cache=shared") &gt;&gt;&gt; curs = conn.cursor() &gt;&gt;&gt; curs.execute("select * from sqlite_master").fetchall() [] &gt;&gt;&gt; curs.execute("create table XYZ (x int, y int, z varchar)") &lt;sqlite3.Cursor object at 0x7ff4b2a06110&gt; &gt;&gt;&gt; curs.execute("insert into XYZ values (?, ?, ?)", (1, 2, '3')) &lt;sqlite3.Cursor object at 0x7ff4b2a06110&gt; &gt;&gt;&gt; curs.execute("select * from sqlite_master").fetchall() [(u'table', u'XYZ', u'XYZ', 2, u'CREATE TABLE XYZ (x int, y int, z varchar)')] &gt;&gt;&gt; curs.execute("select * from XYZ").fetchall() [(1, 2, u'3')] &gt;&gt;&gt; conn.close() &gt;&gt;&gt; Look here, there's a leftover file: % ls -l file* -rw-r--r-- 1 skip skip 8192 Jan 22 12:49 file::memory:?cache=shared And it seems to have some bits left over from the session: % strings -a file* SQLite format 3 atableXYZXYZ CREATE TABLE XYZ (x int, y int, z varchar) Indeed, I can open it. Although it appears to be empty (I didn't explicitly commit() in the first session, so perhaps that's why), the database is still there and accessibe: % python Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) [GCC 7.2.0] on linux2 Type "help"…
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48389822
has answer: http://stackoverflow.com/a/48389822
has answer: http://stackoverflow.com/a/69283213
type: AnsweredQuestion
score: 0
has title: :memory: database with shared cache is not so temporary
answer count: 2
tagged with: sqlite
possible better answer: http://stackoverflow.com/a/69283213
tagged with: memory
tagged with: caching
downvote count: 1

http://stackoverflow.com/q/48439005
has answer: http://stackoverflow.com/a/48695728
score: 3
tagged with: pycharm
upvote count: 3
tagged with: matplotlib
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83873762
tagged with: jupyter
tagged with: interactive
favorite count: 0
has title: Pycharm Jupyter Interactive Matplotlib
type: Question
has body: Interactive matplotlib plotting is already a thing, but does not work properly in Pycharm, when used within a jupyter notebook. The %matplotlib notebook does not work (throws no error, but I get &lt;IPython ... JavaScript object&gt; instead of a plot. If I plot normally (also with or without plt.show()) I just get a png and cannot interact in any way (even if, e.g., sliders are visible). I couldn't find any answers elsewhere to this exact problem. It might be working in the browser version of jupyter, but I would like to stick to using PyCharm. Pycharm v 2017.3 Community Edition
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83881472

http://stackoverflow.com/comment/83978432
type: Comment
comment on: http://stackoverflow.com/q/48481620
type: QuestionComment
score: 0
has text: This indirectly fixed the issue. I added the schema to the ForeignKey declarations because I was getting errors with sqlalchemy unable to find the tables. The explicit schema declarations fixed that, but unknowingly broke the relationship stuff. It ends up all of this was due to me not importing the modules which contain the classes that the Foreign keys point to. So importing modules and removing the schema declarations fixed everything. Thank you!

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/48477042
tags question: http://stackoverflow.com/q/48459269
tags question: http://stackoverflow.com/q/48345006
tags question: http://stackoverflow.com/q/48482746
tags question: http://stackoverflow.com/q/48356424
tags question: http://stackoverflow.com/q/48477997
tags question: http://stackoverflow.com/q/48342068
tags question: http://stackoverflow.com/q/48373710
tags question: http://stackoverflow.com/q/48439153
tags question: http://stackoverflow.com/q/48472346
tags question: http://stackoverflow.com/q/48453143
tags question: http://stackoverflow.com/q/48484664
tags question: http://stackoverflow.com/q/48382597
tags question: http://stackoverflow.com/q/48355700
tags question: http://stackoverflow.com/q/48430916
tags question: http://stackoverflow.com/q/48486598
tags question: http://stackoverflow.com/q/48358853
tags question: http://stackoverflow.com/q/48450932
tags question: http://stackoverflow.com/q/48461297
tags question: http://stackoverflow.com/q/48437889
tags question: http://stackoverflow.com/q/48401148
tags question: http://stackoverflow.com/q/48376724
tags question: http://stackoverflow.com/q/48333900
tags question: http://stackoverflow.com/q/48447686
tags question: http://stackoverflow.com/q/48470539
tags question: http://stackoverflow.com/q/48384434
tags question: http://stackoverflow.com/q/48403239
tags question: http://stackoverflow.com/q/48369959
tags question: http://stackoverflow.com/q/48418907
tags question: http://stackoverflow.com/q/48393959
tags question: http://stackoverflow.com/q/48360972
tags question: http://stackoverflow.com/q/48472080
tags question: http://stackoverflow.com/q/48393536
tags question: http://stackoverflow.com/q/48385830
tags question: http://stackoverflow.com/q/48458635
tags question: http://stackoverflow.com/q/48366379
tags question: http://stackoverflow.com/q/48478653
tags question: http://stackoverflow.com/q/48434960
tags question: http://stackoverflow.com/q/48380962
tags question: http://stackoverflow.com/q/48455837
tags question: http://stackoverflow.com/q/48450785
tags question: http://stackoverflow.com/q/48344228
tags question: http://stackoverflow.com/q/48338492
tags question: http://stackoverflow.com/q/48425128
tags question: http://stackoverflow.com/q/48447371
tags question: http://stackoverflow.com/q/48386740
tags question: http://stackoverflow.com/q/48403445
tags question: http://stackoverflow.com/q/48391075
tags question: http://stackoverflow.com/q/48439930
tags question: http://stackoverflow.com/q/48404263
tags question: http://stackoverflow.com/q/48424084
tags question: http://stackoverflow.com/q/48372575
tag name: machine-learning
tags question: http://stackoverflow.com/q/48483980
tags question: http://stackoverflow.com/q/48370121
tags question: http://stackoverflow.com/q/48385265
tags question: http://stackoverflow.com/q/48485992
tags question: http://stackoverflow.com/q/48361864
tags question: http://stackoverflow.com/q/48422569
tags question: http://stackoverflow.com/q/48343339
tags question: http://stackoverflow.com/q/48429743
tags question: http://stackoverflow.com/q/48342384
tags question: http://stackoverflow.com/q/48397543
tags question: http://stackoverflow.com/q/48377214
tags question: http://stackoverflow.com/q/48407730
tags question: http://stackoverflow.com/q/48373088
tags question: http://stackoverflow.com/q/48343084
tags question: http://stackoverflow.com/q/48348275
tags question: http://stackoverflow.com/q/48439793
tags question: http://stackoverflow.com/q/48416982
tags question: http://stackoverflow.com/q/48432300
tags question: http://stackoverflow.com/q/48426683
tags question: http://stackoverflow.com/q/48362692
tags question: http://stackoverflow.com/q/48431282
tags question: http://stackoverflow.com/q/48452999
tags question: http://stackoverflow.com/q/48347530
tags question: http://stackoverflow.com/q/48377317
tags question: http://stackoverflow.com/q/48400655
tags question: http://stackoverflow.com/q/48359248

http://stackoverflow.com/comment/83759602
type: Comment
has text: @cpburnz Thanks for figuring out , hence it should be changed to PATTERN = re.compile(r"\s(?=[da | de| do| dos| das])(\S+\s*\s\s*\S+)")
score: 0
comment on: http://stackoverflow.com/a/48383699
type: AnswerComment

http://stackoverflow.com/q/48433694
has comment: http://stackoverflow.com/comment/83859252
has comment: http://stackoverflow.com/comment/83858820
has comment: http://stackoverflow.com/comment/83859151
has comment: http://stackoverflow.com/comment/83859214
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83859130
downvote count: 2
tagged with: max
tagged with: python
tagged with: where-clause
has title: find the value of a column that is next to the max value in a pandas df
accepted answer: http://stackoverflow.com/a/48434009
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48434009
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83859093
has body: I am struggling with a problem. I have a pandas df that contains X,Y coordinates from different players. I can get the max X-coordinate value of the row with .max(axis = 1). What I hoping to achieve is to make a new column that contains the value that's next to the max value. That is, how do I find the adjacent value of the max X-coordinate column. So it would be the Y-coordinate that's next to the Max X-coordinate for any given row. Note: There will never to duplicate max values. See below for example. df Player 1_X Player 1_Y Player 2_X Player 2_Y Player 3_X Player 3_Y 6 7 5 8 **9** 3 5 7 6 7 **8** 2 4 6 **7** 7 6 1 Intended df: df1 Player 1_X Player 1_Y Player 2_X Player 2_Y Player 3_X Player 3_Y New Column 6 7 5 8 9 3 3 5 7 4 7 8 2 2 4 7 5 7 6 1 7 I have tried an if statement and where function but don't know were to begin as I'm new to python.
has comment: http://stackoverflow.com/comment/83859022
has comment: http://stackoverflow.com/comment/83859408

http://stackoverflow.com/a/48406541
has comment: http://stackoverflow.com/comment/83803451
score: 0
has body: Just don't use a temporary list and do it like this: def expand(a): o = [] for element in a: if element == 0: o.append([1, 0]) elif element == 1: o.append([0, 1]) return o Another solution would be a list comprehension: def expand(a): # if your input values can only be `1` or `0` # 'if 0' always evaluates to False whereas 'if any_int_except_zero' always evaluates to True return [[0, 1] if element else [1, 0] for element in a]
type: Answer
answers question: http://stackoverflow.com/q/48406242

http://stackoverflow.com/a/48413328
answers question: http://stackoverflow.com/q/48412524
type: Answer
score: 0
type: AcceptedAnswer
has body: As others have already said, python has zip for just this purpose. However, if you insist on doing this without zip: for i in range(len(string_1)): print(string_1[i] + ' equals ' + string_2[i]) will accomplish this.
accepted answer of: http://stackoverflow.com/q/48412524

http://stackoverflow.com/a/48402123
type: Answer
has body: Here's my DFS-like approach to this problem (Complexity O(rows * columns)): # given array ayyyarray = [ [1,1,1,2,2], [1,1,2,3,2], [2,2,2,3,1], [2,1,0,3,2], [2,0,3,3,0]] # function that mark "color" on cell and call take_a_tour for all neighbours with the same number def take_a_tour(ayyyarray, visited, y, x, act_group_number, group_members_cnt): visited[y][x] = act_group_number if act_group_number in group_members_cnt: group_members_cnt[act_group_number] += 1 else: group_members_cnt[act_group_number] = 1 if (x + 1 &lt; len(ayyyarray[y])) and (visited[y][x + 1] == 0) and (ayyyarray[y][x + 1] == ayyyarray[y][x]): take_a_tour(ayyyarray, visited, y, x + 1, act_group_number, group_members_cnt) if (y + 1 &lt; len(ayyyarray)) and (visited[y + 1][x] == 0) and (ayyyarray[y + 1][x] == ayyyarray[y][x]): take_a_tour(ayyyarray, visited, y + 1, x, act_group_number, group_members_cnt) if (x - 1 &gt;= 0) and (visited[y][x - 1] == 0) and (ayyyarray[y][x - 1] == ayyyarray[y][x]): take_a_tour(ayyyarray, visited, y, x - 1, act_group_number, group_members_cnt) if (y - 1 &gt;= 0) and (visited[y - 1][x] == 0 ) and (ayyyarray[y - 1][x] == ayyyarray[y][x]): take_a_tour(ayyyarray, visited, y - 1, x, act_group_number, group_members_cnt) # 0 if not painted, color code(group_number) if already painted visited = [[0 for _ in range(len(ayyyarray[x]))] for x in range(len(ayyyarray))] # actual color we are using to paint same cells act_group_number = 1 # dictionary to store pairs [color : number_of_cells_using_this_color] group_members_cnt = {} # for every cell i call take_a_tour. for y in range(len(ayyyarray)): for x in range(len(ayyyarray[y])): if not visited[y][x]: take_a_tour(ayyyarray, visited, y, x, act_group_number, group_members_cnt) act_group_number += 1 # setting 0 for every cell that are painted with color used in &gt;= 5 cells. for y in range(len(ayyyarray)): for x in range(len(ayyyarray[y])): if group_members_cnt[visited[y][x]] &gt;= 5: ayyyarray[y][x] = 0 # print result for y in ayyyar…
answers question: http://stackoverflow.com/q/48400602
score: 0

http://stackoverflow.com/q/48340340
has title: How to rename a file in python with different numbers in it?
tagged with: python
tagged with: python-os
has answer: http://stackoverflow.com/a/48340786
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83668899
has body: I am trying to rename a list of files with names for example: This is File 132 (file no 132) to This is File 132. So what I want is to replace (file no *) with ''. How to implement this *, where ultimately I want to replace this particular place in the name in every file. This is the code I have written so far. Any help is appreciated. import os directoryname = "/media/username/New Volume/" listFiles = os.listdir(directoryname) print(listFiles) for i in listFiles: os.rename(os.path.join(directoryname, i), os.path.join(directoryname, i.replace('(file no 132)', ''))) listFiles = os.listdir(directoryname) print(listFiles)
downvote count: 0
has comment: http://stackoverflow.com/comment/83667612
has comment: http://stackoverflow.com/comment/83665927
has comment: http://stackoverflow.com/comment/83666079
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83666628
answer count: 2
has answer: http://stackoverflow.com/a/48340584
type: UnansweredQuestion

http://stackoverflow.com/a/48432332
has body: As the documentation reveals, yes it is possible: The execute_js() function runs the execute() function on a Node.js script file. Instead of passing the command to be executed as the first parameter, pass a Node.js script filepath as the first parameter and any additional command arguments as the second parameter (optional). The executed command is concatenated from these strings with the following code: if len(arguments) &gt; 0: js_command = 'node ' + file_path + " " + arguments else: js_command = 'node ' + file_path Parameters: file_path (string) - the filepath to the Node.js script that is to be executed by the shell arguments (string) - optional, any additional arguments to be used with your command Documentation: http://naked.readthedocs.io/toolshed_shell.html#Naked.toolshed.shell.execute_js
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48432203
type: Answer
has comment: http://stackoverflow.com/comment/83858148
answers question: http://stackoverflow.com/q/48432203
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83977520
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48434543
has text: os.path.isfile() by default search in working directory
type: Comment

http://stackoverflow.com/comment/83859561
has text: I know you have already answered this question, but is there some sort of internal timezone at play here? Working through your example I noticed that you get 13,791.60 which when moving your curser through the graph on the website is actually the price for 3:59:20 UTC(Graph time zone) where as when I search the same thing, I get 13,826.50, which is 10:59:20 UTC on the graph. I'm in EST which is 5 hours behind UTC. Could you clear this up for me?
type: Comment
comment on: http://stackoverflow.com/a/48368225
score: 0
type: AnswerComment

http://stackoverflow.com/a/48384807
downvote count: 0
has body: This return items from A that are not in another item in A, but skips instances where the items are exact matches (ie: skip itself) [x for x in A if not any(x in y and x!=y for y in A)] # returns: ['this is a sentence', 'who is alice', 'hi i am carrot']
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48384452
upvote count: 2

http://stackoverflow.com/a/48462578
has comment: http://stackoverflow.com/comment/84065070
has comment: http://stackoverflow.com/comment/84065064
has comment: http://stackoverflow.com/comment/84057289
type: Answer
accepted answer of: http://stackoverflow.com/q/48462442
has comment: http://stackoverflow.com/comment/83941174
score: 0
has body: That's a known bug. That same bug in the google code archive. If you follow the google code archive link, you'll find a patch that possibly fixes your issue. Other than that, there's not much you can do. The issue's status is still open There's also this pull request that you might find interesting, since it presumably fixes the issue.
answers question: http://stackoverflow.com/q/48462442
upvote count: 1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/48348210
has title: Django Markdownx preview shown only after reloading page
has comment: http://stackoverflow.com/comment/83682802
has body: I want django-markdownx to show maths formulas and equations and therefore integrated 'python-markdown-math' with it. Everything works as usual apart from the fact that I need to reload the page to get a preview of the typed mathematical formulas or symbols. The issue is only occurring when I type mathematical formula not others texts or upload image. Maths related stuffs (like $$..$$) seems to get skipped in preview and is shown only when I reload/refresh the page. Parts of my code: # settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'mdx_math', ] MARKDOWNX_UPLOAD_MAX_SIZE = 5 * 1024 * 1024 # 5 MB MARKDOWNX_SERVER_CALL_LATENCY = 1000 MARKDOWNX_IMAGE_MAX_SIZE = { 'size': (500, 500), 'quality': 90, 'crop': True, } MARKDOWNX_MEDIA_PATH = 'markdownx/' # models.py class MyModel(models.Model): content = MarkdownxField() @property def get_content(self): return mark_safe(markdownify(self.content)) # in my template MathJax TeX Test Page {% csrf_token %} {{ form }} {{ form.media }} Please help me find the problem which is causing such a behaviour. Note: Reloading and getting correct output works only in Firefox. Chrome just resets the the textarea.
score: 0
answer count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/83682551
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/83861431
type: QuestionComment
has text: Because you wrote `key <= len(thickness)` instead of `key < len(thickness)`
type: Comment
comment on: http://stackoverflow.com/q/48434989
score: 2

http://stackoverflow.com/a/48426916
downvote count: 0
upvote count: 1
score: 1
has body: You should use arguments in your function, this is in fact bad design to do it the way you did. import urtc import machine rtc = urtc.DS3231(machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2))) from func import * def current_time(rtc): return urtc.tuple2seconds(rtc.datetime()) current_time(rtc)
answers question: http://stackoverflow.com/q/48426834
type: Answer

http://stackoverflow.com/q/48417747
has answer: http://stackoverflow.com/a/48418631
tagged with: python
type: Question
answer count: 2
type: UnansweredQuestion
has body: I have 2 models: teacher and student. They both extend User class with a OneToOneField and they both have receivers defined for creation and saving. Now, in my forms I can only display the fields from student or teacher only, the other fields that come with user I don't know how to include them. But I want that a student or a teacher won't be able to create account, unless all fields are filled in. Here are my forms and view: class StudentSignUpForm(forms.ModelForm): class Meta: model = Student fields = ('student_ID', 'photo', 'phone') class TeacherSignUpForm(forms.ModelForm): class Meta: model = Teacher fields = ('academic_title', 'photo', 'phone', 'website', 'bio') class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'teacher_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return render_to_response('index.html', {'form': form},)
tagged with: django
score: 0
has answer: http://stackoverflow.com/a/48425263
has title: I don't know how to display my customuser and user in same form

http://stackoverflow.com/comment/83777591
comment on: http://stackoverflow.com/a/48394846
score: 0
type: AnswerComment
has text: That was the fault. Thanks Stephen.
type: Comment

http://stackoverflow.com/comment/83850192
comment on: http://stackoverflow.com/q/48429439
has text: Are the recordings made in chronological order?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48451710
has answer: http://stackoverflow.com/a/48453317
has title: Bokeh, Can only update column via callback once
favorite count: 0
type: Question
tagged with: bokehjs
tagged with: python
tagged with: bokeh
upvote count: 2
linked to: http://stackoverflow.com/q/41147984
score: 2
has body: Using some code I found on this question, I managed to update the columns for the graph I am making. The problem is, I am only allowed to make ONE update and then no more effect afterwards. The same problem happens when executing the code from the reference question. I will post a snippet here just for convenience: import bokeh import bokeh.plotting p = bokeh.plotting.figure(x_range=(0,4), y_range=(0,4), plot_height=200 ) csource = bokeh.models.ColumnDataSource(data=dict( x=[1,2,3], y=[1,2,1], colors1=["#ff0000","#00ff00","#0000ff"], colors2=["#ff00ff","#ffff00","#00ffff"])) cir = p.circle(x="x",y="y",fill_color="colors1",line_color="colors1", size=20,source=csource) cb_cselect = bokeh.models.CustomJS(args=dict(cir=cir,csource=csource), code =""" var selected_color = cb_obj.value; cir.glyph.line_color.field = selected_color; cir.glyph.fill_color.field = selected_color; csource.trigger("change") """) color_select = bokeh.models.Select(title="Select colors", value="colors1", options = ["colors1","colors2"], callback = cb_cselect) layout = bokeh.layouts.gridplot([[p],[color_select]]) bokeh.io.output_file("output.html") bokeh.io.show(layout) Basically, I run the code, the html file opens in my browser, I update via the dropdown, then click Reset before any changes can take effect. Afterwards, no more changes are possible unless I refresh my browser. It didn't seem like other users were having this issue, so I'm quite confused as to why this is happening. Also, I apologize, I would have simply commented on that question but I don't have the necessary reputation as of yet.
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51308486
downvote count: 0
score: 4
type: Answer
has body: A oneliner using sort: In [6]: np.count_nonzero(np.diff(np.sort(a)), axis=1)+1 Out[6]: array([2, 2, 3])
answers question: http://stackoverflow.com/q/48473056
upvote count: 4

http://stackoverflow.com/comment/83680606
type: QuestionComment
comment on: http://stackoverflow.com/q/48345573
score: 0
has text: It does sort of filter duplicates, if querying for a single ORM entity only. Can't remember where's the relevant part in the docs, though. But think about it: the ORM handles objects by their identity, so were it to return 3 results, it would return 3 references to the same object.
type: Comment

http://stackoverflow.com/comment/83739886
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48376165
has text: Thanks @jezrael . This does help my case but with the example above it doesn't put a comma between 1.34 and 12BET and so on. I need to seperate them also.
type: AnswerComment

http://stackoverflow.com/q/48431291
has body: In python I cannot seem to overload the below functions: #!/usr/bin/env python import subprocess def my_function (a) : subprocess.call(['proc', a]) return; def my_function (a, b) : subprocess.call(['proc','-i',a,b]) return; def my_function (a, b, c, d) : subprocess.call(['proc','-i',a,b,'-u',c,d]) return; E.g. when I call with: mymodules.my_function("a", "b") I get: Traceback (most recent call last): File "sample.py", line 11, in &lt;module&gt; mymodules.my_function("a", "b") TypeError: my_function() takes exactly 4 arguments (2 given) Why does it try to call the function taking 4 arguments?
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/83853633
linked to: http://stackoverflow.com/q/7113032
answer count: 1
has title: How to overload a function in python?
favorite count: 0
duplicate of: http://stackoverflow.com/q/7113032
type: Question
has comment: http://stackoverflow.com/comment/83853629
duplicate of: http://stackoverflow.com/q/6434482
downvote count: 3
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83853626
has answer: http://stackoverflow.com/a/48431323

http://stackoverflow.com/comment/83916503
comment on: http://stackoverflow.com/a/48461537
has text: I think you should have a go and maybe ask a new question with your attempted code. SO is not a free coding service. Edit: I would point out you're not going to find a simple answer. If there are lots of variations, there isn't going to be a way of avoiding making multiple searches. Thats just how it is.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/48463335
has body: You can use: df.groupby('ID')['Cat'].apply(list) Output: ID 0 [Waterbodies, Beaches] 1 [Waterbodies, Beaches] 3 [Beaches] 7 [Waterbodies, Beaches] 8 [Waterbodies] Name: Cat, dtype: object Here is a MCVE: d = pd.Series(['Waterbodies','Beaches','Waterbodies','Beaches','Beaches','Waterbodies','Beaches','Waterbodies'],index=[0,0,1,1,3,7,7,8]) d = d.rename('Cat') d.index.name = 'id' d.groupby('id').apply(list).reset_index() Output: id Cat 0 0 [Waterbodies, Beaches] 1 1 [Waterbodies, Beaches] 2 3 [Beaches] 3 7 [Waterbodies, Beaches] 4 8 [Waterbodies]
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83924724
has comment: http://stackoverflow.com/comment/84004057
has comment: http://stackoverflow.com/comment/83926352
score: 1
answers question: http://stackoverflow.com/q/48463050
type: Answer
has comment: http://stackoverflow.com/comment/84077093
accepted answer of: http://stackoverflow.com/q/48463050
has comment: http://stackoverflow.com/comment/83923952

http://stackoverflow.com/a/48358790
downvote count: 0
answers question: http://stackoverflow.com/q/48358686
type: Answer
score: 2
upvote count: 2
has body: The code is perfect, except a redundant else, as mentioned in the comment. Are you entering a (a + space) rather than simply a (a without space) ? The problem is in the input that you are providing and not in the code!

http://stackoverflow.com/q/48360056
favorite count: 0
has answer: http://stackoverflow.com/a/48360428
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48360202
score: 5
has comment: http://stackoverflow.com/comment/83706944
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83707076
tagged with: python
possible better answer: http://stackoverflow.com/a/48360202
upvote count: 6
has title: Recursive and random grouping a list
has body: I'm trying to write a function which creates dichotomously grouped list, f. ex. if my input is as following: [a, b, c, d, e, f, g, h] I want to choose random integer which will split it into smaller sublists again and again recursively until the sublists' length is maximum two, like: [[a, [b, c]], [d, [[e, f], [g, h]]]] This is what I've got so far but still gives me TypeError(list indices must be integers or slices, not list): def split_list(l): if l.__len__() &gt; 2: pivot = np.random.random_integers(0, l.__len__() - 1) print(pivot, l) l = [RandomTree.split_list(l[:pivot])][RandomTree.split_list(l[pivot:])] return l I got stuck and I would be very thankful for any advice.
tagged with: recursion
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/83706963
has comment: http://stackoverflow.com/comment/83707073
accepted answer: http://stackoverflow.com/a/48360428
has comment: http://stackoverflow.com/comment/83707170
downvote count: 1

http://stackoverflow.com/comment/83865912
score: 0
comment on: http://stackoverflow.com/a/48425430
type: Comment
has text: Thank you very much, sound like a nice idead. I will definitely try that out as soon as possible and return :)
type: AnswerComment

http://stackoverflow.com/q/48449045
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/83893902
tagged with: macos
has comment: http://stackoverflow.com/comment/83955738
has comment: http://stackoverflow.com/comment/83982159
has comment: http://stackoverflow.com/comment/83923671
has comment: http://stackoverflow.com/comment/83977071
has title: Python tkinter GUI loading differently between Python IDLE+Shell and Terminal
score: 0
has comment: http://stackoverflow.com/comment/83892624
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83898814
has comment: http://stackoverflow.com/comment/83899632
answer count: 0
has comment: http://stackoverflow.com/comment/83904052
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83939721
has comment: http://stackoverflow.com/comment/83923716
has comment: http://stackoverflow.com/comment/83903923
type: Question
has body: I have a tkinter GUI that is set up to work in both Python 2.7 and 3. I programmed it using the standard "Python IDLE + Python 3.6.0 Shell". However, upon doing some test runs using Terminal (such as python3 filename.py) or within a conda python2 environment (via python2 filename.py), I've found that Terminal outputs a tkinter GUI that has some subtle flaws (please see attached images). On the left is Python IDLE+Shell (how I'd like to see the GUI), on the right is Terminal. The colors are much darker in the Terminal version Menu: There is a white edge on the menu screen border (left side and partial top side) in the Terminal version Page1: The page is being cut off at the bottom in the Terminal version (due to fixed dimensions per frame); each label appears to be taking up more space, and pushing the widgets below the frame cutoff. This is the same for all other pages (other pages not shown in this post) Can anyone shed light on this problem? UPDATE 1: Using Bryan's suggestion below, I went in and manually set my label text and heights for each widget; the combination of text= and self.label1.config(height=1) did the trick. As said, it appears the terminal takes certain values by default that differ from IDLE's; thus explicitly defining all values is the correct methodology. Still not sure about the color shift (darker in Terminal) or the place() visual glitch on the splash screen. UPDATE 2: After some experimenting, the menu image actually has a white border natively around the ext. edge, which is only being seen in the Terminal window. Setting up the frame like below fixes the problem: bg_image=Tk.PhotoImage(file=img_path1) bg_label=Tk.Label(self,image=bg_image,borderwidth=0,highlightthickness=0) bg_label.bg_image = bg_image bg_label.place(anchor='nw') Still don't know why the colors are getting darker in the Terminal version - so I'm leaving this as an open question.
tagged with: terminal
has comment: http://stackoverflow.com/comment/83956713

http://stackoverflow.com/comment/83933490
score: 0
type: Comment
type: AnswerComment
has text: Great explanation of how this actually works. Thank you for taking the time, I'm sure others will find this helpful as well. As for the function in one line, I've discovered that many people like to write them, but as a new learner I find them so confusing to try and read. Also didn't know about the underscores, only ever dabbled in c++ and see lots of camel. Great Answer! (2min till except)
comment on: http://stackoverflow.com/a/48469811

http://stackoverflow.com/comment/83773413
type: Comment
type: QuestionComment
has text: I don't notice such drastic jumps with my system, but it does shoot up by 200MB when I import the module
comment on: http://stackoverflow.com/q/48392773
score: 0

http://stackoverflow.com/comment/83663447
comment on: http://stackoverflow.com/a/48338194
type: AnswerComment
has text: is it a *wav file
score: 0
type: Comment

http://stackoverflow.com/a/48352727
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48352488
has comment: http://stackoverflow.com/comment/83692313
has body: The code you're asking here: df['Car_Make'].apply(lambda x:pd.Series(x.split()[::-1])) There are several things going on here: 1.) First, lambda are basically impromptu functions. In this case, it's an unnamed function taking the argument x, and returns pd.Series(x.split()[::-1]. More on x later. 2.) pd.Series(...) as you know creates a pandas Series object much like your original data. 3.) x.split() is splitting the string x with space as a separator by default. 4.) The [::-1] bit is a slice.. Much like range(), it takes 3 params, [start: end: steps]. In this case, it's saying to get the string from start to end, but use -1 as steps, i.e. in reverse. Note that only the end param is mandatory. 5.) The main function here is apply() on your df['Car_Make'] series, which is essentially a list of strings. apply() takes a function (much like map()) and apply it to the df['Car_Make'] series. In this case, it's applying the lambda, which takes the data of your series and use it as argument x for the function. 6.) Putting everything back together. The statement is: passing the df['Car_Make'] string data as x to the lambda lambda then process the x.split() to split the string data into list. The list is then sorted in reverse order by the slice [::-1]. pd.Series() now convert the list into a Series object. The Series object is then returned by lambda to your apply() function. The apply() function then return the resulting Series object, which conveniently, is the reverse sorted string you wanted in a Series. If all you care about is the very last split though, you really don't need to do the reverse split and all that. You could easily have done the following and it would have returned the very last item in the split right away: data['Car Make'].apply(lambda x: pd.Series({'Car_Make':x.split()[-1]})) Car_Make 0 ManualConvertible 1 AutoConvertible 2 ManualConvertible 3 AutoConvertible 4 ManualHatch 5 AutoHatch Thank you for asking this question, I learned a few stuff about pand…
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83724735
comment on: http://stackoverflow.com/a/48368962
score: 0
has text: cant't see session_start in official docs (https://lazka.github.io/pgi-docs/), any chance of a code example?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/136720774
comment on: http://stackoverflow.com/a/59848407
score: 0
has text: Thank you for your answer! I really believe that this is the correct way to use click for this behavior. Thanks for taking the time to write this answer out and post it here.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48404587
score: 1
has comment: http://stackoverflow.com/comment/83797738
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83798226
has comment: http://stackoverflow.com/comment/83799132
type: Answer
has body: Seems that the first (title) line is unsalvageable because it contains spaces &amp; unquoted fields. Could be fixed by a specific regex. I'll skip it instead. The rest of the lines is not csv, but contains quoted tokens separated by spaces, a breeze for shlex.split: import shlex,csv with open("input.csv") as f: title = next(f) # discard title line with open("output.csv","w",newline="",encoding="utf-8") as fw: cw = csv.writer(fw,delimiter=";") # may be changed to "," cw.writerows(shlex.split(l) for l in f) output: Generated On;Device Status;Energy Yield of Current Day (kWh);Inv. efficiency(%);Total Energy Yield (kWh);Input Power (kW);Active Power (kW);Reactive Power (kVar);Power Factor;Grid Frequency (Hz);Grid A Current (A);Grid B Current (A);Grid C Current (A);Grid A Phase Voltage (V);Grid B Phase Voltage (V);Grid C Phase Voltage (V);PV1 Input Current (A);PV2 Input Current (A);PV3 Input Current (A);PV4 Input Current (A);PV5 Input Current (A);PV6 Input Current (A);PV1 Input Voltage (V);PV2 Input Voltage (V);PV3 Input Voltage (V);PV4 Input Voltage (V);PV5 Input Voltage (V);PV6 Input Voltage (V);Cabinet Temperature (℃) 2017-12-22 00:00:00 ;Idle: No irradiation;0.00;0.00;45803.34;0.000;0.000;0.000;0.000;0.00;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0 2017-12-22 00:15:00 ;Idle: No irradiation;0.00;0.00;45803.34;0.000;0.000;0.000;0.000;0.00;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0 the file now opens properly in excel (note that various versions of excel require comma or semicolon separator by default)
has comment: http://stackoverflow.com/comment/83797662
has comment: http://stackoverflow.com/comment/83799267
answers question: http://stackoverflow.com/q/48404294

http://stackoverflow.com/comment/83698249
type: QuestionComment
comment on: http://stackoverflow.com/q/48354279
score: 0
has text: Please update this question with a small sample of the desired output.
type: Comment

http://stackoverflow.com/comment/83714357
score: 0
type: Comment
type: QuestionComment
has text: @James I used line profiler .Here is the link https://github.com/rkern/line_profiler
comment on: http://stackoverflow.com/q/48363560

http://stackoverflow.com/q/48379931
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83746636
linked to: http://stackoverflow.com/q/26724002
has comment: http://stackoverflow.com/comment/83746385
tagged with: big-o
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83746553
answer count: 0
duplicate of: http://stackoverflow.com/q/26724002
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83746444
tagged with: dictionary
has body: Maybe this is a very noob question. The complexity of looking for an element from a list is O(n) (if the list is sorted it can be done in O(log n) which is way better). However the complexity of doing the same operation in a dictionary is O(1) (because keys in a dictionary are hashable). Then, if my data is hashable (integers, strings), I could store my data as dictionary keys just to have this speed boost when looking if an element is in the dictionary. However a dictionary is a pair key/value, and I just want to use it as a list, so I just need keys without values. Of course I can create a dict with empty values for each key, but I'm wondering, does something else already exist to do what I'm suggesting? If I do this it takes O(1) my_dict = {2:[], 8:[], 3:[], 4:[]} 3 in my_dict If I use a list it takes O(n): my_list = [2,8,3,4] `3 in my_list` I want something like my_hashable_list = [2,8,3,4] 3 in my_hashable_list() # so it takes O(1) Does such a datatype exist?
has title: Is there any Hashable list datatype?
tagged with: list
has comment: http://stackoverflow.com/comment/83746482

http://stackoverflow.com/q/48393985
has comment: http://stackoverflow.com/comment/83777110
type: Question
has title: How to run the current python script (forefront buffer) in Vim's command window?
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: vim
linked to: http://stackoverflow.com/q/18948491
score: 0
has body: I want to run the python script (currently editing) in Vim's command window (do not want to switch to terminal). I am currently using this method - :w !python. Are there any other methods available?
has comment: http://stackoverflow.com/comment/83777118
duplicate of: http://stackoverflow.com/q/18948491
favorite count: 0

http://stackoverflow.com/a/48397352
upvote count: 3
downvote count: 0
has body: Just filter the lines and then use join. import re with open('log_file') as file: union = ''.join(filter(lambda line: re.match(r'\w+'), file.readlines())) # change the regex as per your definition of 'special characters'.
type: Answer
answers question: http://stackoverflow.com/q/48397272
score: 3

http://stackoverflow.com/a/48346830
score: 2
has comment: http://stackoverflow.com/comment/83679635
has body: Using the roundrobin itertools recipe: Two Inputs import itertools as it a = list("ABCD") b = list("ABCDEFGH") list(it.chain.from_iterable(roundrobin(zip(it.cycle(a), b)))) # ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H'] itertools.cycle() infinitely extends the shorter iterable. zip() stops iterating after the shorter iterable. roundrobin handles the interleaving of elements between iterables. Longer Inputs To work on more than two inputs, we need to cycle all but the last iterable: def interleave(*inputs): *rest, last = inputs cycles = (it.cycle(x) for x in rest) return list(it.chain.from_iterable(mit.roundrobin(zip(*cycles, last)))) Now for two or more input iterables, we can apply the interleave function: p = list("ab") q = list("abcd") r = list("abcdef") input_list_1 = [a, b] input_list_2 = [p, q, r] print(interleave(*input_list_1)) # ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H'] print(interleave(*input_list_2)) # ['a', 'a', 'a', 'b', 'b', 'b', 'a', 'c', 'c', 'b', 'd', 'd', 'a', 'a', 'e', 'b', 'b', 'f'] Note: you can either reimplement the roundrobin recipe from the docs or install a third-party library that implements it for you, e.g. more_itertools. &gt; pip install more_itertools, then in Python, from more_itertools import roundrobin.
upvote count: 2
has comment: http://stackoverflow.com/comment/83681363
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48346169
has comment: http://stackoverflow.com/comment/83680185
has comment: http://stackoverflow.com/comment/83679722

http://stackoverflow.com/a/48390612
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Meanwhile, consider learning pandas's conditional logic/filter/aggregation methods which are translatable from your SQL skills: trunc(..., 'MM') ---&gt; .dt.month CASE WHEN ---&gt; df.loc or np.where() WHERE ---&gt; [] GROUP BY ---&gt; .groupby AVG --&gt; .agg('mean') Here is an example Random Data (seeded for reproducibility) import numpy as np import pandas as pd import datetime as dt import time epoch_time = int(time.time()) np.random.seed(101) pandas_df = pd.DataFrame({'date': [dt.datetime.fromtimestamp(np.random.randint(1480000000, epoch_time)) for _ in range(50)], 'hour_ending': [np.random.randint(14) for _ in range(50)], 'volume': abs(np.random.randn(50)*100)}) # OUTPUT CSV AND IMPORT INTO DATABASE TO TEST RESULT pandas_df.to_csv('Output.csv', index=False) print(pandas_df.head(10)) # date hour_ending volume # 0 2017-01-01 20:05:19 10 56.660415 # 1 2017-09-02 00:56:27 3 79.060800 # 2 2018-01-04 09:25:05 7 23.076240 # 3 2016-11-27 23:44:55 6 102.801241 # 4 2017-01-29 12:19:55 5 88.824230 # 5 2017-04-15 15:16:09 6 214.168659 # 6 2017-09-07 08:12:45 9 97.607635 # 7 2017-12-31 15:35:36 13 141.467249 # 8 2017-04-21 23:01:44 13 156.246854 # 9 2016-12-22 09:27:49 2 67.646662 Aggregation (calculates columns prior to summarizing) # CALCULATE GROUP MONTH COLUMN pandas_df['month'] = pandas_df['date'].dt.month # CONDITIONAL LOGIC COLUMNS pandas_df.loc[pandas_df['hour_ending'].between(7,24, inclusive = False), 'volume_peak'] = pandas_df['volume'] pandas_df.loc[~pandas_df['hour_ending'].between(7,24, inclusive = False), 'volume_off_peak'] = pandas_df['volume'] print(pandas_df.head(10)) # date hour_ending volume month volume_peak volume_off_peak # 0 2017-01-01 20:05:19 10 56.660415 1 56.660415 NaN # 1 2017-09-02 00:56:27 3 79.060800 9 NaN 79.060800 # 2 2018-01-04 09:25:05 7 23.076240 1 NaN 23.076240 # 3 2016-11-27 23:44:55 6 102.801241 11 NaN 102.801241 # 4 2017-01-29 12:19:55 5 88.824230 1 NaN 88.824230 # 5 2017-04-15 15:16:09 6 214.168659 4 NaN 214.168659 # 6 2017-09-07 08…
score: 2
answers question: http://stackoverflow.com/q/48385853
accepted answer of: http://stackoverflow.com/q/48385853

http://stackoverflow.com/q/48342840
tagged with: pool
score: 1
has body: I have seen this example here on the website and I am wondering how to make the code work in accordance with the pool function. I have been through a lot of documentation but the closest to this code is the question asked by Olson: Can I use a multiprocessing Queue in a function called by Pool.imap? I would like to assign 4 processes to the code. Please be gentle, I have been going through stackoverflow questions as well and all I am asking is that someone provides an example in accordance with the example I provide. Here is the code: import random from multiprocessing import Process, Queue import time from datetime import datetime def function1(q): while True: daydate = datetime.now() number = random.randrange(1, 215) print('Sent to function2: ({}, {})'.format(daydate, number)) q.put((daydate, number)) time.sleep(2) def function2(q): while True: date, number = q.get() print("Recevied values from function1: ({}, {})".format(date, number)) time.sleep(2) if __name__ == "__main__": q = Queue() a = Process(target=function1, args=(q,)) a.start() b = Process(target=function2, args=(q,)) b.start() a.join() b.join() I am new here so please be gentle thank you. So how can I use pool function with this code and assign 4 processes to it? That is the question and I thank you all very much in advance.
has comment: http://stackoverflow.com/comment/83673171
has title: How to make Queue work with Pool function in multiprocessing
has comment: http://stackoverflow.com/comment/83673470
has comment: http://stackoverflow.com/comment/83674455
linked to: http://stackoverflow.com/q/3827065
favorite count: 0
tagged with: multiprocessing
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/83813291
type: Comment
has text: @juanpa.arrivillaga Could you elaborate a bit more on the process the function does to convert it to a string.
type: QuestionComment
comment on: http://stackoverflow.com/q/48411539
score: 0

http://stackoverflow.com/comment/83829524
type: AnswerComment
comment on: http://stackoverflow.com/a/48419819
type: Comment
has text: I get the same output from the code (I'm using a French windows so its should not be a problem to read accent) but it still print the unicode char in my data frame
score: 0

http://stackoverflow.com/a/48481836
type: Answer
has comment: http://stackoverflow.com/comment/83956795
has comment: http://stackoverflow.com/comment/84053011
has body: I just reversed your logic: I walk through the output field and add values from matrix. Please note the use of the exception (that was the hint regarding the "x"s). With this solution, you don't have to shrink your result using pop(). import itertools def minesweeper(matrix): #create the output matrix first to preserve the size #underscored variables to prevent warnings about unused variables output_matrix = [[0 for _j in range(len(matrix[0]))] for _i in range(len(matrix))] #unchanged for x in range(len(matrix)): matrix[x].insert(0, "x") matrix[x].insert(len(matrix)+2, "x") frame = ["x" for i in range(len(matrix[0]))] matrix.insert(0, frame) matrix.insert(len(matrix), frame) #to the logics the other way round: count the bombs around the output fields. #neighyours defines the offsets of all neighouring fields neighbours = [(-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1)] for i, j in itertools.product(range(len(output_matrix[0])), range(len(output_matrix))): #get all indices; you could use two for-loops instead of itertools.product... print(i, j) # just to see how it works... please remove for final version for offset_i, offset_j in neighbours: print(" ", offset_i, offset_j ) # just to see how it works... please remove for final version # the exceptions do the magic here: If you add an "x", a TypeError is raised. # So you don't do anythithing if this happens. Otherwise you'll add 0 or 1 (adding "True" adds 1, "False" adds 0) try: output_matrix[j][i] += matrix[j + offset_j + 1][i + offset_i + 1] print("result = ", output_matrix[j][i]) # just to see how it works... please remove for final version except TypeError: print("pass") # just to see how it works... please remove for final version pass return output_matrix matrix = [[False, False, True], #renamed input variable since "input" is a function name... [False, False, False], [False, False, False]] print(minesweeper(matrix)) In general, your solution is working (if you uncomment the line #matr…
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83959753
has comment: http://stackoverflow.com/comment/83959576
answers question: http://stackoverflow.com/q/48481513
has comment: http://stackoverflow.com/comment/83973179
has comment: http://stackoverflow.com/comment/83956905
has comment: http://stackoverflow.com/comment/84053349
upvote count: 1

http://stackoverflow.com/q/48369855
type: Question
has comment: http://stackoverflow.com/comment/83727081
has comment: http://stackoverflow.com/comment/83726972
has comment: http://stackoverflow.com/comment/83726575
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48370299
has title: Install dependencies only in virtualenv
has body: I need to freeze my dependencies inside of virtualenv. As in virtualenv I have flask web application list of requirements should look like this: Flask==0.10.1 Jinja2==2.7.3 Werkzeug==0.9.6 html5lib==0.999 itsdangerous==0.24 mote==0.0.3 ndg-httpsclient==0.3.2 pyasn1==0.1.7 requests==2.4.3 twython==3.1.2 urllib3==1.9.1 virtualenv==15.1.0 wheel==0.24.0 wsgiref==0.1.2 But when I try to freeze it by doing: source venv/bin/activate sudo sh -c 'sudo pip freeze &gt; require.txt' # baceuse after simple sudo pip freeze &gt; requir.txt I am getting this error -bash: requir.txt: Permission denied I am getting this list: Cap1xxx==0.1.3 ExplorerHAT==0.4.2 Flask==0.10.1 Flask-Email==1.4.4 Flask-Login==0.4.1 Flask-Mail==0.9.1 Jinja2==2.7.3 MarkupSafe==0.23 MySQL-python==1.2.3 Pillow==2.6.1 RPi.GPIO==0.6.3 RTIMULib==7.2.1 Werkzeug==0.9.6 argparse==1.2.1 automationhat==0.0.4 blinker==1.3 blinkt==0.1.0 certifi==2018.1.18 chardet==3.0.4 colorama==0.3.2 dropbox==8.6.0 drumhat==0.0.5 envirophat==0.0.6 fourletterphat==0.0.2 gpiozero==1.4.0 html5lib==0.999 idna==2.6 itsdangerous==0.24 lxkeymap==0.1 mcpi==0.1.1 microdotphat==0.1.3 mote==0.0.3 motephat==0.0.2 ndg-httpsclient==0.3.2 numpy==1.8.2 phatbeat==0.0.2 pianohat==0.0.5 picamera==1.13 picraft==1.0 pifacecommon==4.2.1 pifacedigitalio==3.1.0 piglow==1.2.4 pigpio==1.35 pyOpenSSL==0.13.1 pyasn1==0.1.7 pygame==1.9.2a0 pygobject==3.14.0 pyinotify==0.9.4 pyserial==2.6 python-apt==0.9.3.12 rainbowhat==0.0.2 requests==2.18.4 scrollphat==0.0.7 scrollphathd==1.0.1 sense-emu==1.0 sense-hat==2.2.0 six==1.8.0 skywriter==0.0.7 smbus==1.1 sn3218==1.2.7 spidev==3.0 touchphat==0.0.1 twython==3.1.2 urllib3==1.22 virtualenv==15.1.0 wheel==0.24.0 wsgiref==0.1.2 which as you can see contains all installed packages and many of them are not connected to my flask web application like for instance numpy==1.8.2 or RPi.GPIO==0.6.3 despite the fact I am doing it inside of virtualenv.. So, is there a way to get list of dependencies which are bundled only with my fl…
tagged with: pip
tagged with: python
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83728274
linked to: http://stackoverflow.com/q/45666097
has answer: http://stackoverflow.com/a/48370246
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83726998

http://stackoverflow.com/q/48434059
accepted answer: http://stackoverflow.com/a/48435149
tagged with: python
has answer: http://stackoverflow.com/a/48434925
possible better answer: http://stackoverflow.com/a/48434925
answer count: 4
score: 8
upvote count: 8
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/83859788
has title: Efficient numpy argsort with condition while maintaining original indices
has answer: http://stackoverflow.com/a/48435149
favorite count: 0
has comment: http://stackoverflow.com/comment/83859885
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48434263
has comment: http://stackoverflow.com/comment/83862557
has body: I'm wondering what the most efficient way to do an argsort of an array given a condition, while preserving the original index import numpy as np x = np.array([0.63, 0.5, 0.7, 0.65]) np.argsort(x) #Corrected argsort(x) solution Out[99]: array([1, 0, 3, 2]) I want to argsort this array with condition that x>0.6. Since 0.5 &lt; 0.6, index 1 should not be included. x = np.array([0.63, 0.5, 0.7, 0.65]) index = x.argsort() list(filter(lambda i: x[i] &gt; 0.6, index)) [0,3,2] This is inefficient since its not vectorized. EDIT: The filter will eliminate most of elements. So ideally, it filter first, then sort, while preserving original index.
has answer: http://stackoverflow.com/a/48435322
has comment: http://stackoverflow.com/comment/83859706

http://stackoverflow.com/a/48472909
type: Answer
has comment: http://stackoverflow.com/comment/83939751
has comment: http://stackoverflow.com/comment/83939804
has comment: http://stackoverflow.com/comment/83939892
has body: One can use str.lstrip() method and take the difference of the lengths of both strings, which will be the number of spaces that begin the string. def num_start_spaces(text): return len(text)-len(text.lstrip(" ")) print(num_start_spaces(" spaces")) The above prints "8 spaces". Edit: I enhanced this answer above using info from the duplicate question. However, for the task at hand, I think doing this alone in the context stated is going to be a little tedious and have a lot of overhead. Before you do any text parsing, you'll probably want to use it to make a list of the indents per line (and then when you iterate through the lines, you'll have that for quick reference): lines=myString.split("\n") #lines is the lines of the text we're parsing indents=[] #Values are the number of indents on the line. for line in lines: spaces=num_start_spaces(line) if spaces%4!=0: raise ValueError("The spaces on line "+str(len(indents))+" are not zero or a multiple of four:", spaces) indents.append(spaces/4) i=0 while i&lt;len(lines): #Do text parsing here (and use indents for reference). We're in a while loop so we can reference lines before and after more easily than in a for loop. i+=1
has comment: http://stackoverflow.com/comment/83939727
score: 1
has comment: http://stackoverflow.com/comment/83939775
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48472908

http://stackoverflow.com/q/48374558
type: Question
has answer: http://stackoverflow.com/a/48375404
tagged with: turtle-graphics
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Does turtle have an onkeyhold method
has comment: http://stackoverflow.com/comment/83737562
has body: In a program I am writing, turtle's onkey() method doesn't do exactly what I need. I know there are also onkeypress and onkeyrelease but neither do what I need. Is there a method for continuously running a function while a key is held? Such as import turtle num = 0 def add(): global num num += 1 print(num) turtle.onkey(add, "Up") turtle.listen() turtle.mainloop() If you did something like this, for taking the keyboard input, onkey only responds once, and it only responds on the release of the key. Is there a method that would continuously run the function while it is being held down?
score: 1
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48375647
score: 0
has body: Use module datetime: d = datetime.datetime.strptime('2018-01-15 09:00:01','%Y-%m-%d %H:%M:%S') d.timestamp() #1516024801.0
answers question: http://stackoverflow.com/q/48375425
type: Answer

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/48335994

http://stackoverflow.com/comment/83735532
has text: Through `tkinter` I have a graphical interface where the values of the variables are entered and read
type: QuestionComment
comment on: http://stackoverflow.com/q/48373982
type: Comment
score: 0

http://stackoverflow.com/comment/83936943
type: Comment
comment on: http://stackoverflow.com/a/48471127
type: AnswerComment
has text: @Vasily I'm sorry for the inconvenience. Did you get the error messages? And, for example, can you get the response from a variable like ``res = service.files().copy()``?
score: 0

http://stackoverflow.com/comment/83748698
has text: @eyllanesc Thanks for promt response .
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48379584
score: 0

http://stackoverflow.com/comment/83759773
score: 0
type: QuestionComment
has text: @FrançoisAndrieux sorry about that, I've removed the tag and clarified a bit
type: Comment
comment on: http://stackoverflow.com/q/48386100

http://stackoverflow.com/q/48448830
possible better answer: http://stackoverflow.com/a/48473281
score: 1
has comment: http://stackoverflow.com/comment/83890971
has comment: http://stackoverflow.com/comment/83890242
has answer: http://stackoverflow.com/a/48473281
downvote count: 0
has comment: http://stackoverflow.com/comment/83890245
upvote count: 1
tagged with: account
accepted answer: http://stackoverflow.com/a/48449195
favorite count: 0
type: Question
has body: how i said in the title, i want the password to be hashed when is saved. Its possible with this? def __OnClickSaveLoginButton(self): id = self.idEditLine.GetText() pwd = self.pwdEditLine.GetText() if (len(id) == 0 or len(pwd) == 0): self.PopupNotifyMessage("ID and Password required",self.SetIDEditLineFocus) return file_object = open("account.cfg", "w") file_object.write(id+"\n"+pwd) self.PopupNotifyMessage("Saved.",self.SetIDEditLineFocus) file_object.close()
has answer: http://stackoverflow.com/a/48449195
answer count: 2
tagged with: hash
has comment: http://stackoverflow.com/comment/83892016
has title: Hashing Password in .py file
has comment: http://stackoverflow.com/comment/83890171
tagged with: python
linked to: http://stackoverflow.com/q/19580412
tagged with: passwords
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1054022

http://stackoverflow.com/comment/83789855
type: Comment
comment on: http://stackoverflow.com/a/48400949
has text: Thanks for suggesting this. I originally asked for help in using `subprocess` to launch the script. My understanding is that it is recommended over `os.system`. In that post, someone said that launching a python script from a python script with `subprocess` is quite strange, hence I am trying to use the import module instead.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48455038
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83903353
has comment: http://stackoverflow.com/comment/83903378
linked to: http://stackoverflow.com/q/7865430
has comment: http://stackoverflow.com/comment/83903370
score: 0
has title: Create object while still running code
answer count: 0
tagged with: subprocess
has body: So I have some python code that creates objects like so: paramToPassa = 'test' paramToPassb = 'test2' paramToPassc = 'test3' paramToPassd = 'test4' #... so on objectToCreate = continuouslyRunningObject(paramToPassa, paramToPassb) print('test') objectToCreate2 = continouslyRunningObject(paramToPassc, paramToPassd) The object instantiates with a while True: loop so it runs indefinitely after it's created (it does terminate eventually, but the time varies). The problem is I want to create objectToCreate2 simultaneously and have it also running at the same time as objectToCreate. Normally, the print statement is only called along with objectToCreate2 after the objectToCreate is finished running. Is there any way to do this easily or will I have to look into multi-threading/something of that nature? Thanks! EDIT: Tried using Multiprocessing.Process to create objects like so... a = Process(target=continouslyRunningObject, args=(paramToPassa, paramToPassb)) a.start() but now I get the error 'TypeError: can't pickle _thread.lock objects'. Any ideas?
tagged with: multithreading
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/83903210

http://stackoverflow.com/comment/84033412
has text: Another was to do it: https://stackoverflow.com/a/48519175/1011724
comment on: http://stackoverflow.com/q/48344806
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48358414
has body: How i can find 14 migrations and apply them? How easy is it to solve this problem?
has comment: http://stackoverflow.com/comment/83703826
score: 0
has title: How i can find 14 migrations and apply them?
answer count: 1
has answer: http://stackoverflow.com/a/48358611
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/74977097
has body: Look into hidden modules but the path needs to be included as well.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/132312678
answers question: http://stackoverflow.com/q/48362432

http://stackoverflow.com/q/48433481
type: UnansweredQuestion
downvote count: 0
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/119530642
score: 3
upvote count: 3
tagged with: pyinstaller
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
has title: PyQt5 with PyInstaller error, no module
has body: I am trying to bundle a python program into an application using PyInstaller on Mac OS X. I am running into an issue where when I go to run the application directly from the executable I get an error: ImportError: No module named PyQt5.QtWidgets I have tried to import the module as a hidden import in the .spec file.. This idea didn't worked. When I run the pyinstaller command with no hooks and no imports this prints in terminal 22530 INFO: Excluding import 'PyQt5' 22533 WARNING: Removing import PIL.ImageQt from module PyQt5 These are my import statements from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * Why is pyinstaller excluding PyQt5 from the build? How can I prevent it from doing it?
tagged with: pyqt

http://stackoverflow.com/q/48453660
has comment: http://stackoverflow.com/comment/83900460
has comment: http://stackoverflow.com/comment/83900525
has body: I am using the following function to write a given_dict to csv in python and getting following error below. Any idea what I am doing wrong? def write_dict_as_csv(given_dict): ... with open('dict.csv', 'wb') as csv_file: ... writer = csv.writer(csv_file) ... writer.writerow(given_dict.keys()) ... writer.writerows(zip(*given_dict.values())) Error: &gt;&gt;&gt; write_dict_as_csv(python_csv) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in print_dict_as_csv TypeError: an integer is required additional info using a test case: import csv #this is a test case which is used to test the functions def test_normalization_function(): x1 = {'k1': 'a1', 'k2': 'b1'} x2 = {'k2': 'b2', 'k3': 'c2'} x3 = {'k1': 'a3'} x = [x1,x2,x3] y = normalization(x) # print('') for k in y: print('key: {} : {}'.format(k, y[k])) with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x w = csv.DictWriter(f, y.keys()) w.writeheader() w.writerow(y) def normalization(list_of_dict): super_dict = {} column_counter = 0 for i_dict in list_of_dict: for k, v in i_dict.iteritems(): if k not in super_dict: super_dict[k] = [] for i in range(column_counter): super_dict[k].append('NONE') super_dict[k].append(v) column_counter += 1 for k in super_dict: if k not in i_dict: super_dict[k].append('NONE') return super_dict output for the code when I run test_normalization_function(): &gt;&gt;&gt; test_normalization_function() key: k3 : ['NONE', 'c2', 'NONE'] key: k2 : ['b1', 'b2', 'NONE'] key: k1 : ['a1', 'NONE', 'a3'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 11, in test_normalization_function TypeError: an integer is required it shows the dictionary can be print. But when I am trying to save it in csv file, it is giving an error.
type: Question
has comment: http://stackoverflow.com/comment/83900353
has comment: http://stackoverflow.com/comment/83900373
score: 0
has comment: http://stackoverflow.com/comment/83900581
has comment: http://stackoverflow.com/comment/83901125
has comment: http://stackoverflow.com/comment/83900607
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83900437
has comment: http://stackoverflow.com/comment/83902253
linked to: http://stackoverflow.com/q/1046656
tagged with: python
has comment: http://stackoverflow.com/comment/83900770
has comment: http://stackoverflow.com/comment/83900403
has comment: http://stackoverflow.com/comment/83900626
linked to: http://stackoverflow.com/q/10373247
duplicate of: http://stackoverflow.com/q/1046656
answer count: 0
has title: TypeError when write a dictionary to csv file
has comment: http://stackoverflow.com/comment/83900333
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83900586

web-crawler
tags question: http://stackoverflow.com/q/48473110
tags question: http://stackoverflow.com/q/48435200
tags question: http://stackoverflow.com/q/48393809
tags question: http://stackoverflow.com/q/48406930
tags question: http://stackoverflow.com/q/48340454
tags question: http://stackoverflow.com/q/48395352
tag name: web-crawler
tags question: http://stackoverflow.com/q/48428689
type: Tag
tags question: http://stackoverflow.com/q/48406852
tags question: http://stackoverflow.com/q/48374455

http://stackoverflow.com/q/48413991
tagged with: python
has answer: http://stackoverflow.com/a/48414144
tagged with: dictionary
tagged with: reorganize
has comment: http://stackoverflow.com/comment/83817914
has answer: http://stackoverflow.com/a/48414403
upvote count: 4
score: 2
tagged with: list
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31730845
downvote count: 2
has body: I have a dict inside a list that is currently like this: [ {'name': 'Joe', 'score': 98, 'subject': 'Math'}, {'name': 'Bob', 'score': 90, 'subject': 'Math'}, {'name': 'Bill', 'score': 88, 'subject': 'English'}, {'name': 'Jane', 'score': 95, 'subject': 'English'}] I would like to regroup or reorganize it as follows: [ {'subject': 'Math', 'Results': [{'name': 'Joe','score':98}, {'name':'Bob', 'score':90}]}, {'subject': 'English', 'Results': [{'name': 'Jane','score':95}, {'name':'Bill', 'score':88}]} ] I tried using itertools.groupby and dict.setdefault() as suggested here, but cannot quite get what I want. How can I do this?
answer count: 7
has answer: http://stackoverflow.com/a/48435983
has title: Regroup or reorganize keys in a dict?
has answer: http://stackoverflow.com/a/48414161
favorite count: 0
has answer: http://stackoverflow.com/a/48414137
type: Question
has comment: http://stackoverflow.com/comment/83817935
has answer: http://stackoverflow.com/a/48414056
has answer: http://stackoverflow.com/a/48415152
tagged with: grouping

contour
tags question: http://stackoverflow.com/q/48476923
tags question: http://stackoverflow.com/q/48487346
type: Tag
tag name: contour
tags question: http://stackoverflow.com/q/48408123

http://stackoverflow.com/q/48351265
tagged with: discord
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48357083
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/48357083
has title: On message delete message Discord.py
upvote count: 2
has comment: http://stackoverflow.com/comment/83689394
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 1
downvote count: 0
has body: import discord import asyncio client = discord.Client() @client.event async def on_ready(): print ("I’m Now Online") @client.event async def on_message(message): if message.author == client.user: return elif message.content.startswith("deletethis"): I’m wonder how I could be able to add to this to delete the above command when the author of the message sends the command above. May someone help create one? I’ve tried my self by brain and didn’t find anything online so I’m looking for some help maybe.

http://stackoverflow.com/q/48451833
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83896659
has answer: http://stackoverflow.com/a/48451966
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48451873
type: UnansweredQuestion
has title: How can I change my variable to the players preference?
has body: I've just started to try and get back into coding in python by writing this simple "game" but I can't get nrange and unumber to equal the players preference. Here is the code I've written so far, import random import time nrange = 10 rnumber = random.randint(1, nrange) unumber = 1 def start(): nrange = input("How many numbers do you want to guess between? ") unumber = input("What will your number guess be? ") main() def main(): print ("Number Reveal in...") time.sleep(1) print ("3") time.sleep(1) print ("2") time.sleep(1) print ("1") time.sleep(1) nreveal() def nreveal(): if rnumber == unumber: print("The Number was ", rnumber, " Well done you guessed correctly",) tryagain = input("Do you wanna play again? (Y/N)") if tryagain == ("Y"): start() if tryagain == ("N"): print ("Ok, hope you enjoyed playing") time.sleep(2) quit() if rnumber != unumber: print("The Number was ", rnumber, " sorry but you guessed wrong",) tryagain = input("Do you wanna try again? (Y/N)") if tryagain == ("Y"): start() if tryagain == ("N"): print ("Ok, hope you enjoyed playing") time.sleep(2) quit() start()
tagged with: python

maya
tags question: http://stackoverflow.com/q/48344963
tags question: http://stackoverflow.com/q/48451459
type: Tag
tags question: http://stackoverflow.com/q/48394349
tag name: maya
tags question: http://stackoverflow.com/q/48432692

http://stackoverflow.com/q/48406242
has comment: http://stackoverflow.com/comment/83802796
type: Question
has comment: http://stackoverflow.com/comment/83801413
has title: Python Dilemma this function should be working but it doesn't
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48406412
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48406541
answer count: 2
has body: I think this should work but doesn't could someone explain me why? the function is expand and should behave as following, given a list of 0 and 1 as input: if input = [1,0,1] -&gt; output = [[0, 1], [1, 0], [0, 1]] if input = [1,1,1] -&gt; output = [[0, 1], [0, 1], [0, 1]] if input = [0,1,1] -&gt; output = [[1, 0], [0, 1], [0, 1]] if input = [0,0,0] -&gt; output = [[1, 0], [1, 0], [1, 0]] ecc. WHY THE FOLLOWING IS NOT WORKING? def expand(a): o = [] t = [0]*2 # t = [0,0] for element in a: if element == 0: t[0] = 1 t[1] = 0 elif element == 1: t[0] = 0 t[1] = 1 o.append(t) return o #Es using expand: input [1,0,1] -&gt; output [[1, 0], [1, 0], [1, 0]] #instead of [[0, 1], [1, 0], [0, 1]] what's wrong?

http://stackoverflow.com/q/48424465
tagged with: python
type: Question
has title: Unable to send Subprocess result through Socket
answer count: 0
tagged with: subprocess
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3503879
has body: import socket, os, sys, subprocess s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = '192.168.1.81' port = int(sys.argv[1]) s.connect((host, port)) done = False while not done: print ('Waiting for data....') data_enc = s.recv(1024) data = data_enc.decode() result = os.system(str(data)) s.send(str.encode(result)) here is my code and the error is Traceback (most recent call last): File "trap.py", line 17, in &lt;module&gt; s.send(str.encode(result)) TypeError: descriptor 'encode' requires a 'str' object but received a ' int' when I checked the value of result variable it was 0, but on the machine the subprocess results were fine (when I used 'ls' command it showed the files). I am using python 3 and I tried to run this code on Kali distribution.
has comment: http://stackoverflow.com/comment/83838441
has comment: http://stackoverflow.com/comment/83838602
score: 0
has comment: http://stackoverflow.com/comment/83838870
tagged with: sockets

http://stackoverflow.com/q/48363341
accepted answer: http://stackoverflow.com/a/48364547
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48364547
tagged with: flask
favorite count: 0
has title: Cannot solve mod_wsgi exception in Flask setup
type: Question
tagged with: python
type: AnsweredQuestion
has body: I want to deploy a Flask app using Python 3. I am running Ubuntu 16.04, Apache2. I ran sudo apt-get install libapache2-mod-wsgi-py3 to install wsgi. I followed the instruction here. I have a Flask App on my Linode server at /var/www/html/hxueh.net/finance. Inside the finance folder there is one file and one folder. The structure looks like this. |--------finance |----------------finance |-----------------------static |-----------------------templates |-----------------------venv |-----------------------application.py |----------------finance.wsgi In venv/bin: activate activate_this.py flask pip3.5 python3.5 activate.csh easy_install pip python python-config activate.fish easy_install-3.5 pip3 python3 wheel The finance.wsgi is: #!/usr/bin/python3 import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/html/hxueh.net/finance/") from finance import app as application And my Apache2 config is: ServerName finance.hxueh.net ServerAdmin hxueh1996@gmail.com WSGIScriptAlias / /var/www/html/hxueh.net/finance/finance.wsgi Order allow,deny Allow from all WSGIProcessGroup finance WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all Alias /static /var/www/html/hxueh.net/finance/finance/static Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined I have a Wordpress app running on the same server, with Certbot enabling Let's encrypt certificate. When I visit my server it return Error 500. In error.log it shows: [Sun Jan 21 10:40:56.310304 2018] [mpm_prefork:notice] [pid 26281] AH00169: caught SIGTERM, shutting down [Sun Jan 21 10:41:21.236671 2018] [ssl:warn] [pid 26747] AH01909: hxueh.net:443:0 server certificate does NOT include an ID which matches the server name [Sun Jan 21 10:41:21.276195 2018] [ssl:warn] [pid 26748] AH01909: hxueh.net:443:0 server certificate does NOT include an ID which matches the server name [Sun Jan 21 10:41:21.276370 2018] [wsgi:war…
tagged with: mod-wsgi
score: 1
tagged with: apache

http://stackoverflow.com/comment/83859606
type: Comment
comment on: http://stackoverflow.com/q/48433878
score: 0
type: QuestionComment
has text: Try typing python3 into terminal

http://stackoverflow.com/q/48449895
tagged with: python-3.x
tagged with: linux
type: Question
tagged with: python
has body: I have two images open in a full-screen mode on my Raspberry Pi (using ristretto image viewer). When certain conditions are met, I need to pass an ALT+TAB keystroke combination to display the other one. I am trying to use Popen.communicate, but I don't know how to pass a key combination like ALT+TAB). Does anyone have any ideas? What I need is something like below (replacing "ALT+TAB" with a working code): s = Popen(['ristretto', '-f', 'my.gif' ,'&amp;'],stdin=PIPE) if my_condition: s.communicate("ALT+TAB") I heard about SendKeys package, but it works only for Windows... Thanks, Michal
tagged with: subprocess
type: AnsweredQuestion
score: 3
upvote count: 3
has title: How to pass a keystroke (ALT+TAB) using Popen.communicate (on Linux)?
downvote count: 0
accepted answer: http://stackoverflow.com/a/48455097
answer count: 1
has answer: http://stackoverflow.com/a/48455097
has comment: http://stackoverflow.com/comment/83892646
favorite count: 0
tagged with: raspbian

http://stackoverflow.com/comment/83895481
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48451227
has text: Great, Works exactly as needed. Can you pleas explain what does zip do.
score: 0

http://stackoverflow.com/a/48456915
accepted answer of: http://stackoverflow.com/q/48453315
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48453315
has body: indexserver is deprecated and will be removed. Use install_command: install_command=pip install --index-url=https://localhost --trusted-host=localhost {opts} {packages}
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/86355238
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48480193
type: QuestionComment
has text: Still trying to get pymc3 working. Have now reinstalled "everything", including building hdf5 from sources, but to no avail: now pymc3 imports ok, but crashes when trying a simple example, with: File "/usr/lib/python3.6/site-packages/theano/tensor/type.py", line 269, in dtype_specs }[self.dtype] KeyError: 'object' Interestingly, exactly the same error occurs if I run the same code in Anaconda.

http://stackoverflow.com/comment/83938047
score: 0
type: Comment
type: QuestionComment
has text: Issue here is that `1.1.3.9` is equivalent to `1.1.3.90`
comment on: http://stackoverflow.com/q/48472029

http://stackoverflow.com/comment/83981908
comment on: http://stackoverflow.com/q/48473871
score: 0
type: Comment
type: QuestionComment
has text: @t.m.adam Yes this might be the problem. But this is because of the response from the API. The API might be sending the error in the form other than json. Kindly help me.

http://stackoverflow.com/a/48432310
answers question: http://stackoverflow.com/q/48432211
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48432211
upvote count: 1
has body: a, b = 0, 1 while a &lt; 19: if a: print b, a, b = a + 1, b * (a+1) Use a in-line if statement to check if a is 1. If it's 1 then you know that you already went through the loop at least once.
score: 1
has comment: http://stackoverflow.com/comment/83856200
type: Answer

http://stackoverflow.com/q/48435493
answer count: 4
has comment: http://stackoverflow.com/comment/83862460
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48435600
has answer: http://stackoverflow.com/a/48435630
has body: So, I'm relatively new to python and I have this semantic error. I'm essentially trying to make a program that goes up to 50, then back down. This is not my full program in general but a part of it that I can't seem to solve. This is what I have done: maxH = 50 current = 0 while True: if current &lt; maxH: current += 1 else: current -=1 print(current) I know that the clear error is that when the current becomes max, it subtracts by 1 and then the if statement is true again. any help with an alternative way to get over this logic error would be helpful, thanks.
favorite count: 0
type: Question
has title: I have a semantic error on a program that goes up, then back down in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48435629
tagged with: python
has answer: http://stackoverflow.com/a/48435738

http://stackoverflow.com/q/48465109
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/388490
type: Question
has body: hey guys i have a problem on sqlmap : "cannot properly display Unicode characters inside Windows OS command prompt (http://bugs.python.org/issue1602). All unhandled occurances will result in replacement with '?' character. Please, find proper character representation inside corresponding output files." example : available databases [*] "ذ–HRL\X8BVUJ" please help me :(
has title: sqlmap and encoding databases
tagged with: oracle-database
tagged with: python
has comment: http://stackoverflow.com/comment/83926219
has comment: http://stackoverflow.com/comment/83926045
tagged with: code-injection
score: 0
answer count: 0
tagged with: sql

http://stackoverflow.com/q/48461042
type: Question
linked to: http://stackoverflow.com/q/34082939
type: AnsweredQuestion
score: 3
has body: I would like to access a multidimensional python array with an array of indexes, using the whole array to index the target element. Let me explain it better: A = np.arange(4).reshape(2,2) a = [1,1] &gt;&gt;&gt; A[a[0],a[1]] 3 My intention is to pass the array without hard-coding the indexes values and get the same result, that is the value A[1,1]. I tried but the only way I found is working differently: &gt;&gt;&gt; A[a] array([[2, 3], [2, 3]]) What results is the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row). Thank you.
tagged with: indexoutofboundsexception
tagged with: python
tagged with: numpy
upvote count: 3
has comment: http://stackoverflow.com/comment/86028896
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48461127
downvote count: 0
has title: How can I access an array with an array of indexes in python?
has answer: http://stackoverflow.com/a/48461127
favorite count: 0

http://stackoverflow.com/q/48387847
has title: Overlaying two plots using pcolor
answer count: 1
downvote count: 0
tagged with: overlay
accepted answer: http://stackoverflow.com/a/48388108
has comment: http://stackoverflow.com/comment/83763517
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/48388108
tagged with: matplotlib
has body: I want to plot two numpy arrays Z1 and Z2 in the same figure, Z2 on top of Z1. The array Z2 contains only 0's and 1's, and I want 0's to be fully transparent (alpha = 0) and 1's transparent with some alpha > 0. Here's the code and the resulting image: import numpy as np import matplotlib.pyplot as plt N = 10 x = np.arange(0, N) y = np.arange(0, N) Z1 = np.random.rand(N,N) Z2 = np.ones((N, N)) Z2[0:N//2, 0:N] = 0 X, Y = np.meshgrid(x, y) fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6)) plt.pcolormesh(X, Y, Z1, cmap=plt.cm.Blues) plt.colorbar() plt.pcolormesh(X, Y, Z2, cmap=plt.cm.Reds_r, alpha=0.3) ax.set_xlabel(r'$x$', fontsize=22) ax.set_ylabel(r'$y$', fontsize=22) plt.show() There are two problems: Appearance of the unwanted grid lines The 0's of Z2 are not fully transparent as needed To get rid of the grid lines we can use imshow instead of pcolor, but I really want to use the values of x and y.
tagged with: python
linked to: http://stackoverflow.com/q/20678817
tagged with: numpy
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/62628895
answers question: http://stackoverflow.com/q/48392457
score: 0
type: Answer
has body: OS level command can also be used just in case someone is using Colab To mound your google drive use from google.colab import drive drive.mount('/content/drive', force_remount=True) Code to mount GCS from google.colab import auth auth.authenticate_user() project_id = 'thirumalai_bucket' #your bucket here !gcloud config set project {project_id} !gsutil ls !gsutil -m cp in your case: !gsutil -m cp gs://mybucket/model.h5 /content/drive/My\ Drive/models/ now the file model.h5 available in drive /content/drive/My Drive/models/ move to your models directory using: !cd /content/drive/My\ Drive/models/ load_model('model.h5') Hope this helps!

http://stackoverflow.com/q/48357972
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/48358672
possible better answer: http://stackoverflow.com/a/48358672
type: Question
has body: I'm trying to build an app to show parking spaces. The design I made I'm working in a .kv file to build the GUI, but I don't know how to put the images in the column and row that I would like to do. Can you help me with this Layout positions? main.py # File name: main.py import kivy from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout # Version of kivy kivy.require('1.10.0') class Main(AnchorLayout): parking_space_available = '' parking_space_busy = '' def update(self): app = App.get_running_app() class MainApp(App): def build(self): return Main() if __name__ == '__main__': MainApp().run() main.kv # File name: main.kv &lt;Label&gt;: font_size: 20 &lt;Main&gt;: BoxLayout: id: main_layout orientation: 'vertical' Label: id: label_total text: 'Parking spaces total: ' pos_hint: {'x': 0, 'top':1} Label: id: label_available text: 'Parking spaces available: ' pos_hint: {'x': 0, 'top':.3} GridLayout: cols: 3 rows: 6 BoxLayout: orientation: 'horizontal' size_hint: 0.15, 0.2 Image: source: root.parking_space_available Image: source: root.parking_space_available Image: source: root.parking_space_available Button: text: 'Update' font_size: 20 on_press: root.update()
upvote count: 1
has answer: http://stackoverflow.com/a/48369624
favorite count: 0
has answer: http://stackoverflow.com/a/63244381
type: AnsweredQuestion
answer count: 3
downvote count: 0
score: 1
has title: How can I select a row and column of a GridLayout Kivy?
tagged with: android
accepted answer: http://stackoverflow.com/a/48369624

http://stackoverflow.com/q/48464281
answer count: 3
tagged with: deep-learning
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48464357
has title: Split feature maps (3D arrays) into 2D arrays
tagged with: multidimensional-array
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/48465205
accepted answer: http://stackoverflow.com/a/48465205
possible better answer: http://stackoverflow.com/a/48464357
has answer: http://stackoverflow.com/a/48464422
has body: Let's say I have a feature map (i.e. a 3D array) of shape (32, 32, 96) In [573]: feature_map = np.random.randint(low=0, high=255, size=(32, 32, 96)) Now, I want to visualize each of the feature maps individually. So, I'd like to extract each of the frontal slices (i.e. a 2D array of shape (32, 32)) so that should give 96 such feature maps. How to get these arrays, possibly not as a copy to be memory efficient? Since this is only for visualization, a view is enough!
type: AnsweredQuestion
score: 3
upvote count: 3

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/48433641
type: Tag
tags question: http://stackoverflow.com/q/48456597

http://stackoverflow.com/comment/83818503
has text: You are right, the extra 4 spaces made it out of the scope, I updated the code.
type: AnswerComment
comment on: http://stackoverflow.com/a/48414217
score: 0
type: Comment

http://stackoverflow.com/q/48395742
tagged with: python
has comment: http://stackoverflow.com/comment/83780611
has comment: http://stackoverflow.com/comment/83779649
accepted answer: http://stackoverflow.com/a/48396328
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48396328
has comment: http://stackoverflow.com/comment/83780439
score: 0
has body: My teacher told me to use an if statement to get rid of the Zero Division error but all I see in the internet is function that counters it not an if statement. #date January 22, 2018 #title Finding Slope Of A Line x1 = input ("Give a value for x1 that is less than ten: ") x2 = input ("Give a value for x2 that is less than ten: ") y1 = input ("Give a value for y1 that is less than ten: ") y2 = input ("Give a value for y2 that is less than ten: ") x1 = int(x1) x2 = int(x2) y1 = int(y1) y2 = int(y2) y = y2 - y1 x = x2 - x1 if x == 0: print("Undefined") yx = y/x yx = int (slope) if yx != 0: print ("%d"%yx) if yx == 0: print ("Undefined")
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48395833
favorite count: 0
type: Question
has title: Zero division error even with If statement
has comment: http://stackoverflow.com/comment/83779534
answer count: 3
has comment: http://stackoverflow.com/comment/83779185
has answer: http://stackoverflow.com/a/48396131
possible better answer: http://stackoverflow.com/a/48395833

http://stackoverflow.com/q/48352127
type: AnsweredQuestion
tagged with: pandas
tagged with: pypyodbc
tagged with: python
score: -1
favorite count: 0
has body: I'm reading from one database and outputting certain columns to another database. I use a data frame to store the data and then iterate through the frame to output the column i'm interested in.: for i in range(0,len(myframe.index)): cursor_conn2.execute(SQL2_UPD_NEWEMP,myframe.loc[i,"LNAME_EMP"]) but I keep getting an error: raise TypeError("Params must be in a list, tuple, or Row") This is SQL2_UPD_NEWEMP: SQL2_UPD_NEWEMP="INSERT INTO DBO.NEW_EMP_CAL(LNAME) VALUES(?)" there is data in the frame. 113 rows, and LNAME_EMP is a valid name, and every row contains data. This should be quite simple, but I'm not seeing where the error is being made, and it makes me sad. When I run this code I see all the data: for i in range(0,len(myframe.index)): print(myframe.loc[i,"LNAME_EMP"]) Any help would be appreciated. Thanks!
has title: writing data frames to a sql table
has answer: http://stackoverflow.com/a/48352218
accepted answer: http://stackoverflow.com/a/48352218
tagged with: sql
upvote count: 0
answer count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/48430902
has body: I am trying to pass a variable file location be emailed via the my SQL server. If i am using some other string it will work fine but this is the error I am getting. pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Attachment file C:\\Users\\ME\\Desktop\\Queries\\Fail w email\\PythonEmail\\ErrorList.txt is invalid. (22051) (SQLExecDirectW)') Saying is can't handle '\' And it is driving me crazy. I've tried triple quote, triple double quotes, r"string", but nothing seems to work. CODE: import sys import os import pyodbc con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'SERVER', database = 'DATABASE') cur = con.cursor() f = open('ErrorList.txt','w') f.write("('Station','Sequence','Script','Measurement','Fail Count')"+'\n') f.close() print(os.path.abspath("ErrorList.txt")) pathtofilename = r'C:\Users\ME\Desktop\Queries\Fail w email\PythonEmail\ErrorList.txt' sendEmail = ("EXEC msdb.dbo.sp_send_dbmail " "@body_format = 'TEXT', " "@recipients = 'reci@reci', " "@from_address = 'from@from' ," "@reply_to = 'reply@reply', " "@subject = 'Test Python', " " @file_attachments = '" + os.path.abspath('ErrorList.txt') + "', " "@body = 'No Message with commit attach 2'") cur.execute(sendEmail) con.commit() cur.close() con.close() os.remove("ErrorList.txt")
has comment: http://stackoverflow.com/comment/83856069
favorite count: 0
has comment: http://stackoverflow.com/comment/83852736
type: Question
tagged with: python-3.x
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/83852914
type: UnansweredQuestion
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/30478569
has comment: http://stackoverflow.com/comment/83852946
tagged with: sql-server
has title: Python passing double slash to SQL server
tagged with: sql
duplicate of: http://stackoverflow.com/q/30478569
score: 2

http://stackoverflow.com/q/48384416
has body: I am trying to call a python command from within javascript using the ipykernel.comm. The problem is that I want to use the same code regardless if I run python3 kernel or pyspark3 kernel. For the latter I need to run code with %%local cell magic, which does not work for the pure python 3 kernel. How do I programmatically check if a given (frontend) magic is available? I tried looking into get_ipython().magics_manager.registry but I feel that is not the way. I tried to look on the frontend (javascript) side but I also could not find it. I thought maybe the source for sparkmagic will help me, but no luck. I do not know how to access IPython.CodeCell.config_defaults sparkmagic's kernel.js
tagged with: python
tagged with: jupyter
possible better answer: http://stackoverflow.com/a/48384996
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48384996
has title: jupyter notebook - check if magic is available
upvote count: 2
accepted answer: http://stackoverflow.com/a/48384995
downvote count: 0
has answer: http://stackoverflow.com/a/48384995
favorite count: 0
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48455889
score: 1
upvote count: 1
favorite count: 0
has title: How to dynamically access dictionary attribute in Python?
has comment: http://stackoverflow.com/comment/83904724
type: Question
possible better answer: http://stackoverflow.com/a/48455976
accepted answer: http://stackoverflow.com/a/48455974
tagged with: python
has answer: http://stackoverflow.com/a/48455976
has answer: http://stackoverflow.com/a/48455974
has body: How would you go about editing a dictionary as an object attribute? Right now I have I have a class that looks like this: class Generic_class(object): def __init__(self): self.attr1 = default_dict.copy() self.attr2 = default_dict.copy() self.attr3 = default_dict.copy() self.attr4 = default_dict.copy() ... I am (trying) to do it this way so that I can access the dictionaries as part of an instance of this class, and there could end up being hundreds of different instances. I would like to be able to access the attributes dynamically because the attribute to be accessed is determined by data that is retrieved by the program at run-time. These dictionaries are also going to be edited possibly hundreds of times so something like attr_name = 'This is dynamic' instance_dict = default_dict.copy() instance_dict['a key'] = 'value' setattr(x, attr_name, instance_dict) wont work because I need previous edits to remain. Since I need to access the attributes dynamically I can't use x.y['key] = 'value', but I cant edit the dictionary using setattr() so I am not sure what to do.
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/a/48411979
has comment: http://stackoverflow.com/comment/83813882
has body: Use inspect.getmodule(). You may inspect the module's __package__ after you get the module if it doesn't suffice. Another option would be to get use inspect.getfile() and search for the known strings.
type: Answer
answers question: http://stackoverflow.com/q/48411818
score: 0

http://stackoverflow.com/a/48433587
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48431413
has body: Solution You can use pexpect. Here is an example using two python modules: caller.py import pexpect proc = pexpect.spawn('python3 backwards.py') proc.expect(' > ') while True: n = proc.sendline(input('Feed me - ')) proc.expect(' > ') print(proc.before[n+1:].decode()) backwards.py x = '' while True: x = input(x[::-1] + ' > ') Explanation caller.py is using a "Pseudo-TTY device" to talk to backwards.py. We are providing input with sendline and capturing input with expect (and the before attribute).

http://stackoverflow.com/comment/83878956
comment on: http://stackoverflow.com/a/48431326
type: AnswerComment
has text: @Xenoshell I wouldn't know about that. It is possible to resize image, so if the video is images frame by frame I don't see why not.
score: 0
type: Comment

http://stackoverflow.com/q/48334948
has title: How to get info from this html using beautifulsoup?
answer count: 0
has comment: http://stackoverflow.com/comment/83655043
score: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83655243
has comment: http://stackoverflow.com/comment/83655180
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83654944
tagged with: python
has body: I want to get all the social link of a company from this. When doing summary_div.find("div", {'class': "cp-summary__social-links"}) I am getting this &lt;div class="cp-summary__social-links"&gt; &lt;div data-integration-name="react-component" data-payload='{"props": {"links":[{"url":"http://www.snapdeal.com?utm_source=craft.co","icon":"web","label":"Website"}, {"url":"http://www.linkedin.com/company/snapdeal?utm_source=craft.co","icon":"linkedin","label":"LinkedIn"}, {"url":"https://instagram.com/snapdeal/?utm_source=craft.co","icon":"instagram","label":"Instagram"}, {"url":"https://www.facebook.com/Snapdeal?utm_source=craft.co","icon":"facebook","label":"Facebook"}, {"url":"https://www.crunchbase.com/organization/snapdeal?utm_source=craft.co","icon":"cb","label":"CrunchBase"}, {"url":"https://www.youtube.com/user/snapdeal?utm_source=craft.co","icon":"youtube","label":"YouTube"}, {"url":"https://twitter.com/snapdeal?utm_source=craft.co","icon":"twitter","label":"Twitter"}], "companyName":"Snapdeal"},"name":"CompanyLinks"}' data-rwr-element="true"&gt;&lt;/div&gt;&lt;/div&gt; I also tried getting children of cp-summary__social-links, which I want indeed and then find all a tag to get all the links. This does not work too. Any idea, how to do this? Update: As Sraw suggested, I managed to get all urls by doing like this. urls = [] social_link = summary_div.find("div", {'class': "cp-summary__social-links"}).find("div", {"data-integration-name": "react-component"}) json_text = json.loads(social_link["data-payload"]) for link in json_text['props']['links']: urls.append(link['url']) Thanks in advance.
has comment: http://stackoverflow.com/comment/83655808

http://stackoverflow.com/comment/87768979
comment on: http://stackoverflow.com/q/48363419
score: 0
has text: This sounds like a LinkedIn-related question, more than a scrapy one. Have you checked questions like https://stackoverflow.com/questions/27571419/how-to-avoid-http-1-1-999-request-denied-response-from-linkedin ?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48388438
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48388369
has body: Assuming that your backend is a Scala based Web application, you could then expose a Websocket endpoint to which your client subscribes. You then could push data as soon as there is some change in the backend. Whoever is subscribed to this Websocket channel, will get this update.
type: Answer
downvote count: 0

http://stackoverflow.com/q/48452821
type: AnsweredQuestion
has body: I have a list: S_acc=[Decimal('14674.04881484484319092894299'),Decimal('1287243.594400802980099508539')] I would like to have output in this form: S_acc=[14674.04881484484319092894299, 1287243.594400802980099508539] I tried converting into string first before converting to decimal number but I am getting this error: results = [tuple(str(item) for item in t) for t in s_acc] print(results) TypeError: 'decimal.Decimal' object is not iterable Appreciate any help.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48452868
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48452868
upvote count: 2
has title: How to remove "Decimal" keyword from the output
tagged with: python
has comment: http://stackoverflow.com/comment/83898810
score: 2

http://stackoverflow.com/a/48334011
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48333923
type: Answer
has body: (Spyder maintainer here) Spyder uses spaces by default. However, that can be changed to tabs by going to Preferences &gt; Editor &gt; Advanced settings &gt; Indentation characters
answers question: http://stackoverflow.com/q/48333923
upvote count: 2
score: 2

http://stackoverflow.com/q/48480193
tagged with: python
has comment: http://stackoverflow.com/comment/83953380
has comment: http://stackoverflow.com/comment/83954440
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/83971423
has body: Any thoughts on what to try when installation of pymc3, using pip, works flawlessly, but as soon as the statement import pymc3 is executed, Python3.6 coredumps ? $ python3.6 Python 3.6.1 (default, Mar 21 2017, 21:49:16) [GCC 5.4.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. import pymc3 Segmentation fault (minnesutskrift skapad) TIA, Tommy
has comment: http://stackoverflow.com/comment/83954654
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83965761
tagged with: pymc3
type: UnansweredQuestion
tagged with: windows-10
type: Question
has comment: http://stackoverflow.com/comment/83954704
has comment: http://stackoverflow.com/comment/83964630
has title: pymc3 on windows10/cygwin64/python3.6 core dumps at import statement
has comment: http://stackoverflow.com/comment/84053896
has comment: http://stackoverflow.com/comment/86355238
tagged with: cygwin

http://stackoverflow.com/a/48370703
type: Answer
has body: You have an old version of Flask-WTF installed, but Flask-Blogging expects a newer version. Upgrade Flask-WTF. pip install -U Flask-WTF Flask-WTF renamed Form to Flask-Form in version 0.13, released September 29, 2016.
accepted answer of: http://stackoverflow.com/q/48370668
downvote count: 0
type: AcceptedAnswer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/48370668

http://stackoverflow.com/q/48486764
tagged with: cython
has body: I'm 90% sure the bizarre result I'm seeing here is some kind of UB triggered by my code, however, I cannot find it: cdef char** to_cstring_array(strings): cdef char** result = &lt;char**&gt;malloc(len(strings) * sizeof(char*)) cdef bytes item nelements = len(strings) i = 0 while i &lt; nelements: s = str(strings[i]).encode("utf-8") item = s result[i] = item i += 1 return result cpdef object pykubectl_get(object items, object options=None): cdef size_t nargs = len(items); cdef bytes message cdef char** args = to_cstring_array(items); # message = args[0] # print("1 items encoded: {}".format(message)) json_opts = json.dumps(options or {}).encode("utf-8") cdef char* opts = json_opts print("items: {}".format(items)) message = args[0] print("2 items encoded: {}".format(message)) cdef ResourceGet_return result = kubectl_get( opts, len(json_opts), &lt;const char**&gt;args, nargs ) free(args) if result.r0.n == 0: message = result.r1.p raise Exception("kubectl failed: '{}'".format(message.decode("utf-8"))) message = result.r0.p return json.loads(message.decode("utf-8")) If I uncomment the lines assigning first argument to message, the contents of args changes. My guess is that compiler is trying to optimize something here, and that it could be related to how memory allocation is done, but I cannot see any problems with it. I also know that, in principle, I shouldn't need to cast to const char**, but I'm getting a warning for not casting, so I added it. It changes nothing if I ignore the warning and don't cast. I'm not posting the generated C code because it's huge... but if this will prove inevitable, I'll post it elsewhere.
accepted answer: http://stackoverflow.com/a/48487044
type: Question
has answer: http://stackoverflow.com/a/48487044
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has title: Spot Undefined Behavior in this code snippet
tagged with: undefined-behavior
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/48376379
answers question: http://stackoverflow.com/q/48373685
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/112675298
type: Answer
has body: Well - when you know the batch_size you could obtain number of images from flow_from_directory object: test_batches = ImageDataGenerator().flow_from_directory(.., batch_size=n) number_of_examples = len(test_batches.filenames) number_of_generator_calls = math.ceil(number_of_examples / (1.0 * n)) # 1.0 above is to skip integer division test_labels = [] for i in range(0,int(number_of_generator_calls)): test_labels.extend(np.array(test_batches[i][1]))
accepted answer of: http://stackoverflow.com/q/48373685
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48413310
has body: I assume you are using pandas as per the title. import pandas as pd df_series = pd.Series(data=[4, 1, -5, 6, 6, 7, 9, 8, 4, -5], index=range(10), name='Column1') df_series[df_series &lt; 5] = 'Hello' Note: mixed types are not recommended in columns. The above code will change the type of the column from 'int64' to 'object'.
type: Answer
answers question: http://stackoverflow.com/q/48413215
score: 0

http://stackoverflow.com/q/48449299
tagged with: python
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/48917978
has answer: http://stackoverflow.com/a/73598182
upvote count: 4
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/48450359
has title: GCS - Python download blobs with directory structure
type: UnansweredQuestion
downvote count: 0
has body: I'm using a combination of the GCS python SDK and google API client to loop through a version-enabled bucket and download specific objects based on metadata. from google.cloud import storage from googleapiclient import discovery from oauth2client.client import GoogleCredentials def downloadepoch_objects(): request = service.objects().list( bucket=bucket_name, versions=True ) response = request.execute() for item in response['items']: if item['metadata']['epoch'] == restore_epoch: print(item['bucket']) print(item['name']) print(item['metadata']['epoch']) print(item['updated']) blob = source_bucket.blob(item['name']) blob.download_to_filename( '/Users/admin/git/data-processing/{}'.format(item)) downloadepoch_objects() The above function works properly for a blob that is not within a directory (gs://bucketname/test1.txt) as the item that gets passed in is simply test1.txt. The issue I am running into is when trying to download files from a complex directory tree (gs://bucketname/nfs/media/docs/test1.txt) The item that gets passed is nfs/media/docs/test1.txt. Is it possible to have the .download_to_file() method to create directories if they are not present?
score: 4
favorite count: 0
type: Question
answer count: 3

http://stackoverflow.com/a/48354033
answers question: http://stackoverflow.com/q/48353910
score: 0
has body: You can use this: np.finfo(np.float32).eps
downvote count: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/48468274
tagged with: subprocess
has comment: http://stackoverflow.com/comment/83930369
tagged with: kill
answer count: 1
has comment: http://stackoverflow.com/comment/83930213
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83930500
favorite count: 0
type: AnsweredQuestion
tagged with: popen
score: 1
has comment: http://stackoverflow.com/comment/83930445
tagged with: terminate
tagged with: python
has body: I have small function that is designed for killing or terminating subproces and its subprocesses. I am trying to write it in a more elegant way instead of repeating if, else twice. def kill_process(cls, process, kill_type): process = psutil.Process(process.pid) for proc in process.children(recursive=True): if kill_type== 'terminate': proc.terminate() else: proc.kill() if kill_type== 'terminate': process.terminate() else: process.kill()
accepted answer: http://stackoverflow.com/a/48468466
has title: More elegant way to selecting python popen process.kill() or process.terminate()
has comment: http://stackoverflow.com/comment/83930422
type: Question
has answer: http://stackoverflow.com/a/48468466

http://stackoverflow.com/comment/83692170
has text: `[A-Z][a-z]+` means "all letters between A and Z and a and z." The range, as defined, does not include the apostrophes. Add them to the regular expression.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48352706

http://stackoverflow.com/a/48481925
upvote count: 1
answers question: http://stackoverflow.com/q/48475290
score: 1
has body: Sounds like you have the need for a rather standard django app. I would follow their tutorial in order to grasp django and get you started. In regards to your questions, I've quoted parts and given links to how you can achieve this: "Adding" (CreateView), "removing" (DeleteView), "modifying the attributes"(UpdateView) of an entity should be simple It should allow for "nested attributes" (models.ForeignKey) (sub-entities) e.g Patient -> Consulting doctor Each attribute or sub-entity in the entity can have a set of business rules. (create a 'controller' and call it in overiden methods, this SO answer answers where to put it perfectly) Your requirements pretty much define what django does.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/97004549
type: Comment
has text: @alancalvitti Can you provide more details? It works fine for me.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48471989

http://stackoverflow.com/q/48400838
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/64465130
has comment: http://stackoverflow.com/comment/83796955
has answer: http://stackoverflow.com/a/64465130
downvote count: 0
has body: Disclaimer: I'm not a Windows expert, so this may be something idiosyncratic to Windows. I'm observing a situation where I can import a module in interactive mode but not when requested from a file. Here is foo.py in its entirety: #!/usr/bin/env python import pyftdi When I try to run this in Python 3.6.4, it fails: E:\&gt;py foo.py Traceback (most recent call last): File "foo.py", line 2, in &lt;module&gt; import pyftdi ImportError: No module named pyftdi ...but when I import the module interactively, it succeeds: E:\&gt;py Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pyftdi &gt;&gt;&gt; (FWIW, I don't get an error when repeating this under Mac OS X.) Any thoughts about what's going on?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48400880
type: Question
has answer: http://stackoverflow.com/a/48400880
tagged with: windows
tagged with: python-module
tagged with: python
score: 4
has title: python import works interactively but not from script
upvote count: 4

http://stackoverflow.com/a/48464357
downvote count: 0
score: 6
has body: You can use np.transpose and slicing operations (not creating copies of an array): feature_map = np.random.randint(low=0, high=255, size=(32, 32, 96)) feature_map = np.transpose(feature_map, axes=[2, 0, 1]) for i in range(feature_map.shape[0]): print(feature_map[i].shape) # a view of original array. shape=(32, 32) ... or do just slicing: for i in range(feature_map.shape[2]): print(feature_map[:, :, i].shape) # a view of original array. shape=(32, 32)
has comment: http://stackoverflow.com/comment/83923159
has comment: http://stackoverflow.com/comment/83923125
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/83923738
answers question: http://stackoverflow.com/q/48464281

http://stackoverflow.com/q/48448240
possible better answer: http://stackoverflow.com/a/48449179
has comment: http://stackoverflow.com/comment/83888899
tagged with: pandas
type: AnsweredQuestion
score: 0
answer count: 2
has title: What is the most efficient way to count the number of instances occurring within a time frame in python?
tagged with: list-comparison
type: Question
has answer: http://stackoverflow.com/a/48448455
has answer: http://stackoverflow.com/a/48449179
tagged with: datetime
tagged with: python
has body: I am trying to run a simple count function which runs a dataframe of event times (specifically surgeries) against another dataframe of shift time frames, and returns a list of how many events occur during each shift. These csvs are thousands of rows, though, so while the way I have it set up currently works, it takes forever. This is what I have: numSurgeries = [0 for shift in range(len(df.Date))] for i in range(len(OR['PATIENT_IN_ROOM_DTTM'])): for shift in range(len(df.DateTime)): if OR['PATIENT_IN_ROOM_DTTM'][i] &gt;= df.DateTime[shift] and OR['PATIENT_IN_ROOM_DTTM'][i] &lt; df.DateTime[shift+1]: numSurgeries[shift] += 1 So it loops through each event and checks to see which shift time frame it is in, then increments the count for that time frame. Logical, works, but definitely not efficient. EDIT: Example of OR data file Example of df data file
has comment: http://stackoverflow.com/comment/83888881
linked to: http://stackoverflow.com/q/29370057
accepted answer: http://stackoverflow.com/a/48448455

jira
tags question: http://stackoverflow.com/q/48384775
tags question: http://stackoverflow.com/q/48388459
tag name: jira
type: Tag

http://stackoverflow.com/a/48456514
upvote count: 1
type: Answer
has body: Use itertools.product. import itertools p = itertools.product(range(2),range(3),range(4)) l = [x for x in p] print(l) For the alist with unknown length, store the argument in a list, then use *args to expand them. alist = [5,6,7,8] args = [range(x) for x in alist] # create the arg list p = itertools.product(*args) # expand args ...
score: 1
has comment: http://stackoverflow.com/comment/83906177
downvote count: 0
answers question: http://stackoverflow.com/q/48456383

http://stackoverflow.com/comment/83829067
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48419591
has text: In python `dict`s don't have an order of their keys.
type: AnswerComment

http://stackoverflow.com/a/48456451
has comment: http://stackoverflow.com/comment/83906142
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48434895
has body: I believe an aggregation is indeed typically - if not always - required. That being said, the workaround is to do a meaningless aggregation: In your case, after clicking Visualize, check both timestamp and nav as is_dimension, check timestamp as is_date, and define agg_func as MIN(x) for nav. Click Visualize, select Visualization Type as Time Series - Line Chart, set Metrics as min__nav and remove the Group By. Query and you should get what I think you're looking for.
downvote count: 0
has comment: http://stackoverflow.com/comment/83906060
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48434895
upvote count: 2
has comment: http://stackoverflow.com/comment/83951127

http://stackoverflow.com/a/48350265
answers question: http://stackoverflow.com/q/48350196
has comment: http://stackoverflow.com/comment/83687525
upvote count: 2
has comment: http://stackoverflow.com/comment/83703149
has comment: http://stackoverflow.com/comment/83687348
downvote count: 0
has body: Stop fetching the files as a separate queryset: def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) You can then follow the one-to-one field from lecture to files. {% for lecture in category.list %} {{ lecture.lecture_title }} {{ lecture.content }} {% if lecture.files %} download {% endif %} {% endfor %} Since it's a one-to-one field to a single file upload, it would make more sense to name the field file instead of files: file = models.OneToOneField('FileUpload', on_delete=models.CASCADE, null=True, blank=True) You would then have to update the template to use lecture.file instead.
has comment: http://stackoverflow.com/comment/83687474
score: 2
has comment: http://stackoverflow.com/comment/83696668
has comment: http://stackoverflow.com/comment/83687252
type: Answer
has comment: http://stackoverflow.com/comment/83687681

http://stackoverflow.com/comment/83656883
has text: exactly .. still need more corrections in his program .. Just check and mention that also in your answer .I think it will helps him more .
comment on: http://stackoverflow.com/a/48335697
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48454728
has title: Removing an item from a stack, without using pop, peek, push
has answer: http://stackoverflow.com/a/48455047
has comment: http://stackoverflow.com/comment/83902669
has comment: http://stackoverflow.com/comment/83902721
favorite count: 0
type: Question
tagged with: python-3.x
has body: I don't understand what they're asking. Can someone just clarify the question? The question is: (They gave us the doc-string for it) Write and test the method combine in the stack_array module. Test it from a module named q3.py. This is extending the Stack class. It should produce the same result as Question 1, but it must work at the lowest level of the Stack code definition. In other words, this method cannot call the Stack push and pop, it has to work with _values directly. def combine(self, s2): """ ------------------------------------------------------- Combines a second stack with the current stack. (iterative algorithm) Use: s3 = s1.combine(s2) ------------------------------------------------------- Preconditions: s2 - an array-based stack (Stack) Postconditions: Returns: s3 - the contents of the current stack and s2 are interlaced into s3 - current stack and s2 are empty (Stack) ------------------------------------------------------- """ #Write your code here I've solved it using push,pop, and peek. s3 = Stack() if len(s1._values) &gt;= len(s2._values): for things in s1: if s2.is_empty() != True: s3.push(things) s1.pop() s3.push(s2.peek()) s2.pop() else: s3.push(things) s1.pop() else: for things in s2: if s1.is_empty() != True: s3.push(things) s2.pop() s3.push(s1.peek()) s1.pop() else: s3.push(things) s2.pop() return s3
type: UnansweredQuestion
tagged with: adt
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83902606
upvote count: 0
has comment: http://stackoverflow.com/comment/83902605
tagged with: stack
answer count: 1
has comment: http://stackoverflow.com/comment/83902557
downvote count: 1

http://stackoverflow.com/comment/83912751
comment on: http://stackoverflow.com/q/48459913
type: QuestionComment
score: 2
has text: Are you sure it's 20 *TB*?
type: Comment

http://stackoverflow.com/a/55178726
score: 0
answers question: http://stackoverflow.com/q/48484776
has body: First of all destroy the vagrant box by running following command: vagrant destroy Change your vagrant file to this: sudo pip install virtualenvwrapper if ! grep -q VIRTUALENV_ALREADY_ADDED /home/vagrant/.bashrc; then echo "# VIRTUALENV_ALREADY_ADDED" &gt;&gt; /home/vagrant/.bashrc echo "WORKON_HOME=~/.virtualenvs" &gt;&gt; /home/vagrant/.bashrc echo "PROJECT_HOME=/vagrant" &gt;&gt; /home/vagrant/.bashrc echo "source /usr/local/bin/virtualenvwrapper.sh" &gt;&gt; /home/vagrant/.bashrc fi Now initialize your vagrant box with vagrant init command and then run vagrant up command.
type: Answer

http://stackoverflow.com/q/48385116
type: Question
score: 5
upvote count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/48385739
has body: All tutorials simply import tkinter, I am wondering, though, why not import _tkinter? If my understanding is correct, _tkinter is the actual library in cpython and tkinter is the interface or API. I am simply trying to grasp the paradigm as I read through some of the tkinter source code. It seems there is some python black magic afoot.
has answer: http://stackoverflow.com/a/48385739
has title: Import _tkinter or tkinter?
tagged with: tkinter
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83766874
has comment: http://stackoverflow.com/comment/83757506
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48385298
possible better answer: http://stackoverflow.com/a/48385234
favorite count: 0
has answer: http://stackoverflow.com/a/48385234

http://stackoverflow.com/q/48443462
has answer: http://stackoverflow.com/a/48445785
has comment: http://stackoverflow.com/comment/83881470
upvote count: 3
has answer: http://stackoverflow.com/a/48444179
tagged with: function
accepted answer: http://stackoverflow.com/a/48443890
downvote count: 0
has comment: http://stackoverflow.com/comment/83878340
has comment: http://stackoverflow.com/comment/83880141
possible better answer: http://stackoverflow.com/a/48443862
has answer: http://stackoverflow.com/a/48443890
has comment: http://stackoverflow.com/comment/83878872
has comment: http://stackoverflow.com/comment/83880288
has comment: http://stackoverflow.com/comment/83878348
favorite count: 0
tagged with: recursion
has comment: http://stackoverflow.com/comment/83878309
has comment: http://stackoverflow.com/comment/83878250
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83882294
has comment: http://stackoverflow.com/comment/83882238
tagged with: python
has comment: http://stackoverflow.com/comment/83878269
has body: I am writing a piece of code in python that checks whether a given number is happy or not, that is taking the number and adding the sum of their squares is 1 which is a happy number or ending up with a never ending loop which defines a unhappy number. After that, I want to list the first n Happy Numbers. I got the checking for happy numbers down albeit sloppily, I just can't seem to figure out the listing part. def adder(num): total=0 if len(str(num))&gt;1: #check if given number is double digit or not tens = int(str(num)[0]) # splitting the digits ones = int(str(num)[1]) total = (tens**2)+(ones**2) # summing up the squares #print (total) return total else: # if the given number is a single digit total = (num**2) #print (total) return total #adder(9) def happynumber(num, counter): N = adder (num) # storing the sum in a variable #print ("value of n is {}".format(N)) if N == 1: #checks if the sum is 1 # print ("In just {} tries we found that {} is a happy number.".format(counter, number)) print (number) else: # if the sum isn't 1, racalls the happynumber function counter += 1 # keeps track of number of tries so that we don't end up in an infinite loop if counter &lt; 11: # setting the limit for number of tries #print (counter) happynumber (N, counter) else: #print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number)) return False counter = 0 for i in range(0,100): # listing all the happy numbers between 0 and 100 number = i happynumber (number, counter) Additionally, I would like it if you guys would review my writing style and give some pointers. The problem, I am not able to list the first n numbers however way I try. I tried using counter in the loop but to no avail.
has comment: http://stackoverflow.com/comment/83878574
has title: Printing first n Happy Numbers - Python
answer count: 4
has answer: http://stackoverflow.com/a/48443862
has comment: http://stackoverflow.com/comment/83878407
type: Question

http://stackoverflow.com/a/48449571
has body: If you store both variables in a list, you could use this idiom: def mul(x, y): return x * y xs = [1,2,3,4,5] ys = [10,20,30,40,50] for args in zip(xs, ys): print "mul({}, {}) = {}".format(args[0], args[1], mul(*args)) mul(1, 10) = 10 mul(2, 20) = 40 mul(3, 30) = 90 mul(4, 40) = 160 mul(5, 50) = 250 zip() takes two lists, and returns a list of 2-tuples: &gt;&gt;&gt; zip(xs, ys) &gt;&gt;&gt; [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)] str.format() takes a string, and injects the arguments you supply into the curly braces: &gt;&gt;&gt; "hello {}".format('world') &gt;&gt;&gt; "hello world"
score: 0
answers question: http://stackoverflow.com/q/48449420
type: Answer

http://stackoverflow.com/q/48483157
upvote count: 3
score: 1
downvote count: 2
favorite count: 0
type: Question
has body: I am trying to read a large data file. I have the following code in C#, which can pick up the rows meet the requirement and save them into a separate file. The whole code takes about 20mins to run. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { public class CSVFileConverter { public string FilePath { get; set; } public string OutputDirectory { get; set; } public int numStartLine { get; set; } public string strFeature { get; set; } public string[] colNames {get;set;} private string strcolNames; private int maxNumOfFiles; private int m_numofLines = -1; public int numofLines { get { return this.m_numofLines; } } private int colIndex; private Dictionary&lt;int, StreamWriter&gt; dictSW = new Dictionary&lt;int, StreamWriter&gt;(); public CSVFileConverter(string filepath, string output, string feature, int numstartline) { this.FilePath = filepath; this.OutputDirectory = output; this.strFeature = feature; this.numStartLine = numstartline; this.GetColNames(); this.Converter(); this.CloseStreams(); } private void GetColNames() { try { var strline = ReadCSVLines(this.FilePath).First(); strcolNames = strline; colNames = strline.Split(','); if (!colNames.Contains(this.strFeature)) { throw new Exception(string.Format("The File doesn't have this specified feature: {0}", this.strFeature)); } else { this.colIndex = Array.IndexOf(colNames, this.strFeature); } }catch (Exception ex){ Console.WriteLine(ex); Environment.Exit(0); } } private void OpenFiles() { for (int i = 0; i &lt;= this.maxNumOfFiles; i++) { } } private void Converter() { foreach (var strline in ReadCSVLines(this.FilePath)) { m_numofLines++; if (m_numofLines &lt; this.numStartLine) continue; //skip lines; string[] strsplit = strline.Split(','); int id = 0; try { id = Convert.ToInt32(strsplit[this.colIndex]); } catch { Console.WriteLine("Line {0} is invalid input: {1} = {2}.",m_numofLines, this.strFeature, strsplit[this.colIndex]); co…
tagged with: c#
has title: How can I convert the C# code to python?
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84147266
answer count: 0

http://stackoverflow.com/q/48465287
has comment: http://stackoverflow.com/comment/83930203
score: 0
answer count: 0
has body: I have a DataFrame like that: ID_client l date l contact -------------------------------------- 1 2017/01/01 email 1 2017/01/02 mail 1 2017/01/03 email 1 ......... 1 2017/06/06 sms 2 ...... tel 2 tel 3 . etc until 2017/31/31 etc and I would like to have 2 DataFrames, the first only one line for year with the sum of each contact split in different columns and the last same per month: 1) id l email l sms l tel l mail ---------------------------- 1 40 20 30 50 2 20 30 40 50 2 ........................ 3 ..............etc 2) id l date_month l email l sms l tel l email -------------------------------------------------- 1 2017/01 20 10 5 2 1 2017/02 .............. . 2 2017/01 ............. 2 2017/02 ................ . etc I tried Df.set_index("date") Df["contact"].resample("m") Or Df.groupby(df["date", "I'd_client"])[contact].Count Or I tried to create another dataframe df2=Df.groupby(df.index) Df2="contact" df2.apply(lambda x : x.count()) I tried : Df.set_index("date") Df["contact"].resample("m") Or Df.groupby(df["date", "I'd_client"])[contact]. Count Or I tried to create another dataframe df2=Df.groupby(df.index) Df2="contact" df2.apply(lambda x : x.count()) But it didnt give me what I wanted!!
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83923927
type: Question
type: UnansweredQuestion
tagged with: python
has title: Pandas: groupby / aggregation / sum
tagged with: pandas-groupby

http://stackoverflow.com/a/48403388
has comment: http://stackoverflow.com/comment/83824197
has comment: http://stackoverflow.com/comment/83796035
answers question: http://stackoverflow.com/q/48403327
score: 0
has comment: http://stackoverflow.com/comment/83796291
has body: The Table class has methods to add rows. https://python-docx.readthedocs.io/en/latest/api/table.html#docx.table.Table.add_row
type: Answer

http://stackoverflow.com/comment/83932275
has text: Depends. Up to 120.
type: Comment
comment on: http://stackoverflow.com/q/48469254
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83901683
comment on: http://stackoverflow.com/a/48454218
score: 0
type: Comment
type: AnswerComment
has text: @ChrisHarris, didn't you see a second example in my answer with a custom frequency?

http://stackoverflow.com/comment/83952897
score: 0
comment on: http://stackoverflow.com/a/48479178
type: Comment
has text: Rakesh I change this and I update my problem. Maybe You know how to solve this problem with gmail?
type: AnswerComment

http://stackoverflow.com/comment/83936444
type: Comment
type: QuestionComment
has text: It happens on the first form's post, @melwil
score: 0
comment on: http://stackoverflow.com/q/48470546

http://stackoverflow.com/comment/83910613
has text: curses is a great start it works in py/cmd console but doesn't work in pycharm(Redirection is not supported.). I will try some workarounds with that part but atleast I have now some idea how to do it.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48458781
score: 0

http://stackoverflow.com/a/48363024
has comment: http://stackoverflow.com/comment/83717443
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48362205
answers question: http://stackoverflow.com/q/48362205
has body: I have used Liquibase an a number of projects to solve this database migration problem, and found it to be highly effective.
has comment: http://stackoverflow.com/comment/83733320
type: Answer

http://stackoverflow.com/q/48462792
tagged with: dynamic-loading
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83967873
tagged with: python
tagged with: plugins
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83919506
tagged with: shared-libraries
has body: I am in the situation that I have an executable (main.c) that dynamically loads a shared object (py_plugin.c) which is in turn is linked to python. However, when the python plugin attempts to import a module whose dependencies are not linked to libpython I get the following error: ImportError: /usr/lib/python2.7/lib-dynload/bz2.x86_64-linux-gnu.so: undefined symbol: PyExc_SystemError As far as I can deduce this implies that the library bz2.x86_64-linux-gnu.so does not have access to the python symbols. Note that the error is specific to the "bz2" package because I am forcing it to surface using the minimal working example at the end of the question. There I am performing an explicit import of the "bz2", which loads the library bz2.x86_64-linux-gnu.so, inside the python plugin (py_plugin.c). Looking at the dependencies I verify that: The library bz2.x86_64-linux-gnu.so is not linked to python usr@cmptr $ ldd /usr/lib/python2.7/lib-dynload/bz2.x86_64-linux-gnu.so linux-vdso.so.1 =&gt; (0x00007ffd511fb000) libpthread.so.0 =&gt; /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f8c63a0a000) libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8c6362a000) libbz2.so.1.0 =&gt; /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007f8c6341a000) /lib64/ld-linux-x86-64.so.2 (0x00007f8c63e33000) But my python plugin is: usr@cmptr $ ldd py_plugin.so linux-vdso.so.1 =&gt; (0x00007ffc1ef5c000) libpython2.7.so.1.0 =&gt; /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 (0x00007f56ac01c000) libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f56abc3c000) libpthread.so.0 =&gt; /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f56aba1d000) libz.so.1 =&gt; /lib/x86_64-linux-gnu/libz.so.1 (0x00007f56ab800000) libdl.so.2 =&gt; /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f56ab5fc000) libutil.so.1 =&gt; /lib/x86_64-linux-gnu/libutil.so.1 (0x00007f56ab3f8000) libm.so.6 =&gt; /lib/x86_64-linux-gnu/libm.so.6 (0x00007f56ab0a2000) /lib64/ld-linux-x86-64.so.2 (0x00007f56ac79a000) My questions are the following: …
type: AnsweredQuestion
score: 0
has title: Dynamic loading of Python C extension fails due to missing symbols
accepted answer: http://stackoverflow.com/a/48517485
has comment: http://stackoverflow.com/comment/83918676
has answer: http://stackoverflow.com/a/48517485
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83918572

http://stackoverflow.com/q/48348334
score: -2
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83683117
has comment: http://stackoverflow.com/comment/83685904
has comment: http://stackoverflow.com/comment/83682882
has title: create a dict joining two other dicts [Python]
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38987
answer count: 3
has comment: http://stackoverflow.com/comment/83683096
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/48348560
possible better answer: http://stackoverflow.com/a/48348560
has answer: http://stackoverflow.com/a/48348563
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48348563
has answer: http://stackoverflow.com/a/48348648
has body: I'm trying to create a junction of the dicts bellow: buy_dict = {'Coin1': [{'buy_price': 105, 'id_buy':2 },{'buy_price': 100, 'id_buy':1 }], 'Coin2': [{'buy_price': 1200, 'id_buy':2 },{'buy_price': 1100, 'id_buy':1 }]} sell_dict = {'Coin1': [{'sell_price': 106, 'id_sell':1 }, {'sell_price': 110, 'id_sell':2 }], 'Coin2': [{'sell_price': 1250, 'id_sell':1 },{'sell_price': 1350, 'id_sell':2 }]} On the buy_dict I have a dict with buy prices and its ids, grouped by Coin. The same model on the sell_dict. What I need to do is create a third dict by joining the data from two dicts adobe, so the first record of the new dict would be the first record of the dictA plus the first record of the dictB. Below is how it should look: DictC = {'Coin1': [{'buy_price': 105, 'id_buy':2, 'sell_price': 106, 'id_sell':1}, {'buy_price': 100, 'id_buy':1, 'sell_price': 110, 'id_sell':2}], 'Coin2': [{'buy_price': 1200,'id_buy':2, 'sell_price': 1250,'id_sell':1}, {'buy_price': 1100, 'id_buy':1,'sell_price': 1350,'id_sell':2}]} In short, the records of DictC would be a junction of the highest buying price and the lowest selling prices. No ordering is required because buy_dict and sell_dict are already ordered. Thanks!!

http://stackoverflow.com/a/48354084
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/48350925
type: Answer
has body: Here are the links of the most widely used ChromeDriver properties and ChromeOptions: ChromeDriver - WebDriver for Chrome: Capabilities &amp; ChromeOptions Peter Beverloo: List of Chromium Command Line Switches Chromium Project: Chrome Preferences Chromium Project: Chrome Switches
downvote count: 0

http://stackoverflow.com/a/48348915
type: Answer
answers question: http://stackoverflow.com/q/48347738
has comment: http://stackoverflow.com/comment/83734173
downvote count: 0
has body: You can do this is in vanilla SPSS syntax with a loop. Below is one example way to do it. *Making fake example data. DATA LIST FREE /X1 TO X11 (11F1.0). BEGIN DATA 1 2 4 -5 6 7 1 -5 -5 -5 -5 2 3 4 5 -5 1 -6 -5 -4 -5 -5 4 5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 END DATA. *Using vector and loop to recode ends to system missing. VECTOR X = X1 TO X11. LOOP #i = 11 TO 1 BY -1. IF X(#i) = -5 X(#i) = $SYSMIS. END LOOP IF NOT MISSING(X(#i)). EXECUTE.
upvote count: 1
has comment: http://stackoverflow.com/comment/83753688
score: 1

http://stackoverflow.com/a/48380620
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83747755
downvote count: 0
has body: If want get lengths of some iterable like lists, use str.len which is more general as apply(len): df['desc_len']=df['item_description'].str.len() Your solution: df['desc_len']=df['item_description'].apply(len) working nice in ideal data - only iterable. But if mix - iterable and scalars it raise error.
type: Answer
accepted answer of: http://stackoverflow.com/q/48380586
has comment: http://stackoverflow.com/comment/83747793
answers question: http://stackoverflow.com/q/48380586
score: 2

http://stackoverflow.com/a/48455098
score: 0
type: Answer
has body: Here we get groups or "chunks" for randomly distributed items. Given import random import itertools as it import more_itertools as mit random.seed(4) n = 2 name_list = ["Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7"] blacklist = ["Item1", "Item5"] Code def get_random_groups(lst, size=2, blacklist=None): """Return distributed items among `m` groups of lists.""" if blacklist is None: blacklist = [] # Compute number of chunks length = (len(lst)) if length % 2 == 0: m = length//size else: m = (length+1)//size # Edge cases if len(blacklist) &gt; m: raise ValueError("Black-list is too long. Must be &lt; number of chunks.") if not set(blacklist).issubset(set(lst)): raise ValueError("Black-list is not a subset of the main list.") # Resize list remnant_list = list(set(lst) - set(blacklist)) random.shuffle(remnant_list) # Build chunks and distribute (blacklist first) chunks = [list(c) for c in mit.distribute(m, blacklist)] random.shuffle(chunks) for chunk in chunks[:]: while len(chunk) &lt; size: try: chunk += [remnant_list.pop(-1)] except IndexError: return chunks Demo # Without blacklist get_random_groups(name_list, size=n) # Out: [['Item5', 'Item1'], ['Item3', 'Item6'], ['Item7', 'Item2'], ['Item4']] # With blacklist get_random_groups(name_list, size=n, blacklist=blacklist) # [['Item2', 'Item6'], ['Item1', 'Item3'], ['Item5', 'Item7'], ['Item4']] # Invalid blacklist blacklist = "Item1 Item3 Item 5 Item6 Item7".split() get_random_groups(name_list, size=n, blacklist=blacklist) # ValueError: Blacklist is too long. Must be &lt; number of chunks. # Invalid blacklist blacklist = "Item1 Item9".split() get_random_groups(name_list, size=n, blacklist=blacklist) # ValueError("Black-list is not a subset of the main list.") Details The number of chunks is computed based on lists of even or odd length. Edge cases are tested (optional). Items in the blacklist will be distributed among chunks first. Therefore, those items must be removed from the list of remaining elements …
answers question: http://stackoverflow.com/q/48452939

http://stackoverflow.com/q/48351221
tagged with: tkinter
upvote count: 2
has comment: http://stackoverflow.com/comment/83689238
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83689273
has title: Updating Python tkinter label in realtime
has body: I want to update my label in python after the loop has started. Sadly I get the error File "mygui.py", line 19, in &lt;module&gt; GUI.user_said("General Kenobi") File "mygui.py", line 16, in user_said self.my_label['text'] = self.label_text File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1486, in __setitem__ self.configure({key: value}) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure return self._configure('configure', cnf, kw) File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: invalid command name ".!label" which doesn't help me at all... My Code: from tkinter import * class MyGUI: """A simple class""" def __init__(self): self.__main_window = Tk() self.label_text = "Hello There" self.my_label = Label(self.__main_window, text=self.label_text) self.my_label.pack() self.__main_window.mainloop() def user_said(self, users_request): """Returns what the user says""" self.label_text = "You said:\n{}\n\n".format(users_request) self.my_label.config(text=self.label_text) GUI = MyGUI() GUI.user_said("General Kenobi") I'm very glad if someone helps me to find a solution for my problem.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83689533
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48361570
tagged with: python
has comment: http://stackoverflow.com/comment/83689727
score: 2
has comment: http://stackoverflow.com/comment/83689297

http://stackoverflow.com/comment/93144293
comment on: http://stackoverflow.com/a/53091584
score: 2
type: AnswerComment
has text: No, I'm afraid not!
type: Comment

http://stackoverflow.com/comment/83762399
type: Comment
type: QuestionComment
has text: Possible duplicate of [Invalid character in identifier](https://stackoverflow.com/questions/14844687/invalid-character-in-identifier)
score: 0
comment on: http://stackoverflow.com/q/48387368

http://stackoverflow.com/a/48382192
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48375747
downvote count: 1
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83776772
has comment: http://stackoverflow.com/comment/83754865
accepted answer of: http://stackoverflow.com/q/48375747
has body: With RDD defined as from pyspark.mllib.recommendation import Rating rdd = sc.parallelize([ (1, (Rating(user=1, product=3, rating=0.99), Rating(user=1, product=4, rating=0.91), Rating(user=1, product=9, rating=0.68))), (2, (Rating(user=2, product=11, rating=1.01), Rating(user=2, product=12, rating=0.98), Rating(user=2, product=45, rating=0.97))), (3, (Rating(user=3, product=23, rating=1.01), Rating(user=3, product=34, rating=0.99), Rating(user=3, product=45, rating=0.98)))]) you can mapValues with list: df = rdd.mapValues(list).toDF(["User", "Ratings"]) df.printSchema() # root # |-- User: long (nullable = true) # |-- Ratings: array (nullable = true) # | |-- element: struct (containsNull = true) # | | |-- user: long (nullable = true) # | | |-- product: long (nullable = true) # | | |-- rating: double (nullable = true) or provide schema: df = spark.createDataFrame(rdd, "struct&lt;User:long,ratings:array&lt;struct&lt;user:long,product:long,rating:double&gt;&gt;&gt;") df.printSchema() # root # |-- User: long (nullable = true) # |-- ratings: array (nullable = true) # | |-- element: struct (containsNull = true) # | | |-- user: long (nullable = true) # | | |-- product: long (nullable = true) # | | |-- rating: double (nullable = true) # df.show() # +----+--------------------+ # |User| ratings| # +----+--------------------+ # | 1|[[1,3,0.99], [1,4...| # | 2|[[2,11,1.01], [2,...| # | 3|[[3,23,1.01], [3,...| # +----+--------------------+ If you want to drop user field: df_without_user = spark.createDataFrame( rdd.mapValues(lambda xs: [x[1:] for x in xs]), "struct&lt;User:long,ratings:array&lt;struct&lt;product:long,rating:double&gt;&gt;&gt;" ) If you want to format the column as a single string you have to use udf from pyspark.sql.functions import udf @udf def format_ratings(ratings): return "|".join(",".join(str(_) for _ in r[1:]) for r in ratings) df.withColumn("ratings", format_ratings("ratings")).show(3, False) # +----+-----------------------+ # |User|ratings | # +----+-----…
score: 1
has comment: http://stackoverflow.com/comment/83787906

http://stackoverflow.com/comment/83695455
has text: In other words, I think you need to elaborate a bit more here. I suspect you are misunderstanding the first part of your assignment, are you being tasked to use a Stack to populate a Queue?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48354366
score: 0

http://stackoverflow.com/q/48393253
tagged with: python
has comment: http://stackoverflow.com/comment/83774767
has body: First, I have read Parsing a table with rowspan and colspan. I even answered the question. Please read before you mark this as duplicate. A B C D E F G H It will render like +---+---+---+ | A | B | | +---+---+ | | | D | | + C +---+---+ | | E | F | +---+---+---+ | G | H | | +---+---+---+ A B C D E F G H However, this will render like this. +---+---+-------+ | A | B | | +---+---+-------+ | | | | | C | D +---+---+ | | | E | F | +---+---+---+---+ | G | H | | +---+---+---+---+ My code from previous answer can only parse table which has all the columns defined in the first row. def table_to_2d(table_tag): rows = table_tag("tr") cols = rows[0](["td", "th"]) table = [[None] * len(cols) for _ in range(len(rows))] for row_i, row in enumerate(rows): for col_i, col in enumerate(row(["td", "th"])): insert(table, row_i, col_i, col) return table def insert(table, row, col, element): if row >= len(table) or col >= len(table[row]): return if table[row][col] is None: value = element.get_text() table[row][col] = value if element.has_attr("colspan"): span = int(element["colspan"]) for i in range(1, span): table[row][col+i] = value if element.has_attr("rowspan"): span = int(element["rowspan"]) for i in range(1, span): table[row+i][col] = value else: insert(table, row, col + 1, element) soup = BeautifulSoup(''' 1 2 5 3 4 6 7 ''', 'html.parser') print(table_to_2d(soup.table)) My question is how to parse a table into a 2D array which represent exactly how it render in browser. Or someone can explain how the browser renders the table is also fine.
has comment: http://stackoverflow.com/comment/83774693
upvote count: 16
accepted answer: http://stackoverflow.com/a/48451104
has title: How to parse table with rowspan and colspan
type: AnsweredQuestion
tagged with: html-table
has answer: http://stackoverflow.com/a/48451104
possible better answer: http://stackoverflow.com/a/52094811
answer count: 3
has comment: http://stackoverflow.com/comment/83871993
has answer: http://stackoverflow.com/a/52094811
has comment: http://stackoverflow.com/comment/84103784
linked to: http://stackoverflow.com/q/39278376
downvote count: 0
score: 16
linked to: http://stackoverflow.com/q/9978445
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55137369
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/48478723
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83960434
has body: I'm working on a simple GraphQL Flask API and I'm implementing a simple find user resolver. This is my schema.py import graphene from graphene import relay from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField from models import db_session, Users as UsersModel, Channel as ChannelModel, Video as VideoModel class Users(SQLAlchemyObjectType): class Meta: model = UsersModel interfaces = (relay.Node, ) class Channel(SQLAlchemyObjectType): class Meta: model = ChannelModel interfaces = (relay.Node, ) class Query(graphene.ObjectType): node = relay.Node.Field() users = SQLAlchemyConnectionField(Users) find_user = graphene.Field(Users, name = graphene.String()) all_user = SQLAlchemyConnectionField(Users) def resolve_find_user(self, args, context, info): query = Users.get_query(context) name = args.get('name') return query.get(name) I'm using graphene 2.0 and the code returns an error of "message": "resolve_find_user() got an unexpected keyword argument 'name'", After some Googling, it looks like that is a major change in graphene that change the way resolver works. I went through the UPGRADE-v2.0.md and change things accordingly. The resolver looks like this now. # def resolve_find_user(self, info, name): # query = Users.get_query(info.context) # return query.get(name) Now, the keyword argument disappears but I'm having a new issue. The error is "message": "'Request' object has no attribute 'context'",. Now I'm confused because I thought info.context should have worked but apparently it is not. Any idea about how to fix this context issue? This is my first time working on GraphQL and any help is really appreciated! Edit: It's looks like type(info) is a &lt;class 'graphql.execution.base.ResolveInfo'&gt; and type(info.context) is &lt;class 'werkzeug.local.LocalProxy'&gt;. Should the context be the SQLAlchemy context?
downvote count: 0
has comment: http://stackoverflow.com/comment/84010237
answer count: 1
has title: Graphene - GraphQL : 'Request' object has no attribute 'context'
accepted answer: http://stackoverflow.com/a/48527639
tagged with: sqlalchemy
tagged with: graphene-python
favorite count: 0
has comment: http://stackoverflow.com/comment/83958773
type: Question
tagged with: graphql
tagged with: python
has answer: http://stackoverflow.com/a/48527639

http://stackoverflow.com/comment/83938442
has text: Check out http://pyformat.info. It's a great reference.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48472121
score: 1

http://stackoverflow.com/comment/83896073
score: 0
type: QuestionComment
has text: Yes, but it ran before I upgraded scikit-learn. I agree, a search space should be defined, but you also need to generate samples to try for hyperparameter optimization. I'm following the general setup here: https://github.com/keras-team/keras/issues/1591 (post by jacobzweig). The values here can be fed directly in to models - my problem is that the value needs to be an integer.
type: Comment
comment on: http://stackoverflow.com/q/48450932

http://stackoverflow.com/a/48396100
has comment: http://stackoverflow.com/comment/83781164
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83781023
has body: I'm not sure I understood correctly, but isn't gathering multiple coroutines is what you want? while True: request_raw = await self.ws_server.recv() # process by multiple clients parallely: await asyncio.gather( self.process_by_client_1(request_raw), self.process_by_client_2(request_raw), self.process_by_client_3(request_raw), )
answers question: http://stackoverflow.com/q/48394405

http://stackoverflow.com/comment/83804591
type: QuestionComment
comment on: http://stackoverflow.com/q/48407643
score: 0
has text: please provide a working example, not only data which can't be used with your code!
type: Comment

http://stackoverflow.com/q/48409527
tagged with: regex
has answer: http://stackoverflow.com/a/48410297
tagged with: parsing
tagged with: replace
has body: I am having some very large text file on which I want to execute multiple regex based string replacement. Currently I am doing it using Sublime's similar feature. However, in files larger than a GB my system is hanging. I am running some of the below matches in my sublime currently \\\n - Remove all the backslash followed by newline. \n - Remove all newlines. \=\\\" - Replace all instances of =\" with just =" In one case, I also want to group the match and use it in the replaced text. Some experts around me suggested writing a quick python script for the same, and performance won't be an issue. With my limited python knowledge, I tried something as below: import pandas as pd import numpy as np df = pd.read_csv('story_all.csv') output = df.str.replace('\n', '') output.to_csv(story_done.csv, sep='\n', encoding='utf-8') It, however, isn't working. And somewhere I think, I might be overdoing. Note: The fact the text file is CSV doesn't really matter. I just need to execute some string replaces. The new line required by CSV is preserved while it's done. The error am getting is as below: Traceback (most recent call last): File "replace.py", line 4, in df = pd.read_csv('story_all.csv') File "/Users/safwan/Envs/regex/lib/python2.7/site-packages/pandas/io/parsers.py", line 709, in parser_f return _read(filepath_or_buffer, kwds) File "/Users/safwan/Envs/regex/lib/python2.7/site-packages/pandas/io/parsers.py", line 455, in _read data = parser.read(nrows) File "/Users/safwan/Envs/regex/lib/python2.7/site-packages/pandas/io/parsers.py", line 1069, in read ret = self._engine.read(nrows) File "/Users/safwan/Envs/regex/lib/python2.7/site-packages/pandas/io/parsers.py", line 1839, in read data = self._reader.read(nrows) File "pandas/_libs/parsers.pyx", line 902, in pandas._libs.parsers.TextReader.read File "pandas/_libs/parsers.pyx", line 924, in pandas._libs.parsers.TextReader._read_low_memory File "pandas/_libs/parsers.pyx", line 978, in pandas._libs.parsers.TextReader._read_rows …
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83808669
has comment: http://stackoverflow.com/comment/83808564
type: Question
tagged with: pandas
has title: Multiple regex string replace on large text file using Python
has comment: http://stackoverflow.com/comment/83808960
tagged with: python
has answer: http://stackoverflow.com/a/48410983
type: UnansweredQuestion

http://stackoverflow.com/comment/83913802
type: Comment
type: QuestionComment
score: 0
has text: try to do regex test[1-9] in your filter
comment on: http://stackoverflow.com/q/48460391

http://stackoverflow.com/q/48461510
has body: I have tried to login to the twitter account using requests library. But I am getting url response as "400". It is not working. I used all the required payload parameters and headers. But still, I am unable to figure out how to login. import requests from bs4 import BeautifulSoup payload={ "session[username_or_email]":"***************", "session[password]":"*************", "authenticity_token":"*************", "ui_metrics":'{"rf":{"a4f2d7a8e3d9736f0815ae7b34692191bca9f114a7d5602c7758a3e6087b6b30":0,"ad92fc8b83fb5dec3f720f89a7f0fb415a26130516362f230b02251edd96a54a":0,"a011babb5c5df598f93bcc4a38dfad0276f69df36faff48eea95bac67cefeffe":0,"a75214752b7e90fd50725fce21cc26761ef3613173b0f8764d52c8b53f136bbf":0},"s":"mTArUSdNtTOm6WaGwNeRjMAU3EhNA3VGbFeCIZeEkjjLTAbccFDTJjcTEB2tQ9iuNJUzniFKyvhZNOGdH1LIwmi1YSMcFTOHu2Wi49yKvONv0obfg1dW27znR_C2n-ev2zMvN5166j1ccsxWKIheiWw-eHM7oXA54U40cWHvdCrunJJKj2INkTrcVph-y2fccu1m3hp31vngqBiL-XmeLWYiyZ-NYOmV8f5iXW9WWMvISTcSwzz9vd_n9-tLSKociT-1ap5ZVFWNUWIycSflj8WcOmmRFzq4kwa-NsS0FRp-DQ2FOkozhhhQi9HDvSODUlGsdQWBPkGKKtDWbtnj9gAAAWEty4Xv"}', "scribe_log":"", "redirect_after_login":"", "authenticity_token":"******************", "return_to_ssl":"", "remember_me":"1", "lang":"" } headers={ "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding":"gzip, deflate, br", "accept-language":"en-US,en;q=0.9", "cache-control":"max-age=0", "cookie":'moments_profile_moments_nav_tooltip_self=true; syndication_guest_id=v1%3A150345116906281638; eu_cn=1; kdt=QErLcBT9OjM5gjEznmsRcHlMTK6biDyAw4gfI5ro; remember_checked_on=1; _ga=GA1.2.1923324433.1496571570; tfw_exp=0; _gid=GA1.2.106381927.1516638134; __utma=43838368.1923324433.1496571570.1516764481.1516764481.1; __utmz=43838368.1516764481.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); lang=en; ct0=7ceea26f7fd3d186152512d26365cddf; _twitter_sess=BAh7CiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCL8wyy1hATo…
tagged with: python
tagged with: python-requests
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83925404
score: 1
answer count: 1
has title: Unable to login to twitter using python requests library
tagged with: twitter
favorite count: 0
has comment: http://stackoverflow.com/comment/94693412
has answer: http://stackoverflow.com/a/48461655
type: Question
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/48479115
has comment: http://stackoverflow.com/comment/83923409
has comment: http://stackoverflow.com/comment/83952526
has comment: http://stackoverflow.com/comment/83923864
type: UnansweredQuestion

http://stackoverflow.com/comment/83712357
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48362701
has text: yes, i know. about dict being a type. i was just in a hurry for debugging. this code worked perfectly! thank you very much. i wish you a good evening.
type: AnswerComment

http://stackoverflow.com/q/48433642
has comment: http://stackoverflow.com/comment/83858866
tagged with: parameters
possible better answer: http://stackoverflow.com/a/48433722
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48433723
accepted answer: http://stackoverflow.com/a/48433723
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48433722
has title: how to use a list as a parameter for SQL connection in python using pyodbc
favorite count: 0
type: Question
has body: I am learning python, and I am trying to pass a parameter as part of the WHERE clause. I am using pandas and pyodbc. Here is what I've tried so far. I first get the data for column c from a pandas dataframe, and convert it to a list called df_col, which has about 100 numeric values df_col=df['data_for_colc'].tolist() then, I execute the SQL statement: execu = mycursor.execute( """ Select columnA ,columnb ,columnc where columnc in (?) """,df_col) rows = mycursor.fetchall() print(rows) I am able to connecto and download data from SQL server, but I am not able to pass parameters. I just need to be able to download those 100 rows based on the list I created with 100 values, but I get an error: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ','. (102) (SQLExecDirectW)") any help would be appreciated. Thanks
upvote count: 5
score: 5
tagged with: python
tagged with: pyodbc

http://stackoverflow.com/a/48392258
accepted answer of: http://stackoverflow.com/q/48392164
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48392164
type: AcceptedAnswer
has body: label_to_one_hot_batch is an instance method, so calling it outside of the context of the class makes little sense. You'd want to import IsprsDataset, instantiate it, and call that method on that instance. For instance: from data.isprs import IsprsDataset dataset = IsprsDataset() dataset.label_to_one_hot_batch(label_batch) # where label_batch is defined elsewhere

http://stackoverflow.com/a/48343729
upvote count: 2
score: 2
downvote count: 0
has body: Try this: def sigmoid_op_backward(op, grads): sigmoid = op.outputs[0] return sigmoid * (1 - sigmoid) * grads
has comment: http://stackoverflow.com/comment/83675883
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48343536
accepted answer of: http://stackoverflow.com/q/48343536
type: Answer

http://stackoverflow.com/q/48333298
answer count: 1
has body: For example, when i use matplotlib as plt, a possible statement is like below: plt.plot(x,y,color='blue') so how can i get what arguments like 'color' i can pass to the 'plot' function, and what is the proper values for that argument? Especially when i use some modules. thanks for any answers.
linked to: http://stackoverflow.com/q/3898572
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83652258
type: UnansweredQuestion
score: -2
tagged with: arguments
tagged with: python
has comment: http://stackoverflow.com/comment/83694025
has comment: http://stackoverflow.com/comment/83652237
has title: How can i know what parameters i can pass to a python function and what is the proper values?
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83652145
has answer: http://stackoverflow.com/a/48333617

http://stackoverflow.com/a/48414908
has comment: http://stackoverflow.com/comment/83821130
has body: You can make custom method in class that inherited "resources.ModelResource" class class ApplicationResource(resources.ModelResource): class Meta: model = &lt;model name&gt; def dehydrate_system(self, instance): #def dehydrate_&lt;field name&gt;(self, instanse) return instance.system.title
type: Answer
answers question: http://stackoverflow.com/q/48414074
score: 0

http://stackoverflow.com/q/48476162
has answer: http://stackoverflow.com/a/51845987
tagged with: linux
has comment: http://stackoverflow.com/comment/84004432
has comment: http://stackoverflow.com/comment/83946104
type: Question
has comment: http://stackoverflow.com/comment/83945914
tagged with: python
has title: No module named 'Adafruit_DHT' on a Raspberry Pi Zero W running Raspbian using Python 3 with Berryconda3
has comment: http://stackoverflow.com/comment/83946123
has comment: http://stackoverflow.com/comment/83946375
has body: I am using a Raspberry Pi Zero W where I connected a DHT11 Sensor from Adafruit. While setting up my Raspberry Pi I tried to install miniconda3 to manage my python packages. Somehow I could not install miniconda3 (I guess miniconda3 is not supported on the Raspberry Pi Zero W). However, I managed to install berryconda3. To read the data from my sensor I installed the Adafruit_DHT library (in python2 and python3). I am able to read the data from my sensor in python2 but I am not able to read it in python3. When importing the library with import Adafruit_DHT it always shows the following error message: No module named 'Adafruit_DHT'. For the istallation in python3, I downloaded the Adafruit_Python_DHT library from github.com/adafruit/Adafruit_Python_DHT, copied it to my raspberry and installed it with sudo python3 setup.py install --force-pi. When I try to install it using pip3 install Adafruit_DHT the console replies: pip3: command not found. When using pip install Adafruit_DHT the console replies: "Collecting Adafruit_DHT Could not find a version that satisfies the requirement Adafruit_DHT (from versions: ) No matching distribution found for Adafruit_DHT" When I try to locate the library I found the following three potential locations where the module should be installed: ~/berryconda3/lib/python3.6/ --> no Adafruit-directory in this location /usr/local/lib/python3.5/dist-packages --> directory Adafruit_DHT-1.3.2-py3.5-linux-armv61.egg /usr/local/lib/python2.7/dist-packages --> directory Adafruit_DHT-1.3.2-py2.7-linux-armv61.egg the command which python3 returns the following information: /home/pi/berryconda3/bin/python3 When running the command pip3 freeze in /home/pi/berryconda3/bin/python3 it doesn't work (reply: -bash: pip3: command not found). But pip freeze works. I run the command in /home/pi/berryconda3/bin and it got a list with all other libraries I installed (those libraries listed here all work in my scripts). But Adafruit_DHT is not listed. I guess the …
has comment: http://stackoverflow.com/comment/83946598
has comment: http://stackoverflow.com/comment/83946549
score: 4
upvote count: 4
tagged with: adafruit
has comment: http://stackoverflow.com/comment/83945683
tagged with: raspberry-pi
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83946259
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85172146
has answer: http://stackoverflow.com/a/55857090
favorite count: 0
tagged with: raspbian

http://stackoverflow.com/q/48456000
accepted answer: http://stackoverflow.com/a/48456669
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83904826
tagged with: web
favorite count: 0
has title: How to get renewable information on a web by python3?
type: Question
has body: I want to get some information on a web page. I use requests.get to abstract the page. But I cannot find what I want. Checking it carefully, I found the info I want is in a list with a scrollbar. When I drag scrollbar down, more and more info is loaded. So I guess all the info in the list is not loaded yet when I get the page by module requests. I want to know what is happened in this process and How can I gather the information I want. (I am not familiar with Html language).
score: -2
has answer: http://stackoverflow.com/a/48456669
tagged with: python
tagged with: request
linked to: http://stackoverflow.com/q/21006940
type: AnsweredQuestion

http://stackoverflow.com/comment/83939344
score: 4
type: Comment
comment on: http://stackoverflow.com/a/48472770
type: AnswerComment
has text: Worth pointing out: given the purpose of a queue of fixed length is to `append` and `pop` I think the performance benefit of `deque` over `list` type may be important.

http://stackoverflow.com/comment/83691743
score: 0
comment on: http://stackoverflow.com/a/48352262
type: Comment
has text: first question: it is done by the person deploying the project; CM engineer, devops, CI scripts, web administrator or even developer himself. Second question: yes, it is definitely a bad practice to distribute a copy of numpy with the project code. It is platform dependent, so it is not guaranteed to run properly on a machine with a different CPU architecture or even running a different version of Python
type: AnswerComment

http://stackoverflow.com/comment/83895525
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48451275
score: 0
has text: is there a differencde between extend and []+[]

http://stackoverflow.com/comment/83696447
type: QuestionComment
comment on: http://stackoverflow.com/q/48354773
score: 0
has text: Your answer is not very well defined. What is different? And what is jumbled exactly? If you mean that the first rows look vague, you probably don't want the first rows since they are not tabled. This can be solved with: temp = file.parse('Named Insured', skiprows = 3, header = 0)
type: Comment

http://stackoverflow.com/q/48475989
linked to: http://stackoverflow.com/q/1516889
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83945224
duplicate of: http://stackoverflow.com/q/1516889
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has title: Python list .insert()
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48476005
score: 1
has answer: http://stackoverflow.com/a/48476005
has body: I'm working on a polynomial organizer. I need to insert two items into the list of coefficients and powers, (a zero for the coefficient and the missing power) wherever needed. print poly poly=list(poly.split(',')) for i in range(0,13): if int(poly[i*2+1])!=int(12-i): poly=poly.insert((i*2+1),str(12-i)) poly=poly.insert((i*2+1),"0") returns 0,12,0,11,0,10,0,9,0,8,-7,7,1,5,-1,4,1,3,-2,2,5,0 Traceback (most recent call last): File "python", line 105, in &lt;module&gt; File "python", line 97, in mypoly AttributeError: 'NoneType' object has no attribute 'insert' I'm confused because from what I've read on the insert function, it is made to work on lists, but here it seems not to. Please don't kill this question... I've been trying to figure it out on my own for a while now, and always run into this problem. So I want it to look like this: [0,12,0,11,0,10,0,9,0,8,-7,7,0,6,1,5,-1,4,1,3,-2,2,0,1,5,0] Notice the 0,6 and 0,1.

http://stackoverflow.com/comment/104286727
comment on: http://stackoverflow.com/a/48522557
type: AnswerComment
has text: this prints the list on the console. but is here any way to print them into a text file ?
type: Comment
score: 0

http://stackoverflow.com/q/48428173
has body: I have a pandas dataframe created from measured numbers. When something goes wrong with the measurement, the last value is repeated. I would like to do two things: 1. Change all repeating values either to nan or 0. 2. Keep the first repeating value and change all other values nan or 0. I have found solutions using "shift" but they drop repeating values. I do not want to drop repeating values.My data frame looks like this: df = pd.DataFrame(np.random.randn(15, 3)) df.iloc[4:8,0]=40 df.iloc[12:15,1]=22 df.iloc[10:12,2]=0.23 giving a dataframe like this: 0 1 2 0 1.239916 1.109434 0.305490 1 0.248682 1.472628 0.630074 2 -0.028584 -1.116208 0.074299 3 -0.784692 -0.774261 -1.117499 4 40.000000 0.283084 -1.495734 5 40.000000 -0.074763 -0.840403 6 40.000000 0.709794 -1.000048 7 40.000000 0.920943 0.681230 8 -0.701831 0.547689 -0.128996 9 -0.455691 0.610016 0.420240 10 -0.856768 -1.039719 0.230000 11 1.187208 0.964340 0.230000 12 0.116258 22.000000 1.119744 13 -0.501180 22.000000 0.558941 14 0.551586 22.000000 -0.993749 what I would like to be able to do is write some code that would filter the data and give me a data frame like this: 0 1 2 0 1.239916 1.109434 0.305490 1 0.248682 1.472628 0.630074 2 -0.028584 -1.116208 0.074299 3 -0.784692 -0.774261 -1.117499 4 NaN 0.283084 -1.495734 5 NaN -0.074763 -0.840403 6 NaN 0.709794 -1.000048 7 NaN 0.920943 0.681230 8 -0.701831 0.547689 -0.128996 9 -0.455691 0.610016 0.420240 10 -0.856768 -1.039719 NaN 11 1.187208 0.964340 NaN 12 0.116258 NaN 1.119744 13 -0.501180 NaN 0.558941 14 0.551586 NaN -0.993749 or even better keep the first value and change the rest to NaN. Like this: 0 1 2 0 1.239916 1.109434 0.305490 1 0.248682 1.472628 0.630074 2 -0.028584 -1.116208 0.074299 3 -0.784692 -0.774261 -1.117499 4 40.000000 0.283084 -1.495734 5 NaN -0.074763 -0.840403 6 NaN 0.709794 -1.000048 7 NaN 0.920943 0.681230 8 -0.701831 0.547689 -0.128996 9 -0.455691 0.610016 0.420240 10 -0.856768 -1.039719 0.230000 11 1.187208 0.964340 NaN 12 0.116258 2…
tagged with: python
has comment: http://stackoverflow.com/comment/83852356
has answer: http://stackoverflow.com/a/48428269
possible better answer: http://stackoverflow.com/a/48428269
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/19463985
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48428653
accepted answer: http://stackoverflow.com/a/48428653
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83852349
answer count: 2
has comment: http://stackoverflow.com/comment/83847927
has title: How to change consecutive repeating values in pandas dataframe series to nan or 0?

http://stackoverflow.com/comment/83792087
type: Comment
comment on: http://stackoverflow.com/a/48393795
has text: I'm sorry, I really can't help you more. You could post a new question explaining your problem, @Vindicium
score: 0
type: AnswerComment

http://stackoverflow.com/q/48391911
has body: I am extracting a column from excel document with pandas. After that, I want to replace for each row of the selected column, all keys contained in multiple dictionaries grouped in a list. import pandas as pd file_loc = "excelFile.xlsx" df = pd.read_excel(file_loc, usecols = "C") In this case, my dataframe is called by df['Q10'], this data frame has more than 10k rows. Traditionally, if I want to replace a value in df I use; df['Q10'].str.replace('val1', 'val1') Now, I have a dictionary of words like: mydic = [ { 'key': 'wasn't', 'value': 'was not' } { 'key': 'I'm', 'value': 'I am' } ... + tons of line of key value pairs ] Currently, I have created a function that iterates over "mydic" and replacer one by one all occurrences. def replaceContractions(df, mydic): for cont in contractions: df.str.replace(cont['key'], cont['value']) Next I call this function passing mydic and my dataframe: replaceContractions(df['Q10'], contractions) First problem: this is very expensive because mydic has a lot of item and data set is iterate for each item on it. Second: It seems that doesn't works :( Any Ideas?
tagged with: replace
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: Replace values from pandas dataset with dictionary
accepted answer: http://stackoverflow.com/a/48391937
type: Question
has answer: http://stackoverflow.com/a/48391937
has comment: http://stackoverflow.com/comment/83771773
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83771755

http://stackoverflow.com/q/48372875
tagged with: jupyter-notebook
score: 0
type: UnansweredQuestion
tagged with: title-case
has comment: http://stackoverflow.com/comment/83732922
answer count: 1
type: Question
has title: No module named titlecase (existence confirmed)
tagged with: python-3.x
has body: I tried to use the package called "titlecase" (https://pypi.python.org/pypi/titlecase) My code works on jupyter notebook but it does not work when I tried to run it in cmd. Here is my code: from __future__ import print_function import datetime now = datetime.datetime.now() from titlecase import titlecase f=open(r'C:\Users\GX\everyFirstLetterCapitalized.txt') f.seek(0) message = f.read() outPut=titlecase(message) f=open(r'C:\Users\GX\everyFirstLetterCapitalizedOutput.txt', 'w') f.write("new output:-- {a}\n".format(a=now)+outPut) f.close() But, I always got the result: ImportError: No module named titlecase I tried to use the following code to find the package, it does exist: import imp imp.find_module('titlecase')
has comment: http://stackoverflow.com/comment/83732902
has answer: http://stackoverflow.com/a/48372915
tagged with: python

http://stackoverflow.com/q/48354491
tagged with: steam-web-api
has body: The below block of code works however I'm not satisfied that it is very optimal due to my limited understanding of using JSON but I can't seem to figure out a more efficient method. The steam_game_db is like this: { "applist": { "apps": [ { "appid": 5, "name": "Dedicated Server" }, { "appid": 7, "name": "Steam Client" }, { "appid": 8, "name": "winui2" }, { "appid": 10, "name": "Counter-Strike" } ] } } and my Python code so far is i = 0 x = 570 req_name_from_id = requests.get(steam_game_db) j = req_name_from_id.json() while j["applist"]["apps"][i]["appid"] != x: i+=1 returned_game = j["applist"]["apps"][i]["name"] print(returned_game) Instead of looping through the entire app list is there a smarter way to perhaps search for it? Ideally the elements in the data structure with 'appid' and 'name' were numbered the same as their corresponding 'appid' i.e. appid 570 in the list is Dota2 However element 570 in the data structure in appid 5069 and Red Faction Also what type of data structure is this? Perhaps it has limited my searching ability for this answer already. (I.e. seems like a dictionary of 'appid' and 'element' to me for each element?) EDIT: Changed to a for loop as suggested # returned_id string for appid from another query req_name_from_id = requests.get(steam_game_db) j_2 = req_name_from_id.json() for app in j_2["applist"]["apps"]: if app["appid"] == int(returned_id): returned_game = app["name"] print(returned_game)
tagged with: python-requests
score: 4
has comment: http://stackoverflow.com/comment/83696484
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83695708
has comment: http://stackoverflow.com/comment/83696504
possible better answer: http://stackoverflow.com/a/48354772
tagged with: python
has answer: http://stackoverflow.com/a/48354772
upvote count: 4
has title: Parsing JSON output efficiently in Python?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83696376
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83695585
has answer: http://stackoverflow.com/a/48354739
accepted answer: http://stackoverflow.com/a/48354739
tagged with: steam
has comment: http://stackoverflow.com/comment/83695663

http://stackoverflow.com/comment/83833668
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48421684
has text: I think your code does two whole-dataframe operations for every row - first `shift` and then `fillna`. That's a lot more number-crunching than necessary =).
type: Comment

http://stackoverflow.com/q/48397171
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48397259
has title: pd.core.groupby.data error no numeric types to aggregate - ok for max/min, not ok for mean/std
type: Question
has body: I read many questions related to the "pandas.core.groupby.data error no numeric types to aggregate" error but I was not able to find an answer to the problem I am facing. Namely, I can perform some operations on my .groupby construct, such as .max(), .count()... but operations like .mean(), .std raise the above mentioned error. I saw in other threads that it could have to do with the datatype, but I am dealing with int64, which I believe are fine. In fact, I can call .mean() on the column I am interested in if I call it without grouping first (see second line below).
tagged with: python
has answer: http://stackoverflow.com/a/48397259
type: AnsweredQuestion
score: 0
tagged with: pandas-groupby

http://stackoverflow.com/comment/83718154
score: 0
comment on: http://stackoverflow.com/q/48365723
type: Comment
type: QuestionComment
has text: I tried to answer but ended in error as below C:\Windows\System32>pip install simplesocial Collecting simplesocial Could not find a version that satisfies the requirement simplesocial (from versions: ) No matching distribution found for simplesocial

http://stackoverflow.com/comment/83724298
type: AnswerComment
comment on: http://stackoverflow.com/a/48364191
type: Comment
has text: As I said, if I render the parent by itself, it works fine. That means, that my url pattern is already established. But to your point, I have added my urlpattern for clarification.
score: 0

http://stackoverflow.com/a/48619846
score: 1
type: Answer
has body: Finally I managed to stop the crawler by putting it inside if __name__ == "__main__" block. if __name__ == '__main__': process = CrawlerProcess(get_project_settings()) process.crawl(CoreSpider) process.start() It stops the crawler gracefully once it finishes scrapping all urls.
answers question: http://stackoverflow.com/q/48425792
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48425792
downvote count: 0
has comment: http://stackoverflow.com/comment/93539211
upvote count: 1

http://stackoverflow.com/comment/83919812
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48452349
has text: No worries @johnnycodes! Yes, you would essentially assign that string constant to a new variable which you can then pass around to a function! Note that the name of the variable does not have to be of the same name as the function parameter `var`. You can name that string variable anything you'd like and then _pass it as an argument_ to the function.
score: 0

http://stackoverflow.com/a/48352864
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48352791
has body: You are very close to the right answer: def sort_by_key(x): return key_order.index(x.split(':')[0]) for d in data: print(" ".join(sorted(d.split(), key=sort_by_key))) #ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:a@b.c ST:VIC #ID:b22 GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215 EM:b@d.c ST:VIC #ID:153 GE:m FN:John LN:Liu MN:040181010 EM:d@b.c ST:NSW
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83692491
accepted answer of: http://stackoverflow.com/q/48352791

http://stackoverflow.com/q/48385672
tagged with: python
linked to: http://stackoverflow.com/q/16186361
has answer: http://stackoverflow.com/a/48393688
tagged with: opencv
type: AnsweredQuestion
tagged with: sift
possible better answer: http://stackoverflow.com/a/60926402
favorite count: 0
has answer: http://stackoverflow.com/a/60926402
type: Question
has title: OpenCV (Python) unpack SIFT Octave
answer count: 2
score: 5
upvote count: 5
has body: I just discovered that SIFT writes the Octave as packed value (octave, layer and scale). I need this value unpacked since I have to use SIFT detector in combination with other descriptors (ORB, BRIEF, SURF, BRISK). Here you can find a similar question. I already tried different solutions (see code below) but none seems to work in python (this one as well). Any suggestion? unpackOctave(keypoints[i], octave, layer, scale) or: unpackOctave(const KeyPoint&amp; kpt, int&amp; octave, int&amp; layer, float&amp; scale){ octave = kpt.octave &amp; 255; layer = (kpt.octave &gt;&gt; 8) &amp; 255; octave = octave &lt; 128 ? octave : (-128 | octave); scale = octave &gt;= 0 ? 1.f/(1 &lt;&lt; octave) : (float)(1 &lt;&lt; -octave); }
downvote count: 0
accepted answer: http://stackoverflow.com/a/48393688

http://stackoverflow.com/comment/84131698
comment on: http://stackoverflow.com/a/48531701
type: AnswerComment
has text: if you are using `pandas` to manage your data then you can use [pandas.DataFrame.to_csv] (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html) or you can see [this] (https://stackoverflow.com/questions/2084069/create-a-csv-file-with-values-from-a-python-list) on StackOverflow for creating CSV from `python lists`.
score: 0
type: Comment

http://stackoverflow.com/a/48342355
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48342270
has body: Can I suggest you to use ipython-notebook. It is very friendly and also supports the shell commands directly.
type: Answer
score: 0

http://stackoverflow.com/comment/83809255
has text: Does the new class have to actually **be** an instance of `Class2D` or `Class3D`? That is, does it need to pass `isinstance` checks (or equivalent)?
comment on: http://stackoverflow.com/q/48409078
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48421807
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83836629
has comment: http://stackoverflow.com/comment/83842027
has comment: http://stackoverflow.com/comment/83838318
has body: There is a bug in your method label_fix. Because the &lt;=50K value is always prefixed with a space (&lt;=50K), label_fix will always return 1 resulting in perfect recall and precision. If you fix your method to handle the leading space, you will get more reasonable precision and recalls def label_fix(label): if label.strip().strip('.') == '&lt;=50K': return 0 else: return 1 After fitting your model, you can then use it to predict the income for the adult.test data file as follows: test_data = pd.read_csv('adult.test.csv') test_data['income'] = test_data['income'].apply(label_fix) y_test_data = test_data['income'] pred_fn = tf.estimator.inputs.pandas_input_fn(x=test_data,batch_size=len(test_data),shuffle=False) predictions = list(model.predict(input_fn=pred_fn)) final_preds_test_data=[] for pred in predictions: final_preds_test_data.append(pred['class_ids'][0]) print(classification_report(y_test_data,final_preds_test_data)) Please note that I had to add strip('.') to label_fix method as the test file has a slightly different format for the income column:
accepted answer of: http://stackoverflow.com/q/48419758
type: Answer
answers question: http://stackoverflow.com/q/48419758
has comment: http://stackoverflow.com/comment/83835917

http://stackoverflow.com/a/48368977
answers question: http://stackoverflow.com/q/48368952
score: 2
upvote count: 2
downvote count: 0
has body: I think you are looping and ifs are inside a loop. If so, just print the length outside loop scope. Please share the complete code for a better answer
type: Answer

http://stackoverflow.com/q/48464390
tagged with: python
accepted answer: http://stackoverflow.com/a/48464620
tagged with: sklearn-pandas
has title: brew install sklearn didn't work. What to do next?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17271319
answer count: 2
linked to: http://stackoverflow.com/q/45457225
possible better answer: http://stackoverflow.com/a/78911938
upvote count: 3
tagged with: homebrew
has answer: http://stackoverflow.com/a/48464620
downvote count: 0
has answer: http://stackoverflow.com/a/78911938
tagged with: pip
favorite count: 0
tagged with: quandl
type: Question
score: 3
has body: Heyyy, so I'm following a video tutorial that requires me to install sklearn, quandl, and pandas. Unfortunately the video author is using Windows and gave no explanation of what to do if on a Mac. I thought maybe I could use homebrew, so I installed homebrew and tried brew install sklearn, but that didn't work. Error: No available formula with the name "sklearn" When I tried pip install sklearn I got -bash: pip: command not found I had read this comment by user acidjunk: "a home brew python already has pip." I didn't understand this the first time I read it. Now I understand that pip is included in some Python installations. But I've also since learned that installing that way can result in a double installation of Python, so I'm hesitant about doing that. Also, the accepted answer for that question about installing pip uses sudo, and a comment was made "Never sudo install a package for any language. This is insecure and will ruin your life later as more and more packages need sudo permissions." which sounds like a reasonable argument, and that's why I haven't installed pip that way. Another user commented elsewhere on Stack Overflow "I can use install sklearn using pip or home brew", so there must be some piece of the puzzle I'm missing if it worked for them but not for me. To further complicate matters, another user suggested brew install pip, but when I tried that I got the following message: Homebrew provides pip via: `brew install python`. However you will then have two Pythons installed on your Mac, so alternatively you can install pip via the instructions at: https://pip.readthedocs.io/en/stable/installing/ Of course I followed the link, but on the page it says: pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4 binaries downloaded from python.org, but you'll need to upgrade pip. I have Python 2.7.10 installed, but I didn't get it directly from python.org. I want to make sure that I install it in a way that it will be compatible with …

http://stackoverflow.com/comment/83731284
comment on: http://stackoverflow.com/a/48371736
type: AnswerComment
score: 0
has text: in fact forget() is a shortcut for pack_forget(). So it's better as you use it because sometime later you will use the grid_forget() and I think there is no shortcut there. But I also changed the 2 functions.
type: Comment

http://stackoverflow.com/q/48448512
has comment: http://stackoverflow.com/comment/84380720
downvote count: 2
tagged with: xmlrpclib
has body: How to access Bugzilla bugs with XMLRPC interface. What .py and .XML contains. bugzilla server URL api methods
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83889602
has answer: http://stackoverflow.com/a/48691267
tagged with: xmlrpcclient
type: Question
has title: Example of XMLRPC interface API with BUGZILLA
score: 0
tagged with: bugzilla
tagged with: python
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/48476306
score: 0
has body: Exact size isn't really too important when it comes to complexity. Constants get dropped anyway. If you have a 3d array, internally it has to loop through all the items, even if that's not obvious by the code. So the answer is O(n**3) because it needs a loop inside a loop inside a loop. The exact value of what n means doesn't matter because constants get dropped.
type: Answer
answers question: http://stackoverflow.com/q/48475970

http://stackoverflow.com/comment/83808604
comment on: http://stackoverflow.com/q/48393242
has text: @mootmoot I can put the whole answer together now that I have boto3 working with multiple attachments (combining the MIMEText with boto3's send_raw_email method). Let me know if you want to answer the question formally.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48393069
accepted answer: http://stackoverflow.com/a/48393106
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48393106
has answer: http://stackoverflow.com/a/48393171
downvote count: 0
favorite count: 0
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/48393171
has answer: http://stackoverflow.com/a/48393511
has body: I have generated a dictionary right now that looks like: {'G1':['PF101','PF201','PF204','PF101'],'G2':['PF101','PF202'],'G3': ['PF202','PF204','PF305'],'G4':['PF101','PF305','PF305','PF201']} I want to use it to create a tab delimited count table that looks like: PF101 PF201 PF204 PF202 PF305 G1 2 1 1 0 0 G2 1 0 0 1 0 G3 0 0 0 1 1 G4 1 1 0 0 2 I can't seem to find an efficient way to do this, so any advice would be extremely helpful. (for reference the actual dictionary has ~2,000 keys)
has title: Dictionary to count table
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/comment/83873286
has text: Your `MockClient` is not a `MagicMock`, it's just another plain class, so it doesn't count the calls. Simply make another `MagicMock` out of it, passing custom return values like `'dummy_response'` via `client.copy_object.return_value = 'dummy_response'`.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48392841

http://stackoverflow.com/comment/83801805
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48406389
score: 3
has text: If you insist on the notation `client.users...`, then `users` must be an object, meaning an independent class, meaning you must implement it as standalone class. The `Client` class would then merely compose two of those independent classes into one `client` object. There's no need for it to be the parent class of anything. Memory consumption is pretty irrelevant with these values.

http://stackoverflow.com/q/48411962
has answer: http://stackoverflow.com/a/48412259
accepted answer: http://stackoverflow.com/a/48412086
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83813967
has comment: http://stackoverflow.com/comment/83813941
has comment: http://stackoverflow.com/comment/83814746
upvote count: 5
has answer: http://stackoverflow.com/a/48412064
has answer: http://stackoverflow.com/a/48412062
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48412548
tagged with: numpy
has body: I have a fixed amount of int arrays of the form: [a,b,c,d,e] for example: [2,2,1,1,2] where a and b can be ints from 0 to 2, c and d can be 0 or 1, and e can be ints from 0 to 2. Therefore there are: 3 * 3 * 2 * 2 * 3: 108 possible arrays of this form. I would like to assign to each of those arrays a unique integer code from 0 to 107. I am stuck, i thought of adding each numbers in the array, but two arrays such as: [0,0,0,0,1] and [1,0,0,0,0] would both add to 1. Any suggestion? Thank you.
score: 5
has answer: http://stackoverflow.com/a/48412086
has answer: http://stackoverflow.com/a/48412385
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/48412259
tagged with: python
answer count: 6
has title: Encode array of integers into unique int
has comment: http://stackoverflow.com/comment/83813893

http://stackoverflow.com/a/48367262
has comment: http://stackoverflow.com/comment/83722527
has body: Perhaps you should show a piece of your data, how does it look like? In which format the values are? The code you showed has wrong indentations etc. I suppose that data cannot be read like row[1].speed, or does that really work? Edit: Was that Calculate some kind of pseudocode? Please, try to formulate single rows in Python shell first to see that they are python code...
has comment: http://stackoverflow.com/comment/83723376
type: Answer
answers question: http://stackoverflow.com/q/48366769
score: 0

http://stackoverflow.com/q/48349453
has answer: http://stackoverflow.com/a/48350209
accepted answer: http://stackoverflow.com/a/48350262
has comment: http://stackoverflow.com/comment/83685468
possible better answer: http://stackoverflow.com/a/48349601
has comment: http://stackoverflow.com/comment/83686278
tagged with: python
has comment: http://stackoverflow.com/comment/83685773
linked to: http://stackoverflow.com/q/21592630
tagged with: tkinter-entry
has title: Compare tkinter Entry to actual addition answer
type: AnsweredQuestion
tagged with: tkinter
answer count: 3
has comment: http://stackoverflow.com/comment/83685402
score: 0
has body: I'm trying to compare the input of an Entry box to the actual answer. This is one of my first python projects and I'm still very confused and to be honest I don't even know how to start asking the question. The user will click either the addition or subtraction button. A string will appear asking "What does 4 + 5 equal?" The numbers are generated randomly. I then insert an Entry box using the tkinter library. I don't know how to get() the input and compare it to the sum or difference of the actual numbers. I was trying to follow this video but I've failed using other methods as well. FYI, I was focusing on the addition method mostly so if you test, that with addition first. from tkinter import Entry import tkinter as tk import random as rand root = tk.Tk() root.geometry("450x450+500+300") root.title("Let's play Math!") welcomeLabel = tk.Label(text="LET'S PLAY MATH!").pack() startLabel = tk.Label(text='Select a math operation to start').pack() def addition(): a = rand.randrange(1,10,1) b = rand.randrange(1,10,1) global Answer Answer = a + b tk.Label(text="What does " + str(a) + " + " + str(b) + " equal? ").place(x=0, y=125) global myAnswer myAnswer = Entry().place(x=300, y= 125) def checkAnswer(): entry = myAnswer.get() while int(entry) != Answer: if int(entry) != Answer: tk.Label(text="Let's try again.").pack() elif int(entry) == Answer: tk.Label(text="Hooray!").pack() addBtn = tk.Button(text="Addition", command=addition).place(x=100, y = 60) subBtn = tk.Button(text="Subtraction", command=subtraction).place(x=200, y=60) checkBtn = tk.Button(text="Check Answer", command=checkAnswer).place(x=300, y = 150) tk.mainloop()
upvote count: 1
has answer: http://stackoverflow.com/a/48350262
has answer: http://stackoverflow.com/a/48349601
downvote count: 1
has comment: http://stackoverflow.com/comment/83685250
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83685405

http://stackoverflow.com/comment/83712875
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48362729
has text: Thanks for your link! I've solved my problem as described in my reply to @davinellulinvega.

http://stackoverflow.com/comment/83857966
type: QuestionComment
has text: can you post that code so I can test it?
comment on: http://stackoverflow.com/q/48433076
score: 0
type: Comment

http://stackoverflow.com/q/48471015
tagged with: pyobject
has body: I have been trying to publish some bounding box data (from the YOLOv2 neural network) and have been having some problems with publishing some values to a python script. image.c code: #include "image.h" #include "utils.h" #include "blas.h" #include "cuda.h" #include &lt;stdio.h&gt; #include &lt;math.h&gt; #include &lt;Python.h&gt; #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" int windows = 0; int counter = 0; char *pyArgs[] = {"../networktables/", "run_network.py", "init", "put"}; PyObject* pyModule; void initialize(){ //Setting the Path PySys_SetPath(pyArgs[0]); //Importing pynetworktables PyObject* pyName = PyString_FromString(pyArgs[1]); pyModule = PyImport_Import(pyName); //Constructing the arguments //Calling init() pyFunc = pyObject_CallMethod(pyModule, pyArgs[2], NULL); } void draw_detections(image im, int num, float thresh, box *boxes, float **probs, float **masks, char **names, image **alphabet, int classes){ Some code here int left = (b.x-b.w/2.)*im.w; int right = (b.x+b.w/2.)*im.w; int top = (b.y-b.h/2.)*im.h; int bot = (b.y+b.h/2.)*im.h; /** * @Author Sam Schwartz * So this part is my code that may or may not work good luck to you my friend :) */ Py_Initialize(); //Running initialize if(counter &lt; 1){ initialize(); } //Converting left, right, top, bot to Python integers PyObject* pyLeft = PyInt_FromSize_t(left); PyObject* pyRight = PyInt_FromSize_t(right); PyObject* pyTop = PyInt_FromSize_t(top); PyObject* pyBot = PyInt_FromSize_t(bot); PyObject* pyVal[4] = {pyLeft, pyRight, pyTop, pyBot}; //Setting the four arguments for the put() function PyObject* pythonArgument; pythonArgument = PyTuple_New(4); PyTuple_SetItem(pythonArgument, 0, pyVal[0]); PyTuple_SetItem(pythonArgument, 1, pyVal[1]); pyTuple_SetItem(pythonArgument, 2, pyVal[2]); pyTuple_SetItem(pythonArgument, 3, pyVal[3]); //Calling put() pyFunc = PyObject_CallMethod(pyModule, pyArgs[3], pythonArgument); Py_Finalize(); /…
has answer: http://stackoverflow.com/a/48471838
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/c
tagged with: int
has title: Trying to publish C data through a Python Script
score: 0
answer count: 1

http://stackoverflow.com/comment/83659793
comment on: http://stackoverflow.com/q/48337211
type: Comment
score: 0
has text: Can you add the code that you've tried ?
type: QuestionComment

tensorflow-datasets
tags question: http://stackoverflow.com/q/48471926
tags question: http://stackoverflow.com/q/48415540
tags question: http://stackoverflow.com/q/48389174
tag name: tensorflow-datasets
type: Tag
tags question: http://stackoverflow.com/q/48350117
tags question: http://stackoverflow.com/q/48432622
tags question: http://stackoverflow.com/q/48471688
tags question: http://stackoverflow.com/q/48340309

http://stackoverflow.com/comment/83674216
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48343239
type: Comment
has text: It's in body the widgets that inks to subcategories like golf....just search it in the source

http://stackoverflow.com/comment/83894869
has text: *"my code doesn't work as what I intended"*. Why don't you tell us how the code is supposed to work and what you've tried to fix it? Please read the "how to ask" page: https://stackoverflow.com/help/how-to-ask
type: QuestionComment
comment on: http://stackoverflow.com/q/48436875
score: 0
type: Comment

http://stackoverflow.com/a/48450938
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48450781
has body: When you append arr1 to T, you are not making a new copy of the arr1 list. You need to make a copy of the list before you append it to T so that when you modify arr1, the list that you added to T is not modified. To do this, use T.append(list(arr1)). That will make a new copy of arr1 before adding it to T.

http://stackoverflow.com/comment/83734887
score: 0
type: Comment
type: AnswerComment
has text: sorry, i cannot english tonight.
comment on: http://stackoverflow.com/a/48373846

http://stackoverflow.com/a/48438961
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48438806
has body: There are a couple different methods you may like to be aware of depending on what you're trying to accomplish. The inspect module has a getfile() function which can be used to determine the name of the currently-executing function. Example: #!/usr/bin/env python3 import inspect print(inspect.getfile(inspect.currentframe())) Result: test.py To find out which command-line arguments were used to execute a script, you'll need to use sys.argv Example: #!/usr/bin/env python3 import sys print(sys.argv) Result when invoked with ./test.py a b c: ['./test.py', 'a', 'b', 'c'] Result when invoked with python3 test.py a b c: ['test.py', 'a', 'b', 'c'] Hope this helps!
has comment: http://stackoverflow.com/comment/83869173
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83658864
comment on: http://stackoverflow.com/q/48336820
type: Comment
type: QuestionComment
has text: Well, like your error message says : "register_observer() missing 1 required positional argument'" : when your decorator is called, it receives only self._data_updated as a parameter, and not self.data.
score: 0

http://stackoverflow.com/q/48353538
has comment: http://stackoverflow.com/comment/83693596
has title: Try-catch with exec
tagged with: python
has comment: http://stackoverflow.com/comment/83694593
has comment: http://stackoverflow.com/comment/83701470
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: exec
has comment: http://stackoverflow.com/comment/83694269
linked to: http://stackoverflow.com/q/1856408
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83694287
has body: I'm trying to run a genetic algorithm that generates python code. In other words, I'm conjuring skynet. I'm running into trouble with the SyntaxError, which I thought I caught in an except block. from random import sample from time import time TEST_INPUTS = 100 def sortedness(l=[], fraction=1.00): fraction = 1.00 - fraction # random * percent does not make percent sorted. for p in range(int(len(l)*fraction)): i, j = sample(l, 2) l[i], l[j] = l[j], l[i] class CodeGene(Gene): def mate(self, gene): # this slight improvement over the last version should allow mating between # differently sized codes. self_middle = int(floor(len(self.code)/2)) gene_middle = int(floor(len(gene.code)/2)) return [ Gene(self.code[:self_middle] + gene.code[gene_middle:]), Gene(gene.code[:gene_middle] + self.code[self_middle:]) ] def calc_cost(self, target): score = 100 context = { 'unsorted': sortedness(list(range(TEST_INPUTS)), 0.0) } start = time() i = self.code.find('import') while i &gt; -1: self.code = self.code[i:] + self.code[:i+len('import')] i = self.code.find('import') exec self.code in context end = time() t = end - start() if 'sort' in context: score -= (TEST_INPUTS + 100) try: # only run this code in a virtual machine exec "sorted = sort(unsorted)" in context score -= (TEST_INPUTS + 100) for i in range(TEST_INPUTS): if context['sorted'][i] == i: score -= TEST_INPUTS except(SyntaxError): score += (TEST_INPUTS + 100) class CodePopulation(Population): def __init__(self, target=sorted, size=100, log_costs=False): self.target = target self.members = [] for i in range(size): gene = CodeGene('') gene.random(len(self.target.code)) self.members.append(gene) self.generationNumber = 0 self.log_costs = log_costs if self.log_costs: self.cost_log = [] # logs the cost of the highest ranking member
has comment: http://stackoverflow.com/comment/83693587
duplicate of: http://stackoverflow.com/q/1856408
tagged with: exception
has comment: http://stackoverflow.com/comment/83693649
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83693725
has comment: http://stackoverflow.com/comment/83693629

http://stackoverflow.com/q/48364836
answer count: 4
type: AnsweredQuestion
has title: Generate a 1-0 array in numpy
has body: I am new to numpy. Basically what I want to do is generate a time signal in numpy of 24 hours, in which at a time interval of 6 hours, the first 30 minutes the signal is at 1, and the rest of the time its at 0. In other words - t=0 to t=0.5, value of array is 1. t=6 to t=6.5, value of array is 1. t=18 to t=18.5, value of array is 1. At all other times, it is 0. I am doing this as follows: time is the array of time (in hours) inFlowArray is the required signal. Its a function of time. This is the code - tStart = 0 tEnd = 24 dt = 0.1 time = np.arange(0, tEnd, dt) # in hours inFlowArray = np.logical_or.reduce(np.array(((time&lt;=0.5), np.logical_and(time&gt;=6, time&lt;=6.5), np.logical_and(time&gt;=12, time&lt;=12.5), np.logical_and(time&gt;=18, time&lt;=18.5)))) inFlowArray = inFlowArray.astype(int) The problem is that its a bit tedious to do so if my time array is of a longer length, say 48 hours or more. How do I write the code efficiently? PS. I tried reading other stack overflow answers but could not find any appropriate solution. I also read the numpy docs.
score: 0
has answer: http://stackoverflow.com/a/48364945
has answer: http://stackoverflow.com/a/48364852
accepted answer: http://stackoverflow.com/a/48364912
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48364912
possible better answer: http://stackoverflow.com/a/48364852
has answer: http://stackoverflow.com/a/48365114
tagged with: arrays
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48471127
has comment: http://stackoverflow.com/comment/83936897
upvote count: 1
has comment: http://stackoverflow.com/comment/83956679
has comment: http://stackoverflow.com/comment/83949117
has body: When you use Drive API v3, please use name to give the filename instead of title. And please put kind to the outside of parents. So how about the following modification for body? From : { "parents": [{"kind": "drive#fileLink", "id": folder}], 'title': title } To : { "parents": [folder], "name": title, "kind": "drive#fileLink" } Reference : Files: copy If this didn't lead to the solution, I'm sorry.
has comment: http://stackoverflow.com/comment/83937452
has comment: http://stackoverflow.com/comment/83937181
has comment: http://stackoverflow.com/comment/83944752
has comment: http://stackoverflow.com/comment/83936943
answers question: http://stackoverflow.com/q/48470962
has comment: http://stackoverflow.com/comment/83936833
type: Answer
has comment: http://stackoverflow.com/comment/83944892
accepted answer of: http://stackoverflow.com/q/48470962
has comment: http://stackoverflow.com/comment/83944587
has comment: http://stackoverflow.com/comment/83943417
has comment: http://stackoverflow.com/comment/83977630
has comment: http://stackoverflow.com/comment/83977532
has comment: http://stackoverflow.com/comment/83937362
has comment: http://stackoverflow.com/comment/83937526
has comment: http://stackoverflow.com/comment/83936494
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/73385113
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48391044
score: 5
downvote count: 0
has body: One should understand the difference between make_refs=False and unpicklable=False when trying to simplify the jsonpickle encoding output: make_refs=False will prevent jsonpickle from creating references (those py/id attributes) to identical objects. The references make the output more compact, but less readable, and thus one might prefer make_refs=False at the expense of a larger file. However, the resulting file can still be decoded back to a Python object. unpicklable=False means literally that the jsonpickle output cannot be unpickled, i.e. decoded, to its original type. The output is again more readable, but if the object you're encoding contains non-native datatypes (i.e. classes defined by you), the encoding output will store the value of those objects' properties, but if you try to decode the file back to its python representation, the objects will be dicts, not instances of your classes.

http://stackoverflow.com/comment/83971814
type: Comment
comment on: http://stackoverflow.com/q/48425010
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164044/discussion-between-ian-thompson-and-k-s).
score: 0

http://stackoverflow.com/comment/83821827
has text: @cᴏʟᴅsᴘᴇᴇᴅ I found your link does not work, there are skipped `df1.value` and I don't need to join two dataframes.
comment on: http://stackoverflow.com/q/48394364
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48405452
upvote count: 1
answers question: http://stackoverflow.com/q/48404681
type: AcceptedAnswer
has body: There are two steps involved to download the file after reaching the page you specified. First you have to click on the dorp-down button then you have to select the csv data option. Using the corresponding xpath for these elements, driver.find_element_by_xpath('//*[@id="historical-electric-download"]/a[@class="no-underline"]').click() driver.find_element_by_xpath('//*[@id="historical-electric-download"]/div/a[@class="csv-link"]').click()
has comment: http://stackoverflow.com/comment/83800283
has comment: http://stackoverflow.com/comment/83799911
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48404681

http://stackoverflow.com/comment/83814319
type: AnswerComment
comment on: http://stackoverflow.com/a/48411715
score: 0
type: Comment
has text: @sagar, what is your Pandas version? I'm using Pandas 0.22.0

http://stackoverflow.com/comment/84002403
comment on: http://stackoverflow.com/q/48478653
score: 0
has text: Why are you not using the `count_occurences` in the final X matrix?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83820853
score: 0
has text: @DavidG thanks, your comments were really helpful
type: QuestionComment
comment on: http://stackoverflow.com/q/48398923
type: Comment

http://stackoverflow.com/comment/83653037
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48332867
has text: Per our requirements we must maintain copies of all the software we use (e.g. the `.whl` files from `pip download`). Unfortunately just maintaining a `requirements.txt` file is not enough for us.

insert
tags question: http://stackoverflow.com/q/48356271
tag name: insert
type: Tag
tags question: http://stackoverflow.com/q/48350487

http://stackoverflow.com/a/48368744
score: 0
has body: I guess you are looking for v3 = df.iloc[0, 0] - df.iloc[1, 1] which will return -3.
type: Answer
accepted answer of: http://stackoverflow.com/q/48368588
answers question: http://stackoverflow.com/q/48368588
type: AcceptedAnswer

http://stackoverflow.com/comment/83735848
type: Comment
type: QuestionComment
has text: It seems to me that the issue is that there are several nested fields with the "date-list--time". They are nested into the "date-list infos" list. I guess there is a way to extract data from nested lists...
score: 0
comment on: http://stackoverflow.com/q/48374076

split
tags question: http://stackoverflow.com/q/48382219
tags question: http://stackoverflow.com/q/48407191
tags question: http://stackoverflow.com/q/48460466
tags question: http://stackoverflow.com/q/48397589
tags question: http://stackoverflow.com/q/48358348
tag name: split
tags question: http://stackoverflow.com/q/48381870
tags question: http://stackoverflow.com/q/48476629
tags question: http://stackoverflow.com/q/48405677
type: Tag
tags question: http://stackoverflow.com/q/48376093
tags question: http://stackoverflow.com/q/48352488
tags question: http://stackoverflow.com/q/48436337
tags question: http://stackoverflow.com/q/48413762
tags question: http://stackoverflow.com/q/48481434
tags question: http://stackoverflow.com/q/48412432

http://stackoverflow.com/q/48430792
has title: Script raises HTTPError, but cannot catch
downvote count: 0
has answer: http://stackoverflow.com/a/48430890
has answer: http://stackoverflow.com/a/78236056
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: exception
accepted answer: http://stackoverflow.com/a/48430890
possible better answer: http://stackoverflow.com/a/48430869
tagged with: python
has answer: http://stackoverflow.com/a/48430869
score: 2
has body: I have an error which I have a little difficulty understanding. I have a script which uses biopython to query a database. Sometimes, biopython can't find what we're looking for, and an HTTPError is thrown. I cannot, however catch the HTTPError, as I get the following error message: HTTPError: HTTP Error 404: Not Found During handling of the above exception, another exception occurred: NameError Traceback (most recent call last) in () 51 UniProt = text[index+9:index+15] 52 uniprot_IDs[bigg_ID] = UniProt ---> 53 except HTTPError: 54 if err.code == '404': 55 uniprot_IDs[biGG_ID] = None NameError: name 'HTTPError' is not defined How can an error which is not defined be thrown in the first place? What am I missing? This is the relevant code: from Bio.KEGG import REST, Enzyme from DataTreatment import openJson, write ... try: ec_number = some_string text = REST.kegg_get('ec:'+ec_number).read() ... except HTTPError: if err.code == '404': a_dict[a_key] = None
answer count: 3
upvote count: 2

http://stackoverflow.com/comment/83952704
type: Comment
comment on: http://stackoverflow.com/a/48479860
type: AnswerComment
has text: @ShadowRanger: yes indeed, although the latter is more *functional* since we only make use of already defined functions. Furthermore there are no side effects (whereas there can technically be side effects in list comprehension, since you can override the same variable). The list comprehension is more *Python*, the last one is more *Haskell*,
score: 0

css
tags question: http://stackoverflow.com/q/48484297
tags question: http://stackoverflow.com/q/48385189
tags question: http://stackoverflow.com/q/48482933
tags question: http://stackoverflow.com/q/48405474
tags question: http://stackoverflow.com/q/48469170
tags question: http://stackoverflow.com/q/48431689
tag name: css
tags question: http://stackoverflow.com/q/48390005
tags question: http://stackoverflow.com/q/48396103
tags question: http://stackoverflow.com/q/48448900
type: Tag
tags question: http://stackoverflow.com/q/48473110

http://stackoverflow.com/comment/83711284
type: Comment
type: AnswerComment
score: 0
has text: @coldspeed I just figured that out. Thanks man you helped me a lot and I learnt new things about pandas. because of you. Thanks again!
comment on: http://stackoverflow.com/a/48338439

http://stackoverflow.com/q/48407081
score: 0
has title: Qt keyboard input in other language
answer count: 1
tagged with: pyqt5
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83875475
type: Question
has comment: http://stackoverflow.com/comment/83803982
tagged with: python
has body: Well in word processors, when I change font to Preeti, typing "asdfgh" will result in displaying "बकमानज". I tried changing QPlainTextEdit's font to Preeti, but it's still typing "asdfgh" How can achieve same in Qt? Here's what I am doing: @pyqtSlot() def select_font(self): font, ok = QFontDialog.getFont(self) if ok: ## the text in ui.text_edit is in unicode self.ui.text_edit.setFont(font) Obviously the font exists in the system. The displaying of font is also correct (when loaded from .txt file). What's not working is typing in that font. The key-mapping from keyboard to the chosen font is what i am talking about. Help in c++ or python: language doesn't matter here.
tagged with: qt
tagged with: c++
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48407506
has answer: http://stackoverflow.com/a/48407506

http://stackoverflow.com/a/48445919
score: 1
upvote count: 1
type: Answer
has body: I think you can use this SO answer. i gives you the group number, and the index of g can be used to get the var values. v1=list(np.random.rand(30)) v2=list(np.random.rand(30)) df=pd.DataFrame(data=zip(v1,v2),columns=['var1','var2']) df['cond1']=df['var1']&gt;0.2 df['cond2']=df['var1']&gt;0.8 for i, g in df.groupby([(df['cond1'] != df['cond1'].shift()).cumsum()]): print (i) print (g) print (g['cond1'].tolist()) print(g['cond1'].index[0])#can get var values from this
has comment: http://stackoverflow.com/comment/83883578
answers question: http://stackoverflow.com/q/48445748
has comment: http://stackoverflow.com/comment/83883788
downvote count: 0

http://stackoverflow.com/comment/83883590
type: Comment
type: AnswerComment
has text: What values should i use to create basemap here as my graph has a background and all datapoints are concentrated in center.
comment on: http://stackoverflow.com/a/48426198
score: 0

http://stackoverflow.com/comment/83955074
type: AnswerComment
comment on: http://stackoverflow.com/a/48478816
has text: Im using it with integers, I can set up intvar but what then?
score: 0
type: Comment

http://stackoverflow.com/comment/83656062
has text: @cᴏʟᴅsᴘᴇᴇᴅ , I edited my question with the proper `df.to_dict()` pls check
type: QuestionComment
comment on: http://stackoverflow.com/q/48335265
score: 0
type: Comment

http://stackoverflow.com/a/48356094
has comment: http://stackoverflow.com/comment/83704260
upvote count: 0
has comment: http://stackoverflow.com/comment/83702795
has body: You should not be making this query in your model. It is much better to make the query in views.py whenever you need the information. Below is, if I understand correctly, what you would need to do to make this query in the view. def relevant_view(request,genreID_from_url): # ... # song = Song.objects.filter(author=request.user).filter(genre=genreID_from_url).order_by('-date')[:1] # ... # A couple of points: I think you would need to pass the genre you are querying for in the URL. Here is a good tutorial for that: http://django-book.readthedocs.io/en/latest/chapter03.html#your-third-view-dynamic-urls . You could also do it using a form - it depends on the circumstances in which the query needs to be made. You need to order by '-date' and not 'date' so that you get the most recent song at the start of the query. The [ ] at the end is Django's syntax for limiting a queryset. The above limits it to only the first item of the queryset, as you are attempting to do. The page in the Django docs for queries is really helpful and clear: https://docs.djangoproject.com/en/2.0/topics/db/queries/
answers question: http://stackoverflow.com/q/48355897
downvote count: 1
has comment: http://stackoverflow.com/comment/83704116
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/83699766
has comment: http://stackoverflow.com/comment/83700501
has comment: http://stackoverflow.com/comment/83702817

http://stackoverflow.com/q/48453775
tagged with: python
has title: Error when converting caffe model (VGG_Face2) to coreml
tagged with: coremltools
favorite count: 0
type: Question
has body: I'm trying to convert this model: http://www.robots.ox.ac.uk/~vgg/data/vgg_face2/ from caffe to coreml but I get this error : RuntimeError: Unsupported option '2' for the parameter 'shape size' in layer 'conv2_1_prob_reshape' of type 'Reshape' during caffe conversion. I used coreml_model = coremltools.converters.caffe.convert(('senet50_ft.caffemodel', 'senet50_ft.prototxt'). I also tried adding the class labels (They have a csv file with four columns: ClassID, Name, Sample_Num, Flag. I deleted the last two columns because in other tutorials they use only the first two. I tried having all the columns, only the first two and also the original csv file without converting it to txt). All of the above returned the same error. I'm not sure what this error means (I looked into senet50_ft.prototxt that has all the layers to try to locate the error and it looks like this : layer { name: "conv2_1_prob_reshape" type: "Reshape" bottom: "conv2_1_1x1_up" top: "conv2_1_prob_reshape" reshape_param { shape { dim: 0 dim: 0 } } } but I don't really understand much of this. I'm not very experienced in working with these models, any help is appreciated.
tagged with: coreml
has answer: http://stackoverflow.com/a/48459302
answer count: 1
tagged with: caffe
tagged with: swift
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/48459302

http://stackoverflow.com/q/48343084
favorite count: 0
has body: I am working on conversational chatbot.How to determine whether a given text is demanding an answer or is providing some information? Case 1 : We are thinking of booking this hotel because it is close to the freedom trail. Expected Result : Giving some info Case 2: I would like to know the distance from Boston Logan airport to the hotel. Expected Result : Question Case 3:How far is Airport? Expected Result : Question I have dataset of 19k queries categorized as (Question and Not a Question).What is the best way/model to proceed now (Using Python)?
score: 2
has answer: http://stackoverflow.com/a/50153262
tagged with: python
tagged with: nlp
has title: NLP: Identify whether given text is Query or Statement
type: Question
has comment: http://stackoverflow.com/comment/83678898
tagged with: chatbot
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: machine-learning
linked to: http://stackoverflow.com/q/4083060

http://stackoverflow.com/comment/83813059
type: Comment
has text: That is not a list, that is a `dict`. Do you want a `list` or a `dict`?
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48411636

ffprobe
tags question: http://stackoverflow.com/q/48418688
tag name: ffprobe
type: Tag

http://stackoverflow.com/comment/83968334
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48425010
has text: @IanThompson Hi Ian, sorry for the late reply. I have made changes to my code. Im adding the ttest and rank sum test after writing the file `sum.csv`. Now it is working fine. I guess i need to iterate it over the dataframe. Any suggestions with that ? I have made the changes for the new code in my question. Kindly go through it.
score: 0

http://stackoverflow.com/comment/83917984
has text: This is a great answer.
type: Comment
comment on: http://stackoverflow.com/a/48461617
score: 0
type: AnswerComment

http://stackoverflow.com/q/48428100
upvote count: 18
has body: Let us consider the following pandas dataframe: df = pd.DataFrame([[1,np.array([6,7])],[4,np.array([8,9])]], columns = {'A','B'}) where the B column is composed by two numpy arrays. If we save the dataframe and the load it again, the numpy array is converted into a string. df.to_csv('test.csv', index = False) df.read_csv('test.csv') Is there any simple way of solve this problem? Here is the output of the loaded dataframe.
has title: Save pandas dataframe with numpy arrays column
score: 18
possible better answer: http://stackoverflow.com/a/59189826
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/59189826
answer count: 2
accepted answer: http://stackoverflow.com/a/48428222
tagged with: pandas
has answer: http://stackoverflow.com/a/48428222
downvote count: 0
has comment: http://stackoverflow.com/comment/112254724
favorite count: 0
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/q/48333148
has title: Identify same elements if they don't have different classes
score: 0
has comment: http://stackoverflow.com/comment/83670464
answer count: 1
tagged with: scrapy
type: Question
tagged with: xpath
has body: I was trying to scrape a page http://apps.leg.wa.gov/wac/default.aspx?cite=296-17A&amp;full=true to get an output of type '6903-03' : u'Aerial spraying, seeding, crop dusting, or firefighting' , '6510-00' : u'Domestic servants/home care assistants employed in or about the private residence of a home owner' , '1407-00' : u'Bus companies' , I am using scrapy for the same. I used the following xpath for it response.xpath('//*[@id="ctl00_ContentPlaceHolder1_dlSectionContent"]/span/div/span/text()').extract()) Even though it works properly but it returns some not required lines as well like these u'which also provide farm kill operations away from the custom meat shop', u'Farm kill operations', u'only', u'no farm kill', u'only', u'4302-16 Farm kill', u'exclusively', u'only; ', u'only', u'no farm kill', u'including farm kill', One way I was trying to think was to do a regex on each line to identify the pattern line with regex as u'(?:\d{2}){2}-(?:\d{1}){2} [A-Za-z ]*' Is there any better or cleaner approach of identifying such spans. PS:- The spans don't have any classes. They have only style. I am not sure if I can use styles for identifying the required spans.
has answer: http://stackoverflow.com/a/48358003
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83696179
tagged with: python
linked to: http://stackoverflow.com/q/103325

http://stackoverflow.com/q/48474455
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48474602
answer count: 1
has answer: http://stackoverflow.com/a/48474602
has title: Can't run JACK on Mac OS HS 10.13.2
has body: I've installed JACK-Client with pip, but when importing jack I get this error &gt;&gt;&gt; import jack Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/jack.py", line 44, in &lt;module&gt; raise OSError('JACK library not found') OSError: JACK library not found
tagged with: macos
tagged with: jack

http://stackoverflow.com/a/48373788
answers question: http://stackoverflow.com/q/48373710
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83740512
has body: Change the C value in the parameter grid to be always > 0. Currently you have the parameter grid as parameters = [{'C': [0,1,5], 'kernel':['linear']}, {'C': [0,1,5], 'kernel':['rbf'], 'gamma':[0.01, 0.05]}] And it has C=0 as one possibility. So when grid-search goes to fit the SVR model with C=0, SVR complains that C must not be &lt;=0 (less than or equal to 0). So change it to something like: parameters = [{'C': [0.001, 0.1 ,1,5], 'kernel':['linear']}, {'C': [0.001, 0.1, 1,5], 'kernel':['rbf'], 'gamma':[0.01, 0.05]}] You can look at these examples to check how search for C is done: http://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html#sphx-glr-auto-examples-svm-plot-rbf-parameters-py http://scikit-learn.org/stable/auto_examples/exercises/plot_cv_digits.html#sphx-glr-auto-examples-exercises-plot-cv-digits-py Update for comment: You are using scoring='accuracy'. Accuracy is mainly defined for classification tasks. For regression models, accuracy is not a valid metric. Please check this page for valid metrics:- http://scikit-learn.org/stable/modules/model_evaluation.html#common-cases-predefined-values You can either remove scoring param from grid-search like this: gs = GridSearchCV(estimator = reg, param_grid = parameters,cv =10) In this case, the default scoring method of the estimator (SVR in this case) will be used which is R-squared score (Most common used for regression) Or you can set scoring to any of the valid regression metrics on the page I linked above. Like this: gs = GridSearchCV(estimator = reg, param_grid = parameters, scoring='neg_mean_squared_error', cv =10)
score: 3
has comment: http://stackoverflow.com/comment/83734881
type: Answer
accepted answer of: http://stackoverflow.com/q/48373710

http://stackoverflow.com/comment/83772409
comment on: http://stackoverflow.com/q/48392079
type: Comment
type: QuestionComment
has text: Can you please clearly indicate your expected output and how it is generated?
score: 0

http://stackoverflow.com/a/69330557
downvote count: 0
has body: You can also modify the SlugRelatedField by inheriting it as shown below class SlugRelatedGetOrCreateField(serializers.SlugRelatedField): def to_internal_value(self, data): queryset = self.get_queryset() try: return queryset.get_or_create(**{self.slug_field: data})[0] except (TypeError, ValueError): self.fail("invalid") I disagree with @dukebody 's views that automatic serializers can be a bit too rigid If you can browse around the code of DRF there are plenty of methods that can be overridden to achieve any desirable result.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/139353389
score: 5
answers question: http://stackoverflow.com/q/48371544

http://stackoverflow.com/comment/83797661
has text: I want the value of the index value at any specific element of the dataframe.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48404505
score: 0

http://stackoverflow.com/q/48385609
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/12082886
tagged with: python
has body: Suppose I have the following string s = '\t 1\n\t 2\n\t 3\n\t 4\n\t 5\n\t 6\n\t 7\n\t 8\n\t 9\n\t 10\n\t 11\n\t 12\n\t 13\n\t 14\n\t 15\n\t 16\n\t 17\n\t 18\n\t' I want to start each (indented) row with the string 'item'. So I write s = re.sub('\t', '\t\item ', s, re.DOTALL) The output I get is: \item 1 \item 2 \item 3 \item 4 \item 5 \item 6 \item 7 \item 8 \item 9 \item 10 \item 11 \item 12 \item 13 \item 14 \item 15 \item 16 17 18 Why is the operation only performed the first 16 times?
tagged with: regex
has answer: http://stackoverflow.com/a/48385700
score: 2
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/48385700
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/12082886
tagged with: string
has comment: http://stackoverflow.com/comment/83758668
has title: Python: re.sub replaces only 16 times

http://stackoverflow.com/comment/83773597
type: QuestionComment
type: Comment
has text: @JohnE that stinks.
score: 0
comment on: http://stackoverflow.com/q/48392604

http://stackoverflow.com/comment/83652274
score: 1
type: QuestionComment
has text: How did you obtain the string in the first place? Did you correctly `.decode()` the Web data?
type: Comment
comment on: http://stackoverflow.com/q/48333346

http://stackoverflow.com/q/48392109
has answer: http://stackoverflow.com/a/48392958
score: 0
tagged with: amazon-ec2
answer count: 1
has title: python boto3 - how to get the value from the return of a function
has body: Using python boto3 library, I am using the ec2.create_instances function which returns the data shown below: [ec2.Instance(id='i-34304930394309409')] How do I simply extract the value for the id and put that into a another variable? I just want to retrieve "i-34304930394309409" and set that to a variable named "instanceid" Is there a way to just call ec2.instance to retrieve this value?
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: boto3

http://stackoverflow.com/q/48481873
tagged with: neural-network
has title: how to set stride to zero when using tf.layers.conv2d
tagged with: python
has body: is there a way that I can turn off stride in tensor flow when using: tf.layers.conv2d()? According to the docs, the default is (1,1) but when I try to change this to (0,0) I get an error telling me that it has to be a positive number. Thanks.
score: 0
tagged with: conv-neural-network
type: UnansweredQuestion
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48482421

http://stackoverflow.com/a/48418016
answers question: http://stackoverflow.com/q/48417950
has comment: http://stackoverflow.com/comment/83962551
has body: You can use set_index + unstack + add_prefix: df = (df.set_index(['Name','Age','Grade', 'Class'])['Score'] .unstack() .add_prefix('Class_') .reset_index() .rename_axis(None, axis=1)) print (df) Name Age Grade Class_Algebra Class_Biology Class_French 0 John 16 9 95 98 96
type: Answer
has comment: http://stackoverflow.com/comment/83827840
score: 2
has comment: http://stackoverflow.com/comment/83975251
has comment: http://stackoverflow.com/comment/83827750
upvote count: 2
has comment: http://stackoverflow.com/comment/83827904
has comment: http://stackoverflow.com/comment/83962359
downvote count: 0
has comment: http://stackoverflow.com/comment/83974977

http://stackoverflow.com/comment/83805685
score: 2
has text: Show your code, and why do you believe you shouldn't you use append? It is the best and most pythonic way to do so.
comment on: http://stackoverflow.com/q/48408263
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48386297
has title: All the widgets disappear when window size is decreased
tagged with: pyqt4
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83773093
has body: When I decrease the window size all the widgets disappear.I want the widgets to move along when size is decreased.How do I solve this problem? I have a drop-down menu from which a value is selected.When an "Add cmd" button is pressed the value is added to edit box. Thanks in advance. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class tabdemo(QTabWidget): def __init__(self, parent = None): super(tabdemo, self).__init__(parent) self.setGeometry(50, 50, 400,400) QShortcut(QKeySequence("Esc"), self, self.close) self.tab1 = QWidget() self.tab2 = QWidget() self.addTab(self.tab1,"Tab 1") self.tab1UI() self.setWindowTitle("Main Window") def tab1UI(self): self.comboBox = QComboBox(self.tab1) self.comboBox.addItem('ABC') self.comboBox.addItem('BCD') self.comboBox.addItem('CDE') self.comboBox.move(5,20) self.comboBox.resize(180,30) self.button = QPushButton('Add Cmd', self.tab1) self.button.move(190,20) self.button.resize(80,30) self.button.clicked.connect(self.handleTest) self.b = QTextEdit(self.tab1) self.b.move(20,75) self.b.resize(290,200) self.button = QPushButton('Send Batch', self.tab1) self.button.move(40,300) self.button.resize(150,30) self.button = QPushButton('Clear', self.tab1) self.button.move(200,300) self.button.resize(80,30) self.button.clicked.connect(self.deletevalue) layout = QFormLayout() self.setTabText(4,"BatchCMDS") self.tab1.setLayout(layout) def handleTest(self): self.b.append(str(self.comboBox.currentText())) def deletevalue(self): self.b.clear() def main(): app = QApplication(sys.argv) ex = tabdemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48389861
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83763254
has answer: http://stackoverflow.com/a/48389861
favorite count: 0
type: Question

http://stackoverflow.com/a/65532553
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48349048
has body: You can get the beginning of the month with the trunc function (as Alper) mentioned or with the date_trunc method. The trunc function returns a date column and the date_trunc function returns a time column. Suppose you have the following DataFrame: +----------+ | some_date| +----------+ |2017-11-25| |2017-12-21| |2017-09-12| | null| +----------+ Run the trunc and date_trunc functions: datesDF\ .withColumn("beginning_of_month_date", trunc(col("some_date"), "month"))\ .withColumn("beginning_of_month_time", date_trunc("month" ,col("some_date")))\ .show() Observe the result: +----------+-----------------------+-----------------------+ | some_date|beginning_of_month_date|beginning_of_month_time| +----------+-----------------------+-----------------------+ |2017-11-25| 2017-11-01| 2017-11-01 00:00:00| |2017-12-21| 2017-12-01| 2017-12-01 00:00:00| |2017-09-12| 2017-09-01| 2017-09-01 00:00:00| | null| null| null| +----------+-----------------------+-----------------------+ Print the schema to confirm the column types: root |-- some_date: date (nullable = true) |-- beginning_of_month_date: date (nullable = true) |-- beginning_of_month_time: timestamp (nullable = true) Scala users should use the beginningOfMonthDate and beginningOfMonthTime functions defined in spark-daria. PySpark users should use the beginning_of_month_date and beginning_of_month_time functions defined in quinn. Notice how the trunc function takes the column argument first and the date_trunc takes the column argument second. The trunc method is poorly named - it's part of the functions package, so it's easy to mistakenly think this function is for string truncation. It's surprising that date_trunc is returning a timestamp result... sounds like it should return a date result. Just make sure to wrap these functions with descriptive function / UDF names so your code is readable. See here for more info.
type: Answer
upvote count: 3

http://stackoverflow.com/comment/83785025
comment on: http://stackoverflow.com/a/48398532
score: 0
type: Comment
type: AnswerComment
has text: Thanks. Show me how I would call it pls

http://stackoverflow.com/comment/83861458
score: 0
type: Comment
type: QuestionComment
has text: To elaborate, the indices of thickness begin at 0 in python, not 1.
comment on: http://stackoverflow.com/q/48434989

http://stackoverflow.com/comment/83978123
score: 0
type: Comment
has text: I was thinking this also, but what if the polygon were shaped concave inwards say like a crescent moon or pacman-shaped? It would try to go through it directly only to hit the concave directly and go around, rather than go around it in the first place.
type: QuestionComment
comment on: http://stackoverflow.com/q/48487482

http://stackoverflow.com/q/48458104
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/83908953
accepted answer: http://stackoverflow.com/a/48458316
tagged with: python
has answer: http://stackoverflow.com/a/48458316
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83909028
has comment: http://stackoverflow.com/comment/83909020
tagged with: arrays
answer count: 1
has title: Optimising the double for-loop to find the count of particular value on 2-dimensional array
has body: To calculate the number of blank spaces on board, I need to call the following piece of code every time. for i in range(game.width): for j in range(game.height): if game.__board_state__[i][j] == 0: blank_spaces += 1 Currently game.width = 7 and game.height = 7. So there is a loop with the complexity of O(width*height). Is there a builtin function/ or any other way, that is more optimized?
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83909601
type: AnsweredQuestion

http://stackoverflow.com/comment/83947967
comment on: http://stackoverflow.com/q/48477359
score: 0
type: Comment
type: QuestionComment
has text: Use a running average and iterate over the list just once.

http://stackoverflow.com/comment/83670377
comment on: http://stackoverflow.com/a/48342107
has text: I understand the docs. And I agree with adding ^. But for me matching /^a/ and /^a.*/ is exactly the same /^a/ will stop after matching. So it should do /^a.*/ . Of course /^a.*$/ will be slower. But once again matching "foo_bar" should be slower than matching "foo_.*": we only have to compare the first four characters in the former case. In the first case we have to compare the 7 chars. The regex should be faster.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48421426
answer count: 4
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/42490368
has answer: http://stackoverflow.com/a/48421507
score: 5
downvote count: 0
has title: How to check if subprocess has finished?
tagged with: python
has answer: http://stackoverflow.com/a/48421523
favorite count: 0
has answer: http://stackoverflow.com/a/48421556
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48421502
upvote count: 5
has answer: http://stackoverflow.com/a/48421502
accepted answer: http://stackoverflow.com/a/48421556
has body: I am starting a process by doing: for i in range(1, processes + 1): hup = MyURLParser() //A class I made p = Process(target = hup.run) p.start() After that, so that the main thread doesn't exit immediately I do: while (True): print("Main sleeping...") sleep(20) Instead of doing this, how can I check that each of the child processes are still running from the main thread ? Then instead of having the infinite loop I can break out of the loop at the right time and do something else....

http://stackoverflow.com/q/48417830
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83825869
has title: Wagtail: How to filter text in streamfield within model.py
score: 0
tagged with: wagtail
tagged with: django
tagged with: wagtail-streamfield
answer count: 1
has comment: http://stackoverflow.com/comment/83826114
type: Question
has body: I would like to write a filter which replaces some $variables$ in my streamfield text. What is the best way to do this in my "Page" model? I tried the following but it is sometimes not working if I save my model as draft and publish it afterwards. Does anyone know a better way doing this? class CityPage(Page, CityVariables): cityobject = models.ForeignKey(CityTranslated, on_delete=models.SET_NULL, null=True, blank=True) streamfield = StreamField(BasicStreamBlock, null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('cityobject', classname="full"), StreamFieldPanel('streamfield'), ] def get_streamfield(self): for block in self.streamfield: if type(block.value) == unicode: block.value = self.replace_veriables(block.value) elif type(block.value) == RichText: block.value.source = self.replace_veriables(block.value.source) else: print "notimplemented" return self.streamfield And this is just the class which replaces $variables$ with values from my database. class CityVariables(): def replace_veriables(self, repstr): reprules = self.get_city_context() for key, value in reprules.iteritems(): repstr = repstr.replace(key, value) return repstr def get_city_context(self): context = {} if self.cityobject.population: context['$population$'] = unicode(self.cityobject.population) if self.cityobject.transregion: context['$region$'] = unicode(self.cityobject.transregion) return context class BasicStreamBlock(blocks.StreamBlock): h2 = blocks.CharBlock(icon="title", classname="title") h3 = blocks.CharBlock(icon="title", classname="title") h4 = blocks.CharBlock(icon="title", classname="title") h5 = blocks.CharBlock(icon="title", classname="title") paragraph = blocks.RichTextBlock(icon="pilcrow") image = ImageChooserBlock(label="Image", icon="image") aligned_html = blocks.RawHTMLBlock(icon="code", label='Raw HTML')
has answer: http://stackoverflow.com/a/48421012
tagged with: python

http://stackoverflow.com/a/48369183
has comment: http://stackoverflow.com/comment/83726072
accepted answer of: http://stackoverflow.com/q/48368952
downvote count: 0
has body: Well as Syed Abdul Wahab said, the problem is that the "list" is getting recreated each loop. This makes so that the print reports "1", as it is the actual length of the list. The other problem, repetition of the printng is similar - you are actually printing "each time in the loop". The solution is then simple: you initialize the list outside the loop; and also report outside the loop. def Q3(): from datetime import datetime, timedelta inputauth = open("auth.log", "r") authStrings = inputauth.readlines() failedPass = 'Failed password for' countAttack1 = [] # after this line the countAttack will be empty for line in authStrings: time = line[7:15] dateHour = line[0:9] if time in line and failedPass in line: if dateHour == 'Feb 3 08': countAttack1.append(time) length1 = len(countAttack1) print("Attack 1: " + str(length1)) I'd also like to take a bit of time to link you to string formatting While the documentation is complex it will make printing much easier, above print is trnasformed into: print("Attack 1: {0}".format(length1)) Further analysing the code gives some peculiarities, you check if time is in the line string. - However just a few codelines above you create time from a slice of line - so it will always be inside line. (Except for the edge case where line is not of correct length, but that'll error anyways). So that if statement should be simplified to: if failedPass in line:
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83725623
score: 1
answers question: http://stackoverflow.com/q/48368952
type: Answer

http://stackoverflow.com/a/48477308
has comment: http://stackoverflow.com/comment/83949168
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48477275
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48477275
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83949517
has comment: http://stackoverflow.com/comment/83948878
has body: {% csrf_token %} {{ form1.as_p }} {{ form2.as_p }} Save according to your context the names of your forms are form1 and form2, so form only wont display any form
type: Answer

http://stackoverflow.com/comment/83669177
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48339549
has text: This is the answer you are looking for. You were previously simply losing the error message, and now you are not losing it. It tells you that there is a problem in your code, and now you know.

http://stackoverflow.com/comment/83744839
has text: Fatal error reading PNG image file: Not a PNG file
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48378996
type: Comment

http://stackoverflow.com/q/48470398
upvote count: 2
has comment: http://stackoverflow.com/comment/83938843
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83934832
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/83939125
has comment: http://stackoverflow.com/comment/83934977
downvote count: 0
has body: Like many before me I've lost my 7zip password. Actually it was destroyed along with everything else in my previous cell phone. I'm 99% sure I know most of the password so I'm assuming it will be tractable to brute force crack it so I wrote the code shown and it works but is horrifically slow. 21 attempts in 6.1 seconds to get the example. The bottleneck is clearly the sp.wait() but everything I've tried to get around that won't work. I guess it makes sense since Python can't know anything about the process till its done. I tried many variations of try/except on the subprocess.Popen() to no avail. Note that 7zip will place a 0KB version of the file in the folder with the wrong password but the folder has to be empty when the right password is used to not generate a different error. Fictional password in the code. Working on Win 7 in Python 3.5.1 with 7zip v9.2. Any help is greatly appreciated. Thanks, Joe. import os import time import itertools import subprocess start_time = time.time() cmdline = r"C:\Program Files\7-Zip\7z e C:\archive.7z -oC:\temp -p" path = r"C:\temp" unknown_part='$oz' known_part='MiStup!dB' attempts = 0 for password_length in range(2, 4): for guess in itertools.product(unknown_part, repeat=password_length): try: os.remove(r'C:\temp\extractedfile.txt') except: None attempts += 1 guess = ''.join(guess) newline = cmdline + known_part + guess sp = subprocess.Popen(newline, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) sp.wait() if sp.returncode == 0: print("Password is %s, Found in %i attempts in %s seconds" % (known_part+guess, attempts, time.time()-start_time)) break
has comment: http://stackoverflow.com/comment/83938874
has comment: http://stackoverflow.com/comment/83934893
favorite count: 0
has title: Slow Code Trying to get 7zip Password
type: Question
tagged with: python-3.x
answer count: 0

http://stackoverflow.com/comment/83883285
type: AnswerComment
score: 0
has text: Thank you, I found it. http://openpyxl.readthedocs.io/en/default/_modules/openpyxl/styles/numbers.html?highlight=number%20format
comment on: http://stackoverflow.com/a/48444611
type: Comment

http://stackoverflow.com/q/48373164
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/83733803
has answer: http://stackoverflow.com/a/48373825
has comment: http://stackoverflow.com/comment/83733671
score: 0
has comment: http://stackoverflow.com/comment/83733486
has comment: http://stackoverflow.com/comment/83733696
answer count: 1
has comment: http://stackoverflow.com/comment/83733582
tagged with: google-chrome
has title: HTML Form generates file download but where did the file come from?
type: Question
tagged with: ajax
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83733644
tagged with: http://stackoverflow.com/tag/html
has body: I've been using the developer tools in Chrome to see what happens at various points when on a website. This has helped me automate some tasks that I do from time to time. I am trying to automate downloading a file with python currently. https://newjersey.mylicense.com/Verification_4_6/Verification_Bulk_4_6/Search.aspx?facility=Y Using this website if you fill out the form you will be presented with pages of information, or you can opt to download a csv containing all of the information. I've been trying to track the source of the data down so that I can use python to download the file periodically using preset filters. I cannot seem to determine where the file is coming from, I am assuming it is being generated on the fly. I have copied the request as CURL and converted it to python in the past to do similar tasks. I can't find the correct request for this file though. Any help would be appreciated!

http://stackoverflow.com/a/48439584
score: 0
answers question: http://stackoverflow.com/q/48430360
has body: If you're concerned about performance, consider doing a generator comprehension instead which is many orders of magnitude faster than the list comprehension. # adapting coldspeed's approach to generator comprehension (y for y in range(1, 100000) if '7' in str(y)) In [86]: %timeit [y for y in range(1, 100000) if '7' in str(y)] 21.8 ms ± 883 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [87]: %timeit (y for y in range(1, 100000) if '7' in str(y)) 555 ns ± 3.72 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
type: Answer

auth0
tags question: http://stackoverflow.com/q/48476737
type: Tag
tag name: auth0

http://stackoverflow.com/comment/83902257
comment on: http://stackoverflow.com/q/48454151
score: 0
has text: I'm not concerned about the speed of query yet. I merely want to be able to do it in pure django queryset functions. Please see the added graph
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83662441
type: Comment
has text: That was really descriptive. Thanks. But this does not seem to solve the problem. Let's say there are 5 lines in while loop and the control was on 2 line inside while loop in t2 when the flag was set by t1. So I want that t2 should exit there and not continue with the rest of the three lines. With the soln you have suggested, the flag will be checked when the current iteration of loop will complete. I actually have function executions inside the while loop that cannot execute if the flag from t1 is set.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48337947

http://stackoverflow.com/q/48477469
answer count: 1
has comment: http://stackoverflow.com/comment/83949961
has body: I want that my set /p Input1 = does something like py "Python.py" %Input1% but with multiple inputs. I also want to get the input from that very batch file into a python code. How do I take the input? I normally do it with a single input like sys.argv() but that doesn't seem to work. Any suggestions?
type: Question
has comment: http://stackoverflow.com/comment/83950207
has answer: http://stackoverflow.com/a/48477630
has comment: http://stackoverflow.com/comment/83954981
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: batch-file
has title: How to insert Batch input into Python

http://stackoverflow.com/q/48343268
has comment: http://stackoverflow.com/comment/83672968
has title: Can a generic function using eval be of any use?
tagged with: python
tagged with: generic-programming
has answer: http://stackoverflow.com/a/48343788
has comment: http://stackoverflow.com/comment/83672825
has comment: http://stackoverflow.com/comment/83673444
upvote count: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48343648
accepted answer: http://stackoverflow.com/a/48343648
downvote count: 1
favorite count: 0
type: Question
has body: I know, that eval() is evil. I'm sure there are much better ways. This is just a general question of approaching a problem. What do you think about using eval() in order to make a function more generic? In a very simple example, it could look like this: def generic_eval_func(a, operator, b): return eval('a '+operator+' b') if __name__ == '__main__': a = 6 b = 7 print generic_eval_func(a, '&lt;', b) I have not used such a function, yet. But every now and then it pops into my mind when thinking about how to make functions more generic. Instead of having two functions subtract(a,b) add(a, b) there would be one function operation(a, '+', b) or operation(a, '-', b) or operation(a, '&lt;', b). I'm really not sure about it.
tagged with: eval
linked to: http://stackoverflow.com/q/1832940
possible better answer: http://stackoverflow.com/a/48343788
score: 1

http://stackoverflow.com/a/58586850
type: Answer
has body: pip3 install twilio==6.0 Its worked for me. As python3 installed in my server.
answers question: http://stackoverflow.com/q/48340747
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/83809923
type: Comment
comment on: http://stackoverflow.com/a/48409178
type: AnswerComment
has text: Ok, but if `import matplotlib` already fails, why should `import matplotlib.pyplot` suddenly work? (That's a rethorical question.) Hence this is not really helpful. Don't be disappointed, it's not really your fault; sometimes questions are simply not answerable because of missing information.
score: 0

http://stackoverflow.com/q/48477997
has answer: http://stackoverflow.com/a/58490269
tagged with: nearest-neighbor
score: 3
upvote count: 3
has body: I'm trying to solve KNN using tensorflow. After I get the K neighbours for N vectors, I have a N by K tensor. Now, for each vector in N, I need to use tf.unique_with_counts to find the majority vote. However, I cannot iterate in a tensor and I cannot run tf.unique_with_counts with a multi-dimensional tensor. It keeps giving me InvalidArgumentError (see above for traceback): unique expects a 1D vector. Example: def knnVote(): ''' KNN using majority vote ''' #nearest indices A = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8]) print(A.shape) nearest_k_y, idx, votes = tf.unique_with_counts(A) print("y", nearest_k_y.eval()) print("idx", idx.eval()) print("votes", votes.eval()) majority = tf.argmax(votes) predict_res = tf.gather(nearest_k_y, majority) print("majority", majority.eval()) print("predict", predict_res.eval()) return predict_res Result: y [1 2 4 7 8] idx [0 0 1 2 2 2 3 4 4] votes [2 1 3 1 2] majority 2 predict 4 But how can I extend this to N by D input A, such as the case when A = tf.constant([[1, 1, 2, 4, 4, 4, 7, 8, 8], [2, 2, 3, 3, 3, 4, 4, 5, 6]])
has answer: http://stackoverflow.com/a/48479695
downvote count: 0
has title: How to use tf.unique_with_counts for each row/column of a tensor
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
tagged with: machine-learning
tagged with: python
type: UnansweredQuestion
tagged with: artificial-intelligence

http://stackoverflow.com/comment/83686364
comment on: http://stackoverflow.com/q/48349563
score: 0
type: Comment
type: QuestionComment
has text: Then you need to use `pool.map` within `partial`, not from the outside. You need to ask another question.

http://stackoverflow.com/comment/83736737
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48374598
has text: Thank you! Much appreciated. I was not clear in my qs that a, b, c were not characters but represented strings e.g. itemname1, itemname2, itemname3. So I had to modify your solution a bit to change separated_data creation to separated_data = [el.split(',') for el in s['col1']]
score: 0

http://stackoverflow.com/comment/84021017
type: AnswerComment
comment on: http://stackoverflow.com/a/48456134
has text: That did help, it converges now....however it is still not converging to the values that I calculated using least squares. They are just slightly off. The slope parameter using this algorithm is giving 12.3 where least squares gives 14.56.
type: Comment
score: 0

http://stackoverflow.com/comment/113112173
comment on: http://stackoverflow.com/a/48342103
type: Comment
has text: Do you know how to assign resample date as a new column to original dataframe ? for example , 300*24 rows with date column fromat like `%Y-%m-%d %H` (300days in hour ). I need groupby them every 7days , last day anchor to today, rolling back with 7* 24 . Because there are some reason I can't use resample.agg , so I need set the resampled date column back to original dataframe
score: 0
type: AnswerComment

http://stackoverflow.com/q/48477154
has comment: http://stackoverflow.com/comment/83947506
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has body: I have a large collection of bzip2-compressed text files. Uncompressed, some of these take up several GB, so I would like to use the compressed version in my scripts instead of having the uncompressed version take up space on disk. The performance impact caused by this is acceptable in this case. Unfortunately, these files are compressed with varying compression levels, so when iterating over them, eventually I run into an error: File "/usr/lib64/python3.6/bz2.py", line 219, in readline return self._buffer.readline(size) File "/usr/lib64/python3.6/_compression.py", line 68, in readinto data = self.read(len(byte_view)) File "/usr/lib64/python3.6/_compression.py", line 103, in read data = self._decompressor.decompress(rawblock, size) OSError: Invalid data stream I assume this is because bz2.open() takes an argument compresslevel, which, once set, is applied to all files in a call like this: import bz2 dataset = ['first-archive.bz2', 'second-archive.bz2'] for file in dataset: with bz2.open(file, 'r', compresslevel=9) as f: # do stuff to f Hence my question is this: is it possible, either using Python or Unix-tools, to figure out the compression level used when the bzip2-archive was created?
tagged with: bzip2
has comment: http://stackoverflow.com/comment/83947668
has comment: http://stackoverflow.com/comment/83947709
favorite count: 0
type: Question
has title: How to determine compression level of bzip2?
type: UnansweredQuestion
tagged with: bigdata
tagged with: python
has comment: http://stackoverflow.com/comment/83948457

http://stackoverflow.com/comment/83653404
type: Comment
has text: This question is fairly broad, as there are lots of ways to solve this but here's a hint, which hopefully lets you solve this on your own: Why do you need to call the `random.choice()` function twice? And is there a way to avoid doing so?
comment on: http://stackoverflow.com/q/48334019
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83669800
has text: i am having this alone, fail_timeout=0
comment on: http://stackoverflow.com/q/48341413
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83922583
comment on: http://stackoverflow.com/q/48453474
has text: Also, can some moderator reopen this question, as it is not a duplicate of the stated answer at all, so I can post a proper answer for it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55316104
score: 3
has body: upgrade your pillow package by running pip install --upgrade pillow
type: Answer
answers question: http://stackoverflow.com/q/48456378
downvote count: 0
upvote count: 3

http://stackoverflow.com/a/48464257
answers question: http://stackoverflow.com/q/48464189
has body: You need to tell int that the numbers are in base 16: hex((int(a, 16) &lt;&lt; 8) | int(b, 16))
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48464189
downvote count: 0

http://stackoverflow.com/comment/83950034
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48478246
score: 0
has text: Could you show the code for the user profile model, and the user profile admin?

http://stackoverflow.com/q/48456130
score: 0
answer count: 1
tagged with: xgboost
type: Question
has body: I'm using XGBoost 0.7 with Python 3.6 on a 2017 MacBook Pro. I run: sysctl -n hw.ncpu and get back 8 So I test that multi-threading is working properly and almost everything looks normal. I see improvement up to 8 cores. However, when I use numthreads=-1, I get terrible performance. Specifically, I run this using the Otto train.csv file from Kaggle: from pandas import read_csv from xgboost import XGBClassifier from sklearn.preprocessing import LabelEncoder import time from matplotlib import pyplot # load data data = read_csv('train.csv') dataset = data.values # split data into X and y X = dataset[:,0:94] y = dataset[:,94] # encode string class values as integers label_encoded_y = LabelEncoder().fit_transform(y) # evaluate the effect of the number of threads results = [] num_threads = [2, 4, 8, 16, -1] for n in num_threads: start = time.time() model = XGBClassifier(nthread=n) model.fit(X, label_encoded_y) elapsed = time.time() - start print(n, elapsed) results.append(elapsed) and I get back this: 2 48.96274280548096 4 26.73108983039856 8 24.160531997680664 16 24.71382975578308 -1 91.67938613891602 According to the xgboost docs, numthreads=-1 should use all available cores on your machine. So shouldn't I get the best performance with this, at least as good performance as with 8 cores? Thanks!
accepted answer: http://stackoverflow.com/a/48456450
has title: XGBoost: Strange Run-Time with Multiple Cores
has answer: http://stackoverflow.com/a/48456450
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83916382
has text: Because message from each number won't have the same format.
score: 0
comment on: http://stackoverflow.com/a/48461537
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83685494
type: Comment
type: QuestionComment
has text: please google about "lists in Python" and update your question with valid notation
comment on: http://stackoverflow.com/q/48349548
score: 0

http://stackoverflow.com/q/48345087
has answer: http://stackoverflow.com/a/48345410
tagged with: time-series
type: Question
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: datetimeoffset
has title: Pandas Time convert to business day time
score: 0
tagged with: datetime
has body: I have a Pandas DataFrame with a Date column of the format datetime64[ns]. 0 2016-10-19 23:41:03 1 2016-10-22 03:25:54 2 2016-10-21 23:58:05 3 2016-10-23 00:13:22 4 2016-10-22 00:51:26 5 2016-10-23 00:52:45 6 2016-10-23 02:18:42 Because of the specific type of project I am working on, I want to convert it so that the time is not based on regular days (0 am to 0 am) but to nightlife days (12 pm to 12pm). It means that if I do data.dt.weekday_name and get the weekdays based on the timestamps I get Monday going from Monday 12pm to Tuesday 12pm, and not from Monday 12 am to Tuesday 12pm as is it normally considered. Is is possible to do it in Pandas ? Do you have a trick to do it ?
tagged with: date

http://stackoverflow.com/a/78369694
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48370307
type: Answer
has body: PEP 646, which introduced variadic generics, also allows tuple types to be unpacked: TripleInt: TypeAlias = tuple[int, *tuple[int, int]] # TripleInt = tuple[int, int, int] As tuple[int, ...] denotes a tuple with 0 or more int elements, the type of a tuple consisting of at least 8 int elements would be: (playgrounds: Mypy, <a href="https://pyright-play.net/?pythonVersion=3.13&amp;strict=true&amp;code=C4TwDgpgBAQizQLxWAVzAGwgbQJYDtgAaKA40wksqyi86ukgKjUxwYDouBdbgWABQgwcAAMARgBcseEigAKcUQCUUNeo2at2nbo0BiKBABOxgPbGRogEzS4CKMkUlrqve4%2BfDJ85YFiAZjtZRwUlKGsSALdPWLjvUwsrABZghydwyKgAkmSYuILtBN8rAFY0uWcIqNySUvzCwuKk-1EANgrQqqycqGS6kjaGxo9mvzEAdk6Mlxq%2Bgag2kgnhkaKjRPHRAA5psNns2qhSweWSbdW1tUMAMwIIKwBOPe65-uPTqAnzkkfLxtu9xE4lEL0ybwWSy%2BPygjxIIP%2BXigd3wD384ikMnS%2B2qh3mH0WZyg21%2B8NE8PEiJ0gNRwNsWMq4Lx7xOhOhxNJUBBFPhrliNLRwHEQQZXSZvRZn2%2BHNhZJ5XKywsRAuBqVFM1xEshRJJsq55K54XEit64jyWhV6PK6pxPSOrKh0t1cP18uN8NN73E9WuyKBAiAA" rel="nofollow noreferrer">Pyright (PEP 695 syntax)) Byte: TypeAlias = tuple[ int, int, int, int, int, int, int, int, # 8 `int` *tuple[int, ...] ] For 3.10 and older, the unpacking operator would cause a SyntaxError and thus will need to be replaced with Unpack: Byte: TypeAlias = tuple[ int, int, int, int, int, int, int, int, # 8 `int` Unpack[tuple[int, ...]] ]

http://stackoverflow.com/a/48394596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83777467
has body: If I understand your question. This should do what you want. Or at least point you in the right direction. json_array = [{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5,"foo":"bar"}]}] def get_ids(json_array): ids = [] for obj in json_array: if isinstance(obj, dict): ids.append(obj.get('id')) children = obj.get('children', None) if children: ids.extend(get_ids(children)) elif isinstance(obj, list): ids.extend(get_ids(obj)) return ids &gt;&gt;&gt; get_ids(json_array) [1, 2, 3, 4, 5]
has comment: http://stackoverflow.com/comment/83777597
has comment: http://stackoverflow.com/comment/83777065
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48394368
score: 3
answers question: http://stackoverflow.com/q/48394368
has comment: http://stackoverflow.com/comment/83777034
upvote count: 3

http://stackoverflow.com/comment/83773392
comment on: http://stackoverflow.com/q/48392734
type: Comment
score: 1
type: QuestionComment
has text: Please don't post pictures of code or error messages. Post the full traceback here on SO instead. [The reason for this is explained here.](http://idownvotedbecau.se/imageofanexception/)

identifier
tag name: identifier
tags question: http://stackoverflow.com/q/48404881
type: Tag

http://stackoverflow.com/q/48410453
type: UnansweredQuestion
tagged with: odoo
has body: I've created a new module in order to extend sale.advance.payment.inv. The problem is that the form from my module is not being used, it is being used the default form (and also the new values defined in my module are not being loaded in the old form...) I'm using this files: __manifest__.py: # -*- coding: utf-8 -*- { 'name': "invoice_sales_order", 'summary': """Allows invoice percentage for each line in sales order""", 'description': """ Allows invoice percentage for each line in sales order """, 'author': "Miquel", 'website': "http://example.com", 'category': 'Uncategorized', 'version': '0.5', 'depends': ['base', 'account', 'Sales'], 'data': [ 'views/views.xml', ], 'demo': [ 'demo/demo.xml', ], 'installable': True, } controllers/controllers.py: # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from odoo import api, fields, models, _ from odoo.addons import decimal_precision as dp from odoo.exceptions import UserError class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" @api.model def _count(self): return len(self._context.get('active_ids', [])) @api.model def _get_advance_payment_method(self): if self._count() == 1: sale_obj = self.env['sale.order'] order = sale_obj.browse(self._context.get('active_ids'))[0] if all([line.product_id.invoice_policy == 'order' for line in order.order_line]) or order.invoice_count: return 'all' return 'delivered' advance_payment_method = fields.Selection([ ('delivered', 'Invoiceable lines'), ('all', 'Invoiceable lines (deduct down payments and quantity percentage)'), ('soprecentage', 'Quantity percentage line by line'), ('percentage', 'Down payment (percentage)'), ('fixed', 'Down payment (fixed amount)') ], string='What do you want to invoice?', default=_get_advance_payment_method, required=True) @api.onchange('advance_payment_method') def onchange_advance_payment_method(self): if self.advance_payment_method == 'percentage' or self.advanc…
tagged with: python
score: -1
upvote count: 0
tagged with: odoo-10
answer count: 1
has answer: http://stackoverflow.com/a/48410567
downvote count: 1
favorite count: 0
type: Question
has title: odoo 10 Addon view not being used

http://stackoverflow.com/comment/83851100
comment on: http://stackoverflow.com/a/48429736
score: 0
type: AnswerComment
has text: I tried the *.flush() and it worked. The output is now in 2 files. Just need to work on the formatting so it's not strung together. Thanks for the advice!
type: Comment

http://stackoverflow.com/comment/83811162
comment on: http://stackoverflow.com/q/48407338
has text: scatter would expect 3 lists or arrays as input, not single numbers. So I would try `ax.scatter([160],[245],[85])`. If that doesn't help, did you check if the point is on the other side of the plane?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/48382862
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83752535
accepted answer of: http://stackoverflow.com/q/48382626
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48382626
has comment: http://stackoverflow.com/comment/83753725
has comment: http://stackoverflow.com/comment/83752592
type: Answer
has body: I guess you refer to the line in the tutorial which is plt.show(fig1). This is simply wrong. You can either call plt.show() to show all plots present in the pyplot state. Or you can call fig1.show() if there is a figure fig1, but this would probably not work in a jupyter notebook. In a Jupyter notebook you can instead simply state the name of the figure to show it, fig1

unicode
tags question: http://stackoverflow.com/q/48464972
tags question: http://stackoverflow.com/q/48424692
tags question: http://stackoverflow.com/q/48403108
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/48419346
tags question: http://stackoverflow.com/q/48365494
tags question: http://stackoverflow.com/q/48340622
tags question: http://stackoverflow.com/q/48390671
tags question: http://stackoverflow.com/q/48347331
tags question: http://stackoverflow.com/q/48434487
tags question: http://stackoverflow.com/q/48413821
tags question: http://stackoverflow.com/q/48335063
tags question: http://stackoverflow.com/q/48342671
tags question: http://stackoverflow.com/q/48404881
tags question: http://stackoverflow.com/q/48333346

http://stackoverflow.com/a/48391599
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48391502
score: 1
has body: You can use itertools.groupby to pair all values with the same key. First, the code calls dict.items on every dictionary in foo and flattens the result, thus enabling the groups to be found: import itertools foo = [ { "name": "Bob", "occupation": "", "standing": "good", "locations": ["California"], "meta": { "last_updated": "2018-01-15" } }, { "name": "", "occupation": "Carpenter", "standing": "bad", "locations": ["Arizona"], "meta": { "last_updated": "2018-01-15", "email": "bob@domain.com" } }, ] new_data = [(a, map(lambda x:x[-1], list(b))) for a, b in itertools.groupby(sorted(itertools.chain(*map(lambda x:x.items(), foo)), key=lambda x:x[0]), key=lambda x:x[0])] final_data = {a:filter(None, b)[-1] for a, b in new_data} Output: {'occupation': 'Carpenter', 'standing': 'bad', 'meta': {'last_updated': '2018-01-15', 'email': 'bob@domain.com'}, 'locations': ['Arizona'], 'name': 'Bob'}
downvote count: 0
has comment: http://stackoverflow.com/comment/83771276
has comment: http://stackoverflow.com/comment/83771327

http://stackoverflow.com/comment/83692079
type: QuestionComment
comment on: http://stackoverflow.com/q/48352638
type: Comment
score: 0
has text: please add more details: what is the input format, what is the expected result, what have you tried so far and why it did not work

http://stackoverflow.com/q/48367352
tagged with: maximization
tagged with: python
tagged with: plot
score: 0
has comment: http://stackoverflow.com/comment/83721639
has body: I was solving a problem in which I needed to graphic this: r = (16442.21*(((np.e**(-10468.04/T))*(P1.5))/((2-X)**1.5))*(((1-X)**2.5)/X))-17374.99*(((np.e(-23855.06/T))(Fo0.2)((2-X)**0.5))/(P0.5))*(X/((1-X)**1.3)) The graphic that I needed was X(T), and the curves represents the values of T and X for which the parametre r has the same value. So I made the plot from the implicit equation, usin this code: #Librerías from __future__ import division import numpy as np import matplotlib.pyplot as plt #Ingreso de datos P=float(input("Ingrese la presión de trabajo en atmosferas: ")) Fo=float(input("Ingrese el flujo inicial de moles de nitrógeno, en kmol/d: ")) #Definición de la función de manera implícita def f(T,X,r): return (16442.21*(((np.e**(-10468.04/T))*(P**1.5))/((2-X)**1.5))*(((1-X)**2.5)/X))-17374.99*(((np.e**(-23855.06/T))*(Fo**0.2)*((2-X)**0.5))/(P**0.5))*(X/((1-X)**1.3))-r #Definición de vectores T y X T=np.linspace(10,2000,500) X=np.linspace(0.0001,0.9999,500) #Pasaje a matriz T,X=np.meshgrid(T,X) #Gráfico r=0.000001 hola=plt.contour(T,X,f(T,X,r),[0],colors='g',label='r=0.000001') r=0.001 plt.contour(T,X,f(T,X,r),[0],colors='b',label='r=0.001') r=0.002 plt.contour(T,X,f(T,X,r),[0],colors='m',label='r=0.002') r=0.005 plt.contour(T,X,f(T,X,r),[0],colors='y',label='r=0.005') r=0.01 plt.contour(T,X,f(T,X,r),[0],colors='k',label='r=0.01') r=0.02 plt.contour(T,X,f(T,X,r),[0],colors='r',label='r=0.02') r=0.05 plt.contour(T,X,f(T,X,r),[0],colors='g',label='r=0.05') r=0.1 plt.contour(T,X,f(T,X,r),[0],colors='c',label='r=0.1') r=0.2 plt.contour(T,X,f(T,X,r),[0],colors='b',label='r=0.2') r=0.5 plt.contour(T,X,f(T,X,r),[0],colors='m',label='r=0.5') r=1 plt.contour(T,X,f(T,X,r),[0],colors='y',label='r=1') plt.xlabel('Temperatura [K]') plt.ylabel('Conversión') plt.title('Curvas de isovelocidad a presión constante') plt.show() This was the result: https://i.sstatic.net/5ugDZ.png The problem is that I need to maximize each curve, and I don't know how to do it because I can't f…
answer count: 0
tagged with: equation
type: Question
has comment: http://stackoverflow.com/comment/83725212
type: UnansweredQuestion
tagged with: implicit
has title: Maximization from an implicit equation's plot in Python

http://stackoverflow.com/a/48355773
has comment: http://stackoverflow.com/comment/83700034
type: Answer
answers question: http://stackoverflow.com/q/48354342
score: 0
has body: Sequential solution you have does not look parallelizable, because fate of every element depends on a complete history (removing a single item can affect all items located after it). It is easy to get an approximation of your sequential code by pruning partitions first: d = 3 rdd = sc.parallelize([1, 3, 4, 7, 8, 11], 4) def prune(xs, d=3): prev = None for x in xs: if prev is None or abs(x - prev) &gt;= d: prev = x yield x pruned = rdd.mapPartitions(prune) and then sweep once again borders = pruned.mapPartitions(lambda xs: [max(xs)]).collect() pruned.filter(lambda x: any(b &lt; x &lt; b + 3 for b in borders)).collect() # [3, 8] but as you can see this approach is less conservative and doesn't return the same results as sequential solution. With larger partitions, and random distributed differences between max(p) and min(p + 1) where p is partition, this should converge to similar output on average, but without any guarantees. If you want to apply it this by group you can just repartitionAndSortWithinPartitions and apply local logic for each partition.
has comment: http://stackoverflow.com/comment/83698348

http://stackoverflow.com/comment/83958396
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48482665
has text: Which pip depends on the OS and distribution and... Find your python install dir with `which python` or `where python`. Use the pip in the scripts directory there.

http://stackoverflow.com/comment/83969283
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48484324
score: 0
has text: added input and expected output

http://stackoverflow.com/comment/83759067
has text: ` ` is a *preamble*, it is not part of the HTML document proper.
comment on: http://stackoverflow.com/q/48361104
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83715318
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48364134
has text: @Tai - [link] (https://www.kaggle.com/csyhuang/predicting-chronic-kidney-disease/notebook) [link] The dataset can be downloaded from here
score: 0

http://stackoverflow.com/comment/83924891
comment on: http://stackoverflow.com/a/48465706
type: AnswerComment
type: Comment
score: 4
has text: You wanted `{'name': 'tom', 'age': '14', 'sex': 'm', 'color': 'w', 'weight': '58', 'style': 'good', 'sports': 'cricket', 'music': 'rock', 'dance': 'disco'}` as the result and my example gives exactly that.

http://stackoverflow.com/comment/83731945
score: 0
comment on: http://stackoverflow.com/q/48372449
type: QuestionComment
type: Comment
has text: The executable is called `my_command.py`, not `my_command`. What is `$my_command`? Is there a shell variable called `my_command` which you expect python to know about?

http://stackoverflow.com/q/48435774
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/79428860
has body: I'm trying to run a Python script from Visual Studio code, but the script fails to run and crashes with a SyntaxError pointing to the comment at the beginning of launch.json. launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python | Default", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "${config:python.pythonPath}", "program": "${file}", "cwd": "${workspaceFolder}", "env": {}, "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput" ] } ] } Terminal Output: File ".../.vscode/launch.json", line 2 // Use IntelliSense to learn about possible attributes. ^ SyntaxError: invalid syntax settings.json: { "python.pythonPath": "${workspaceFolder}/venv/bin/python" } I was working on my Windows machine earlier and all of this worked perfectly fine. For some reason, VSCode is trying to run the launch.json file through Python and // is an invalid comment syntax in Python. If I remove the comments, I get this error: Traceback (most recent call last): File ".../.vscode/launch.json", line 8, in <module> "stopOnEntry": false, NameError: name 'false' is not defined If I use Python's False, I don't crash but nothing happens and my script does not run. It seems very much like launch.json is being parsed by Python erroneously. Any fix for this?
tagged with: python
has comment: http://stackoverflow.com/comment/128110362
answer count: 4
possible better answer: http://stackoverflow.com/a/64441830
accepted answer: http://stackoverflow.com/a/48435859
has answer: http://stackoverflow.com/a/48435859
has answer: http://stackoverflow.com/a/64441830
downvote count: 1
favorite count: 0
type: Question
has title: `SyntaxError: invalid syntax` when starting Python script in VS Code on macOS
type: AnsweredQuestion
score: 38
has answer: http://stackoverflow.com/a/72036804
tagged with: visual-studio-code
upvote count: 39

http://stackoverflow.com/comment/83775016
has text: @sfjac Edit, never mind, just noticed it's exactly like yours. Sorry, I'm still not sure what your expected output is and how your current output is incorrect... can you help me understand better please?
type: AnswerComment
comment on: http://stackoverflow.com/a/48393385
score: 0
type: Comment

http://stackoverflow.com/q/48351637
tagged with: python
accepted answer: http://stackoverflow.com/a/48352406
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48352406
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83690150
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83690076
has title: Index pandas dataframe by time difference
upvote count: 1
has body: I have two columns and one is time and the other is volume. I need to subtract the volume from each point with the volume from exactly 24hrs ago. What is the best way to go about doing this in pandas? What if there are holes in the data and there is no point in the data frame from exactly 24hrs ago, can I set a rule so that it will index the nearest point to 24hrs ago? sample df: In [1]: df Out[1]: Volume Time 10 24/12/2017 18:40 27 24/12/2017 18:41 -19 24/12/2017 18:42 7 24/12/2017 18:43 -23 24/12/2017 18:44 18 24/12/2017 18:45 4 24/12/2017 18:46
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83690131

http://stackoverflow.com/comment/83803688
type: Comment
score: 0
type: AnswerComment
has text: Excel's format is a package of zipped XML files. If it can be done with Excel, the value is visible in the file and can be replicated. VBA can't do what Excel itself can't do
comment on: http://stackoverflow.com/a/48407315

http://stackoverflow.com/a/48483512
score: 4
has comment: http://stackoverflow.com/comment/83959907
accepted answer of: http://stackoverflow.com/q/48483447
has comment: http://stackoverflow.com/comment/83959886
has comment: http://stackoverflow.com/comment/83959915
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48483447
upvote count: 4
has comment: http://stackoverflow.com/comment/83959885
has body: Here is a little test for you that will help; class A: def __init__(self): self.var1 = 5 print("In A") class B(A): def __init__(self): self.var2 = 10 print("In B") class C(B): def __init__(self): self.var3 = 20 print("In C") super().__init__() ## Line 1 c = C() will print; In C In B but if you add a call in B to the constructor of A; class A: def __init__(self): self.var1 = 5 print("In A") class B(A): def __init__(self): self.var2 = 10 print("In B") super().__init__() class C(B): def __init__(self): self.var3 = 20 print("In C") super().__init__() ## Line 1 c = C() You get what you would expect; In C In B In A and this... print(c.var1) 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83766749
type: Comment
type: QuestionComment
score: 0
has text: I think you need to better specify your question, there should be tens of examples in SO, but I'm still not sure what the issue you're having is.
comment on: http://stackoverflow.com/q/48389065

http://stackoverflow.com/comment/83686745
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48346418
score: 0
has text: `rv_continuous` and `rv-discrete`, in https://docs.scipy.org/doc/scipy/reference/stats.html, are intended for this purpose, assuming I understand you correctly.

http://stackoverflow.com/a/48362631
score: 0
type: Answer
has body: According to the documentation you should pass the string which is a filename of file that you want to use as background. Documentation also states that you can use GIFs. PNG will do too. JPEGs don't work with turtle. wn.bgpic("background.png") or wn.bgpic("background.gif") Perhaps your files are corrupt. (Note, changing file extension of file doesn't actually change it's type)
answers question: http://stackoverflow.com/q/48362535

http://stackoverflow.com/q/48394493
linked to: http://stackoverflow.com/q/19483351
tagged with: curl
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48395126
possible better answer: http://stackoverflow.com/a/48395126
has body: This is sample document. { "_index": "mqtt-index-2018.01.23", "_type": "iot_data", "_id": "AWEjA7LNRU4cTUO-Lyj4", "_score": null, "_source": { "message": "{\"datastream_name\": \"roshni\", \"value\": 12, \"context\": {\"latitude\": 0, \"elevation\": 0, \"longitude\": 0}, \"device_id\": 31}", "@version": "1", "@timestamp": "2018-01-23T12:34:59.687Z", "host": "iot-elk", "topic": "telemetry/f2a55827ef554475a41c3c96369957f0/roshni", "datastream_name": "roshni", "value": 12, "context": { "latitude": 0, "elevation": 0, "longitude": 0 }, "device_id": 31, "tstamp": "2018-01-23T12:34:59.687Z" }, "fields": { "tstamp": [ 1516710899687 ], "@timestamp": [ 1516710899687 ] }, "sort": [ 1516710899687 ] } I want to delete document using device_id field. How to delete it using API call or using python client? I have tried it using Document _id and particular index but i want to delete it by using device_id field or other field.
tagged with: pyelasticsearch
has answer: http://stackoverflow.com/a/48419524
tagged with: logstash
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48419454
accepted answer: http://stackoverflow.com/a/48419454
has answer: http://stackoverflow.com/a/48403317
type: AnsweredQuestion
score: 3
upvote count: 3
has title: How to delete documents from multiple indices using particular field name in elasticsearch python?
tagged with: elasticsearch
downvote count: 0

http://stackoverflow.com/q/48449888
type: UnansweredQuestion
type: Question
has body: Somewhat new to python. Effectively what I'm interested in doing is iterating over rows in a dataframe, performing a calculation on a specific column if a condition is met, and then having the answer be placed on the same row in a new column. For sake of example, if I had a dataframe: c1 c2 0 20 82 1 15 14 2 10 19 I may want to half the value in c1 if the value in c2 is greater than fifty, double the value in c1 if the value in c2 is less than fifty, and have the answers appear in a new column, c3, so I'd end up with: c1 c2 c3 0 20 82 10 1 15 14 30 2 10 19 20 I'm aware of how to do the maths bit, and how to use if/else functions, its just iterating over the rows I'm struggling with and how to put each answer into the new column. I'm aware of iterrows, but I'm not convinced I fully understand how to use it, or if its appropriate in this instance? Cheers.
has title: Iterating over rows in a dataframe, performing calculations on each and putting answer in a new column
tagged with: pandas
has answer: http://stackoverflow.com/a/48450037
tagged with: dataframe
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48449994
upvote count: 2
score: 2
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83896659
type: Comment
comment on: http://stackoverflow.com/q/48451833
type: QuestionComment
has text: Put `global nrange, unumber` at the top of `start()`.
score: 0

http://stackoverflow.com/comment/83939312
type: AnswerComment
score: 4
has text: With `lst.append(xxx)`.
type: Comment
comment on: http://stackoverflow.com/a/48472732

http://stackoverflow.com/q/48479032
type: UnansweredQuestion
has body: I am making a smart mirror with a voice interface on the Raspberry Pi. There are two separate scripts, one for voice control and one for a GUI. I am trying to launch both of them when the RPi boots up. The problem is that only the GUI script boots up. I can run the SR script manually from terminal, but I can't launch it automatically. So far I have tried: -launching with crontab -launching with rc.local -starting one script from the other with OS.SYSTEM -starting one script from the other with POPEN -starting one script from the other with a bash script -launching at boot with a bash script -launching only after LXDE is loaded -launching a separate script that launches both of them Every scenario just sends the script into an infinite error loop. Below is the simplified code: #!/usr/bin/env python from os import environ, path, system import pyaudio import time import sys from pocketsphinx.pocketsphinx import * from sphinxbase.sphinxbase import * MODELDIR = "pocketsphinx/model" DATADIR = "pocketsphinx/test/data" # Create a decoder with certain model config = Decoder.default_config() config.set_string('-hmm', path.join(MODELDIR, 'en-us/en-us')) config.set_string('-lm', path.join(MODELDIR, 'MERLIN/MERLINv3.lm')) config.set_string('-dict', path.join(MODELDIR, 'MERLIN/MERLINv3.dic')) config.set_string('-logfn', '/dev/null') decoder = Decoder(config) def getKWord(): try: stream.start_stream() in_speech_bf = False decoder.start_utt() while True: buf = stream.read(4096) 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() stream.stop_stream() #system('mpg321 /home/pi/MERLIN_main/process_sounds/Beep_low.mp3') return str(decoder.hyp().hypstr) system('mpg321 /home/pi/MERLIN_main/process_sounds/Beep_low.mp3') else: decoder.end_utt() stream.stop_stream() print('PocketSphinx could not decode') return "Pocketsphinx could not decode. Try again" decoder.end_utt() excep…
has comment: http://stackoverflow.com/comment/83961127
tagged with: python
has title: Can't run Pocketsphinx script at boot
tagged with: pyaudio
has comment: http://stackoverflow.com/comment/83956992
score: 0
has comment: http://stackoverflow.com/comment/83954117
tagged with: pocketsphinx
answer count: 0
has comment: http://stackoverflow.com/comment/83956808
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/83953952

http://stackoverflow.com/comment/83656512
comment on: http://stackoverflow.com/a/48335627
type: AnswerComment
has text: works very well, thank you coldspped and @jezrael . coldspeed may I know how many years you've been in data science/pandas ?
score: 0
type: Comment

http://stackoverflow.com/comment/83965207
comment on: http://stackoverflow.com/q/48486205
type: Comment
score: 0
type: QuestionComment
has text: Sorry about the indentation, I guess it automatically indents in the python shell but won't copy it? I have added the indentation anyway

http://stackoverflow.com/comment/83898326
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48452402
has text: You can't safely use `xargs` that way -- if you have more arguments than will fit on a single command line, you have no knowing if it'll split after a filename or after a `-f`. (Also, it's unsafe with filenames containing spaces, literal quotes, literal backslashes, etc).

http://stackoverflow.com/q/48487278
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83967509
downvote count: 0
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48487869
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83967728
score: 1
tagged with: quaternions
has title: quaternion creation by spherical coords in numpy
has answer: http://stackoverflow.com/a/48487869
tagged with: python
has body: While trying to understand the usage the quaternion extension of numpy, I saw that import numpy as np import quaternion as q theta = np.pi * 1.0 / 3.0 phi = 0.0 print(q.from_spherical_coords(theta,phi)) prints out (quaternion(0.866025403784439, -0, 0.5, 0)) This quaternion is a 60 degrees rotation around Y axis, but I expected a 60 degrees rotation around Z axis only, since phi is 0.0. Have theta and phi changed with respect to source files or am I missing something? Thanks for any help.

http://stackoverflow.com/q/48359798
upvote count: 1
tagged with: pypi
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/37531231
tagged with: trend
has answer: http://stackoverflow.com/a/57985527
has title: Missing Python Package Download Data from PyPI in 2016
type: UnansweredQuestion
downvote count: 0
has body: Here is a plot of monthly download data from PyPI's old system pypi.python.org and new data storage on BigQuery. Total Downloads of Module Missing on PyPi mentions that, Donald Stufft (PyPI maintainer in 2016 (is Donald still in charge?)), disabled the broken PyPI's download count system. Donald also mentioned in the email that "this isn't a permanent loss of the feature and we won't lose any data". My question is that is where I can find the "missing" data from late 2015 to 2016? Is the raw data stored somewhere? update 1: another related question Why PyPi doesn't show download stats anymore? Footnote: the graph is a raw measure of user downloads but is far from accurate due to 1. PyPI data is cumulative downloads for each file, BQ data is the accurate download data. 2. non-PyPI sources are not counted, such as Anaconda, etc other ways to install packages.
tagged with: popularity
tagged with: python
linked to: http://stackoverflow.com/q/38102317
score: 1
answer count: 1

http://stackoverflow.com/comment/83649840
has text: Use a different language?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48332009
score: 0

http://stackoverflow.com/a/59303427
score: 4
answers question: http://stackoverflow.com/q/48343387
downvote count: 0
upvote count: 4
has body: ValueError a function is called on a value of the correct type, but with an inappropriate value TypeError : a function is called on a value of an inappropriate type
type: Answer

http://stackoverflow.com/q/48361494
answer count: 1
tagged with: authentication
tagged with: django
type: Question
tagged with: django-admin
has title: create separate Django admin panel
type: UnansweredQuestion
tagged with: session
tagged with: python
has body: I couldn't find the answer to my questions after hours of research! is it possible to create completely separate admin panel in Django? how authentication works on Django?! on a user control panel for example how to control sessions and let user log in into the panel etc. what is the correct way to use NOSQL DB's like Mongodb as backend for Django?
score: 0
has answer: http://stackoverflow.com/a/48364065

http://stackoverflow.com/a/49660428
answers question: http://stackoverflow.com/q/48456322
downvote count: 0
has body: might be quite late for your question. You may use same model by different app just by refering to it. First your apps should be under the same project. Choose one app as 'core' and define your models under it,(I have read that models are better to be at app level) Then whenever you would like to use a model from that app, import that app's model at the beginning of the code. Let say we have two apps: app_1 and app_2 and a model defined under app_1/models.py: model_1 In app_2/views.py , import model_1 from app_1.models import model_1
upvote count: 5
type: Answer
score: 5

http://stackoverflow.com/a/48389207
has comment: http://stackoverflow.com/comment/98683064
type: Answer
accepted answer of: http://stackoverflow.com/q/48389157
has body: You're looking for types.ModuleType.
answers question: http://stackoverflow.com/q/48389157
upvote count: 122
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/98699787
score: 121

http://stackoverflow.com/a/48455949
answers question: http://stackoverflow.com/q/48453412
upvote count: 2
downvote count: 0
type: Answer
has body: This problem is simple enough to use str methods. For a non-regex approach: [x for x in sample_str.split() if (not x.startswith(pat)) and (not x.endswith(pat))] # ['aaron'] Note: this will include any string that does not start or end with the pattern. If you wish to extend the condition to include words that contain the pattern, try this: sample_str = "rose aaron robert moro nopattern" pat = "ro" [x for x in sample_str.split() if (not x.startswith(pat)) and (not x.endswith(pat)) and (pat in x)] # ['aaron']
score: 2

http://stackoverflow.com/q/48343024
has body: Is there a way to schedule a python script loading data to Bigquery without having to copy the authentication code generated from a google account link for each run. I am currently using the windows task scheduler to achieve this.
has title: Schedule a python script loading data to BigQuery under windows 10
has answer: http://stackoverflow.com/a/48343166
favorite count: 0
accepted answer: http://stackoverflow.com/a/48620815
type: Question
has answer: http://stackoverflow.com/a/48620815
tagged with: oauth
tagged with: windows
tagged with: python
tagged with: google-bigquery
type: AnsweredQuestion
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/48343166
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48346604
score: 1
accepted answer of: http://stackoverflow.com/q/48345699
has comment: http://stackoverflow.com/comment/83686224
has body: Instead of xpath("/html/body/div[3]/div[3]/div/div/div/span/img"), you can use the following xpath : img = browser.find_element_by_xpath("/html/body/div[3]/div[3]//div[@class='searchResult' and @id='image.3dw.bcf0b18a19bce6d91ad107790a9e2d51.0']/img[@class='enlarge']") src = img.get_attribute('src')
type: Answer
answers question: http://stackoverflow.com/q/48345699
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83685925
has comment: http://stackoverflow.com/comment/83686322

http://stackoverflow.com/comment/83967112
type: Comment
comment on: http://stackoverflow.com/a/48485948
has text: The third state is mostly useful when you have a hierarchy of checkbuttons. If you have a group of checkbuttons where some are checked and some are not, their parent checkbutton will have this third value. The canonical tcl/tk documentation describes it here: http://tcl.tk/man/tcl8.5/TkCmd/checkbutton.htm#M6
type: AnswerComment
score: 1

time-series
tags question: http://stackoverflow.com/q/48429743
tags question: http://stackoverflow.com/q/48367368
type: Tag
tags question: http://stackoverflow.com/q/48340463
tags question: http://stackoverflow.com/q/48428729
tags question: http://stackoverflow.com/q/48391526
tags question: http://stackoverflow.com/q/48474878
tags question: http://stackoverflow.com/q/48461808
tag name: time-series
tags question: http://stackoverflow.com/q/48393080
tags question: http://stackoverflow.com/q/48436665
tags question: http://stackoverflow.com/q/48345087
tags question: http://stackoverflow.com/q/48341233

http://stackoverflow.com/q/48358852
has answer: http://stackoverflow.com/a/48359005
possible better answer: http://stackoverflow.com/a/48358908
has answer: http://stackoverflow.com/a/48358924
has answer: http://stackoverflow.com/a/48358908
answer count: 4
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have a list of lists in python 3.x: deliveryData=[[1,5,3],[2,7,8],[8,10,5]] I want to compare/operate on individual items of the current list (e.g. [2,7,8]) with a previous list (e.g. [1,5,3]). How do I do that? Testing this feature with sample code below: deliveryData=[[1,5,3],[2,7,8],[8,10,5]] for data in deliveryData[1:]: print(data) print(data[-1]) I was thinking I can access the list [1,5,3] with data[-1] while I am on the list [2,7,8] but that is not right. Can anyone please offer any suggestions?
upvote count: 2
has title: Accessing list items of a previous list
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48358902
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48358902

http://stackoverflow.com/q/48459519
score: 2
answer count: 0
upvote count: 2
downvote count: 0
has body: My higher level goal is to have a polymorphic association between models and I think I can solve it with a model with this signature: class Relation(models.Model): left = ForeignKey(Entity) right = ForeignKey(Entity) class Meta: db_table = 'entities' then I can extend Relation as proxy so I can be more clear on my intention of left and right field, for ex: class Authorship(Relation) author = AliasField('left') content = AliasField('right') class Meta: proxy = True So then we can do the following: Authorship.objects.filter(author=user_entity) or Authorship.objects.create(author=user_entity) My question is, how do I implement AliasField function described above? I have looked at: https://shezadkhan.com/aliasing-fields-in-django/ How to create an alias for Django Model field? for the first link, I am getting error about name is not a field or something for the second one, I am getting an error saying "can't adapt type" is this even possible to do in Django 2.0? I prefer not to use django-polymorphic Thank you!
has title: django 2.0 model, alias field
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
linked to: http://stackoverflow.com/q/18985466

http://stackoverflow.com/comment/83795998
score: 0
comment on: http://stackoverflow.com/q/48403484
has text: It does change, but the values have to be above 1 to work.you should also show the grid on the plot for better visual.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48436679
score: 0
has comment: http://stackoverflow.com/comment/83878216
has answer: http://stackoverflow.com/a/48445535
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83878329
has comment: http://stackoverflow.com/comment/83874479
answer count: 1
has comment: http://stackoverflow.com/comment/83879679
has title: Improve scrapy and selenium with firefox in headless mode
tagged with: firefox-headless
linked to: http://stackoverflow.com/q/47999568
type: Question
has comment: http://stackoverflow.com/comment/83874543
has comment: http://stackoverflow.com/comment/83868112
tagged with: selenium
has body: I am scraping a javascript heavy site and I have setup a vagrant instance to check the feasibility ( 1GB RAM ). The system crashes after parsing few urls. I am unable to determine memory requirements for this setup and reason for the crash. However I had htop running in parallel and got a screenshot before system crash, attached below. I suspect the memory is not sufficient , but I dont know how much I need. Therefore, I am looking for : Memory requirements for my setup ( Scrapy + selenium + fireofox -headless Reason of crash How to improve the scraping process Alternatives to either of ( scrapy , selenium , firefox) SeleniumMiddleWare: import os, traceback from shutilwhich import which from scrapy import signals from scrapy.http import HtmlResponse from scrapy.utils.project import get_project_settings from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.firefox.options import Options SELENIUM_HEADLESS = False settings = get_project_settings() class SeleniumMiddleware(object): driver = None @classmethod def from_crawler(cls, crawler): middleware = cls() crawler.signals.connect(middleware.spider_opened, signals.spider_opened) crawler.signals.connect(middleware.spider_closed, signals.spider_closed) return middleware def process_request(self, request, spider): if not request.meta.get('selenium'): return self.driver.get(request.url) #if setting new cookies remove old if len(request.cookies): self.driver.implicitly_wait(1) self.driver.delete_all_cookies() #add only desired cookies if session persistence is requested request_cookies=[] if request.meta.get('request_cookies'): request_cookies=request.meta.get('request_cookies') for cookie in request.cookies: if cookie['name'] in request_cookies: print ' ---- set request cookie [%s] ---- ' % cookie['name'] new_cookie={k: cookie[k] for k in ('name', 'value','path', 'expiry') if k in cookie} self.driver.add_cookie(new_cookie) if request.meta.get('…
has comment: http://stackoverflow.com/comment/83874521
tagged with: scrapy
has comment: http://stackoverflow.com/comment/83879958
has comment: http://stackoverflow.com/comment/83874599
has comment: http://stackoverflow.com/comment/83866025

http://stackoverflow.com/comment/83967700
comment on: http://stackoverflow.com/q/48487171
type: Comment
type: QuestionComment
score: 0
has text: Notice at the end of the code, I dont know how to continue to actually execute `Delete`

http://stackoverflow.com/comment/83797820
comment on: http://stackoverflow.com/q/48404618
score: 3
has text: `server_name = input('Server: ')` `"ssh admin@{} switchshow".format(server_name)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83938802
has text: http://csmining.org/tl_files/Project_Datasets/r8%20r52/r8-test-all-terms.txt this link has some raw text of many documents. each document has following pattern: category<tab><sometext1> \n category<tab><sometext2> \n . . i want doc[1] = category<tab><sometext1> doc[2] = category<tab><sometext2> and so on
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48472346
type: Comment

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/48397197
tags question: http://stackoverflow.com/q/48389806

http://stackoverflow.com/comment/83816928
comment on: http://stackoverflow.com/q/48412858
has text: What's the programming question?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48432211
score: 0
has comment: http://stackoverflow.com/comment/83855718
has comment: http://stackoverflow.com/comment/83855655
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48432310
type: AnsweredQuestion
has title: Factorial number printing
has comment: http://stackoverflow.com/comment/83855608
tagged with: python
accepted answer: http://stackoverflow.com/a/48432310
has body: I'm a newbie at python. I started it not long a ago as a hobby after uni lecture hours. I found this exercise ( forgot where I got it from now) to do which is to print out the factorial numbers. Which I did. But, problem is that I'm tasked to manipulate line 3 so it only prints out the number 1 once at the start of the sequence and I'm having trouble with that. Please can any help? :) In advance sorry if the question wasn't worded as good as it could have been. a, b = 0, 1 while a &lt; 19: print b, a, b = a + 1, b * (a+1) Result: 1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000 20922789888000 355687428096000 6402373705728000

http://stackoverflow.com/comment/83859316
has text: Oops, yes. I meant to say 6 in #2 above. (background plus five numbers for a total of six). Does anyone know how to do a pull request to update the OpenCV documentation?
comment on: http://stackoverflow.com/q/48433745
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48350329
tagged with: gmail-api
has body: I'm experiencing a couple of issues with the API as I move emails between our application and the users inbox. These issues manifest when I send to a Gmail account from another Gmail account. However, these issues don't seem to manifest when working with an email generated by Google itself. I have samples in JSON format to allow others to reproduce the issue to the GitHub issue I created: https://github.com/google/google-api-python-client/issues/468 I use the "get" request (https://developers.google.com/gmail/api/v1/reference/users/messages/get) to obtain an email and I store it in a PostgreSQL database in two different columns with both raw and full formats. I use the "delete" request (https://developers.google.com/gmail/api/v1/reference/users/messages/delete) to remove the email from Gmail. I use use the raw format of the data along with the "insert" request (https://developers.google.com/gmail/api/v1/reference/users/messages/insert) to place the email back into the users inbox. When working with an email sent by Google to a users Gmail account it moves between our software and Gmail without an issue. When working with an email I send from my Gmail account to another Gmail account it gives me an error. If I send the JSON format of the email (the full format) I get a 400 error. If I send the raw format of the email I get a 404 not found error. Exact Errors: 404 - https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Not Found"> 400 - https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "'raw' RFC822 payload message string or uploading message via /upload/* URL required"> I'm using Python3.6 and Google API Client 1.6.4 Does anyone know if this is a bug in the client software or is there something else I need to consider when using this API to insert emails?
has title: 400, 404 Errors with Google API Python Client
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: gmail
score: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/79415985
favorite count: 0
type: Question

http://stackoverflow.com/q/48375006
has comment: http://stackoverflow.com/comment/83737112
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83737738
favorite count: 0
type: Question
has body: PLEASE IGNORE! Trying to use UpdateView to update a model object with name "Tag" Here is the model: NAME_REGEX = r'^[a-zA-Z0-9\s.\-]+$' class Tag(TimeStampModel): name = models.CharField(max_length=40, validators = [ RegexValidator(regex=NAME_REGEX, message='name must be alphanumeric, may contain - _', code='invalid tag name')], unique=True) slug = models.SlugField(max_length=60, unique=True, blank=True) text = models.TextField(blank=True) def __str__(self): return self.name def get_absolute_url(self): url = reverse('tags:tag_detail', kwargs={'slug':self.slug}) print('Tag *************** 010 ********************') print(url) return url def save(self, *args, **kwargs): self.slug = make_slug(self.name) super().save() I am able to create a Tag using CreateView, list the Tags using ListView and access the Tag detail using DetailView. I am also able to edit the tag using a function based view. However, it falls down with UpdateView. Here are the urls: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('tag_list/', views.TagListView.as_view(), name='tag_list'), path('tag_detail/<slug:slug>/', views.TagDetailView.as_view(), name='tag_detail'), path('create_tag/', views.CreateTagView.as_view(), name = 'create_tag'), path('update_tag/<slug:slug>/', views.UpdateTagView.as_view(), name = 'update_tag'), path('category_list/', views.CategoryListView.as_view(), name = 'category_list'), path('category_detail/<slug>/', views.CategoryDetailView.as_view(), name = 'category_detail'), ] In a template called "tag_detail.html" I provide a link that should take the user to an edit form as follows: {{ tag_dict.slug }} Edit Tag (I've printed the value of the slug before the link. That is not the problem. The slug value is correct. in this case slug = "brown") When I click the link it takes me to: http://localhost:8000/tags/update_tag/brown/ In this case the slug has the value "brown" I get the following error message: Reverse for 'update_tag' with no arguments not found…
has title: Django 2.0 UpdateView NoReverseMatch
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84179138
tagged with: django
has comment: http://stackoverflow.com/comment/83737262
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48487928
has comment: http://stackoverflow.com/comment/83968720
linked to: http://stackoverflow.com/q/5347065
tagged with: python
duplicate of: http://stackoverflow.com/q/5347065
type: AnsweredQuestion
has title: Interleave NumPy arrays
has comment: http://stackoverflow.com/comment/83968788
has answer: http://stackoverflow.com/a/48488404
accepted answer: http://stackoverflow.com/a/48488404
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/48488164
possible better answer: http://stackoverflow.com/a/48488164
has body: I'm trying to interleave arrays as below. import numpy as np x = np.array([1,2,3,4,5]) y = np.array([4,6,2,6,9], [5,9,8,7,4], [3,2,5,4,9]) Desired result: [[1,2,3,4,5], [4,6,2,6,9], [1,2,3,4,5], [5,9,8,7,4], [1,2,3,4,5],[3,2,5,4,9]] Is there an elegant way to do this? This is the way I wrote it, but I was looking to improve this line, data = np.array([x, y[0], x, y[1], x, y[2]]). Is there another way to write this? x = np.array([1,2,3,4,5]) y = np.array([[4,6,2,6,9], [5,9,8,7,4], [3,2,5,4,9]]) data = np.array([x, y[0], x, y[1], x, y[2]]) print(data)
score: 2
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83803205
has text: Running `sc.master` returns a URL.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48406749
type: QuestionComment

pos-tagger
tags question: http://stackoverflow.com/q/48360678
type: Tag
tag name: pos-tagger

http://stackoverflow.com/comment/83680537
has text: Would be better design to have it throw on error statuses, IMO. But there’s the “O” part.
type: Comment
comment on: http://stackoverflow.com/q/48347290
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83756012
score: 0
comment on: http://stackoverflow.com/a/48381421
type: AnswerComment
type: Comment
has text: seems only your python file and the terminal command is working. I cannot see any running server information. Have you started the server manually?. https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-rethinkdb-on-an-ubuntu-12-04-vps

http://stackoverflow.com/q/48418029
has body: I am interested in using a SparseTensor in tensorflow, however, I often get LookupError: No gradient defined for operation ... Apparently gradient computation is not defined for many ops for sparse tensors. Are there any easy ways to check if an op has a gradient or not before actually writing and running my code?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48421080
answer count: 1
has title: How can I tell if a tf op has a gradient or not?
upvote count: 10
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: autodiff
score: 10
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48421080

http://stackoverflow.com/a/48383448
answers question: http://stackoverflow.com/q/48382380
downvote count: 0
score: 3
type: Answer
has body: Regarding the cursor.commit() speed up that you are noticing: when you are using autocommit=True you are requesting the code to execute one database transaction per each of the insert. This means that the code resumes only after the database confirms the data is stored on disk. When you use cursor.commit() after the numerous INSERTs you are effectively executing one database transaction and the data is stored in RAM in the interim (it may be written to disk but not all at the time when you instruct the database to finalize the transaction). The process of finalizing the transaction typically entails updating tables on disk, updating indexes, flushing logs, syncing copies, etc. which is costly. That is why you observe such a speed up between the 2 scenarios you describe. When going the faster way please note that until you execute cursor.commit() you cannot be 100% sure that the data is in the database so there may be a need to reissue the query in case of an error (any partial transaction is going to be rolled back).
upvote count: 3

http://stackoverflow.com/q/48439821
tagged with: utf-8
upvote count: 4
score: 4
type: Question
has body: I use python 3.6 with msgpack==0.5.1 and msgpack_numpy==0.4.2. When trying to encode and decode a dict, the string needs to be handled using utf-8 to restore the dict's keys as strings (instead of binaries). For example: import msgpack d = {'key': None} binary = msgpack.packb(d) ret = msgpack.unpackb(binary) ret.keys() &gt;&gt;&gt; dict_keys([b'key']) ret = msgpack.unpackb(binary, encoding='utf-8') ret.keys() &gt;&gt;&gt; dict_keys(['key']) However, when using msgpack_numpy, passing encoding='utf-8' brakes the numpy decoding: import numpy as np import msgpack_numpy as m m.patch() d['key'] = np.arange(5) binary = msgpack.packb(d) ret = msgpack.unpackb(binary) ret.keys() &gt;&gt;&gt; dict_keys([b'key']) ret[b'key'] &gt;&gt;&gt; array([0, 1, 2, 3, 4]) ret = msgpack.unpackb(binary, encoding='utf-8') ret.keys() &gt;&gt;&gt; dict_keys(['key']) ret['key'] &gt;&gt;&gt; {'data': '\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00', 'kind': '', 'nd': True, 'shape': [5], 'type': '&lt;i8'} Is it possible to encode/decode numpy arrays using msgpack without replacing the dict's keys to binary?
tagged with: numpy
downvote count: 0
tagged with: encoding
has title: Decoding msgpack_numpy with utf-8 strings
has answer: http://stackoverflow.com/a/48440145
answer count: 1
tagged with: msgpack
favorite count: 0
linked to: http://stackoverflow.com/q/46960419
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48319949
accepted answer: http://stackoverflow.com/a/48440145
tagged with: python

http://stackoverflow.com/comment/83900879
type: Comment
score: 0
type: AnswerComment
has text: Yes, that is definitely possible. I missed the part where you wanted to capture all "instances" in the user string. @ospahiu has the solution in his answer. Using `(.*?)` instead of `(.*)` tells the regex engine to match *as few characters as possible*
comment on: http://stackoverflow.com/a/48452597

http://stackoverflow.com/q/48338687
score: 3
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83668427
has comment: http://stackoverflow.com/comment/83662775
has comment: http://stackoverflow.com/comment/83669304
has comment: http://stackoverflow.com/comment/83668603
has title: Speeding up this code snippet
has comment: http://stackoverflow.com/comment/83668242
has comment: http://stackoverflow.com/comment/83666874
has comment: http://stackoverflow.com/comment/83670814
has comment: http://stackoverflow.com/comment/83662968
has comment: http://stackoverflow.com/comment/83671131
upvote count: 3
has comment: http://stackoverflow.com/comment/83663357
answer count: 0
downvote count: 0
has body: I am rewriting one code from Matlab to Python. Matlab code looks like this: validIntSize = length(prices1)-125; %valid interval size interval720s = zeros(validIntSize,120+1); interval360s = zeros(validIntSize,60+1); interval180s = zeros(validIntSize,30+1); for i = 1:intJump:validIntSize interval180s(i,:) = [prices1(i:i+29),priceDiff(i+29)]; interval360s(i,:) = [prices1(i:i+59),priceDiff(i+59)]; interval720s(i,:) = [prices1(i:i+119),priceDiff(i+119)]; end It populates the rows of this huge matrix in a nutshell. I do this through append in Python and it takes way too long: intervals = [] for mean in self.means: intervals.append([]) for i in range(stop_point): for idx, mean in enumerate(self.means): intervals[idx].append(list(prices1[i:(i+mean)])+[price_diff[i+mean]]) I suspect that this is due to the append method that I am using? P.S. it takes about 2 seconds in Matlab and about 2 minutes in Python. P.P.S changing my code to list comprehension as suggested in the comments: for idx, k_mean in enumerate(self.k_means): intervals[idx] = [list(prices1[i:(i+k_mean)])+[price_diff[i+k_mean]] for i in range(stop_point)] does not speed up the code. Takes virtually the same amount of time.
has comment: http://stackoverflow.com/comment/83671102
has comment: http://stackoverflow.com/comment/83671319
has comment: http://stackoverflow.com/comment/83667524
favorite count: 0
tagged with: matlab
has comment: http://stackoverflow.com/comment/83671996
has comment: http://stackoverflow.com/comment/83662741
has comment: http://stackoverflow.com/comment/83662599
type: Question

http://stackoverflow.com/comment/83667081
type: QuestionComment
has text: Also, is the goal to compute some sort of distance/similarity between the two matrices? There are ways to that that do not involve finding a mapping from one set of indices to another.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48336165

http://stackoverflow.com/comment/83792109
score: 0
has text: OK, thanks. Is possible share your data, via wetransfer or something similar?
comment on: http://stackoverflow.com/a/48353780
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83939767
comment on: http://stackoverflow.com/a/48465822
type: AnswerComment
score: 2
has text: I also tried using np.exp() function, but it does not give me the accurate result. It gives me the output array with scientific value(including greater than 1). How is it possible? because probability is never greater than 1.
type: Comment

http://stackoverflow.com/q/48389060
has comment: http://stackoverflow.com/comment/83957978
tagged with: dll
score: 10
upvote count: 10
tagged with: python
has body: This may be a red herring, but my non-array version looks like this: C# using RGiesecke.DllExport; using System.Runtime.InteropServices; namespace Blah { public static class Program { [DllExport("printstring", CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.AnsiBStr)] public static string PrintString() { return "Hello world"; } } } Python import ctypes dll = ctypes.cdll.LoadLibrary(“test.dll") dll.printstring.restype = ctypes.c_char_p dll.printstring() I am looking for a printstrings, which would fetch a List&lt;string&gt; of variable size. If that's not possible, I will settle for a fixed-length string[].
has answer: http://stackoverflow.com/a/48481504
tagged with: ctypes
downvote count: 0
linked to: http://stackoverflow.com/q/26277322
has comment: http://stackoverflow.com/comment/83937363
type: UnansweredQuestion
answer count: 1
has title: Can one have Python receive a variable-length string array from C#?
favorite count: 0
has comment: http://stackoverflow.com/comment/83866409
type: Question
tagged with: c#

http://stackoverflow.com/a/48437319
answers question: http://stackoverflow.com/q/48432737
type: Answer
score: 0
has body: You can always use set intersection: list1 = [6, 7, 8, 9] list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007'] list1 = set(map(str, list1)) # {'6', '8', '9', '7'} list2[:] = [x for x in list2 if not list1.intersection(x)] print(list2) Which Outputs: ['0001', '0003', '0004', '0005']

http://stackoverflow.com/comment/83693596
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48353538
has text: [Potential dupe](https://stackoverflow.com/q/1856408/5267751)
score: 1

http://stackoverflow.com/q/48450692
answer count: 1
favorite count: 0
type: Question
tagged with: setup.py
tagged with: python
has title: Is __pycache__ crossplatform?
type: AnsweredQuestion
score: 3
has body: I have a folder of files /foo. This folder gets included as package_data in the setup.py for my Python package. When someone pip install's my package, they're able to download /foo to their computer. I've noticed though that when this happens, a __pycache__ folder gets included for all the *.py files in /foo. I'm not sure if this is created when my wheel is created, or when it's installed. I'm assuming it's during wheel creation though. Since my package should work on windows/osx/linux, will things break because of the __pycache__ folder? Is it platform specific, or will it work cross platform? Or does the folder get created during wheel installation and it doesn't matter anyway.
upvote count: 3
has answer: http://stackoverflow.com/a/48450872
accepted answer: http://stackoverflow.com/a/48450872
downvote count: 0
tagged with: setuptools

http://stackoverflow.com/a/48463727
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48463361
has comment: http://stackoverflow.com/comment/83920706
score: 1
has body: You can unpack the __dict__ on desired variables but the names must be the same: class A: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def function(x, y, z): print(x, y, z) tmp = a(1, 2, 3) func(**tmp.__dict__) #(1,2,3)
type: Answer

http://stackoverflow.com/comment/109055079
type: QuestionComment
has text: The answer is quite literally written in the error message..
score: 1
comment on: http://stackoverflow.com/q/48399498
type: Comment

http://stackoverflow.com/comment/83961342
comment on: http://stackoverflow.com/q/48484333
has text: This has been asked before... with a little modification you can use anything in https://stackoverflow.com/questions/48197234/explode-stack-a-series-of-strings.
score: 1
type: Comment
type: QuestionComment

lbph-algorithm
tags question: http://stackoverflow.com/q/48413398
tag name: lbph-algorithm
type: Tag

http://stackoverflow.com/a/48449296
downvote count: 1
answers question: http://stackoverflow.com/q/48449153
score: 0
type: Answer
has body: Your approach implies that the string will always be of that form, i.e., a dict with a single key-value pair, whose value is another dict with 2 string key-value pairs. In which case, I think regex is the most straight-forward way: &gt;&gt;&gt; s = "foo 1=bar 2=bar" &gt;&gt;&gt; import re &gt;&gt;&gt; pattern = r"(\w+)\s+(\w+)=(\w+)\s+(\w+)=(\w+)" &gt;&gt;&gt; K, k0, v0, k1, v1 = re.search(pattern, s).groups() &gt;&gt;&gt; {K:{k0:v0,k1:v1}} {'foo': {'1': 'bar', '2': 'bar'}}
has comment: http://stackoverflow.com/comment/83891300
upvote count: 1

algorithm
tags question: http://stackoverflow.com/q/48370560
tags question: http://stackoverflow.com/q/48358320
tags question: http://stackoverflow.com/q/48400602
tags question: http://stackoverflow.com/q/48369279
tags question: http://stackoverflow.com/q/48335994
type: Tag
tag name: algorithm
tags question: http://stackoverflow.com/q/48423348
tags question: http://stackoverflow.com/q/48487962
tags question: http://stackoverflow.com/q/48465407
tags question: http://stackoverflow.com/q/48354366
tags question: http://stackoverflow.com/q/48454826
tags question: http://stackoverflow.com/q/48368855
tags question: http://stackoverflow.com/q/48482444
tags question: http://stackoverflow.com/q/48352591
tags question: http://stackoverflow.com/q/48484525
tags question: http://stackoverflow.com/q/48454870
tags question: http://stackoverflow.com/q/48382873
tags question: http://stackoverflow.com/q/48362837
tags question: http://stackoverflow.com/q/48348480
tags question: http://stackoverflow.com/q/48342073
tags question: http://stackoverflow.com/q/48442775
tags question: http://stackoverflow.com/q/48366962
tags question: http://stackoverflow.com/q/48444590
tags question: http://stackoverflow.com/q/48429114
tags question: http://stackoverflow.com/q/48454604
tags question: http://stackoverflow.com/q/48460508
tags question: http://stackoverflow.com/q/48393707
tags question: http://stackoverflow.com/q/48383591
tags question: http://stackoverflow.com/q/48371219
tags question: http://stackoverflow.com/q/48386070
tags question: http://stackoverflow.com/q/48455182
tags question: http://stackoverflow.com/q/48464979
tags question: http://stackoverflow.com/q/48455837
tags question: http://stackoverflow.com/q/48360056
tags question: http://stackoverflow.com/q/48349630
tags question: http://stackoverflow.com/q/48370122
tags question: http://stackoverflow.com/q/48448584
tags question: http://stackoverflow.com/q/48350063
tags question: http://stackoverflow.com/q/48339523
tags question: http://stackoverflow.com/q/48410012
tags question: http://stackoverflow.com/q/48453373
tags question: http://stackoverflow.com/q/48382047
tags question: http://stackoverflow.com/q/48343033
tags question: http://stackoverflow.com/q/48460917
tags question: http://stackoverflow.com/q/48386293

http://stackoverflow.com/comment/83903968
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48453535
type: Comment
has text: Why doesn't that same slicing work if I create a DataFrame, using prn's index as the DataFrame index? I get an error.

http://stackoverflow.com/q/48460455
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49319925
tagged with: scikit-learn
favorite count: 0
has body: I want to implement lemmatization with Spacy package. Here is my code : regexp = re.compile( '(?u)\\b\\w\\w+\\b' ) en_nlp = spacy.load('en') old_tokenizer = en_nlp.tokenizer en_nlp.tokenizer = lambda string: old_tokenizer.tokens_from_list(regexp.findall(string)) def custom_tokenizer(document): doc_spacy = en_nlp(document) return [token.lemma_ for token in doc_spacy] lemma_tfidfvect = TfidfVectorizer(tokenizer= custom_tokenizer,stop_words = 'english') But this error message was occured when i run that code. C:\Users\yu\Anaconda3\lib\runpy.py:193: DeprecationWarning: Tokenizer.from_list is now deprecated. Create a new Doc object instead and pass in the strings as the `words` keyword argument, for example: from spacy.tokens import Doc doc = Doc(nlp.vocab, words=[...]) "__main__", mod_spec) How can i solve this problem ?
type: Question
has title: Overriding tokenizer of scikitlearn vectorizer with spacy
tagged with: tfidfvectorizer
has answer: http://stackoverflow.com/a/48530867
tagged with: python
answer count: 2
tagged with: spacy

http://stackoverflow.com/comment/83689236
type: Comment
type: AnswerComment
score: 1
has text: Not at all. Go for it ;-)
comment on: http://stackoverflow.com/a/48351218

http://stackoverflow.com/comment/83850756
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48378692
type: AnswerComment
has text: I thank you, the map is way better! And so is the navigation!

http://stackoverflow.com/comment/83817076
type: Comment
type: QuestionComment
has text: Sorry, what I meant to say is: matplotlib is turning the strings into x-coordinates by ordering all the strings, and returning the position of each one. The order of the line is unchanged, and still passes through the months in order
score: 0
comment on: http://stackoverflow.com/q/48413069

http://stackoverflow.com/a/48451673
has comment: http://stackoverflow.com/comment/83899742
accepted answer of: http://stackoverflow.com/q/48451425
has comment: http://stackoverflow.com/comment/83899565
answers question: http://stackoverflow.com/q/48451425
has comment: http://stackoverflow.com/comment/83897006
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83904888
has comment: http://stackoverflow.com/comment/83899562
upvote count: 1
has comment: http://stackoverflow.com/comment/83898614
has comment: http://stackoverflow.com/comment/83979139
has comment: http://stackoverflow.com/comment/83899644
type: Answer
has body: First you should write more readable python code: for x,y in data[0]: for x1, y1 in data[1]: if (x1 - x)**2 + (y1 - y)**2 &lt; somevalue: matches1.append((x,y)) matches2.append((x1,y1)) The you can vectorize the inner loop with numpy: for x,y in data[0]: x1, y1 = data[1].T indices = (x1 - x)**2 + (y1 - y)**2 &lt; somevalue matches.append(((x,y), data[1][indices]))

plaintext
tag name: plaintext
tags question: http://stackoverflow.com/q/48389084
type: Tag

http://stackoverflow.com/q/48462599
has comment: http://stackoverflow.com/comment/83918230
tagged with: math
tagged with: probability
answer count: 1
has title: How to perform a polynomial regression from N-dimensions set of samples in Python?
has comment: http://stackoverflow.com/comment/83918638
downvote count: 1
favorite count: 0
type: Question
has body: Here is the context of my problem: I have data samples from measurements. I'm reccording N properties. From those data I would like to perform a sensitivity analysis to focus my study on significant parameters. If I use the sobol method for example, I need to transform my data into a "model" to manipulate it (estimation from regression). As a result, here is my question: do you know a method (or a toolbox if it exists) to perform a N-dimensions polynomial/spline regression (not linear), in Python language? I heard something about a catmull-rom method, but I don't understand how to apply it. Thank you for your help!
tagged with: regression
linked to: http://stackoverflow.com/q/31406975
has comment: http://stackoverflow.com/comment/83918556
has comment: http://stackoverflow.com/comment/83918352
has answer: http://stackoverflow.com/a/78908170
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/78908170
tagged with: statistics
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83881148
type: QuestionComment
has text: @Nae I'm not sure how to go about doing this: `In which you can filter with if to run whichever methods based on that string`
comment on: http://stackoverflow.com/q/48444246
type: Comment
score: 0

http://stackoverflow.com/q/48477136
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48477221
has comment: http://stackoverflow.com/comment/83947442
tagged with: string
has comment: http://stackoverflow.com/comment/83947738
tagged with: mutagen
has body: I’m trying to figure out why two strings which appear to be equal in python are not equal. There appears to be a similar question posted Why are my two python strings not equal in my program but equal in the interpreter? but this does not address my problem. In this above post, the problem was apparently a new line at the end of one string but not the other. I’m writing a script to organize music files in my music collection. I’m using mutagen to read file metadata. I encounter the problem with .m4p files. I use import mutagen metadata = mutagen.File(“audio.m4p”) to get a dict of the file metadata. I view the keys in the dict by for key in metadata.keys(): print(key) which returns ----:com.apple.iTunes:tool ----:com.apple.iTunes:iTunNORM cnam cART aART cwrt calb cgen trkn disk cday cpil pgap apID cprt cnID rtng atID cmID plID geID sfID akID stik purd ----:com.apple.iTunes:iTunMOVI covr ‘cnam’ appears to be the index of the dict item containing the title of the file. However when I try to access it with mutagen[‘cnam’] I get KeyError: 'cnam'. Puzzled, I then assigned this key to a variable with the_key = list(metadata.keys())[2] to help gather information. I did the following: &gt;&gt;&gt; the_key=='cnam' False &gt;&gt;&gt; the_key[0]=='c' False &gt;&gt;&gt; the_key[1]=='n' True &gt;&gt;&gt; the_key[2]=='a' True &gt;&gt;&gt; the_key[2]=='m' False And below tested the equality of the copied value of the_key from the command line (left) and the manually typed version of what appears to be the key (right) &gt;&gt;&gt; 'cnam'=='cnam' True finding that they were equal. There seems to be some sort of text formatting issue going on that I don’t understand. I assume there are characters which look the same but actually aren’t, but I can’t seem to prove this by copying and pasting. My questions are: what is the issue here and how can I address it? I could imagine a work around involving manipulations of the dict or something else, but I would rather figure out the problem at …
type: Question
has answer: http://stackoverflow.com/a/48477194
score: 0
has comment: http://stackoverflow.com/comment/83947429
has title: Python - two strings appear to be equal but are not
tagged with: python
linked to: http://stackoverflow.com/q/36208446
has answer: http://stackoverflow.com/a/48477548

http://stackoverflow.com/a/48346904
score: 0
answers question: http://stackoverflow.com/q/48338727
has body: Think of removing current.next instead of removing current. This way if current.next is the last element, then current would be the new tail
type: Answer

http://stackoverflow.com/a/48444327
downvote count: 0
has comment: http://stackoverflow.com/comment/83880629
has comment: http://stackoverflow.com/comment/83880411
upvote count: 1
answers question: http://stackoverflow.com/q/48444218
has comment: http://stackoverflow.com/comment/83880176
accepted answer of: http://stackoverflow.com/q/48444218
type: Answer
has comment: http://stackoverflow.com/comment/83880142
has comment: http://stackoverflow.com/comment/83880626
has comment: http://stackoverflow.com/comment/83880073
has comment: http://stackoverflow.com/comment/83880307
score: 1
type: AcceptedAnswer
has body: Try this : Script1.py import time import otherscript variable_intermediate=1 while True: if variable_intermediate==1: from script2 import primitives, main main() # this is the line you're missing time.sleep(0.01)

http://stackoverflow.com/a/50579578
score: 49
upvote count: 49
has comment: http://stackoverflow.com/comment/129629986
type: Answer
accepted answer of: http://stackoverflow.com/q/48471648
answers question: http://stackoverflow.com/q/48471648
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110163932
has body: Since Pandas 0.23.0, the groupby method can now take a parameter observed which fixes this issue if it is set to True (False by default). Below is the exact same code as in the question with just observed=True added : import pandas as pd group_cols = ['Group1', 'Group2', 'Group3'] df = pd.DataFrame([['A', 'B', 'C', 54.34], ['A', 'B', 'D', 61.34], ['B', 'A', 'C', 514.5], ['B', 'A', 'A', 765.4], ['A', 'B', 'D', 765.4]], columns=(group_cols+['Value'])) for col in group_cols: df[col] = df[col].astype('category') df.groupby(group_cols, as_index=False, observed=True).sum()

http://stackoverflow.com/q/48474682
has answer: http://stackoverflow.com/a/48475602
type: Question
has comment: http://stackoverflow.com/comment/83942947
tagged with: python
type: UnansweredQuestion
has body: I have following model and after Migrate, I tried to add data through Admin page. However, I got the error NOT NULL constraint failed: HVAC_chiller.basicinfo_ptr_id. Referring to other stackoverflow, I understood problem. However, I cannot find any model which has attribute ptr. Does anyone know which attribute I should revise? models.py class BasicInfo(models.Model): title = models.CharField(max_length=100) manufacturer = models.CharField(max_length=50, blank = True) used_project = models.CharField(max_length=50, null=True,blank=True) cost=models.IntegerField(null = True, blank = True) url=models.URLField(null=True,blank=True) comment=models.TextField(null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class VRV(BasicInfo): InletT = models.FloatField(blank=True) OutletT = models.FloatField(blank=True) Capacity = models.IntegerField(blank=True) # Reference capacity COP = models.FloatField(blank=True) # Reference COP class CapacityFunction(models.Model): name=models.CharField(max_length=100, blank = True) c1=models.FloatField() c2=models.FloatField() c3 = models.FloatField() c4 = models.FloatField() c5 = models.FloatField() c6 = models.FloatField() minX= models.FloatField(blank=True) maxX = models.FloatField(blank=True) minY = models.FloatField(blank=True) maxY = models.FloatField(blank=True) def __str__(self): return self.name class EIRofTemp(CapacityFunction): pass class EIRofPLR(models.Model): name = models.CharField(max_length=100, blank=True) c1=models.FloatField() c2= models.FloatField() c3 = models.FloatField() c4 = models.FloatField(blank=True,null=True) minX = models.FloatField(blank=True) maxX = models.FloatField(blank=True) def __str__(self): return self.name class Chiller(VRV): CONDENSER_CHOICES = ( ('WaterCooled','WaterCooled'), ('AirCooled', 'AirCooled'), ('EvaporativelyCooled','EvaporativelyCooled') ) Condenser=models.CharField(max_length=15,choices=CONDENSER_CHOICES,default='Water') CHWFlowRa…
has title: Cannot find which model is getting error in Django
has comment: http://stackoverflow.com/comment/83942886
linked to: http://stackoverflow.com/q/25964312
score: 0
tagged with: django
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/84016050
type: QuestionComment
score: 0
has text: The question is how do you start you script / change the position than? Maybe Unity just lost focus again?
comment on: http://stackoverflow.com/q/48481100
type: Comment

http://stackoverflow.com/comment/83780639
score: 0
type: Comment
has text: please see the images, hope that helps
comment on: http://stackoverflow.com/a/48396131
type: AnswerComment

http://stackoverflow.com/comment/83698154
type: Comment
type: QuestionComment
has text: I see those extra characters are not part of the string they are just displayed in the terminal
score: 0
comment on: http://stackoverflow.com/q/48355713

http://stackoverflow.com/q/48434117
duplicate of: http://stackoverflow.com/q/285061
has comment: http://stackoverflow.com/comment/83860013
has comment: http://stackoverflow.com/comment/83859927
type: Question
has title: Overwriting instance variables by looping - is there a better way?
has body: I have a class that I'm trying to create objects for with a given variable adjusted by a loop. I'm struggling to explain so perhaps an example will help. The actual class is more complicated than the below, but the general idea is the same. The below method works, but feels very wrong. #!/usr/bin/python class Cuboid: # default values for new instances width = 123 height = 456 depth = 789 def __init__(self, var, val): exec("self." + var + " = val") # This feels un-pythony def area(self): return self.width*self.height*self.depth param_list=[ ['width',[5,10,15,20]], ['height',[5,10,15,20]] ] for param_i in range(0,len(param_list)): for val_i in range(0,len(param_list[param_i][1])): thisCuboid = Cuboid(param_list[param_i][0],param_list[param_i][1][val_i]) print(str(thisCuboid.area())) This gives the expected output: 1798920 3597840 5396760 7195680 485235 970470 1455705 1940940 Apologies if the question is poorly worded, I'm quite new to python. Please feel free to suggest better wording/ask for clarification! Note that the actual number of parameters that need changing is much more (something like a 20 dimensional cuboid to extend the analogy and the "area" depends on all 20 values), so the simple approach (create a list for each parameter and loop through the lists in turn, setting the named parameter accordingly) gets messy quickly (I need to add a loop for each of the parameters I want to change)
has comment: http://stackoverflow.com/comment/83859813
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48434210
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83859883
has comment: http://stackoverflow.com/comment/83859762
favorite count: 0
linked to: http://stackoverflow.com/q/285061
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83859781

http://stackoverflow.com/a/48348544
answers question: http://stackoverflow.com/q/48348134
has comment: http://stackoverflow.com/comment/83700898
downvote count: 0
type: Answer
upvote count: 1
has body: you can either do: r = tf.multiply(r_by_mean, mean, name = 'r') and p = tf.divide(1, tf.add(r_by_mean, 1), name = 'p') or you can (as suggested in Name the output of an expression in Tensorflow ): r = r_by_mean * mean r = tf.identity(r, name = 'r') and p = 1 / (r_by_mean + 1) p = tf.identity(p, name = 'p') Also, should i pack this method into a sub-class of "tf.contrib.distributions.NegativeBinomial" or should I create some utils.py file for it? I would not put it into any 'official' namespace such as tf but use your own file such that it is clear that this is functionality added by you / your project and not by Tensorflow (unless you need to fix / override some standard tensorflow functionality).
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48348134

http://stackoverflow.com/comment/83932226
type: Comment
comment on: http://stackoverflow.com/q/48468975
type: QuestionComment
score: 0
has text: @SaketMittal no it doesn't work :(

http://stackoverflow.com/comment/83938008
score: 0
has text: my file structure is films/templates/films/add_comment.html. If I do {{ film.title }} it displays the title of an individual film.
type: QuestionComment
comment on: http://stackoverflow.com/q/48471964
type: Comment

http://stackoverflow.com/q/48387874
answer count: 1
has comment: http://stackoverflow.com/comment/83771250
has answer: http://stackoverflow.com/a/48390917
has body: I am writing a Python program to generate line graphs of cryptocurrency prices. The goal is to be able to overlay multiple arbitrary pairs, i.e., BTC/USD + ETH/BTC, or BTC/USD + BCH/LTC + XRP/BTG, across the same horizontal timeline, similar to https://coinmarketcap.com/currencies/ethereum/ The bells and whistles in the above example are not required. It doesn't need click-to-zoom technology, the log-scale button, or fancy tool tips, if these features increase the implementation difficulty. Separate colors for each line would be helpful. This is the format of the data I have to work with: https://min-api.cryptocompare.com/data/histominute?fsym=BTC&amp;tsym=USD&amp;limit=60&amp;aggregate=1&amp;e=Coinbase https://min-api.cryptocompare.com/data/histominute?fsym=ETH&amp;tsym=BCH&amp;limit=30&amp;aggregate=1&amp;e=CCCAGG Currently, I have Anaconda 3.6 on Visual Studio, which according to https://docs.anaconda.com/anaconda/packages/py3.6_win-64.html should include multiple packages to plot this data without needing to manually install third party code through a command line. However, when I try to import any of them (i.e., matplotlib, bokeh, seaborn), I receive a "ModuleNotFoundError" message, so I'm not sure if my Anaconda is functioning properly. What is the easiest way to graph this data with Anaconda?
has title: Line Graphs in Anaconda
accepted answer: http://stackoverflow.com/a/48390917
favorite count: 0
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/83768254
tagged with: package
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
downvote count: 0
tagged with: linegraph
has comment: http://stackoverflow.com/comment/83771217
upvote count: 1
score: 1

http://stackoverflow.com/q/48472352
tagged with: python-3.x
has title: how do I find the temperature in the stuff written below?
answer count: 2
has answer: http://stackoverflow.com/a/48472947
upvote count: 0
type: UnansweredQuestion
has body: How do i find the temperature in degrees(F) from this openweathermap api: { coord: { lon: -73.36, lat: 40.81 }, weather: [ { id: 800, main: "Clear", description: "clear sky", icon: "01n" } ], base: "stations", main: { temp: 272.69, pressure: 1039, humidity: 63, temp_min: 270.15, temp_max: 275.15 }, visibility: 16093, wind: { speed: 2.6, deg: 190 }, clouds: { all: 1 }, dt: 1517014560, sys: { type: 1, id: 2100, message: 0.005, country: "US", sunrise: 1517054882, sunset: 1517090692 }, id: 0, name: "Huntington Station", cod: 200 }
tagged with: python
score: -3
tagged with: openweathermap
has answer: http://stackoverflow.com/a/48472413
downvote count: 3
favorite count: 0
type: Question

http://stackoverflow.com/q/48378866
has answer: http://stackoverflow.com/a/48381491
has title: Python list encoding and exporting to CSV issue
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/83745005
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: pandas
answer count: 1
upvote count: 1
has body: I am trying out Python scraping for the first time so I'm kind of patching up codes from all over the place. Right now I have encountered 2 issues that I do not know how to solve: My tbl list outputs to test.csv into only the first cell and is not delimited as well even though I've specified the conditions in .writer() The output into the CSV file has some encoding issues even though I don't see any when I output on my Python shell. I am currently using Python 2.7 import urllib2 from bs4 import BeautifulSoup import csv import pandas as pd site= "https://www.investing.com/currencies/usd-sgd-forward-rates" hdr = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(site,headers=hdr) page = urllib2.urlopen(req) soup = BeautifulSoup(page) px_table = str(soup.find('table', attrs={'id':'curr_table'})) print type(px_table) tbl = pd.read_html(px_table, encoding='utf-8') with open('test.csv', 'w') as myFile: wr = csv.writer(myFile, delimiter=' ') wr.writerow(tbl) output: Unnamed: 0 Name Bid Ask High Low Chg. Time 0 NaN USDSGDÂ ONÂ FWD -0.85 0.15 -0.29 -1.19 0.75 9:40:00 1 NaN USDSGDÂ TNÂ FWD -0.50 -0.45 -0.35 -0.45 -0.08 9:43:00 2 NaN USDSGDÂ SNÂ FWD -0.30 -0.20 -0.29 -0.21 0.10 9:42:00 3 NaN USDSGDÂ SWÂ FWD -2.17 -1.69 -1.80 -1.80 -0.16 9:42:00 4 NaN USDSGDÂ 2WÂ FWD -5.32 -1.72 -3.58 -3.44 -1.22 9:43:00 5 NaN USDSGDÂ 3WÂ FWD -6.15 -4.35 -5.12 -5.17 -0.30 9:42:00 6 NaN USDSGDÂ 1MÂ FWD -8.53 -7.74 -8.00 -8.10 -0.17 9:42:00 7 NaN USDSGDÂ 2MÂ FWD -15.81 -14.81 -14.75 -15.15 -0.25 9:43:00 8 NaN USDSGDÂ 3MÂ FWD -25.00 -24.07 -23.53 -24.07 -0.40 9:42:00 9 NaN USDSGDÂ 4MÂ FWD -35.72 -27.72 -32.16 -32.37 -1.18 9:43:00 10 NaN USDSGDÂ 5MÂ FWD -46.53 -35.47 -40.00 -40.96 -2.41 9:42:00 11 NaN USDSGDÂ 6MÂ FWD -50.83 -48.67 -48.75 -50.00 0.94 9:42:00 12 NaN USDSGDÂ 7MÂ FWD -65.77 -53.06 -59.68 -58.69 -3.27 9:43:00 13 NaN USDSGDÂ 8MÂ FWD -79.41 -59.65 -66.98 -69.70 -6.61 9:42:00 14 NaN USDSGDÂ 9MÂ FWD -84.51 -73.85 -74.05 -79.19 -1.84 9:42:00 15 NaN USDSGDÂ 10MÂ FWD -102.16 -75.06 -85.01 -87…
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48381491
has comment: http://stackoverflow.com/comment/83745219

http://stackoverflow.com/a/48372768
downvote count: 0
has body: from . import spam searches for module spam in the current (same level) package. For instance, if you have package like this: mypackage __init__.py foo.py spam.py , inside foo.py, you can import spam by using from . import spam. import spam searches for module spam in the module search path defined as a list sys.path. For instance, spam could be a builtin module, or the one you install using pip.
has comment: http://stackoverflow.com/comment/83732826
has comment: http://stackoverflow.com/comment/83733125
answers question: http://stackoverflow.com/q/48372742
has comment: http://stackoverflow.com/comment/83733088
type: Answer
has comment: http://stackoverflow.com/comment/83733000
has comment: http://stackoverflow.com/comment/83732725
score: 2
has comment: http://stackoverflow.com/comment/83732711
accepted answer of: http://stackoverflow.com/q/48372742
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48386112
linked to: http://stackoverflow.com/q/4779963
has answer: http://stackoverflow.com/a/48386257
type: UnansweredQuestion
tagged with: python
has body: I have created a python program which can detect the number of cars in a parking area(small scale MVP model)from a camera feed.I now need to create an Android application that shows the 'count' of the cars.The App continuously refresh by itself showing the latest 'count' value. The python program will run on my pc while the connection to the Cell phone is done via a usb or a WiFI hotspot .No online hosting is done. B.T.W I'm fairly new to developing Android application and I'm doing this as my final year project in college.
tagged with: data-connections
score: 3
tagged with: android
has title: How to connect Python program(on PC) to an Android App(on Mobile Phone)?
answer count: 1
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/91225772
favorite count: 0
type: Question

http://stackoverflow.com/q/48433878
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83859606
tagged with: python
score: 2
tagged with: atom-editor
has body: I'm using MacOS and Atom as a text editor to write and execute python scripts. I get the following error upon beginning to type (box in upper right corner appears w/ a split-screen that has a bunch of HTML appear) "Failed to spawn command python3. Make sure python3 is installed and on your PATH" any help on how to fix this? I can't type anything w/o it continually popping up and stopping me.
has title: Atom error: "Failed to spawn command python3: Make sure python3 is installed and on your PATH"
favorite count: 0
type: Question
upvote count: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/q/48461443
answer count: 2
has body: I am working on a binary text classification problem. As the classes are highly imbalanced, I am using sampling techniques like RandomOversampler(). Then for classification I would use RandomForestClassifier() whose parameters need to be tuned using GridSearchCV(). I am trying to create a pipeline to do these in order but failed so far. It throws invalid parameters. param_grid = { 'n_estimators': [5, 10, 15, 20], 'max_depth': [2, 5, 7, 9] } grid_pipe = make_pipeline(RandomOverSampler(),RandomForestClassifier()) grid_searcher = GridSearchCV(grid_pipe,param_grid,cv=10) grid_searcher.fit(tfidf_train[predictors],tfidf_train[target])
tagged with: random-forest
has answer: http://stackoverflow.com/a/48504102
accepted answer: http://stackoverflow.com/a/48504102
score: -3
tagged with: imblearn
tagged with: scikit-learn
tagged with: python
favorite count: 0
type: AnsweredQuestion
has title: pipeline for RandomOversampler, RandomForestClassifier & GridSearchCV
downvote count: 3
has answer: http://stackoverflow.com/a/59951236
possible better answer: http://stackoverflow.com/a/59951236
type: Question
tagged with: gridsearchcv
upvote count: 0

http://stackoverflow.com/a/48480737
type: Answer
has body: Try using 'full join' instead of inner join
answers question: http://stackoverflow.com/q/48480666
score: 0
has comment: http://stackoverflow.com/comment/83954559

http://stackoverflow.com/q/48333351
score: 0
has title: Interceptor or filter for rest endpoint
answer count: 1
upvote count: 1
tagged with: flask-restful
has body: I just complete my python flask 101 tutorial here. All went well and now I have flask server running successfully. However, now I want to add another rest endpoint /products that should return a sample list of products in this case. Since it is a jwt based implementation, I would like to make sure the user request is intercepted by /status or /auth api before it is executed. Is there a way to reuse current implementation rather than copy pasting the whole thing again for new rest endpoints?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48333451
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48333451
tagged with: python
tagged with: flask
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/83706846
type: AnswerComment
comment on: http://stackoverflow.com/a/48360039
type: Comment
has text: Ah! Obviously I was unaware of that behaviour of this method.
score: 0

http://stackoverflow.com/q/48396554
tagged with: anaconda
has title: Upgrade Tensorflow in Anaconda from 1.2.1 to 1.3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48397615
answer count: 2
has comment: http://stackoverflow.com/comment/83783495
score: 1
has body: I want to upgrade my tensorflow package in anaconda to at least 1.3, however, i receive following message after trying to run "conda update tensorflow": Solving environment: done # All requested packages already installed. Is there a way to use v1.3 on anaconda?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88543018
has answer: http://stackoverflow.com/a/55159172
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/a/48342521
type: Answer
has comment: http://stackoverflow.com/comment/83670284
has comment: http://stackoverflow.com/comment/83670469
downvote count: 0
score: 1
upvote count: 1
has body: You can flatten the nested list and apply the max function: my_list = [ ['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']] new_list = [i for x in my_list for i in x] max_val = max(new_list, key=lambda x:new_list.count(x)) Output: 'red'
has comment: http://stackoverflow.com/comment/83670648
has comment: http://stackoverflow.com/comment/83670327
answers question: http://stackoverflow.com/q/48342492
has comment: http://stackoverflow.com/comment/83670245

http://stackoverflow.com/comment/84006828
has text: and if you work with some decision making system you can see this amateur project: https://github.com/goodot/fuzzy-dm
type: Comment
comment on: http://stackoverflow.com/q/48478132
score: 0
type: QuestionComment

http://stackoverflow.com/a/48336208
downvote count: 0
has comment: http://stackoverflow.com/comment/83658296
has comment: http://stackoverflow.com/comment/83657767
answers question: http://stackoverflow.com/q/48336175
has comment: http://stackoverflow.com/comment/83658189
has comment: http://stackoverflow.com/comment/83658518
has comment: http://stackoverflow.com/comment/83657864
score: 3
has comment: http://stackoverflow.com/comment/83658416
has comment: http://stackoverflow.com/comment/83658069
accepted answer of: http://stackoverflow.com/q/48336175
type: Answer
has comment: http://stackoverflow.com/comment/83658156
has comment: http://stackoverflow.com/comment/83667621
has body: Why is the 'URL' column appearing first even though I defined the 'code' column first? This is a consequence of the fact that dictionaries are not ordered. Columns are read in and created in any order, depending on the random hash initialization of the python interpreter. What is wrong in my code when I am trying to remove all those rows where the 'URL' column does not have the pattern .de? You'd need to escape the ., because that's a special regex meta-character. df[df.code.eq(1) &amp; ~df.URL.str.contains(r'\.de$', case=True)] URL code 1 https://www.abc.fr/-de 1 This may not be succifient if de can be found anywhere after the TLD (and not at the very end). Here's a general solution addressing that limitation - p = '''.* # match anything, greedily \. # literal dot de # "de" (?!.* # negative lookahead \. # literal dot (should not be found) )''' df[df.code.eq(1) &amp; ~df.URL.str.contains(p, case=True, flags=re.VERBOSE)] URL code 1 https://www.abc.fr/-de 1
has comment: http://stackoverflow.com/comment/83658040
upvote count: 3
has comment: http://stackoverflow.com/comment/83657792
type: AcceptedAnswer

http://stackoverflow.com/a/48445249
accepted answer of: http://stackoverflow.com/q/48445154
has body: The error is saying that no Sales instance with pk=1 exists, as the error is likely thrown by get_object_or_404(Sales, pk=1). So you might want to check if that's really the case. You can try checking the pk of your instance by doing Sales.objects.first().pk to see. Update: How to make it dynamic Before going into that, it might be useful to understand what RESTful API endpoints are like. But briefly in this context you might want to have something like this # urls.py path('sale/', views.list_sale, name='list_sale'), path('sale/&lt;int:pk&gt;/', views.retrieve_update_delete_sale, name='retrieve_update_delete_sale') # names of the view can be whatever you want What happens here is that the pk argument is passed from the URL (&lt;int:pk&gt;) to the view as an argument in the function-based view. Accessing the arguments passed from URLs in your view def retrieve_update_delete_sale(request, pk): # &lt;-- you will be able to access it here """Edit an existing sales record.""" entry = get_object_or_404(Sales, pk=pk) # this is now dynamic! if request.method != 'POST': form = SalesForm(instance=entry) else: form = SalesForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('geo_gas:sales')) context = {'entry': entry, 'form': form} return render(request, 'ht/edit_sale.html', context) So now if you want to access the Sale instance with pk=1, all you need to do is visit the url with /sale/1/, and so on.
has comment: http://stackoverflow.com/comment/83949235
answers question: http://stackoverflow.com/q/48445154
has comment: http://stackoverflow.com/comment/83894648
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83902447
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83768300
type: QuestionComment
has text: There are ways. However the biggest question you are going to get in response to this request is, why did you think you need to do this? What is the problem you are actually trying to solve with this approach?
score: 6
type: Comment
comment on: http://stackoverflow.com/q/48390226

http://stackoverflow.com/a/48386104
type: Answer
has comment: http://stackoverflow.com/comment/83763232
has body: Remove exception handler from your Python script. Let Oracle database propagate it and you'll know what exactly caused the error, seeing its Oracle error code and message text. Then, if you aren't sure what these mean, come back here and post how Oracle responded.
answers question: http://stackoverflow.com/q/48385954
has comment: http://stackoverflow.com/comment/83760517
score: 0
has comment: http://stackoverflow.com/comment/83759770
has comment: http://stackoverflow.com/comment/83759714
has comment: http://stackoverflow.com/comment/83760560

http://stackoverflow.com/q/48370990
has answer: http://stackoverflow.com/a/48371044
has body: I would think that this is a basic task but most of my searches refer to adding zeros. I just want to strip the leading zeros from every file. I have files like "01.jpg, 02.jpg... 09.jpg". Chapter 9 of Automate the Boring Stuff talks specifically about using python for this task but does not go over any examples of this. import os, sys for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))): Well that is the start of what I have so far.
has answer: http://stackoverflow.com/a/48371373
score: 0
answer count: 2
type: Question
has title: Python: Removing Leading Zeros in the Filename of Every File in a Folder and Subfolders
tagged with: operating-system
tagged with: python
type: UnansweredQuestion
tagged with: module

http://stackoverflow.com/comment/83920754
score: 0
has text: parse the string instead of generating a string from a date. See linked answers
comment on: http://stackoverflow.com/q/48463780
type: Comment
type: QuestionComment

http://stackoverflow.com/a/78923357
score: 0
answers question: http://stackoverflow.com/q/48484776
has comment: http://stackoverflow.com/comment/139153152
type: Answer
has body: If someone has the error of mkvirtualenv not found then try this pip install virtualenv python -m venv venv then simple for mac Source venv/bin/activate for window Source venv/scripts/activate

http://stackoverflow.com/q/48395982
downvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48396895
has answer: http://stackoverflow.com/a/48397194
accepted answer: http://stackoverflow.com/a/48397194
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83779549
has title: generate array element if not exists in python
has comment: http://stackoverflow.com/comment/83779529
has answer: http://stackoverflow.com/a/48396045
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48396895
has body: What is the right way to check if element does not exist in Python ? The element is expected to be present most of the time, and if it is empty it is not an "error" and need to be processed normally: def checkElement(self, x, y): if not (self.map[x][y]): self.map[x][y] = 'element {}:{}'.format(x, y) return self.map[x][y]
score: 0
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/83779537

http://stackoverflow.com/comment/83655776
type: Comment
type: QuestionComment
has text: it throws this error `Expected to see 2 arrays but instead got the following list of 1 arrays: `
comment on: http://stackoverflow.com/q/48335212
score: 0

http://stackoverflow.com/q/48430023
has body: I have a dataframe generated by this code lcust = [1, 1, 1, 1, 2, 2, 3, 3, 3, 3] lmonth = [3, 4, 5, 9, 3, 5, 99, 101, 102, 105] lval1 = np.random.randint(2, 100, len(lmonth)).tolist() lval2 = np.random.rand(len(lmonth)).tolist() index_ = pd.MultiIndex.from_arrays([lcust, lmonth], names=('number','month')) df_ = pd.DataFrame(data=np.array([lval1, lval2]).T, columns = ['val1', 'val2'], index = index_) It looks as follows: val1 val2 number month 1 3 8.0 0.306048 4 45.0 0.151272 5 91.0 0.695793 9 50.0 0.927028 2 3 68.0 0.925622 5 49.0 0.402069 3 99 58.0 0.704662 101 93.0 0.759338 102 10.0 0.555434 105 39.0 0.030003 My question is whether there is a convenient way to get it to look like this: val1_y val2_y number month 1 3 8.0 0.306048 4 45.0 0.151272 5 91.0 0.695793 6 0.0 0.000000 7 0.0 0.000000 8 0.0 0.000000 9 50.0 0.927028 2 3 68.0 0.925622 4 0.0 0.000000 5 49.0 0.402069 3 99 58.0 0.704662 100 0.0 0.000000 101 93.0 0.759338 102 10.0 0.555434 103 0.0 0.000000 104 0.0 0.000000 105 39.0 0.030003 That is, I am looking for some code to fill out the missing months. In my database these values are just mmissing, but in actuality they should be zero and I need them for further calculations.You can think of number being a customer ID and month is the number of month the customer is a member. val1 and val2 are some values of interest. Please let me know in case you need further information. Many thanks c
possible better answer: http://stackoverflow.com/a/48430249
accepted answer: http://stackoverflow.com/a/48430651
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48430651
has answer: http://stackoverflow.com/a/48430249
tagged with: python
has title: generating missing rows in running index in pandas
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/48438765
has answer: http://stackoverflow.com/a/48439513
tagged with: django
tagged with: python
has body: I have 2 querysets from 2 different models like this: qs1=[[username1, lastname1, firstname1], [username2, lastname2, firstname2]........[username10, lastname10, firstname10]] qs2=[[username1, email1], [username2, email2]...[username10, email10]] I need to combine them to one and sorted by username. So it becomes like this: qs=[[username1, lastname1, firstname1, email1], [username2, lastname2, firstname2, email2]...[username10, lastname10, firstname10, email10]] qs1 and qs2 are querysets with multiple entries. I have code in view.py like this: usernames = C.objects.values('username') for username in usernames: try: qs1=A.objects.filter(username=username).values('username','lastname',' 'firstname') qs2=B.objects.filter(username=username).values('username','email') qs = sorted(chain(qs1, qs2)) return qs How do I combine qs1 and qs2 to qs?
score: 0
tagged with: django-queryset
has title: Combine two querysets
answer count: 1
has comment: http://stackoverflow.com/comment/83869246
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83868982

http://stackoverflow.com/comment/83679855
type: QuestionComment
comment on: http://stackoverflow.com/q/48346897
has text: @Norrius I've attached it.
score: 0
type: Comment

http://stackoverflow.com/comment/123110852
score: 0
type: Comment
comment on: http://stackoverflow.com/a/67054139
type: AnswerComment
has text: Thank you, sir! I was looking for the right reason for hours...

http://stackoverflow.com/a/64974246
has comment: http://stackoverflow.com/comment/125482029
score: 4
answers question: http://stackoverflow.com/q/48362621
type: Answer
upvote count: 4
downvote count: 0
has body: You need to perform 3 steps. (step 2 wasn't specified in other answers): 1 ) You add a uri to Authorized redirect URIs. 2 ) The Authorized redirect URIs uri is equal to the one you entered in Authorized JavaScript origins just with a closing slash /. 3 ) Download client_secret.json again and add it to your working direcory.

http://stackoverflow.com/q/48369578
has answer: http://stackoverflow.com/a/67266239
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48369727
accepted answer: http://stackoverflow.com/a/48369727
score: 5
has answer: http://stackoverflow.com/a/56280982
answer count: 5
has answer: http://stackoverflow.com/a/48369741
possible better answer: http://stackoverflow.com/a/48369741
downvote count: 1
upvote count: 6
has body: I have a dataframe of that contains some date objects. I need to convert to a json for use in JavaScript, which requires YYYY-MM-DD, but to_json() keeps adding a time component. I've seen a number of answers that convert to a string first, but this is part of a loop of about 15 queries each with many columns (simplified it for the SO question) and I don't want to hardcode each column conversion as there are a lot. import pandas as pd from datetime import date df = pd.DataFrame(data=date(year=2018, month=1, day=1)) print df.to_json(orient='records', date_format='iso', date_unit='s') Output: [{"0":"2018-01-01T00:00:00Z"}] Desired Output: [{"0":"2018-01-01"}]
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
has title: Prevent Pandas to_json() from adding time component to date object
has answer: http://stackoverflow.com/a/48369675
tagged with: python
tagged with: date
has comment: http://stackoverflow.com/comment/83726140

http://stackoverflow.com/comment/83819900
has text: You appear to have two different models files: `accounts/models.py` and `groups/models.py`. Is `User` defined in both files, or only one?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48415015
score: 0

http://stackoverflow.com/comment/123476851
type: Comment
comment on: http://stackoverflow.com/a/69852027
has text: You only need to pip install jupyter, the "notebook" will be ignored.. Don't see how this will solve OP's problem
score: 0
type: AnswerComment

http://stackoverflow.com/q/48468309
tagged with: django
has comment: http://stackoverflow.com/comment/83930284
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83930381
has comment: http://stackoverflow.com/comment/83930741
accepted answer: http://stackoverflow.com/a/48468503
has answer: http://stackoverflow.com/a/48468503
has comment: http://stackoverflow.com/comment/83930455
linked to: http://stackoverflow.com/q/3608487
tagged with: python
tagged with: dictionary
has title: How to create and save object in bulk for dictionary in Django
type: AnsweredQuestion
score: 2
upvote count: 2
has body: I want to create object in bulk for my models. My models is class Fees(models.Model): city = models.CharField(max_length=200, blank=True) contact = models.CharField(max_length=200, blank=True) class = models.CharField(max_length=200, blank=True) veg = models.BooleanField(default=False) rollno = models.CharField(max_length=200, blank=True) and my dictionary values are - response = { 'A101': { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', }, 'A102': { 'VEG': True, 'CONTACT': '54321', 'CLASS': 'SEVEN', 'ROLLNO': 'A102', 'CITY': 'GANGTOK', }, } Currently I am doing like as follow- def create_obj(response): for key, value in response.items(): fee_obj, _ = Fees.objects.get_or_create( rollno=key, defaults={ **change_value }) yield fee_obj So how can i create object in bulk. Any help would be appreciated.
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48372909
has answer: http://stackoverflow.com/a/48373026
tagged with: python
has body: I have a python code that has the following line: os.system("gnuplot data3.gnu") my data3.gnu has the following commands plot "data3.txt" pause -1 set terminal png set output 'plot10.png' so what i want it to do is show me the plot which it does then when i exit it saves the plot to a file called "plot10.png" it is ploting data3.txt fine however it is not saving the file. Thanks for the help
has title: Saving a graph with gnuplot on xubuntu
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48373026
favorite count: 0
type: Question
tagged with: gnuplot

http://stackoverflow.com/a/48368753
has comment: http://stackoverflow.com/comment/83728326
has body: In two lines: (assuming you already read the entire file to content) new_list = [int(i.split("|")[1]) for i in content.split("\n") if "|" in i] print "The average is " + str(sum(new_list) / float(len(new_list)))
answers question: http://stackoverflow.com/q/48368563
has comment: http://stackoverflow.com/comment/83728394
score: 0
has comment: http://stackoverflow.com/comment/83728052
has comment: http://stackoverflow.com/comment/83730076
type: Answer
has comment: http://stackoverflow.com/comment/83730223

http://stackoverflow.com/a/48364165
type: Answer
has comment: http://stackoverflow.com/comment/83715354
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83715157
has comment: http://stackoverflow.com/comment/83715329
has comment: http://stackoverflow.com/comment/83715274
has body: There's no reason to expect the capacity to be 8. There's also no reason to expect the capacity to be 10 again if you run this on a new Python version, or a different implementation (like PyPy). The fact that it happened to be 10 is an implementation detail you should not rely on and not expect to remain unchanged. The capacity happened to be 10 because remove-ing down to less elements than half the capacity triggered a shrinkage, and (for now, on modern CPython) the resize routine calculates the overallocation as new_allocated = (newsize &gt;&gt; 3) + (newsize &lt; 9 ? 3 : 6); When newsize is 7, this produces a 3-element overallocation, for a new capacity of 10.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48363766
downvote count: 0
answers question: http://stackoverflow.com/q/48363766

http://stackoverflow.com/comment/83808015
has text: @Dhanabalan, please try to attach all details in a single shot to your post, try Karakfa and mine code and let us know how it goes then.
type: Comment
comment on: http://stackoverflow.com/a/48409024
score: 0
type: AnswerComment

http://stackoverflow.com/q/48388550
tagged with: beautifulsoup
score: 0
has comment: http://stackoverflow.com/comment/83764899
has comment: http://stackoverflow.com/comment/83767237
has comment: http://stackoverflow.com/comment/83765069
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/83813355
has comment: http://stackoverflow.com/comment/83765871
has body: This simple scanner depicted below is designed to find the tag which displays a stock's percent change for the day on yahoo finance. When I examine the source code of the webpage I can easily identify that there is only one span tag which has a class equal to what I have written below. The tags class either reads $dataGreen if the price has gone up, or $dataRed if it has gone down. I am using iterators in many other places on this webpage, all are formatted exactly the same way, and are functional. But for some reason, no amount of tweaking here will give me a result. It is as though this tag cannot be detected. I haven't a clue why this tag can be found by ctrl+f but not .find_all() Any guidance you can give me would be most appreciated. Here's my code. import bs4 as bs from urllib.request import urlopen import urllib.request, urllib.error url = str('https://finance.yahoo.com/quote/ABEO?p=ABEO') source = urllib.request.urlopen(url, timeout=30).read() soup = bs.BeautifulSoup(source,'lxml') for row in soup.find('span',{"class":"Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataGreen)"}): print (1) for row in soup.find('span',{"class":"Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataRed)"}): print (2) Edit: I've saved the source to a .txt and poured through it for the tag, though I couldnt detect it with ctrl+feither. When I compare what I found in the .txt to what I had pulled from the webpage, it differs. My problem seems to be solved, but I would love for someone to explain why that worked. Trsdu(0.3s) Fw(500) Fz(14px) C($dataRed)
tagged with: urllib
type: Question
answer count: 0
has title: Cannot get Beautifulsoup to recognize tag
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83764825

http://stackoverflow.com/q/48413440
has body: def test_dates(self): days = (date.today() + timedelta(days=2)) - date.today() print days if days &gt;= -2 and days &lt;= 4: print days How do I check that difference between two dates is in the range -2 to 4 days?
type: Question
has answer: http://stackoverflow.com/a/48413482
has answer: http://stackoverflow.com/a/48413473
has answer: http://stackoverflow.com/a/48413487
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48413513
tagged with: python
answer count: 4
score: 0
has title: Test dates using date.today()?
tagged with: date

http://stackoverflow.com/comment/83771773
score: 0
comment on: http://stackoverflow.com/q/48391911
type: Comment
has text: @juanpa.arrivillaga yes sorry It was a mistake, I corrected the question
type: QuestionComment

http://stackoverflow.com/comment/83806610
comment on: http://stackoverflow.com/a/48408216
score: 0
type: Comment
has text: yeah, I was thinking that it shouldn't have changed the dimensions at all as it was just deciding which pooling technique to use. okay, edited.
type: AnswerComment

http://stackoverflow.com/comment/83893170
score: 0
comment on: http://stackoverflow.com/q/48448995
type: Comment
type: QuestionComment
has text: Without internet, your only option would be IronPython. Here's a link with an example of how to read values returned from a Python script in c#. It details how to do it with native C# code, or the fully managed IronPython library (I recommend IronPython because it can catch and return exceptions in your python script): https://medium.com/@dpursanov/running-python-script-from-c-and-working-with-the-results-843e68d230e5

http://stackoverflow.com/a/48343515
has body: I would change the structure of the code. Below is what I would do. Just curious, why do you want to use multi-processing on foo_2 vice foo_1? from multiprocessing import Pool # method broken out def foo_2(j, i): # blah blah blah return i + j def foo_1(i): count = 1 for something: # blah blah blah h=0 while len()&lt;count: return_foo_2 = foo_2(j, i) h = h+1 count +=1 if __name__ == '__main__': pool = Pool(4) # you will have to create a list of tasks to run # in your multiprocessing pool list_tasks = [(range(), range())] pool.imap_unordered(foo_2, list_tasks): pool.close() pool.join()
answers question: http://stackoverflow.com/q/48339871
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/83934166
has text: Related: https://stackoverflow.com/questions/35983172/why-does-sqlalchemy-boolean-column-fail-with-typeerror-an-integer-is-required
type: QuestionComment
comment on: http://stackoverflow.com/q/48462859
score: 0
type: Comment

http://stackoverflow.com/comment/83920053
type: Comment
type: AnswerComment
score: 0
has text: @RobertBailey, so it solved your problem described in question? If yes -- check a tick near my answer, please. According to your comment -- it's another question.
comment on: http://stackoverflow.com/a/48458527

datamodel
tag name: datamodel
tags question: http://stackoverflow.com/q/48430297
type: Tag

http://stackoverflow.com/comment/83894063
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48450527
has text: Thanks! If you want to write it in an answer, I'll accept it.
score: 0

http://stackoverflow.com/comment/83896395
type: AnswerComment
has text: why not `if result is None:` ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48451713

http://stackoverflow.com/comment/83866594
comment on: http://stackoverflow.com/q/48437673
type: Comment
type: QuestionComment
score: 3
has text: Your question shows no research done, we really don't appreciate these kind of questions. Please take a tour: https://stackoverflow.com/tour

http://stackoverflow.com/comment/83903603
type: QuestionComment
score: 0
has text: @alvits sorry for noob question but how should I go about finding all of that. Are there commands I could enter in the command line to get that info?
comment on: http://stackoverflow.com/q/48455129
type: Comment

http://stackoverflow.com/a/48362607
type: Answer
has comment: http://stackoverflow.com/comment/83721877
score: 2
answers question: http://stackoverflow.com/q/48362587
upvote count: 3
has comment: http://stackoverflow.com/comment/83722683
downvote count: 1
has body: You can do this with a list comprehension. It iterates over the list of tuples and checks that all of the elements of the tuple are less than or equal to the corresponding elements in f. You can compare tuples directly for element-wise inequality [t for t in wk if all(x&lt;=y for x,y in zip(t,f)] # returns: [(1, 3, 8), (1, 1, 1)]

http://stackoverflow.com/comment/83878870
type: QuestionComment
type: Comment
has text: What architecture does your network have?
score: 0
comment on: http://stackoverflow.com/q/48443389

http://stackoverflow.com/q/48449153
has comment: http://stackoverflow.com/comment/83890982
favorite count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/48449713
has body: Is there a more elegant way to achieve the same result using dictionary comprehension? For clarification the format of s will always be "foo 1=bar 2=bar" s = "foo 1=bar 2=bar" x = s.split() for i in x: if '=' not in i: d = { i:{ x[1].split('=')[0]: x[1].split('=')[1], x[2].split('=')[0]: x[1].split('=')[1] } } d Out[27]: {'foo': {'1': 'bar', '2': 'bar'}}
has title: Python 3: Is there an elegant way to turn a string into a 2 dimensional dict using dictionary comprehension?
has comment: http://stackoverflow.com/comment/83892650
has comment: http://stackoverflow.com/comment/83891072
downvote count: 2
has comment: http://stackoverflow.com/comment/83890944
possible better answer: http://stackoverflow.com/a/48449296
accepted answer: http://stackoverflow.com/a/48450379
tagged with: python
has comment: http://stackoverflow.com/comment/83891089
has answer: http://stackoverflow.com/a/48449296
answer count: 4
has answer: http://stackoverflow.com/a/48450379
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48449666
upvote count: 1

http://stackoverflow.com/comment/83903441
type: Comment
has text: Wow that makes so much sense (sorry my second comment occurred before I saw your first reply) Thank you so much. I believe I was overthinking things a bit there
comment on: http://stackoverflow.com/a/48455137
type: AnswerComment
score: 0

http://stackoverflow.com/a/48372696
type: Answer
answers question: http://stackoverflow.com/q/48367861
score: 0
has body: A relatively simple parser for your string can be built and the passed directly to pandas.DataFrame like: Code: def meal_string_parser(meal_string): category = '' meal = [] price = 0 for word in meal_string.split(): if word: try: price = float(word) yield category, ' '.join(meal), price meal = [] except ValueError: # this is not a number, so not a price if word.upper() == word and word.isalnum(): # found category category = word else: meal.append(word) if meal: yield category, ' '.join(meal), price Test Code: meals_string = """ APPETIZERS Southern Fried Quail with Greens,Huckleberries,Pecans &amp; Blue Cheese 14.00 Park Avenue Cafe Chopped Salad Goat Feta Cheese,Nigoise Olives,Marinated White 13.00 ENTREES Horseradish Crusted Canadian Salmon,Potato Fritters, Marinated Cucumbers,Chive Vinaigrette 27.00 Sautéed Prawns with Mushroom Tortellini,Grilled Tomato Vinaigrette &amp; Sweet Corn 29.50 """ import pandas as pd df = pd.DataFrame(meal_string_parser(meals_string), columns='Category Meal_name Price'.split()) print(df) Results: Category Meal_name Price 0 APPETIZERS Southern Fried Quail with Greens,Huckleberries... 14.0 1 APPETIZERS Park Avenue Cafe Chopped Salad Goat Feta Chees... 13.0 2 ENTREES Horseradish Crusted Canadian Salmon,Potato Fri... 27.0 3 ENTREES Sautéed Prawns with Mushroom Tortellini,Grille... 29.5

http://stackoverflow.com/comment/99505072
type: AnswerComment
comment on: http://stackoverflow.com/a/56447722
type: Comment
has text: Hey Aaron, thanks for the heads-up and the link. I've added a description of how my code works to avoid having a single link as an answer. I still think my answer is valid because it a) provides a direct solution to the problem and b) I'm linking to open-source code, I'm not selling a product. I hope by providing a description I'm not violating any rules anymore.
score: 0

http://stackoverflow.com/q/48411801
answer count: 3
downvote count: 3
tagged with: regex
has comment: http://stackoverflow.com/comment/83813601
has title: Extract everything before a particular string in python
has answer: http://stackoverflow.com/a/48411895
type: Question
has answer: http://stackoverflow.com/a/48412156
has comment: http://stackoverflow.com/comment/83814279
has comment: http://stackoverflow.com/comment/83813660
possible better answer: http://stackoverflow.com/a/48411895
tagged with: python
has comment: http://stackoverflow.com/comment/83813457
favorite count: 0
has answer: http://stackoverflow.com/a/48411833
accepted answer: http://stackoverflow.com/a/48411833
type: AnsweredQuestion
upvote count: 3
score: 0
has body: Let's say I have a string s = 'ab@cD!.2e.cp' I want to extract only ab@cD!.2e out of it. I am trying this: print(re.search(r'^(.*?)\.cp',s).group()) But still getting the output as ab@cD!.2e.cp. Can someone please tell me where I am doing it wrong and what should be the correct regex for this?

http://stackoverflow.com/a/48403808
has comment: http://stackoverflow.com/comment/83895476
type: Answer
answers question: http://stackoverflow.com/q/48376732
score: 0
has body: You didn't try very hard or at least didn't provide your attempts at cracking this. def filterFileLines(filterFunction): with open("sample.txt") as file: # discard_first_line file.readline() for line in file: id, type = line.strip().split(' ') if filterFunction(id, type): print (line, end='') print('') def isTypeA(a, b): return b == 'A' def isNotTypeA(a, b): return not isTypeA(a, b) if __name__ == '__main__': print('Lines with type == "A"') filterFileLines(isTypeA) print('lines with type not "A"') filterFileLines(isNotTypeA)

http://stackoverflow.com/a/48478498
score: 2
answers question: http://stackoverflow.com/q/48478357
has body: To get the first number of the number-range we'll use split('-') and get its first value. Then we convert it to an integer. To look up numbers from the second object we'll convert it to a dictionary. Here's the resulting code: a = {'0-4': 0, '86-90': 0, '30-34': 0, '35-39': 0, '25-29': 0, '10-14': 0, '76-80': 0, '40-44': 0, '5-9': 0, '50': 0, '61-65': 0, '91-95': 0, '51-55': 0, '96-100': 0, '81-85': 0, '56-60': 0, '15-19': 0, '66-70': 0, '20-24': 0, '45-49': 0, '71-75': 0} b = [(0, 4L), (5, 2L), (10, 2L), (15, 4L), (20, 5L), (25, 4L), (30, 4L), (35, 2L), (40, 1L), (45, 1L), (51, 7L), (56, 2L), (61, 4L), (66, 4L), (71, 4L), (76, 4L), (81, 8L), (86, 2L), (91, 1L), (96, 2L)] b2 = dict(b) c = {k: b2.get(int(k.split('-')[0]), 0) for k, v in a.items()}
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83951120
type: Answer
accepted answer of: http://stackoverflow.com/q/48478357

bigdata
tags question: http://stackoverflow.com/q/48393979
tags question: http://stackoverflow.com/q/48411339
tags question: http://stackoverflow.com/q/48477154
type: Tag
tags question: http://stackoverflow.com/q/48430916
tag name: bigdata

http://stackoverflow.com/comment/83701619
score: 0
type: AnswerComment
has text: @thib is this on the server script or the client script?
comment on: http://stackoverflow.com/a/48349031
type: Comment

http://stackoverflow.com/comment/84290597
comment on: http://stackoverflow.com/a/48465221
type: Comment
has text: @ReblochonMasque I opened an issue there, we will see what happens next. I will report news here as edit to the OP.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83720301
comment on: http://stackoverflow.com/q/48365802
type: Comment
type: QuestionComment
score: 0
has text: @Cyzanfar I tried different commands such as `conda install wikipedia-api`, `conda install -c akode wikipedia` etc. However it returns `PackageNotFoundError: Packages missing in current channels:`. Can you please tell me how to install wikipedia api in conda??

http://stackoverflow.com/comment/83958436
has text: `$ which python /usr/bin/python `
score: 0
comment on: http://stackoverflow.com/a/48482665
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85292371
type: AnswerComment
has text: That's strange, because I have a stack of dicoms that I know are 3 channels, 180 images in the stack, and has a height of 480 pixels and a width of 680 pixels. Then, `.shape` gives me `(3, 180, 480, 640)`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48470192

http://stackoverflow.com/comment/83738811
comment on: http://stackoverflow.com/a/48375935
has text: Yes, so it _is_ a stack! Your answer tells me exactly what the bytecode is doing, so thanks, your answer is great.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/83656598
score: 0
has text: You could [`inspect` who the caller was](https://stackoverflow.com/questions/2654113/python-how-to-get-the-callers-method-name-in-the-called-method) and adapt accordingly
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48335791

http://stackoverflow.com/a/48335883
has comment: http://stackoverflow.com/comment/83656821
has comment: http://stackoverflow.com/comment/83687885
has comment: http://stackoverflow.com/comment/83677153
has comment: http://stackoverflow.com/comment/83657744
has comment: http://stackoverflow.com/comment/83658352
type: Answer
has comment: http://stackoverflow.com/comment/83658530
answers question: http://stackoverflow.com/q/48335474
has comment: http://stackoverflow.com/comment/83658599
score: 0
has body: To be able to exec a file it must have the execute bit set (chmod +x your_file.py). Also, since it is a script, you'll need to make the first line of your script a shebang: #!/usr/bin/env python3 As I mentioned in the comments, you really shouldn't need to be exec-ing yourself. What you should probably be doing is something like this: from time import sleep if __name__ == '__main__': while True: xml = request_train_status() print(get_red_status(xml)) print(get_blue_status(xml)) # etc. sleep(1) # Don't constantly slam the API with requests Had a few minutes so I refactored your code a tad. You had a lot of duplicated logic. Made it very difficult to reason about what was happening when and how you could repeat your process. I pulled out the GPIO stuff, request to the API, and pulling the status out of the XML into separate functions. I also introduced an Enum for line colors and namedtuple for the status to make things more obvious: from collections import namedtuple from enum import Enum import RPi.GPIO as GPIO from time import sleep from urllib import request LIGHT_1 = 5 def setup_gpio(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(LIGHT_1, GPIO.OUT) GPIO.output(LIGHT_1, 0) def set_light(on): GPIO.output(LIGHT_1, on) def request_train_status(): req = request.urlopen('http://lapi.transitchicago.com/api/1.0/' + 'ttpositions.aspx?key=' + '5c78297a2f28427e9b87435118367766&amp;' + 'rt=red,blue,G,pink,Brn,Org,P,Y') return BeautifulSoup(req, 'xml') class Line(Enum): BLUE = 'blue' GREEN = 'g' PINK = 'pink' BROWN = 'brn' ORANGE = 'org' PURPLE = 'p' YELLOW = 'y' LineStatus = namedtuple('LineStatus', ('approaching', 'num', 'station', 'direction')) def get_line_status(xml, line): color = line.value train = xml.select_one(f'route[name="{color}"] train') approaching = train.select_one('isApp').get_text() == '1' num = train.select_one('rn').get_text() station = train.select_one('nextStaNm').get_text() direction = train.select_one('destNm').get_text() return LineStat…
has comment: http://stackoverflow.com/comment/83656948
has comment: http://stackoverflow.com/comment/83657508
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48335474
has comment: http://stackoverflow.com/comment/83657698
has comment: http://stackoverflow.com/comment/83657821

http://stackoverflow.com/comment/83927444
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48454717
has text: I tried the dot product operation and can verify the resulting transform was ill formed. I did find a solution though which I've posted.
type: Comment

http://stackoverflow.com/comment/83730245
score: 0
has text: It's easy to count the number of NaN per row or column is easy in numpy. But choosing the optimal mix of row/column deletes may be a search problem, which is not a numpy strong point. I did a bit with the [tag:hungarian-algorithm] a while back, https://stackoverflow.com/questions/43162526/performance-of-the-linear-sum-assignment-algorithm.
comment on: http://stackoverflow.com/q/48355644
type: Comment
type: QuestionComment

http://stackoverflow.com/a/78251548
type: Answer
score: 0
has body: In vobject, the value of an EXDATE property is a list of datetime values. So, instead of: ev.instance.vevent.add("exdate").value = vevent.dtstart.value your code should do something like: ev.instance.vevent.add("exdate").value.append(vevent.dtstart.value) This avoids the exception reported during serialization.
answers question: http://stackoverflow.com/q/48365080

http://stackoverflow.com/comment/83872213
has text: Possible duplicate of [Having Django serve downloadable files](https://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files)
score: 0
comment on: http://stackoverflow.com/q/48440502
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48357646
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83703168
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83703935
has body: I am using Google App Engine to deploy a very simple App which takes user's email and send them email daily (at the same time, say around 10 am). I am using the schedule with the following code after user submit an email address: class Submission (Handler): def get(self): self.render('submitted.html') schedule.every().day.at("10:00").do(send_email) while True: print "The email is working" schedule.run_pending() time.sleep(1) But when deploy this code, the page ("submitted.html") can never be loaded (maybe because the while loop I think). I am new to programming, not really sure whether this makes sense. But generally, how to deploy a Python code which can keep running and send the regular email out?
has title: how to send DAILY email using python at Google App Engine
score: 0
tagged with: google-app-engine
tagged with: email
tagged with: python

http://stackoverflow.com/comment/83709118
score: 0
has text: The title is good for a chatbox, not for a knowledge database.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48360650

http://stackoverflow.com/q/48462408
favorite count: 0
type: Question
tagged with: subset
accepted answer: http://stackoverflow.com/a/48462648
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48462648
has title: pandas: rapidly calculating sum of column with certain values
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: I have a pandas dataframe and I need to calculate the sum of a column of values that fall within a certain window. So for instance, if I have a window of 500, and my initial value is 1000, I want to sum all values that are between 499 and 999, and also between 1001 and 1501. This is easier to explain with some data: chrom pos end AFR EUR pi 0 1 10177 10177 0.4909 0.4056 0.495988 1 1 10352 10352 0.4788 0.4264 0.496369 2 1 10617 10617 0.9894 0.9940 0.017083 3 1 11008 11008 0.1346 0.0885 0.203142 4 1 11012 11012 0.1346 0.0885 0.203142 5 1 13110 13110 0.0053 0.0567 0.053532 6 1 13116 13116 0.0295 0.1869 0.176091 7 1 13118 13118 0.0295 0.1869 0.176091 8 1 13273 13273 0.0204 0.1471 0.139066 9 1 13550 13550 0.0008 0.0080 0.007795 10 1 14464 14464 0.0144 0.1859 0.161422 11 1 14599 14599 0.1210 0.1610 0.238427 12 1 14604 14604 0.1210 0.1610 0.238427 13 1 14930 14930 0.4811 0.5209 0.500209 14 1 14933 14933 0.0015 0.0507 0.044505 15 1 15211 15211 0.5371 0.7316 0.470848 16 1 15585 15585 0.0008 0.0020 0.002635 17 1 15644 15644 0.0008 0.0080 0.007795 18 1 15777 15777 0.0159 0.0149 0.030470 19 1 15820 15820 0.4849 0.2714 0.477153 20 1 15903 15903 0.0431 0.4652 0.349452 21 1 16071 16071 0.0091 0.0010 0.011142 22 1 16142 16142 0.0053 0.0020 0.007721 23 1 16949 16949 0.0227 0.0159 0.038759 24 1 18643 18643 0.0023 0.0080 0.009485 25 1 18849 18849 0.8411 0.9911 0.170532 26 2 30923 30923 0.6687 0.9364 0.338400 27 2 20286 46286 0.0053 0.0010 0.006863 28 2 21698 46698 0.0015 0.0010 0.002566 29 2 42159 47159 0.0083 0.0696 0.067187 So I need to subset based on the first two columns. For example, if my window = 500, my chrom = 1 and my pos = 15500, I will need to subset my df to include only those rows that have chrom = 1 and 15000 > pos &lt; 16000. I would then like to sum the AFR column of this subset of data. Here is the function I have made: #vdf is my main dataframe, #polyChrom is the chromosome to subset by, #polyPos is the position to subset by. #Distance is how far the window should …
answer count: 1

http://stackoverflow.com/comment/83872947
type: QuestionComment
score: 0
has text: @DenizKaplan `profiles` is already in my `INSTALLED_APPS`, along with my 8 other apps. They all fail (all 9 apps get the Import Error).
comment on: http://stackoverflow.com/q/48440753
type: Comment

http://stackoverflow.com/a/52541212
downvote count: 0
answers question: http://stackoverflow.com/q/48348611
score: 2
type: Answer
has body: Installing numpy+mk from this link: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy and cvxopt with wheel file found in this link should solved problem: https://www.lfd.uci.edu/~gohlke/pythonlibs/#cvxopt
upvote count: 2

http://stackoverflow.com/comment/83664189
score: 0
comment on: http://stackoverflow.com/q/48336715
type: Comment
has text: @Nishant Correct. But I could not find any such mechanism in python. Please let me know if you know of any way to interrup the thread in python.
type: QuestionComment

http://stackoverflow.com/a/48428269
type: Answer
has comment: http://stackoverflow.com/comment/83847859
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83847967
has body: Option 1 Specialized solution using diff. Get's at the final desired output. df.mask(df.diff().eq(0)) 0 1 2 0 1.239916 1.109434 0.305490 1 0.248682 1.472628 0.630074 2 -0.028584 -1.116208 0.074299 3 -0.784692 -0.774261 -1.117499 4 40.000000 0.283084 -1.495734 5 NaN -0.074763 -0.840403 6 NaN 0.709794 -1.000048 7 NaN 0.920943 0.681230 8 -0.701831 0.547689 -0.128996 9 -0.455691 0.610016 0.420240 10 -0.856768 -1.039719 0.230000 11 1.187208 0.964340 NaN 12 0.116258 22.000000 1.119744 13 -0.501180 NaN 0.558941 14 0.551586 NaN -0.993749
answers question: http://stackoverflow.com/q/48428173

http://stackoverflow.com/comment/83794363
type: Comment
type: QuestionComment
score: 0
has text: did you install `django_heroku`? check if you can import it into your env when opening a shell for example.
comment on: http://stackoverflow.com/q/48402868

http://stackoverflow.com/comment/83749981
has text: @cᴏʟᴅsᴘᴇᴇᴅ - I dont know if creating new dataFrames or creating lists is more consumed. But if I test it `s = df['keys'].str.split(',').apply(set).memory_usage() v = df['keys'].str.split(',',expand=True).memory_usage()` and `print (s) print(v.sum())` it seems `DataFrame` lost here. But not sure how the best test it.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48380509

http://stackoverflow.com/a/48408281
type: Answer
has comment: http://stackoverflow.com/comment/83807363
has comment: http://stackoverflow.com/comment/83807298
accepted answer of: http://stackoverflow.com/q/48392776
has comment: http://stackoverflow.com/comment/83808244
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/107291819
upvote count: 1
has body: You need to create the accuracy yourself in model_fn using tf.metrics.accuracy and pass it to eval_metric_ops that will be returned by the function. def model_fn(features, labels, mode): # define model... y = tf.nn.sigmoid(...) predictions = tf.cast(y &gt; 0.5, tf.int64) eval_metric_ops = {'accuracy': tf.metrics.accuracy(labels, predictions)} #... return tf.estimator.EstimatorSpec(mode=mode, train_op=train_op, loss=loss, eval_metric_ops=eval_metric_ops) Then the output of estimator.evaluate() will contain an accuracy key that will hold the accuracy computed on the validation set. metrics = estimator.evaluate(test_input_fn) print(metrics['accuracy'])
score: 1
answers question: http://stackoverflow.com/q/48392776

http://stackoverflow.com/comment/83783814
type: Comment
score: 0
has text: I meant, no need of udf for creating unique number for the categorical data from stringIndexer. The udf whatever he has in his code.
type: AnswerComment
comment on: http://stackoverflow.com/a/48397997

http://stackoverflow.com/comment/83699783
score: 0
comment on: http://stackoverflow.com/a/48356511
type: AnswerComment
has text: @rajeev - then need aggregate each column, so instad `dfmin = df['milesrun'].groupby(df['Date'].dt.strftime('%m-%d')).min()` need `dfmin = df.groupby(df['Date'].dt.strftime('%m-%d')).agg({'milesrun':'min', 'city':'first'})`
type: Comment

http://stackoverflow.com/q/48402276
has answer: http://stackoverflow.com/a/65449613
has title: Solving 'is one away' with set()
has answer: http://stackoverflow.com/a/61129683
has body: I am taking a Udemy course. The problem I am working on is to take two strings and determine if they are 'one edit away' from each other. That means you can make a single change -- change one letter, add one letter, delete one letter -- from one string and have it become identical to the other. Examples: s1a = "abcde" s1b = "abfde" s2a = "abcde" s2b = "abde" s3a = "xyz" s3b = "xyaz" s1a changes the 'c' to an 'f'. s2a deletes 'c'. s3a adds 'a'. The instructors solution (and test suite): def is_one_away(s1, s2): if len(s1) - len(s2) &gt;= 2 or len(s2) - len(s1) &gt;= 2: return False elif len(s1) == len(s2): return is_one_away_same_length(s1, s2) elif len(s1) &gt; len(s2): return is_one_away_diff_lengths(s1, s2) else: return is_one_away_diff_lengths(s2, s1) def is_one_away_same_length(s1, s2): count_diff = 0 for i in range(len(s1)): if not s1[i] == s2[i]: count_diff += 1 if count_diff &gt; 1: return False return True # Assumption: len(s1) == len(s2) + 1 def is_one_away_diff_lengths(s1, s2): i = 0 count_diff = 0 while i &lt; len(s2): if s1[i + count_diff] == s2[i]: i += 1 else: count_diff += 1 if count_diff &gt; 1: return False return True # NOTE: The following input values will be used for testing your solution. print(is_one_away("abcde", "abcd")) # should return True print(is_one_away("abde", "abcde")) # should return True print(is_one_away("a", "a")) # should return True print(is_one_away("abcdef", "abqdef")) # should return True print(is_one_away("abcdef", "abccef")) # should return True print(is_one_away("abcdef", "abcde")) # should return True print(is_one_away("aaa", "abc")) # should return False print(is_one_away("abcde", "abc")) # should return False print(is_one_away("abc", "abcde")) # should return False print(is_one_away("abc", "bcc")) # should return False When I saw the problem I decided to tackle it using set(). I found this very informative: Opposite of set.intersection in python? This is my attempted solution: def is_one_away(s1, s2): if len(set(s1).sym…
tagged with: python
type: AnsweredQuestion
answer count: 3
score: 1
tagged with: set
downvote count: 0
accepted answer: http://stackoverflow.com/a/48402578
upvote count: 1
has answer: http://stackoverflow.com/a/48402578
favorite count: 0
possible better answer: http://stackoverflow.com/a/61129683
linked to: http://stackoverflow.com/q/29947844
type: Question

popen
tags question: http://stackoverflow.com/q/48468274
tags question: http://stackoverflow.com/q/48341053
tags question: http://stackoverflow.com/q/48341612
type: Tag
tags question: http://stackoverflow.com/q/48386248
tags question: http://stackoverflow.com/q/48433478
tag name: popen
tags question: http://stackoverflow.com/q/48355172

http://stackoverflow.com/a/69453872
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48366469
type: Answer
has body: You can do this using babel: from babel.numbers import get_currency_symbol, get_territory_currencies def currency_symbol(country_code): try: currency_code = get_territory_currencies(country_code)[0] symbol = get_currency_symbol(currency_code, locale='en_US') except IndexError: symbol = '' return symbol Now print to get the output you need: &gt;&gt;&gt; print(currency_symbol('US')) $ Notes: The function will return an empty string when it cannot find the country code you entered. The function will return the ISO code for the currency when the symbol does not exist for the given locale. Modify the function according to your needs.

http://stackoverflow.com/q/48484664
has title: How can I make TensorFlow RNN training more robust?
accepted answer: http://stackoverflow.com/a/48486010
has comment: http://stackoverflow.com/comment/83962016
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83962046
has comment: http://stackoverflow.com/comment/83962036
has answer: http://stackoverflow.com/a/48486010
answer count: 1
tagged with: machine-learning
tagged with: recurrent-neural-network
has body: I am training an RNN on a time series. I subclassed RNNCell and I use it in dynamic_rnn. The topology of the RNNCell is as follows: input (shape [15, 100, 3]) 1x3 convolution (5 kernels), ReLu (shape [15, 98, 5]) 1x(remaining) convolution (20 kernels), ReLu (shape [15, 1, 20]) concatenate previous output (shape [15, 1, 21]) squeeze and 1x1 convolution (1 kernel), ReLu (shape [15, 1]) squeeze and softmax (shape [15]) The batch size for dynamic_rnn is around 100 (not the same 100 of the description above, that's the number of time periods in a window of data). Epochs are made of about 200 batches. I would like to experiment with hyperparameters and regularization, but too often what I try stops the learning entirely and I don't understand why. These are some of the weird things that happen: Adagrad works, but if I use Adam or Nadam the gradients are all zero. I am forced to set a huge learning rate (~1.0) to see learning from epoch to epoch. If I try to add dropout after any of the convolutions, even if I set keep_prob to 1.0 it stops learning. If I tweak the number of kernels in the convolutions, for some choices that would seem just as good (e.g. 5, 25, 1 vs 5, 20, 1) again the network stops learning entirely. Why is this model so fragile? Is it the topology of the RNNCell? EDIT: This is the code of the RNNCell: class RNNCell(tf.nn.rnn_cell.RNNCell): def __init__(self): super(RNNCell, self).__init__() self._output_size = 15 self._state_size = 15 def __call__(self, X, prev_state): network = X # ------ 2 convolutional layers ------ network = tflearn.layers.conv_2d(network, 5, [1, 3], activation='relu', weights_init=tflearn.initializations.variance_scaling(), padding="valid", regularizer=None) width = network.get_shape()[2] network = tflearn.layers.conv_2d(network, 20, [1, width], [1, 1], activation='relu', weights_init=tflearn.initializations.variance_scaling(), padding="valid", regularizer=None) # ------ concatenate the previous state ------ _, height, width, feature…
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83962225

http://stackoverflow.com/q/48486130
has comment: http://stackoverflow.com/comment/83965101
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48486341
has answer: http://stackoverflow.com/a/48489815
has body: I want to use the dendogram of scipy. I have the following data: I have a list with seven different means. For example: Y = [71.407452200146807, 0, 33.700136456196823, 1112.3757110973756, 31.594949722819372, 34.823881975554166, 28.36368420190157] Each mean is calculate for a different user. For example: X = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"] My aim is to display the data described above with the help of a dendorgram. I tried the following: Y = [71.407452200146807, 0, 33.700136456196823, 1112.3757110973756, 31.594949722819372, 34.823881975554166, 28.36368420190157] X = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"] # Attempt with matrix #X = np.concatenate((X, Y),) #Z = linkage(X) Z = linkage(Y) # Plot the dendogram with the results above dendrogram(Z, leaf_rotation=45., leaf_font_size=12. , show_contracted=True) plt.style.use("seaborn-whitegrid") plt.title("Dendogram to find clusters") plt.ylabel("Distance") plt.show() But it says: ValueError: Length n of condensed distance matrix 'y' must be a binomial coefficient, i.e.there must be a k such that (k \choose 2)=n)! I already tried to convert my data into a matrix. With: # Attempt with matrix #X = np.concatenate((X, Y),) #Z = linkage(X) But that doesn´t work too! Are there any suggestions? Thanks :-)
has answer: http://stackoverflow.com/a/48486341
score: 0
tagged with: hierarchical-clustering
tagged with: scipy
type: Question
possible better answer: http://stackoverflow.com/a/48489815
answer count: 2
linked to: http://stackoverflow.com/q/13079563
has title: Python: Dendogram with Scipy doesn´t work
tagged with: python
has comment: http://stackoverflow.com/comment/83965326

http://stackoverflow.com/comment/83889843
has text: It's not clear what the `user` in `def student_register(request, user):` is for, or why you then set `user.username = cd1["username"]` - I would expect that code to give an error at that point.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48448563

http://stackoverflow.com/comment/83738530
score: 1
type: QuestionComment
has text: Possible duplicate of [Removing u in list](https://stackoverflow.com/questions/9773121/removing-u-in-list)
comment on: http://stackoverflow.com/q/48375618
type: Comment

http://stackoverflow.com/comment/83787175
type: QuestionComment
has text: @schwobaseggl can u show me how ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48397608

http://stackoverflow.com/q/48385082
has title: How can I loop through an index and keep the associated row information?
answer count: 3
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83759240
has comment: http://stackoverflow.com/comment/83757710
accepted answer: http://stackoverflow.com/a/48386024
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/83757969
has body: I have a loop within my function that is supposed to find the max rate, min rate, and compute the average, and the function that I wrote is doing this right, but how can I keep the row information when I find the max, and min within my data? I'm a beginner at python, but here is the loop that I have. max_rate = -1 min_rate = 25 count = 0 sum = 0 with open(file_names, "r") as file_out: # skips the headers in the file next(file_out) for line in file_out: values = line.split(",") # since rate is index 6 that is what we are going to compare to values above if float(values[6]) &gt; max_rate: max_rate = float(values[6]) if float(values[6]) &lt; min_rate: min_rate = float(values[6]) count += 1 # sum up all rates in the rates column sum = float(values[6]) + sum avg_rate = sum / count print(avg_rate) I have printed the average just to test my function. Hopefully the question I am asking makes sense, I don't just want the 6th index but I want the rest of the row information that has the min or the max. An example would be to get the company name, state, zip, and rate. Don't worry about indentations, I don't know if I formatted it right in the code block here, but all the indents are right in my code chunk.
tagged with: arrays
has comment: http://stackoverflow.com/comment/83757635
has comment: http://stackoverflow.com/comment/83759054
has comment: http://stackoverflow.com/comment/83758022
possible better answer: http://stackoverflow.com/a/48385738
tagged with: python
has answer: http://stackoverflow.com/a/48385727
has answer: http://stackoverflow.com/a/48386024
has answer: http://stackoverflow.com/a/48385738
type: AnsweredQuestion
score: 0
tagged with: list

http://stackoverflow.com/q/48425010
has comment: http://stackoverflow.com/comment/83840411
has comment: http://stackoverflow.com/comment/83840125
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83968334
has comment: http://stackoverflow.com/comment/83930096
has comment: http://stackoverflow.com/comment/83890112
answer count: 1
has comment: http://stackoverflow.com/comment/83926061
has comment: http://stackoverflow.com/comment/83840314
has comment: http://stackoverflow.com/comment/83849948
has comment: http://stackoverflow.com/comment/83840791
has answer: http://stackoverflow.com/a/48425604
accepted answer: http://stackoverflow.com/a/48425604
has title: Scipy Ttest_ind and Ranksum
favorite count: 0
has body: I am trying to perform tow sample t test. My data set consists of 744 rows and 186 columns for which I have calculated total sum and mean. I need to perform two sample t test. My csv looks like this from which I have to calculate ttest and rank sum test for each row as individual row denotes separate ID and have the corresponding values : SRA ID ERR169499 ERR169498 ERR169497 Label 1 0 1 TaxID PRJEB3251_ERR169499 PRJEB3251_ERR169499 PRJEB3251_ERR169499 333046 0.05 0.99 99.61 1049 0.03 2.34 34.33 337090 0.01 9.78 23.22 99007 22.33 2.90 0.00 The labels 0 and 1 are for case and control respectively.I have to calculate ttest for case columns vs ctrl columns. df = pd.read_csv('final_out_transposed.csv') for row in df.iterrows(): (tt_val, p_ttest) = ttest_ind(df.sum_case, df.sum_ctrl) (tr_val, p_ranksum) = ranksums(df.sum_case, df.sum_ctrl) print (tt_val) print (p_ttest) print (tr_val) print (p_ranksum) Kindly help me with this.
type: Question
has comment: http://stackoverflow.com/comment/83840238
has comment: http://stackoverflow.com/comment/83848064
has comment: http://stackoverflow.com/comment/83886197
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83840681
has comment: http://stackoverflow.com/comment/83849549
has comment: http://stackoverflow.com/comment/83840797
has comment: http://stackoverflow.com/comment/83845633
has comment: http://stackoverflow.com/comment/83889256
has comment: http://stackoverflow.com/comment/83891071
has comment: http://stackoverflow.com/comment/83882677
has comment: http://stackoverflow.com/comment/83971814
has comment: http://stackoverflow.com/comment/83884810
has comment: http://stackoverflow.com/comment/83882225
has comment: http://stackoverflow.com/comment/83845308
has comment: http://stackoverflow.com/comment/83889563
has comment: http://stackoverflow.com/comment/83884200
tagged with: python
has comment: http://stackoverflow.com/comment/83839824
has comment: http://stackoverflow.com/comment/83890937
has comment: http://stackoverflow.com/comment/83888950
has comment: http://stackoverflow.com/comment/83927217
tagged with: numpy
has comment: http://stackoverflow.com/comment/83889330
has comment: http://stackoverflow.com/comment/83919549
has comment: http://stackoverflow.com/comment/83927311
has comment: http://stackoverflow.com/comment/83927045
downvote count: 0
has comment: http://stackoverflow.com/comment/83893381
tagged with: pandas
has comment: http://stackoverflow.com/comment/83868218
has comment: http://stackoverflow.com/comment/83915279

http://stackoverflow.com/q/48475960
upvote count: 2
has comment: http://stackoverflow.com/comment/109837559
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83956291
answer count: 1
tagged with: portability
has body: It seems that Python Tkinter and Tcl/Tk ask the system for color names and do not maintain it themselves. Looking at the standard Python/Tcl/Tk sources does not show any of those colors. You can only find them in color.n which is part of the Tk documentation and in an optional pygment library. Is there a portable way to ask the system itself (and not any other source which might or might not match the system one) through Python and Tkinter or any other GUI library, for a list of the available color names? This was previously marked as a duplicate of Named colors in tkinter, but the only answer there involves reading /etc and so is Linux-specific. I am looking for a portable method that would work with Linux, Windows, and Mac.
score: 1
has comment: http://stackoverflow.com/comment/109862512
has comment: http://stackoverflow.com/comment/83945236
downvote count: 1
favorite count: 0
has title: Portable method to get a list of accepted color names with tkinter
has answer: http://stackoverflow.com/a/62102682
tagged with: colors
linked to: http://stackoverflow.com/q/38539993
has comment: http://stackoverflow.com/comment/83956044
has comment: http://stackoverflow.com/comment/83945298
tagged with: python
has comment: http://stackoverflow.com/comment/83950011
type: Question
tagged with: tkinter

http://stackoverflow.com/q/48421447
answer count: 3
has title: When I am trying to run django development server (using command line),I get following error traceback:
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48421528
has body: My system is: Ubuntu16.04. Python version: 3.5.2 Django version: 2.0.2 root@nanlyvm:/home/mydj/mysite# python manage.py runserver Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fbb791cd1e0&gt; Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126,…
upvote count: 0
has answer: http://stackoverflow.com/a/48421744
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48421540
tagged with: django
has comment: http://stackoverflow.com/comment/83862149
tagged with: python
score: -1

http://stackoverflow.com/comment/83713178
type: QuestionComment
has text: You have the wrong platform for what you want to do. iOS devices don't support that sort of background execution. Jailbreaking may be an option for you.
comment on: http://stackoverflow.com/q/48362944
score: 1
type: Comment

http://stackoverflow.com/comment/83733658
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48355349
type: AnswerComment
has text: @cdlane I don't know what you want to ask. "Weridly" just want to cleanup text So I explain it as easy as I can.

http://stackoverflow.com/comment/83692211
type: QuestionComment
has text: You may have a look at this: https://stackoverflow.com/questions/25346058/removing-list-of-words-from-a-string
comment on: http://stackoverflow.com/q/48352745
score: 1
type: Comment

http://stackoverflow.com/comment/83759564
has text: You code does not produce the correct output. Try `print(split_overlap_Aviad(list(range(10),7,2))`
type: AnswerComment
comment on: http://stackoverflow.com/a/48382376
score: 0
type: Comment

http://stackoverflow.com/q/48433478
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/114192831
has answer: http://stackoverflow.com/a/48433624
has comment: http://stackoverflow.com/comment/83859223
accepted answer: http://stackoverflow.com/a/48433624
has title: How to activate an anaconda environment within a Python script on a remote machine?
linked to: http://stackoverflow.com/q/35982273
tagged with: python
score: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83858662
tagged with: subprocess
tagged with: popen
linked to: http://stackoverflow.com/q/36275308
tagged with: os.system
downvote count: 0
answer count: 1
has body: I am currently trying to find a way to activate an anaconda environment within a Python script that is running on a remote server. I have found the following similar questions on Stack Overflow here, and here, but have had no success with what they suggest. I just keep getting this simple error sh: 1: source: not found.From my understanding this is because the conda environment it not being found After much research, I have found no other way to do this when using a python script, but if anyone has an suggestions I would love to pass some ideas around! Thanks, in advance! Here is the code: import os import subprocess from subprocess import Popen value = 'activate punc2' #os.system("cd /Users/elicobler/tiny_dancer/Testing/thrive/API_text_results") #os.system('source root/conda3/envs/punc2/bin/activate /root/conda3/envs/punc2') #os.system('source activate punc2') #Popen('source activate punc2') #subprocess.call('source', value) subprocess.run('source root/conda3/envs/punc2/bin/activate /root/conda3/envs/punc2 &amp;&amp; cat /var/www/html/1.22.18 - Monday - Hr 1 - Seg 1-5a65e2698c1dd07f02c25679.txt | python punctuator.py models/endquote.pcl /var/www/html/1.22.18 - Monday - Hr 1 - Seg 1-5a65e2698c1dd07f02c25679.txt &amp;&amp; source deactivate', shell=True)
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/a/48453223
upvote count: 1
type: Answer
has body: the code for min() means to output the min value of that object, otherwise you'll just get it's type (function float64.min.) because dx is a scalar taking it's minimal value is meaningless, it has only one value to begin with. the conversion you seek should be: dt = a*min(dx)./abs(v)
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48433769

http://stackoverflow.com/comment/83812341
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48411251
score: 0
has text: Have you checked the [documentation for `UdpClient`](https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient) yet? The endpoint you pass in is for the *other party in the communication*, not the IP address you bind to. Passing in a port number means you want to bind to a local IP address, which is why 127.0.0.1 is bound to. You pass in a `IPEndPoint` instance to the `Receive` method, so you want to receive data only if it was sent *from* 192.168.1.100.

http://stackoverflow.com/q/48429234
linked to: http://stackoverflow.com/q/39900124
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83849409
tagged with: python
has title: how o make django-autocomplete light return selected text not id
tagged with: django-autocomplete-light
score: 0
has answer: http://stackoverflow.com/a/48861367
answer count: 1
tagged with: django
has body: I have a simple form which lets a user select his country, state and district and redisplays the selected data. Everything works as expected apart from the fact that what is displayed is not the "text" but "ids" of the selected data. Expectation: You belong to India, Punjab, Jalandhar. Me too. ;) Output: You belong to 1, 2, 4. Me too. ;) # my form class MyInfoForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ListSelect2( url='country-autocomplete', ) ) state = forms.ModelChoiceField( queryset=State.objects.all(), widget=autocomplete.ListSelect2( url='state-autocomplete', forward=(forward.Field('country'),) ) ) district = forms.ModelChoiceField( queryset=District.objects.all(), widget=autocomplete.ListSelect2( url='district-autocomplete', forward=(forward.Field('state'),) ) ) # my view which handles MyInfoForm class CountryView(FormView): template_name = 'home.html' form_class = MyInfoForm success_url = '/thanks/' def form_valid(self, form): print("Request :", self.request.POST) country = self.request.POST["country"] state = self.request.POST["state"] district = self.request.POST["district"] msg = "You belong to {country}, {state}, {district}. Me too. ;)".format( country=country, state=state, district=district) return HttpResponse(msg) # other auto-complete views (similar to official tutorials) class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(country_name__istartswith=self.q) return qs class StateAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return State.objects.none() qs = State.objects.all() country = self.forwarded.get('country', None) if country: qs = qs.filter(country_name=country) if self.q: qs = qs.filter(state_na…

http://stackoverflow.com/q/48343941
has answer: http://stackoverflow.com/a/48345444
tagged with: django-rest-framework
has title: Django Rest: Add data to a "required" field automatically
favorite count: 0
type: Question
has body: I want to automatically assign a value for a required field in Django Rest framework, without the value having to be given in the post request. My View: class WaitercallCreate(CreateAPIView): serializer_class = WaitercallCreateSerializer permission_classes = (IsAuthenticated, ) The Serializer: class WaitercallCreateSerializer(serializers.ModelSerializer): class Meta: model = Waitercall fields = ('order', 'user', 'done', 'type_of_call') read_only_fields = ('user', 'done') Users should be able to do a postrequest, only giving their token in the header and the order id as the body. I want to set the value for user by default to the requests user. I tried overwriting the perform_create method in my view like this: def perform_create(self, serializer): serializer.save(user=self.request.user) This didn't work. Then I tried overwriting the create method in the view like this: def create(self, request, *args, **kwargs): data = request.data data['user'] = request.user serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Which also didn't work, because Orderdicts are immutable. For the first (and the last try, read further) I always get the same response: { "user": [ "This field is required." ] } Lastly I found this stackoverflow post, which recommends overwriting the create method in the serializer. Like this: def create(self, validated_data): print(self.context['request'].user) validated_data['user'] = self.context['request'].user return super(WaitercallCreateSerializer, self).create(validated_data) It also gave me the same response. I'm lost. What can I try next?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48345001
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/42346200
tagged with: httprequest
has comment: http://stackoverflow.com/comment/83674966
answer count: 2
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48361145
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83709210
has comment: http://stackoverflow.com/comment/83709178
answer count: 0
has comment: http://stackoverflow.com/comment/83719342
tagged with: mysql
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/83719315
has body: I'm trying to scrape a website with Scrapy and store the information to a MySQL database. My spider works on it's own. When I use it alongside a pipeline I get two errors [twisted] CRITICAL: Unhandled error in Deferred: TypeError: connect() argument 1 must be string, not None I'm new to python and scrapy. Here is my Spider: from scrapy import Spider #from scrapy.selector import Selector from scraper.items import ExpertScraperItem class expertSpider(Spider): name = 'expert' start_urls = [ 'https://www.expert.ie/products/home-appliances/laundry', ] def parse(self, response): # follow links to product pages for href in response.css('a.product-list-link::attr(href)'): yield response.follow(href, self.parse_product) # follow pagination links for href in response.css('a.UnselectedPage::attr(href)'): yield response.follow(href, self.parse) def parse_product(self, response): def extract_with_css(query): return response.css(query).extract_first().strip() item = ExpertScraperItem() item['model'] = extract_with_css('header strong::text')[12:100].strip() item['price'] = extract_with_css('span.TotalPrice::text')[1:100].strip() yield item Here is my pipeline (this has been updated to show errors corrected 21/01/2018) import scrapy import MySQLdb import MySQLdb.cursors from twisted.enterprise import adbapi class ScraperPipeline(object): def __init__(self, dbpool): self.dbpool = dbpool @classmethod def from_settings(cls, settings): dbargs = dict( host = settings['MYSQL_HOST'], db = settings['MYSQL_DBNAME'], port = settings['MYSQL_PORT'], user = settings['MYSQL_USER'], passwd = settings['MYSQL_PASSWD'], charset = 'utf8', cursorclass = MySQLdb.cursors.DictCursor, use_unicode = True, ) dbpool = adbapi.ConnectionPool('MySQLdb', **dbargs) return cls(dbpool) #pipeline the default call def process_item(self, item, spider): d = self.dbpool.runInteraction(self._do_upinsert, item, spider) return item #Each row is updated or written to the database def _do_upinsert(self, conn, item, spider): …
has comment: http://stackoverflow.com/comment/115257147
type: Question
has title: Scrapy & MySQL database:
has comment: http://stackoverflow.com/comment/83709145
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83709122

http://stackoverflow.com/comment/83739561
type: AnswerComment
has text: sr is an integer
comment on: http://stackoverflow.com/a/48376275
type: Comment
score: 0

http://stackoverflow.com/q/48456420
type: UnansweredQuestion
tagged with: nifti
answer count: 1
downvote count: 0
has body: I am attempting to read a NIFTI file inside a .zip without having to extract the directory to the root directory. More specifically, I am working with the ADNI database and the files are stored by subjectID in individual .zip files. Inside the .zip file there is all the data pertaining to that subject, I would like to extract the NIFTI file (.nii.gz) from within the .zip without extracting the files. Currently I have the following code snippet def openNIFTI(filename): return nib.load(filename).get_data() zip_filename = filepath + str(subject_id) + '_3T_Structural_unproc.zip' filename = str(subject_id) + '/unprocessed/3T/T1w_MPR1/' + str(subject_id) + '_3T_T1w_MPR1.nii.gz' file = zf.extract(filename) data = openNIFTI(file) The filepath is the path to the collection of .zip files. filename is the path inside the .zip file to the NIFTI file I want to extract. (Edit) It seem the error is coming from the nibabel load function. Then function checks if not op.exists(filename): Upon testing the os.path.exists(filename) function independently I found that. os.path.exists(r'C:/Users/eee/workspace_python/Image Reconstruction/data/ADNI/MRI data/100206_3T_Structural_unproc.zip/100206/unprocessed/3T/T1w_MPR1/100206_3T_T1w_MPR1.nii.gz') False However, this path is copy/pasted from the file I am attempting to open. It seems to me the error appears due to the .zip in the file path because os.path.exists(r'C:/Users/eee/workspace_python/Image Reconstruction/data/ADNI/MRI data/100206_3T_Structural_unproc.zip') True Is there another way of doing this?
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48456462
has title: Accessing files inside a .zip archive without extracting them
score: 1
type: Question
tagged with: http://stackoverflow.com/tag/zip
linked to: http://stackoverflow.com/q/19371860

http://stackoverflow.com/comment/83962069
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48484615
type: Comment
has text: Can you provide some sample input and expected output please?

http://stackoverflow.com/q/48477909
score: 10
has answer: http://stackoverflow.com/a/51944026
tagged with: python
has comment: http://stackoverflow.com/comment/83949060
has title: Tensorflow import error
tagged with: cuda
accepted answer: http://stackoverflow.com/a/48478822
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83949121
answer count: 2
has comment: http://stackoverflow.com/comment/83949541
has answer: http://stackoverflow.com/a/48478822
has comment: http://stackoverflow.com/comment/94078665
downvote count: 0
upvote count: 10
tagged with: tensorflow
favorite count: 0
type: Question
has body: I'm trying to install tensorflow which supports GPU. I tried the information in the following link https://www.tensorflow.org/install/install_windows CUDA® Toolkit 8.0 cuDNN v6.0 GPU card with CUDA Compute Capability 3.0 - GeForce 940MX Then used pip3 install --upgrade tensorflow-gpu to install tensorflow. But I'm getting the following error when trying to import tensorflow. Traceback (most recent call last): File "C:\Research\Python_installation\lib\site-packages\tensorflow\python\platform\self_check.py", line 75, in preload_check ctypes.WinDLL(build_info.cudart_dll_name) File "C:\Research\Python_installation\lib\ctypes\__init__.py", line 347, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; import tensorflow as tf File "C:\Research\Python_installation\lib\site-packages\tensorflow\__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "C:\Research\Python_installation\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "C:\Research\Python_installation\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in &lt;module&gt; self_check.preload_check() File "C:\Research\Python_installation\lib\site-packages\tensorflow\python\platform\self_check.py", line 82, in preload_check % (build_info.cudart_dll_name, build_info.cuda_version_number)) ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 9.0 from this URL: https://developer.nvidia.com/cuda-toolkit Can someone please advice me on how to use this.
possible better answer: http://stackoverflow.com/a/51944026
has comment: http://stackoverflow.com/comment/83949019

http://stackoverflow.com/q/48487323
has body: I trained Naive Bayes model with scikit-learn to classify articles in my web application.To avoid learning the model repeatedly, I want to save the model and deploy it to the application later. When i search for this problem, many people recommend the pickle library. I have this model : import pickle import os def custom_tokenizer (doc) : tokens = vect_tokenizer(doc) return [lemmatizer.lemmatize(token) for token in tokens] tfidf = TfidfVectorizer(tokenizer = custom_tokenizer,stop_words = "english") clf = MultinomialNB() I have already executed tfidf.fit_transform() and trained clf. Finally, i got a model and saved clf classifier using this code : dest = os.path.join('classifier','pkl_object') f = open(os.path.join(dest,'classifier.pkl'),'wb') pickle.dump(best_classifier,f,protocol = 4) f.close() I also tried to save my Vectorizer as a file this way. f = open(os.path.join(dest,'vect.pkl'),'wb') pickle.dump(custom_tokenizer,f,protocol = 4) pickle.dump(best_vector,f,protocol = 4) f.close() There was no error. but when i tried to load the file, this error message popped up. import pickle import os with open(os.path.join('pkl_object','classifier.pkl'),'rb') as file : clf = pickle.load(file) with open(os.path.join('pkl_vect','vect.pkl'),'rb') as file: vect = pickle.load(file) error message : AttributeError Traceback (most recent call last) &lt;ipython-input-55-d4b562870a02&gt; in &lt;module&gt;() 11 12 with open(os.path.join('pkl_vect','vect.pkl'),'rb') as file: ---&gt; 13 vect = pickle.load(file) 14 15 ''' AttributeError: Can't get attribute 'custom_tokenizer' on &lt;module '__main__'&gt; I think the pickle library does not have the ability to store function properly. How can i serialize my custom TfidfVectorizer as a file.
has comment: http://stackoverflow.com/comment/83967815
accepted answer: http://stackoverflow.com/a/48487762
linked to: http://stackoverflow.com/q/27732354
tagged with: scikit-learn
tagged with: pickle
has answer: http://stackoverflow.com/a/48487762
tagged with: python
tagged with: text-mining
has comment: http://stackoverflow.com/comment/83967554
type: AnsweredQuestion
score: 2
has title: Save and load scikit-learn machine learning model and function
has comment: http://stackoverflow.com/comment/83967609
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: serialization

http://stackoverflow.com/comment/83951739
has text: @CoryKramer I see. So when we create M, what are the initial values of the elements? Also, why do we create such an object? What is the point of doing this?
comment on: http://stackoverflow.com/q/48479317
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83727200
type: QuestionComment
has text: And it worked good in PyQt4...
score: 0
comment on: http://stackoverflow.com/q/48357025
type: Comment

http://stackoverflow.com/q/48373812
linked to: http://stackoverflow.com/q/2134706
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83735044
tagged with: pickle
tagged with: python
upvote count: 7
favorite count: 0
tagged with: beautifulsoup
has body: I want to pickle html from websites. I save the html to a list and try to pickle it. An example of one such list is the html from brckhmptn.com/tour. Of course the html from this site is a lot, is that my error? The whole script is there but the error is called in the last few lines. I'm using Python 3.6.1 Traceback (most recent call last): File "./showNotifier.py", line 128, in &lt;module&gt; scrape_html(combinedUrls) File "./showNotifier.py", line 125, in scrape_html pickle.dump(sites, hf) RecursionError: maximum recursion depth exceeded #!/home/steph/unix/miniconda3/bin/python ''' By Stephen Wist stphnwist@gmail.com ShowNotifier --------------------- script takes cmd line args to: indiacte URLS to add default behaviour is checking if new shows were added ''' import requests import pickle import sys import argparse import os import urllib from bs4 import BeautifulSoup urlFile = "urls" htmlFile = "htmls" # take in cmd line args parseArgs = argparse.ArgumentParser(description='Add URLs to cache.') parseArgs.add_argument('urls', type=str, nargs='*', help='URLs to be added.') # assign cmd line args to urls.urls urls = parseArgs.parse_args() # this function makes sure all files are in place def status_report(): # this should be the case only the first time the # script is run if (os.path.getsize(urlFile) == 0): urlFileExists = 0 # create urlFile if it does not exist if (not urls.urls): print ("No data in the url file. Run the script again but include url(s) on the command line.\n\ e.g. ./showNotifier.py www.myfavoriteband.com") sys.exit() else: urlFileExists = 1 # these file should never be deleted, but just in case if (not os.path.isfile(urlFile)): f = open("urls","w") f.close() if (not os.path.isfile(htmlFile)): f = open("htmls","w") f.close() return urlFileExists urlFileExists = status_report() # grab the urls in urlFile, or make # urlFile if it does not exist def read_urls(urlFileExists): print(urlFileExists) # assign all urls in urlFile to prevUrls if (urlFileExis…
type: Question
possible better answer: http://stackoverflow.com/a/60238371
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/60238371
has comment: http://stackoverflow.com/comment/83734813
has answer: http://stackoverflow.com/a/70034992
score: 7
has title: Recursion Depth Exceeded, pickle and BeautifulSoup
accepted answer: http://stackoverflow.com/a/48373846
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48373846

http://stackoverflow.com/comment/83900692
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [Why does foo = filter(...) return a <filter object>, not a list?](https://stackoverflow.com/questions/33174276/why-does-foo-filter-return-a-filter-object-not-a-list)
comment on: http://stackoverflow.com/q/48453806

http://stackoverflow.com/a/48363381
has body: scipy mode can return the count as well from scipy import stats df['D']=stats.mode(df.values,1)[1] df Out[829]: A B C D 0 1 1 2 2 1 2 1 2 2 2 3 3 3 3 3 3 2 1 1 More Info: stats.mode(df.values,1) Out[830]: ModeResult(mode=array([[1], [2], [3], [1]], dtype=int64), count=array([[2], [3], [4], [2]]))
answers question: http://stackoverflow.com/q/48363338
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/83922236
score: 0
comment on: http://stackoverflow.com/a/48464445
has text: I wish to get all values, some are decimals and some are integers. The Python documentation suggested that so i tried.. Obviously that was not the problem but i mentioned it as i tried it.. thanks for your answer. Yes its in the traceback.. yes i feel dumb :)
type: Comment
type: AnswerComment

trigram
tag name: trigram
type: Tag
tags question: http://stackoverflow.com/q/48331315

http://stackoverflow.com/comment/83695474
type: Comment
comment on: http://stackoverflow.com/a/48353869
score: 0
type: AnswerComment
has text: this doesn't seems to be work as its giving error. workbook object has not attribute add_format

http://stackoverflow.com/a/48400059
type: Answer
accepted answer of: http://stackoverflow.com/q/48362041
score: 0
answers question: http://stackoverflow.com/q/48362041
type: AcceptedAnswer
has body: After couples of days i came up with solution to my problem: from tkinter import * import webbrowser class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.Scrol = Scrollbar(self.master) self.Text = Text(self.master, height=50, width=500) self.Scrol.pack(side=RIGHT, fill=Y) self.Text.pack(side=LEFT, fill=X) self.Scrol.config(command=self.Text.yview) self.Text.config(yscrollcommand=self.Scrol.set) self.Text.tag_configure('red', foreground='red') self.Text.tag_configure('blue', foreground='blue') self.Text.tag_configure('hlink', foreground='blue', underline=1) line1 = "This is line 1 with link: " myLink1 = "My_link1" line2 = "This is line 2 with link: link: " myLink2 = "My_link2" self.Text.insert(END, line1 + " ", "red") self.Text.insert(END, myLink1 + "\n", "blue") self.Text.insert(END, line2 + " ", "red") self.Text.insert(END, myLink2 + "\n", "blue") self.master.after(1000, self.more_text) def more_text(self): line3 = "This is line n with link: " my_link3 = "My_link3" self.Text.insert(END, line3 + " ", "red") self.Text.insert(END, my_link3 + "\n", "hlink") self.Text.bind('&lt;Double-Button-1&gt;', self.openHLink) self.master.after(2000, self.more_text) def openHLink(self, event): start, end = self.Text.tag_prevrange("hlink", self.Text.index("@%s,%s" % (event.x, event.y))) webbrowser.open(self.Text.get(start, end)) top = Tk() top.geometry('1000x1000') app = Window(top) top.mainloop() Now every time new My_link3 link appears on the screen a user can click on it and web browser will open it. As i mention in my question earlier i wanted to go to my_link3 which was different every time and this answer solved my problem. Hope it will help someone..

http://stackoverflow.com/comment/83716639
score: 0
has text: No output at all ? No errors ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48364969

http://stackoverflow.com/q/48370988
tagged with: port-scanning
type: UnansweredQuestion
tagged with: sockets
tagged with: multithreading
score: 0
has answer: http://stackoverflow.com/a/48520470
answer count: 1
tagged with: python
has body: I wrote a little threaded port scanner, where I paid attention to closing the sockets after I'm done with them. Despite closing the sockets, I'm getting Too many open files errors when I run it against a large number of target hosts (~ 12'000 hosts, and 5 ports, so a total of 60'000 sockets created/closed). My understanding is that I should only encounter this error when closing the ports. I'm not really interested in the option that requires me to modify the number of open files my system can handle (recommend in other SO posts). Full port scanner code below. import socket import itertools from concurrent.futures import ThreadPoolExecutor, as_completed def check_port(host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) if sock.connect_ex((host, port)) == 0: sock.close() return host, port sock.close() return False hosts = open('/tmp/hosts').read().splitlines() ports = [80, 443, 8000, 8080, 8443] with ThreadPoolExecutor(max_workers=100) as executor: future_to_host_port = [ executor.submit(check_port, host, port) for host, port in itertools.product(hosts, ports) ] for future in as_completed(future_to_host_port): try: result = future.result() if not result: continue print(result) except socket.gaierror as e: print(f'couldn\'t resolve') except socket.timeout as e: print(f'socket timeout') except Exception as e: print(type(e)) print(f'error {e}')
has title: Threaded port scanner: Too many open files (after closing socket)
type: Question

http://stackoverflow.com/comment/83824071
type: Comment
type: QuestionComment
score: 2
has text: Looks like you have a file in you path called "pandas.py"
comment on: http://stackoverflow.com/q/48417236

iterable
tags question: http://stackoverflow.com/q/48471212
tags question: http://stackoverflow.com/q/48376607
type: Tag
tag name: iterable

http://stackoverflow.com/comment/83735632
has text: Your second last line should be `t_passage = time_passage.text`. If that still fails, perhaps the page retrieved by your program is different than your browser display (happens with webpages that require javascripts and such).
score: 0
comment on: http://stackoverflow.com/q/48374076
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83864125
comment on: http://stackoverflow.com/q/48436380
type: Comment
type: QuestionComment
score: 0
has text: It's a good point; you definitely need optimizations for a fair comparison with C++, but the tricky thing is not optimizating away the code you are trying to time

http://stackoverflow.com/comment/83792021
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc thanks.Sorry for inconvenience.I have updated code.Please can you take a look?
comment on: http://stackoverflow.com/q/48382245

http://stackoverflow.com/a/48457733
score: 0
has comment: http://stackoverflow.com/comment/83908256
upvote count: 1
has body: Try this one: t.txt ['10', '0', '1915', '387', '1933', '402'] ['10', '0', '3350', '387', '3407', '391'] ['10', '0', '842', '505', '863', '521'] ['2', '29', '2986', '282', '3112', '300'] ['2', '29', '2753', '286', '2809', '297'] Program: file = open('t.txt','r') l = [] for line in file: l += [ eval(line) ] d = {} for i in l: dkey = str(i[0]) + "-" + str(i[1]) dValue = i[2:] if dkey in d: cList = [] for i in d[dkey]: cList.append(i) cList.append(dValue) d[dkey] = cList else: d[dkey] = [] d[dkey].append(dValue) print(d) Outputs: {'10-0': [['1915', '387', '1933', '402'], ['3350', '387', '3407', '391'], ['842', '505', '863', '521']], '2-29': [['2986', '282', '3112', '300'], ['2753', '286', '2809', '297']]} See it in action here
downvote count: 1
answers question: http://stackoverflow.com/q/48457570
type: Answer

http://stackoverflow.com/comment/83913650
has text: @BenyaminJafari I tried that and tried to deploy again but there where no changes on source code: Uploading 0 files to Google Cloud Storage
comment on: http://stackoverflow.com/q/48459712
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/48863662
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48478711
type: Answer
answers question: http://stackoverflow.com/q/48478711
score: 2
has body: Solution with MultiLabelBinarizer: s = pd.Series([['a1','b1'], ['c1'], ['d1']]) from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df = pd.DataFrame(mlb.fit_transform(s),columns=mlb.classes_, index=s.index) And pure pandas solution with get_dummies and aggregate max: df = pd.get_dummies(pd.DataFrame(s.values.tolist()), prefix='', prefix_sep='').max(axis=1, level=0) print (df) a1 b1 c1 d1 0 1 1 0 0 1 0 0 1 0 2 0 0 0 1 Timings: #Generated 10 paragraphs, 224 words, 1710 bytes of Lorem Ipsum #https://www.lipsum.com/ L = [['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit'], ['sed', 'mollis', 'ligula', 'a', 'pellentesque', 'commodo'], ['morbi', 'convallis', 'ante', 'dignissim', 'leo', 'imperdiet', 'vitae', 'molestie', 'nulla', 'euismod'], ['ut', 'consequat', 'quam', 'ut', 'mauris', 'dictum', 'consequat'], ['pellentesque', 'id', 'odio', 'congue', 'vulputate', 'tortor', 'in', 'interdum', 'ex'], ['nam', 'cursus', 'lectus', 'vel', 'convallis', 'facilisis'], ['vivamus', 'sed', 'dui', 'pulvinar', 'dapibus', 'quam', 'in', 'posuere', 'velit'], ['donec', 'vitae', 'diam', 'at', 'mauris', 'eleifend', 'eleifend'], ['vestibulum', 'bibendum', 'erat', 'eget', 'massa', 'varius', 'accumsan'], ['donec', 'consequat', 'nibh', 'at', 'risus', 'elementum', 'quis', 'volutpat', 'purus', 'dapibus'], ['nulla', 'ornare', 'dolor', 'id', 'neque', 'malesuada', 'mattis'], ['nunc', 'a', 'lacus', 'vestibulum', 'laoreet', 'neque', 'a', 'maximus', 'velit'], ['etiam', 'nec', 'metus', 'eu', 'ligula', 'bibendum', 'malesuada'], ['morbi', 'vestibulum', 'ante', 'ac', 'nulla', 'efficitur', 'dignissim'], ['curabitur', 'maximus', 'velit', 'at', 'euismod', 'pellentesque'], ['nunc', 'non', 'turpis', 'pellentesque', 'aliquam', 'lectus', 'at', 'mollis', 'lectus'], ['donec', 'auctor', 'nunc', 'id', 'vestibulum', 'efficitur'], ['duis', 'volutpat', 'mi', 'vel', 'sem', 'cursus', 'commodo'], ['fusce', 'condimentum', 'eros', 'id', 'elementum', 'facilisis'], ['sed', 'l…
upvote count: 2

http://stackoverflow.com/comment/83766732
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48389320
score: 0
has text: What do you mean by "faster?"

http://stackoverflow.com/a/48457473
has body: The way I approach the problem is to first calculate all unique levels in the dataset. Then loop through a cartesian product of those levels. At each step, filter the dataset to create a subset where condition is True. Then, count the number of rows in the subset where the event has happened. Below is my code. import pandas as pd from itertools import product from collections import defaultdict df = pd.DataFrame({ 'col1': ['a', 'a', 'b'], 'col2': ['x', 'y', 'x'], 'col3': ['l', 'l', 'l'] }) levels = df.stack().unique() res = defaultdict(dict) for event, cond in product(levels, levels): # create a subset of rows with at least one element equal to cond conditional_set = df[(df == cond).any(axis=1)] conditional_set_size = len(conditional_set) # count the number of rows in the subset where at least one element is equal to event conditional_event_count = (conditional_set == event).any(axis=1).sum() res[event][cond] = conditional_event_count / conditional_set_size result_df = pd.DataFrame(res) print(result_df) # OUTPUT # a b l x y # a 1.000000 0.000000 1.0 0.500000 0.500000 # b 0.000000 1.000000 1.0 1.000000 0.000000 # l 0.666667 0.333333 1.0 0.666667 0.333333 # x 0.500000 0.500000 1.0 1.000000 0.000000 # y 1.000000 0.000000 1.0 0.000000 1.000000 I am sure there are other faster methods, but it is the first thing that comes to my mind.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48456348
type: Answer
answers question: http://stackoverflow.com/q/48456348

http://stackoverflow.com/q/48427498
has body: I have used DesiredCapabilities capabilities = dict(DesiredCapabilities.CHROME) capabilities['proxy'] = {'proxyType': 'MANUAL', 'httpProxy': proxy['address'], 'ftpProxy': proxy['address'], 'sslProxy': proxy['address'], 'noProxy': '', 'class': "org.openqa.selenium.Proxy", 'autodetect': False } chrome_options = Options() chrome_options.add_argument('--headless') But nothing happen, where if I remove headless I get to see Authentication required alert. I have also used chrome_options.add_argument('--proxy-server=http://%s:%s@%s:%s'%(Config.PROXY_USERNAME,Config.PROXY_PASSWORD,Config.PROXY_URL,Config.PROXY_PORT)) But this did not help. Where I have changed "http" to "socks","socks4" and "socks5" where this didn't help even.
answer count: 1
has comment: http://stackoverflow.com/comment/88453593
linked to: http://stackoverflow.com/q/19199424
tagged with: python
linked to: http://stackoverflow.com/q/6183276
has comment: http://stackoverflow.com/comment/83845712
favorite count: 0
has comment: http://stackoverflow.com/comment/83845272
type: Question
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/56860055
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has title: How to use proxy with authentication in headless chorme browser using selenium and python?
tagged with: google-chrome
tagged with: proxy

http://stackoverflow.com/comment/83964176
comment on: http://stackoverflow.com/q/48482751
has text: Can you check the answer if it solves the problem?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48473973
answers question: http://stackoverflow.com/q/48473543
upvote count: 0
has comment: http://stackoverflow.com/comment/84904060
downvote count: 1
has body: another less efficient way you can go about is to loop through the entire list, then grab the first and second elements of each tuple, concatenate them, then return them in a list.
type: Answer
score: -1

http://stackoverflow.com/comment/83720950
has text: It might be helpful to include the code you are using that generates this error.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48367201
score: 0

http://stackoverflow.com/q/48387136
downvote count: 0
has answer: http://stackoverflow.com/a/48387356
upvote count: 1
favorite count: 0
type: Question
has title: Clear a QGraphicsScene from an event of one of the items
tagged with: pyside
tagged with: python
linked to: http://stackoverflow.com/q/20387679
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48387356
score: 1
has body: I have a QGraphicsScene with many QGraphicsItem. Some items have buttons that clear and repaint the scene. The problem is that the clear() method deletes the QButton (and its associated data structures) in the middle of a method call that uses those very data structures. Then, immediately after clear() returns, the calling method tries to access the now-deleted data (because it wasn't expecting to be deleted in the middle of its routine), and bang -- a crash. From here. I found the solution for C ++ here, however I am using PySide and could not use the same solution for python. Follow my code: class GraphicsComponentButtonItem(QtGui.QGraphicsItem): def __init__(self, x, y, update_out): super(GraphicsComponentButtonItem, self).__init__() self.x = x self.y = y self.update_out = update_out self.setPos(x, y) self.createButton() self.proxy = QtGui.QGraphicsProxyWidget(self) self.proxy.setWidget(self.button) def boundingRect(self): return QtCore.QRectF(self.x, self.y, self.button.width(), self.button.height()) def paint(self, painter, option, widget): # Paint same stuffs def createButton(self): self.button = QtGui.QPushButton() self.button.setText('Clear') self.button.clicked.connect(self.action_press) def action_press(self): # Run some things self.update_out() class QGraphicsViewButtons(QtGui.QGraphicsView): def __init__(self, scene, parent=None): QtGui.QGraphicsView.__init__(self, parent) self.scene = scene # It's called outside def updateScene(self): self.scene.clear() self.scene.addItem(GraphicsComponentButtonItem(0, 0, self.updateScene)) self.scene.addItem(GraphicsComponentButtonItem(0, 50, self.updateScene)) self.scene.addItem(GraphicsComponentButtonItem(0, 100, self.updateScene))
answer count: 1

http://stackoverflow.com/q/48359053
has comment: http://stackoverflow.com/comment/83731514
has answer: http://stackoverflow.com/a/48359137
tagged with: python
tagged with: linear-algebra
upvote count: 6
has title: Subtract each row of matrix A from every row of matrix B without loops
has comment: http://stackoverflow.com/comment/83704961
tagged with: numpy
type: AnsweredQuestion
answer count: 2
tagged with: array-broadcasting
tagged with: matrix
downvote count: 0
score: 6
has body: Given two arrays, A (shape: M X C) and B (shape: N X C), is there a way to subtract each row of A from each row of B without using loops? The final output would be of shape (M N X C). Example A = np.array([[ 1, 2, 3], [100, 200, 300]]) B = np.array([[ 10, 20, 30], [1000, 2000, 3000], [ -10, -20, -2]]) Desired result (can have some other shape) (edited): array([[ -9, -18, -27], [-999, -1998, -2997], [ 11, 22, 5], [ 90, 180, 270], [-900, -1800, -2700], [ 110, 220, 302]]) Shape: 6 X 3 (Loop is too slow, and "outer" subtracts each element instead of each row)
possible better answer: http://stackoverflow.com/a/48372254
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48372254
accepted answer: http://stackoverflow.com/a/48359137

http://stackoverflow.com/comment/83913989
comment on: http://stackoverflow.com/q/48460391
type: Comment
type: QuestionComment
has text: If those strings are your real data, your problem is completely trivial. If those are not similar to your real data, you are unlikely to receive answers which actually help you.
score: 0

http://stackoverflow.com/comment/84401578
comment on: http://stackoverflow.com/a/48695728
has text: While I believe this should really work, I think I should have the professional version in order to uncheck the Sciview option :/
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84039929
type: AnswerComment
has text: Thank you very much! it's helpful!
comment on: http://stackoverflow.com/a/48379871
score: 0
type: Comment

http://stackoverflow.com/comment/83939108
type: QuestionComment
has text: is this possible? any suggestions? I'm pretty new.
comment on: http://stackoverflow.com/q/48472683
score: 0
type: Comment

http://stackoverflow.com/comment/83785826
comment on: http://stackoverflow.com/a/48381194
has text: Just created clf instance to load classifier to fit data for model building using linear kernel. As u can choose different kernel methods for prediction which is also depends upon you data.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83835016
has text: Please put that in your post and title. The text to speech library is not important for the problem at hand.
type: AnswerComment
comment on: http://stackoverflow.com/a/48421727
score: 0
type: Comment

http://stackoverflow.com/a/48381810
accepted answer of: http://stackoverflow.com/q/48379584
type: Answer
has body: The solution of the post that samples is only valid if you use QTableView, QTableWidget does not allow to establish a new model, there are several options to solve this problem. For the example I will assume that the data has the following form: Number Company Equipment Status ---------- ---------- ---------- ---------- 1 company1 Equipment1 YES 2 company2 Equipment2 NO 3 company3 Equipmen3 NO 4 company4 Equipment4 YES Using the setBackground() method of QTableWidgetItem self.tableWidget.setRowCount(0) for row_number, row_data in enumerate(results): self.tableWidget.insertRow(row_number) for column_number, data in enumerate (row_data): self.tableWidget.setItem(row_number,column_number, QTableWidgetItem(str(data))) if column_number == 3 and data == "NO": [self.tableWidget.item(row_number, c).setBackground(Qt.red) for c in range(len(row_data))] Using a delegate: class Delegate(QStyledItemDelegate): def paint(self, painter, option, index): ix = index.model().index(index.row(), 3) if ix.data() == "NO": painter.fillRect(option.rect,Qt.red) QStyledItemDelegate.paint(self, painter, option, index) [...] self.tableWidget.setItemDelegate(Delegate(self.tableWidget)) Output:
has comment: http://stackoverflow.com/comment/83753395
answers question: http://stackoverflow.com/q/48379584
score: 0
has comment: http://stackoverflow.com/comment/83766872
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83753352

http://stackoverflow.com/comment/102234919
has text: @OstapDidenko https://www.alexkras.com/copy-any-api-call-as-curl-request-with-chrome-developer-tools/
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48555404

http://stackoverflow.com/a/48407834
has comment: http://stackoverflow.com/comment/83805379
has body: ...is there a better way to make all the views restricted and only a few available to unauthenticated users? This is a good use-case for class based views. Define a base class with the login handling, say LoginRequiredView, and make any authenticated endpoints subclass this base, rather than using function-based views with decoration on each function. The few views available to unauthenticated users will inherit from Django's generic View rather than the login required base. Django actually provides a mixin class which you can use: from django.contrib.auth.mixins import LoginRequiredMixin class LoginRequiredView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' When a view uses this mixin, or subclasses a base with the mixin, requests by non-authenticated users will be redirected to the login page.
has comment: http://stackoverflow.com/comment/83804843
has comment: http://stackoverflow.com/comment/83805362
type: Answer
upvote count: 6
score: 2
answers question: http://stackoverflow.com/q/48407790
downvote count: 4

http://stackoverflow.com/q/48374664
accepted answer: http://stackoverflow.com/a/48374756
tagged with: variable-assignment
tagged with: python
has comment: http://stackoverflow.com/comment/83736572
possible better answer: http://stackoverflow.com/a/48374745
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/83736524
upvote count: 1
has title: Determining length of a random list being altered
has comment: http://stackoverflow.com/comment/83736563
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48374745
tagged with: list
tagged with: random
downvote count: 0
has body: I have a list being accessed randomly within a list, to which I am adding an element. (note that the element has to be inserted randomly inside of the list, i.e. I don't want to insert at the end or start) For example: myList = [[0, 1, 4, 7],[0, 3, 2, 7]] toinsert = [5, 6] for item in toinsert: random.choice(myList).insert(random.randint(1,len(`the list that got chosen`)-2), item) I have tried using choicelist = random.choice(myList) choicelist.insert(randint(1,len(choicelist))) but then I'm not sure how to put that back in where the original list was - considering it's a random list. I know I could randomly choose an index for myList and use that method, but I was looking for a hopefully more Pythonic - and shorter - way of doing so.
score: 1
has answer: http://stackoverflow.com/a/48374756

micropython
tags question: http://stackoverflow.com/q/48367213
type: Tag
tags question: http://stackoverflow.com/q/48385068
tag name: micropython
tags question: http://stackoverflow.com/q/48357989

http://stackoverflow.com/a/48349031
upvote count: 1
has comment: http://stackoverflow.com/comment/83702423
has comment: http://stackoverflow.com/comment/83703799
has comment: http://stackoverflow.com/comment/83701712
score: 1
has comment: http://stackoverflow.com/comment/83701619
answers question: http://stackoverflow.com/q/48342556
type: Answer
has body: First of all, the python code you've posted is broken, if you did copy&amp;paste from your own script, then your code is invalid python because the indentation is wrong. Secondly, it's a bad idea to just execute a script with exec, this can be dangerous, specially if you are not the owner of the script and how knows what the script does. So let's modify your root/externalFunc.py first: let's add a run method that does the work of the script. Instead of just printing to the standard output, the run function should return something, for example the a string or a dictionary containing the results. Because you haven't shown us the code of root/externalFunc.py, I assume that the script may look like this: #!/usr/bin/env python # root/externalFunc.py # old version def run(): # ... doing some work, # result is a variable with the result print "Result: %d" % result if __name__ == '__main__': main() Now let's modify it. create an empty file __init__.py in the root/ directory: // on linux/mac/bsd $ touch root/__init__.py // on windows cmd&gt; type NUL &gt; root/__init__.py This allows to use from root.whatever export something in another module. Let's add a run method that actually does the work: The new version: #!/usr/bin/env python # root/externalFunc.py # new version import sys def run(parm1, param2, param3): # ... doing some work, # result is a variable with the result return = { "success": True, "value": result } def main(): if len(sys.argv) != 4: print &gt;&gt; sys.stderr, "usage: %s param1 param2 param3" % sys.argv return 1 param1 = int(sys.argv[1]) param2 = sys.argv[2] param3 = int(sys.argv[3]) res = run(param1, param2, param3) if res["success"]: print "Result: %d" % res["value"] return 0 else: print "Error, ..." return 1 if __name__ == '__main__': return main() Now we have to change your server code to import the run method and use that method instead of using exec or execfile from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from root.externalFunc impor…
has comment: http://stackoverflow.com/comment/83700365
has comment: http://stackoverflow.com/comment/83726767
has comment: http://stackoverflow.com/comment/83701518
has comment: http://stackoverflow.com/comment/83726909
has comment: http://stackoverflow.com/comment/83701317
has comment: http://stackoverflow.com/comment/83701698
downvote count: 0

http://stackoverflow.com/comment/83830956
type: AnswerComment
has text: it depends, if you are using multiple django apps , you need a uwsgi process for each of them thus need a separate socket for each uwsgi, the answer above is a draft implementation and you should read the Nginx, uwsgi documentation for a specific code for your use case
comment on: http://stackoverflow.com/a/48419709
score: 0
type: Comment

http://stackoverflow.com/a/51420036
downvote count: 0
has body: you have two options use pyenv and pyenv-virtualenv wrapper together. for example, you want to create a new project test and also want to create a virtual env for it. pyenv install 3.6.5 pyenv virtualenv 3.6.5 test cd /project_path pyenv local test next time, you access the project dir, it will change to test environment automatically use pyenv and pipenv together firstly, add this script to the env config(bashrc or zshenv, etc.) export PIPENV_VENV_IN_PROJECT=1 PROMPT_COMMAND='prompt' precmd() { eval "$PROMPT_COMMAND" } function prompt() { if [ ! $PIPENV_ACTIVE ]; then if [ `pipenv --venv 2&gt;/dev/null` ]; then export PIPENV_INITPWD="$PWD" pipenv shell fi elif [ $PIPENV_INITPWD ] ; then cd "$PIPENV_INITPWD" unset PIPENV_INITPWD fi } then pyenv install 3.6.5 pyenv shell 3.6.5 pip install pipenv cd /project_path pipenv --python 3.6.5 next time you access the directory, it will change to the correct vent(note: you should use pyenv shell 3.6.5 before you access the project dir)
type: Answer
answers question: http://stackoverflow.com/q/48470540
upvote count: 3
score: 3

http://stackoverflow.com/comment/83913628
has text: Works. But may you explain a bit more why update() instead of = works?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48460264
score: 0

http://stackoverflow.com/a/48435693
has comment: http://stackoverflow.com/comment/83863065
has body: Here's a similar approach to the previous answer, which will give you the table from the web page in nested list form (i.e. [[table row], [table row], ...': data = soup.find_all("ul", {"id": "tco_detail_data"}) # get all list elements lis = data[0].find_all('li') # add a helper lambda, just for readability find_ul = lambda x: x.find_all('ul') uls = [find_ul(elem) for elem in lis if find_ul(elem) != []] # use a nested list comprehension to iterate over the &lt;ul&gt; tags # and extract text from each &lt;li&gt; into sublists text = [[li.text.encode('utf-8') for li in ul[0].find_all('li')] for ul in uls] # [ # ['\xc2\xa0', 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', '5 Yr Total'], # ['Depreciation', '$4,853', '$1,658', '$1,459', '$1,293', '$1,161', '$10,424'], # ['Taxes &amp; Fees', '$2,057', '$21', '$66', '$21', '$66', '$2,231'], # ['Financing', '$1,026', '$821', '$605', '$376', '$136', '$2,964'], # ['Fuel', '$1,606', '$1,654', '$1,704', '$1,755', '$1,808', '$8,527'], # ['Insurance', '$764', '$791', '$818', '$847', '$877', '$4,097'], # ['Maintenance', '$230', '$601', '$385', '$1,653', '$1,504', '$4,373'], # ['Repairs', '$0', '$0', '$109', '$257', '$374', '$740'], # ['Tax Credit', '$0', '', '', '', '', '$0'], # ['True Cost to Own \xc2\xae', '$10,536', '$5,546', '$5,146', '$6,202', '$5,926', '$33,356'] # ] # write "text" list to csv with open('ford_escape_2017.csv', 'w') as f: writer = csv.writer(f) writer.writerows(text)
has comment: http://stackoverflow.com/comment/83864280
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48435390
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83877203
answers question: http://stackoverflow.com/q/48435390

http://stackoverflow.com/comment/83948349
has text: Thanks a lot Idlehands. I realized it was the same issue as before and spent several hours trying to figure it out but to no avail. I've adapted your updated suggestion even further to pull out some other bits. It's all working just fine now -- thanks again
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48456072

http://stackoverflow.com/q/48340494
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48340793
has comment: http://stackoverflow.com/comment/83666350
has body: So I am simply trying to add LectureCategory in my Lecture model, I want the user to be only able to select between Classes or Seminars. If I put choices in both models, I can see them on django admin, but I get the error: Cannot assign "'0'": "Lecture.lecture_category" must be a "LectureCategory" instance. If I dont put choices in second model, then in admin panel will show 0 or 1, instead of my values. Any suggestion ? class LectureCategory(models.Model): lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) def __str__(self): return str(self.lecture_category) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', null=True, ) lecture_category = models.ForeignKey('LectureCategory', on_delete=models.CASCADE, default='', related_name='categories', choices=((0, "Classes "), (1, "Seminars"), ) )
has answer: http://stackoverflow.com/a/48340793
type: Question
has answer: http://stackoverflow.com/a/48340787
has comment: http://stackoverflow.com/comment/83666275
has comment: http://stackoverflow.com/comment/83666162
has title: Django cannot assign value, must be another instance
has comment: http://stackoverflow.com/comment/83666508
has comment: http://stackoverflow.com/comment/83666313
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48340787
has comment: http://stackoverflow.com/comment/83666127
has comment: http://stackoverflow.com/comment/83666144

http://stackoverflow.com/comment/83773324
comment on: http://stackoverflow.com/q/48392381
type: Comment
type: QuestionComment
score: 0
has text: Glob can also find folders only, see: https://stackoverflow.com/a/36426997/2305545

http://stackoverflow.com/comment/83740219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48341767
type: AnswerComment
has text: @Manoranjan It might be that your parent process is not waiting for the child process to finish, leaving a "zombie" process... Anyway I believe you should ask a different question about that. Specify which OS you are using (processes behaviour is OS specific, especially in "corner case" situations like termination etc) and provide a very simple example that replicates the situation.

http://stackoverflow.com/comment/83720198
score: 0
type: Comment
type: QuestionComment
has text: But where do you think you are redirecting? There are no redirects anywhere in this code.
comment on: http://stackoverflow.com/q/48366707

http://stackoverflow.com/comment/83784260
comment on: http://stackoverflow.com/q/48384175
has text: @bipll Yea. That's the way I need to follow. Do You have any suggestions for some library?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83877996
has text: @HolyMonk but `f(x) >= 0` is not what your code on the Question says. The -1 I get now. And yes, in that case it is fine
score: 0
comment on: http://stackoverflow.com/q/48443095
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83721220
has text: 19 can also be made with 2+17. Also how can 3 be made from sum of 2 elements of list B?
type: QuestionComment
comment on: http://stackoverflow.com/q/48367308
score: 0
type: Comment

http://stackoverflow.com/q/48389545
has title: numpy multidimension array from pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/83767860
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83768280
has comment: http://stackoverflow.com/comment/83767002
has body: I have a Pandas dataframe and I chose some coluns from them and create two dataframe with same length: series1 = df'VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5','VAL6' series2 = df'OTHER_VAL1', 'OTHER_VAL2', 'OTHER_VAL3', 'OTHER_VAL4', 'OTHER_VAL5','OTHER_VAL6' After that i create two numpy array from each DataFrame series_1_np = series1.values series_2_np = series2.values Both array shape looks like this: (69193, 6) I would like to reshape my series1 to shape like: (69193, 6, 6) and would like to add each values from series2 to the new expanded dimension. I'm asking it because I would like to create a Conv1D keras model. Now i'm doing it this way: I create a new dimension in my series1: series1 = np.expand_dims(series1, axis=-1) Then I create my model: model = Sequential() model.add(Conv1D(filters=2 , kernel_size=3, strides=1, input_shape=(6, 1)) ) ... ... It's running, there isn't any problem with this. But, I have another feature set in my series2 and would like to send it to my model input. How can I do that? Sorry but I can't even start it. Thank you! Thank you!
tagged with: pandas
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/83768481
has comment: http://stackoverflow.com/comment/83766916
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83768353
tagged with: numpy
upvote count: 0
has answer: http://stackoverflow.com/a/48390410
accepted answer: http://stackoverflow.com/a/48390410
has comment: http://stackoverflow.com/comment/83766972
has comment: http://stackoverflow.com/comment/83766873
has comment: http://stackoverflow.com/comment/83768430
has comment: http://stackoverflow.com/comment/83767016
has comment: http://stackoverflow.com/comment/83767794
tagged with: python
tagged with: keras

http://stackoverflow.com/comment/83756089
has text: Please see https://stackoverflow.com/questions/48384516/python-opencv-cropping-images-and-isolating-specific-objects Hope this is clear.
type: AnswerComment
comment on: http://stackoverflow.com/a/48356640
score: 0
type: Comment

http://stackoverflow.com/comment/83841094
score: 0
type: Comment
type: AnswerComment
has text: Are you sure a five minutes lag is enough for me not to get banned for running this 24/7 ?
comment on: http://stackoverflow.com/a/48425235

http://stackoverflow.com/comment/83950231
type: QuestionComment
has text: Note that `command=check_value()` would call `check_value` method immediately after that line was read if `ScrollMenu` was an actual widget.
score: 0
comment on: http://stackoverflow.com/q/48469593
type: Comment

http://stackoverflow.com/q/48417818
score: 0
has title: Python installation in custom directory (Linux): PIP not working
accepted answer: http://stackoverflow.com/a/48417945
tagged with: pip
answer count: 1
tagged with: linux
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48417945
has body: I have installed Python3.6.4 in a Linux machine, under a user directory, lets say /drive/username/Python3.6.4 I've setup my path and aliases, and Python is working properly (i.e. executing python3 puts me in the correct environment, which python3 produces: /drive/username/Python3.6.4/bin/python3) The problem is with pip! When i execute pip3, i am getting: -bash: /username/Python3.6.4/bin/pip3: /usr/local/bin/python3.6: bad interpreter: No such file or directory the command which pip3 gives: /drive/username/Python3.6.4/bin/pip3 What am i missing?
tagged with: bash
type: AnsweredQuestion

http://stackoverflow.com/comment/83812595
comment on: http://stackoverflow.com/q/48410832
score: 0
has text: You're welcome, I just suddenly hit a wall and wondered whether there was some practical limitation that stopped me developing my answer. So, if you get the correct output from me supplying `dictlines` as a list, e.g. `dictlines = ['Monday', 'Tuesday']` then there is no limitation stopping you from doing it this way?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83871399
has text: @Yang glad I could help - and feel free to accept the answer if it solved your problem ;)
type: Comment
comment on: http://stackoverflow.com/a/48423970
type: AnswerComment
score: 0

http://stackoverflow.com/a/48434845
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/48433682
type: AcceptedAnswer
has body: Maybe have you changed your default user model in the settings? Instead of using User directly with the the Foreign key, you should use user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) in your Comment Model, as follow class Comment(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) You need to apply migrations to be able to add user to Comment, python manage.py makemigrations python manage.py migrate if at the moment that you are applying migrations, shell shows a message telling You are trying to add a non-nullable field 'user' to comment without a default You have 2 Options Skip migrations and add a default value to the field in the models or set the attribute as nullable, whatever else that you need ie user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) and apply migrations again Or select a default value to the new field, should be an id of an existing user in databse This is because django should populate existing records in database, if exist
downvote count: 0
has comment: http://stackoverflow.com/comment/92434574
type: Answer
accepted answer of: http://stackoverflow.com/q/48433682
has comment: http://stackoverflow.com/comment/83861440

http://stackoverflow.com/a/48355054
type: Answer
answers question: http://stackoverflow.com/q/48354740
has body: group by your key columns and call cumsum: df['CumSum'] = df.groupby(['F(1)', 'F(2)', 'F(3)'])['Amount'].cumsum() df Out: F(1) F(2) F(3) Amount CumSum 0 A B C 100 100 1 A B C 100 200 2 A B C 100 300 3 D E F 300 300 4 D E F 150 450 5 G H I 100 100 6 G H I 200 300
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83697327
score: 1

http://stackoverflow.com/a/48482475
has comment: http://stackoverflow.com/comment/84070749
has comment: http://stackoverflow.com/comment/84051449
type: Answer
has comment: http://stackoverflow.com/comment/84022501
has comment: http://stackoverflow.com/comment/84044292
has comment: http://stackoverflow.com/comment/84063937
has comment: http://stackoverflow.com/comment/84032287
has comment: http://stackoverflow.com/comment/83990136
score: 0
has comment: http://stackoverflow.com/comment/83969665
has comment: http://stackoverflow.com/comment/84023843
has comment: http://stackoverflow.com/comment/84020373
has comment: http://stackoverflow.com/comment/83982481
answers question: http://stackoverflow.com/q/48477818
has body: Only when dropdown is a HTML native dropdown which defined by Select &amp; Option Tag, you can use the Select class. Your auto-suggest list is not native dropdown, it's a css simulated dropdown, so you should operate it as button or text field by finding it and clicking it. Option 1) directly click on the wanted option def select_campus(campus_name): driver.find_element_by_css_selector('input#autoCampusId') .sendKeys(campus_name) WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR , "div.ac_results li")) auto_suggest_list = driver.find_elements_by_css_selector('div.ac_results li') found = false; print '@' + campus_name.upper() + '@' for item in auto_suggest_list: print '#' + item.text.upper() + '#' print 'location: ' + item.location if(item.text.strip().upper() == campus_name.strip().upper()): print 'find matched option' item.click() found = true break if found == false : print 'Can not find campus: ' + campus_name Option 2) Use Down Key move to wanted option from selenium.webdriver.common.keys import Keys def select_campus(campus_name): input_ele = driver.find_element_by_css_selector('input#autoCampusId'); input_ele.sendKeys(campus_name) WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR , "div.ac_results li")) auto_suggest_list = driver.find_elements_by_css_selector('div.ac_results li') for item in auto_suggest_list: if(item.text.strip().upper() != campus_name.strip().upper()): input_ele.sendKeys(Keys.DOWN) else: input_ele.sendKeys(Keys.ENTER) break A tip: From your screenshot for HTML code, the div.ac_results is not visible (there is display: none in style attribute). Selenium can't operate on invisible element also its descendants.
has comment: http://stackoverflow.com/comment/84003682
accepted answer of: http://stackoverflow.com/q/48477818
has comment: http://stackoverflow.com/comment/84028726
has comment: http://stackoverflow.com/comment/84022540
has comment: http://stackoverflow.com/comment/83979619
type: AcceptedAnswer

http://stackoverflow.com/a/62289179
answers question: http://stackoverflow.com/q/48481134
type: Answer
score: 0
has body: The make_scorer function sign flips if greater_is_better is False

http://stackoverflow.com/comment/83871722
type: Comment
has text: Yes the Raspberry got an monitor (hdmi) and the Kivy samples run fine on it. @dsgdfg
type: QuestionComment
comment on: http://stackoverflow.com/q/48439807
score: 0

canny-operator
tags question: http://stackoverflow.com/q/48477739
type: Tag
tag name: canny-operator

http://stackoverflow.com/q/48370072
upvote count: 0
has body: So I need to import game_state.py in in order to use a class in it called State in some other classes. However, when I try to initialize a class attribute using State it says local variable referenced before assignment from game_state import State class Game: current_state: State name: str def __init__(self, is_p1_turn: bool) -&gt; None: self.is_p1_turn = is_p1_turn self.current_state = State('Player 1', None, self) if self.is_p1_turn \ else self.current_state = State('Player 2', None, self) self.name = self.__name__ the first State('player1' None, self) shows error msg: local variable 'State' value not used the second State('Plyaer2' None, self) shows another msg: local variable might referenced &amp; unresolved reference 'State' I know there's something wrong but just couldn't figure it out
answer count: 1
has title: Python - Local variable error where variable is an imported class
has answer: http://stackoverflow.com/a/48370153
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83726784
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83726906
has comment: http://stackoverflow.com/comment/83726803

http://stackoverflow.com/a/48419709
type: Answer
has comment: http://stackoverflow.com/comment/83861715
score: 0
has body: Nginx can work with multiple domains using the server namespace server { listen 80; server_name example.org www.example.org; ... } you can set multiple servers (best practice as multiple files) and multiple upstream as so upstream uwsgi { server unix:///tmp/uwsgi.sock; } so each server will invoked by different domain and pass the request to different uwsgi process (aka different django app) An example Nginx configuration can look like this, keep in mind that you will need multiple uwsgi process, one for each app upstream uwsg_app_a { server unix:///tmp/uwsg_app_b.sock; } upstream uwsg_app_b { server unix:///tmp/uwsg_app_a.sock; } server { listen 80; server_name www.test.com; location / { root /homapge/static; } } server { listen 80; server_name appa.test.com; location / { uwsgi_pass uwsg_app_a; } } server { listen 80; server_name appb.test.com; location / { uwsgi_pass uwsg_app_b; } }
has comment: http://stackoverflow.com/comment/83829978
has comment: http://stackoverflow.com/comment/83868260
answers question: http://stackoverflow.com/q/48419372
has comment: http://stackoverflow.com/comment/83830956
has comment: http://stackoverflow.com/comment/83861588

http://stackoverflow.com/q/48430142
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48430422
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: pipenv
has answer: http://stackoverflow.com/a/48432040
tagged with: python
has body: having a little trouble trying to use pipenv. i ran the following command pipenv install bs4 and it came out with : ���������������������������������Requirement already satisfied: bs4 in /home/sam/.local/share/virtualenvs/ICOtools-kKWO0fqD/lib/python2.7/site-packages Requirement already satisfied: beautifulsoup4 in /home/sam/.local/share/virtualenvs/ICOtools-kKWO0fqD/lib/python2.7/site-packages (from bs4) Adding bs4 to Pipfile's [packages]��� Locking [dev-packages] dependencies��� Locking [packages] dependencies��� Updated Pipfile.lock (5de6ca)! then when i run my script i still get 'ImportError: No module named bs4' the second line of my script is 'from bs4 import BeautifulSoup' I am running Ubuntu(xenial) on a chromebook using crouton not sure if that effects this.
score: 2
answer count: 2
has title: bs4 import error using pipenv

http://stackoverflow.com/q/48475420
accepted answer: http://stackoverflow.com/a/48476132
answer count: 1
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48476132
favorite count: 0
type: AnsweredQuestion
has body: I have a purpose to create the same private key / public key based on an input string: I am facing a problem when trying to import a ECC private key: This private key was created from a hash: import sys import base64 import string from Crypto.PublicKey import ECC from Crypto.Hash import SHA256 from Crypto.IO import PEM input = sys.argv[1] input_hash = SHA256.new(input) private_pem = PEM.encode(input_hash.digest(), "PRIVATE KEY", passphrase=None, randfunc=None) key = ECC.import_key(private_pem) bellow the trace: Traceback (most recent call last): File "request.py", line 29, in key = ECC.import_key(private_pem) File "C:\Python27\lib\site-packages\Crypto\PublicKey\ECC.py", line 792, in import_key return _import_der(der_encoded, passphrase) File "C:\Python27\lib\site-packages\Crypto\PublicKey\ECC.py", line 725, in _import_der raise ValueError("Not an ECC DER key") ValueError: Not an ECC DER key Anyone have an idea about the problem?
tagged with: cryptography
type: Question
score: 2
has title: Error when trying to import a ECC private key with python
upvote count: 2

http://stackoverflow.com/comment/83734607
has text: `str(int(A) | int(B))` removes leading 0's. We need to add back a certain number of 0's, precisely `len(A) - len(c_1)`. The `*0` repeats a string by the preceding integer.
type: Comment
comment on: http://stackoverflow.com/a/48373645
score: 0
type: AnswerComment

http://stackoverflow.com/a/48476181
score: 1
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: It looks like that for row in reader running only once try change the order of your code Try to open the file inside the while True: like this: while True: with open("accounts.csv") as csvfile: reader = csv.reader(csvfile) should work fine because you close the file before each iteration
answers question: http://stackoverflow.com/q/48476040
accepted answer of: http://stackoverflow.com/q/48476040

http://stackoverflow.com/comment/83712489
type: QuestionComment
has text: What have you tried so far? Please post your code
comment on: http://stackoverflow.com/q/48362768
type: Comment
score: 1

http://stackoverflow.com/comment/83778018
type: QuestionComment
comment on: http://stackoverflow.com/q/48395051
has text: I guess I should update that, ''123.com': [ None ], ' should probbly read '123.com': None, not in a list.
type: Comment
score: 0

http://stackoverflow.com/comment/83769410
comment on: http://stackoverflow.com/q/48390451
has text: ... you never print anything with regards to `df`, so I wouldn't expect to *see anything*.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48450994
has body: from collections import defaultdict import csv inpath = '' # Path to input CSV file outpath = '' # Path to output CSV file output = defaultdict(list) # Dictionary like {user_id: [meetings]} for row in csv.DictReader(open(inpath)): output[row['user']].append(row['meetings']) with open(outpath, 'w') as f: for user, meetings in output.items(): row = user + ',' + str(meetings) + '\n' f.write(row)
answers question: http://stackoverflow.com/q/48450639
score: 0
type: Answer

http://stackoverflow.com/comment/83933955
type: QuestionComment
comment on: http://stackoverflow.com/q/48467779
type: Comment
has text: The first step is making sure that VS Code picked up the interpreter you expect. So if you do step #3 of the [tutorial prerequisites](https://code.visualstudio.com/docs/python/python-tutorial#_prerequisites) you will see the instructions on how to explicitly select the interpreter. After that you can write a file that does nothing but `import pandas; print "It worked!"`, right-click, and select `Run Python File in Terminal`. If that didn't work then you didn't install pandas for the Python interpreter you thought you did. If that works but debugging fails then your `launch.json` might be off.
score: 1

http://stackoverflow.com/comment/83848369
comment on: http://stackoverflow.com/q/48428689
score: 0
type: QuestionComment
has text: It looks like you didn't set Anaconda to be the default python version on your system when you installed it?
type: Comment

http://stackoverflow.com/comment/84043413
type: Comment
has text: Make sure you're using an authorized email account; this mostly has to be a gmail account. This can be done in the GAE settings, email sender section.
type: AnswerComment
comment on: http://stackoverflow.com/a/48483853
score: 0

http://stackoverflow.com/comment/83870965
has text: If this works you could permanently add that path to your pythonpath.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48426017
type: Comment

http://stackoverflow.com/q/48481246
type: Question
has answer: http://stackoverflow.com/a/51188024
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85305284
has answer: http://stackoverflow.com/a/48481525
has title: Scrape socket.io data from website using python
has body: I am trying to scrape latest bid and ask prices from this website "http://btc-exchange.com/" I can see that the prices are being provided by this socket.io wss://pusher.mistertango.com/socket.io/?EIO=3&amp;transport=websocket&amp;sid=XXX The sessionID is being generated from this call https://pusher.mistertango.com/socket.io/?EIO=3&amp;transport=polling&amp;t=1517079662330-10 This is the code which I am currently using import requests from websocket import create_connection import json SID_url = "https://pusher.mistertango.com/socket.io/?EIO=3&amp;transport=polling" SID_req = requests.get(SID_url, headers={'User-Agent': 'Mozilla/5.0'}).text SID = SID_req[SID_req.index("sid")+6:SID_req.index(",")-1] print(SID_req) print(SID) ws = create_connection("wss://pusher.mistertango.com/socket.io/?EIO=3&amp;transport=websocket&amp;sid="+SID) ws.send('2probe') print(ws.recv()) ws.send('5') print(ws.recv()) ws.send('42["subscribe",{"chan":"market-e559906eda4362f58bcaab40a4bfb5b4"}]') while True: result = ws.recv() print(result) ws.close() This is the output of the code ÿ0{"sid":"mURV8OnaNqax_AmvAAF2","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000} mURV8OnaNqax_AmvAAF2 3probe 40 The messages which I have sent are based on the messages I saw in chrome-dev tool. Websocket msgs My connection stops receiving any message after '40'. What am I doing wrong?
tagged with: python
upvote count: 3
answer count: 2
downvote count: 0
tagged with: websocket
tagged with: web-scraping
tagged with: socket.io
favorite count: 0

http://stackoverflow.com/a/48398063
has body: just try this one and check does it meet your requirements : from django.db.models import Avg frst = Item.objects.value_list('id', flat=True) scnd = ItemRating.objects.filter( item_id__in=frst).annotate(rating=Avg('score')).order_by('rating').values_list('rating', flat=True)
answers question: http://stackoverflow.com/q/48397761
has comment: http://stackoverflow.com/comment/83886106
has comment: http://stackoverflow.com/comment/83864244
has comment: http://stackoverflow.com/comment/83907409
type: Answer
score: 0

http://stackoverflow.com/comment/83763016
type: AnswerComment
has text: Great! Would you mind elaborating on why it was filling the interior with triangles?
type: Comment
comment on: http://stackoverflow.com/a/48373269
score: 0

http://stackoverflow.com/comment/85667817
score: 0
type: AnswerComment
has text: It doesn't work, and AWS Support have confirmed on this, that only pure python libaries/packages are supported by Glue currently, and any packages relying on C extensions are not supported. ImportError is due to the reason, glue couldn't recognize the PyServe library.
type: Comment
comment on: http://stackoverflow.com/a/49330132

http://stackoverflow.com/comment/83658123
type: QuestionComment
has text: half of the data? have you tried to add `stderr=subprocess.STDOUT` to also capture error stream?
score: 1
comment on: http://stackoverflow.com/q/48336543
type: Comment

http://stackoverflow.com/comment/83652803
type: Comment
score: 0
type: AnswerComment
has text: First of all, thanks for your response. It will be something like this? def get(self, request, format=None): users = User.objects.all() response = self.serializer(users, many=True) dictionary = {} for j in range(0,len(response.data)): dictionary.update(response.data[j]) myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = [{"text":v} for v in dictionary.values()] print(myresponse)
comment on: http://stackoverflow.com/a/48333592

http://stackoverflow.com/a/48393743
type: Answer
answers question: http://stackoverflow.com/q/48393259
has comment: http://stackoverflow.com/comment/83775151
score: 1
has body: You can using category df.ID=df.ID.astype('category',categories=[1,2,3,4]) df.ATTR=df.ATTR.astype('category',categories=[0,10,20,30]) pd.crosstab(df.ID,df.ATTR) Out[1143]: ATTR 0 10 20 30 ID 1 0 0 2 0 2 0 0 0 0 3 0 1 0 0 4 0 0 0 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48360386
downvote count: 2
tagged with: arrays
has answer: http://stackoverflow.com/a/48360460
has comment: http://stackoverflow.com/comment/83707516
has comment: http://stackoverflow.com/comment/83707537
favorite count: 0
has answer: http://stackoverflow.com/a/48360440
tagged with: list
tagged with: multidimensional-array
answer count: 3
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48360466
type: Question
has comment: http://stackoverflow.com/comment/83707591
has title: How to assign [A-Z] to values in multi-dimensional array Py2.7
upvote count: 1
has body: Context I have a list of numbers in an array, I want to append a letter to the value in the array depending on the number. Code numbers = [] numbers.append(9,8,7,6,5,4,3,2,1) Psuedo-Code I've tried something like this but got stuck it failed and just assigned [A-Z] to each letter for x in numbers: x.join('[A-Z]') I want to add A to 9, B to 8, etc... How do I do this dynamically?
type: UnansweredQuestion

http://stackoverflow.com/a/48361167
answers question: http://stackoverflow.com/q/48361143
has comment: http://stackoverflow.com/comment/83709108
has comment: http://stackoverflow.com/comment/83709453
type: Answer
has body: Your regex needs to account for all the possibilities of 140000 to 150000 ^mark_1(4\d{4})|(50{4})
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83709209
has comment: http://stackoverflow.com/comment/83709231

http://stackoverflow.com/a/48462132
answers question: http://stackoverflow.com/q/48461808
score: 0
accepted answer of: http://stackoverflow.com/q/48461808
type: AcceptedAnswer
has body: Just add a key attribute to each dataframe and concat, like so: import pandas as pd d = {'k1': pd.DataFrame({'max': [1, 2, 3], 'min': [1, 2, 3]}, index=[0, 1, 2]), 'k2': pd.DataFrame({'max': [4, 5, 6], 'min': [4, 5, 6]}, index=[3, 4, 5])} for k in d: d[k].insert(0, 'key', [k]*len(d[k])) res = pd.concat(d.values()) print(res) prints out key max min 0 k1 1 1 1 k1 2 2 2 k1 3 3 3 k2 4 4 4 k2 5 5 5 k2 6 6 n.b. this also works if the indices are repeated across dataframes: key max min 0 k1 1 1 1 k1 2 2 2 k1 3 3 0 k2 4 4 1 k2 5 5 2 k2 6 6
type: Answer

http://stackoverflow.com/comment/83770204
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48391097
has text: Can you tell us what you already tried to do? Which part is not working, give some sample code etc.?

http://stackoverflow.com/q/48445023
has comment: http://stackoverflow.com/comment/83881925
tagged with: python
has answer: http://stackoverflow.com/a/48448294
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83882128
has comment: http://stackoverflow.com/comment/83882016
has comment: http://stackoverflow.com/comment/83881601
has body: I need to uninstall anaconda completely. I have followed the instruction on this website: but after that, when i key in conda list, conda --version commands in mac bash, it still outputs results as if anaconda is still in my system how can I check if I have uninstalled all anaconda-related files completely? the output of conda --version is: conda 4.4.7 and when I run $ which python, I get: /Applications/anaconda3/bin/python when I run $ python -V, I get: Python 3.6.3 :: Anaconda custom (64-bit)
tagged with: bash
tagged with: anaconda
score: 0
has title: Unable to have anaconda fully uninstalled
answer count: 1
type: Question

http://stackoverflow.com/q/48418843
type: AnsweredQuestion
has title: Find smaller subset when comparing elements in two lists of lists
downvote count: 0
has comment: http://stackoverflow.com/comment/83827844
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48419706
has comment: http://stackoverflow.com/comment/83827378
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48419706
has comment: http://stackoverflow.com/comment/83827773
has body: Sorry if this is complicated, but I'll try to explain this as best I can. I have two lists of lists with the same number of elements but organized in a different way, for example: a = [1],[2,3,4],[5,6],[7,8,9],[10,11,12,13] b = [1,2,3,4],[5,6],[7,8,9],[10,11,12],[13] I'm trying to 1) find what are the differing lists between the two lists of lists, and 2) for each differing list, find the length of the smaller subset. Hence, for list a, [1] and [2,3,4] are subsets of [1,2,3,4] in b - therefore, [1] is the smaller subset and its length is 1. I'm able to create a list of differing lists for both a and b via: matches = [x for x in a if x in b] adiff = [x for x in a if x not in matches] bdiff = [x for x in b if x not in matches] However, I can't seem to get to part 2. Is this possible in python? Edit: Sorry, the list in b should be [5,6]. So the desired output when a is compared against b is 1, given that the length of [1] is 1. When b is compared against a, the desired output is also 1 since the length of [13] is also 1.
type: Question
has comment: http://stackoverflow.com/comment/83827560
has comment: http://stackoverflow.com/comment/83828902
has comment: http://stackoverflow.com/comment/83828001
tagged with: python
has comment: http://stackoverflow.com/comment/83827612
has comment: http://stackoverflow.com/comment/83828146
has comment: http://stackoverflow.com/comment/83834499
has comment: http://stackoverflow.com/comment/83827615
has comment: http://stackoverflow.com/comment/83828262
has comment: http://stackoverflow.com/comment/83828325
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83829790
has comment: http://stackoverflow.com/comment/83834462

http://stackoverflow.com/comment/83709231
type: AnswerComment
has text: i am dense, youre right :) `^(mark_1(?:4\d{4})|(?:50{4}))$` would get cleaner groups
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48361167

http://stackoverflow.com/q/48369279
tagged with: python-3.x
answer count: 2
tagged with: time-complexity
upvote count: 1
type: UnansweredQuestion
downvote count: 0
has title: Time and Space Complexity of 2 Functions
has body: def bar(n): if n==0: return 0 else: return n+bar(n-1) def foo(n): if n==0: return 0 else: return bar(n)+foo(n-1) Hi, I have just learnt about space and time complexity. Can anyone confirm with me whether I'm right to say the time complexity of foo is O(n**2) and the space complexity of foo is O(n)? Not too sure about the time complexity as foo calls bar which only calls itself once, while foo always calls out 2 functions.
favorite count: 0
has comment: http://stackoverflow.com/comment/83725348
type: Question
has answer: http://stackoverflow.com/a/48371680
tagged with: algorithm
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48369589

http://stackoverflow.com/comment/83892357
has text: nice! just so everyone else uses the same code I did: training'Pclass','Sex','Age' = training.set_index(['Pclass','Sex']).Age.fillna(table.Age).reset_index()
type: AnswerComment
comment on: http://stackoverflow.com/a/48449158
score: 1
type: Comment

http://stackoverflow.com/a/48410398
has comment: http://stackoverflow.com/comment/83849482
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48410032
has comment: http://stackoverflow.com/comment/83845032
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83852320
accepted answer of: http://stackoverflow.com/q/48410032
has body: Simply merge the two sets on matching criteria and then run a groupby sum: merged_df = pd.merge(df1, df2, on=['date', 'Jurisdiction', 'Product']) merged_df.groupby(['date', 'Jurisdiction', 'Product'])['Rate'].sum() Or with most recent date of df2: most_recent_df2 = df2.merge(df2.groupby(['Jurisdiction', 'Product'])['date'].max().reset_index(), on=['date', 'Jurisdiction', 'Product']) merged_df = pd.merge(df1, most_recent_df2, on=['Jurisdiction', 'Product'], suffixes=['', '_']) merged_df.groupby(['date', 'Jurisdiction', 'Product'])['Rate'].sum()
type: Answer

http://stackoverflow.com/q/48363552
has comment: http://stackoverflow.com/comment/83713974
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34835951
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
duplicate of: http://stackoverflow.com/q/34835951
has body: Ok I've been searching for about an hour now to no avail. I am trying to mimic the following code in a list comprehension. b= [] for i in [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]: b.append(cls.somefunc(**i)) I want to create a list of the returned values from somefunc with the unpacked dictionary as arguments. b = [cls.somefunc() for i in [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}] This was as close as I got. This sends each dictionary as an argument in my list to somefunc but I want each key/value pair to be passed as an argument instead of the dictionary cls.somefunc(a=1, b=2, c=3) I'm open to using map or lambda if it's required.
score: 0
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/83713905
type: Question
has title: Trying to unpack a dictionary to a method in a list comprehension
tagged with: python-3.x

http://stackoverflow.com/q/48389317
has answer: http://stackoverflow.com/a/48389344
tagged with: roundtrip
has body: Consider this snippet: &gt;&gt;&gt; import json &gt;&gt;&gt; a = {1:'1'} &gt;&gt;&gt; json_a = json.dumps(a) &gt;&gt;&gt; json.loads(json_a) {'1': '1'} My attempt was to pass a Python dict to json.dumps(), and then use json.loads() to get it back. But that doesn't happen, probably because JSON alays considers keys as strings. Is there any other way I can retain the original key types?
has answer: http://stackoverflow.com/a/48390610
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83767880
tagged with: python
score: 2
upvote count: 2
answer count: 2
has title: Can I losslessly recover integer keys which json.dumps() has converted to strings?
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question

http://stackoverflow.com/a/48332766
has comment: http://stackoverflow.com/comment/84889434
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84906760
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48332649
accepted answer of: http://stackoverflow.com/q/48332649
has body: Nothing wrong with the setup. The phrase This module is always available simply means that in every environment you should be able to import the standard math module. Since that phrase states that what you are seeing is a module and it also stated in Python's documentation that modules need to be imported I wouldn't call it inconsistent.
type: Answer

http://stackoverflow.com/comment/83941219
type: QuestionComment
score: 0
has text: Since we are going down the Python implementation rabbit hole, I took the time to write an answer.
type: Comment
comment on: http://stackoverflow.com/q/48473457

http://stackoverflow.com/comment/83940635
score: 0
has text: I already stated that I am using iteration .
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48473457

http://stackoverflow.com/comment/83889065
score: 2
comment on: http://stackoverflow.com/q/48448206
type: QuestionComment
has text: That looks like invalid syntax to me.
type: Comment

http://stackoverflow.com/comment/83954857
type: Comment
comment on: http://stackoverflow.com/q/48480667
has text: @StefanPochmann `zipfile` doesn't support creating password encrypted files, only reading them.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48391018
has body: You can't invert (~) floating point numbers and arrays. Try with: a = np.ma.masked_where(np.isclose(a, 0), a) (no for loop needed either.)
answers question: http://stackoverflow.com/q/48390503
score: 0
type: Answer

http://stackoverflow.com/a/74751890
answers question: http://stackoverflow.com/q/48396944
has body: This is hacky and needs requests and BeautifulSoup, but works for me: pip install requests # might not need this pip install beautifulsoup4 and then #!/opt/homebrew/bin/python3 import requests from bs4 import BeautifulSoup fbUrl='https://facebook.com/761051684025235' r = requests.get(fbUrl) if r.ok: soup = BeautifulSoup(r.text, 'html.parser') for link in soup.find_all('link'): if 'facebook.com' in link.get('href'): fbHandle = link.get('href').split('/')[-1] print(fbHandle) break
score: 0
type: Answer

http://stackoverflow.com/q/48468009
has answer: http://stackoverflow.com/a/48468122
upvote count: 1
accepted answer: http://stackoverflow.com/a/48468122
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83929908
has title: Regular expression for word with specific prefix/suffix
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83930014
has comment: http://stackoverflow.com/comment/83929776
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83929661
type: AnsweredQuestion
has body: i want to match the word only if the word is surrounded with a maximum of 1 wild character on either side followed by space or nothing on either side. for example I want ring to match 'ring' , ' ring' , ' tring', 'ring ', ' ringt', '' ringt ', ' ring ', 'tringt ', 'tringt ' but not: 'ttring', 'ringttt', 'ttringtt' so far I have: [?\s\S]ring[?\s\S][?!\s] any suggestions?

http://stackoverflow.com/q/48409128
has body: I've noticed three methods of selecting a column in a Pandas DataFrame: First method of selecting a column using loc: df_new = df.loc[:, 'col1'] Second method - seems simpler and faster: df_new = df['col1'] Third method - most convenient: df_new = df.col1 Is there a difference between these three methods? I don't think so, in which case I'd rather use the third method. I'm mostly curious as to why there appear to be three methods for doing the same thing.
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/52919794
has title: What is the difference between using loc and using just square brackets to filter for columns in Pandas/Python?
linked to: http://stackoverflow.com/q/31593201
upvote count: 185
type: AnsweredQuestion
score: 185
has answer: http://stackoverflow.com/a/54774806
has comment: http://stackoverflow.com/comment/83807776
linked to: http://stackoverflow.com/q/11285613
accepted answer: http://stackoverflow.com/a/48411543
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83807726
has answer: http://stackoverflow.com/a/78247649
has comment: http://stackoverflow.com/comment/136809823
linked to: http://stackoverflow.com/q/76766136
linked to: http://stackoverflow.com/q/54496766
has comment: http://stackoverflow.com/comment/83807837
has comment: http://stackoverflow.com/comment/83808346
has answer: http://stackoverflow.com/a/69933874
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/38886080
has answer: http://stackoverflow.com/a/48411543
answer count: 5
possible better answer: http://stackoverflow.com/a/52919794
has comment: http://stackoverflow.com/comment/83808389

grpc
tags question: http://stackoverflow.com/q/48394486
tags question: http://stackoverflow.com/q/48442743
type: Tag
tags question: http://stackoverflow.com/q/48448577
tags question: http://stackoverflow.com/q/48456784
tag name: grpc

http://stackoverflow.com/comment/83911749
comment on: http://stackoverflow.com/q/48459455
type: Comment
type: QuestionComment
has text: Do you mean just changing the numbers (2,3,4) of the filenames to `N`? How about if my files were not sharing common prefixes in their name?
score: 0

http://stackoverflow.com/comment/83995756
has text: Your answer has pointed me to my error. So it is helpful :) I haven't yet taken a look at your code, as I want to solve this problem by myself.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48462866

http://stackoverflow.com/comment/83774516
type: Comment
type: AnswerComment
has text: @Bruno Cerk I think you understood it basically. You need to hold a reference to the created instance if you want to invoke further methods on **that** instance.
score: 0
comment on: http://stackoverflow.com/a/48389167

http://stackoverflow.com/q/48375747
has title: PySpark RDD with Typed List convert to DataFrame
tagged with: pyspark
tagged with: python
tagged with: rdd
accepted answer: http://stackoverflow.com/a/48382192
type: AnsweredQuestion
score: 0
tagged with: apache-spark
answer count: 1
has body: I have an RDD in the following format: [(1, (Rating(user=1, product=3, rating=0.99), Rating(user=1, product=4, rating=0.91), Rating(user=1, product=9, rating=0.68))), (2, (Rating(user=2, product=11, rating=1.01), Rating(user=2, product=12, rating=0.98), Rating(user=2, product=45, rating=0.97))), (3, (Rating(user=3, product=23, rating=1.01), Rating(user=3, product=34, rating=0.99), Rating(user=3, product=45, rating=0.98)))] I'm have been unable to find any example of using map lambda etc to work with this kind of named data. Ideally, I would like the output to be a dataframe in the following format: User Ratings 1 3,0.99|4,0.91|9,0.68 2 11,1.01|12,0.98|45,0.97 3 23,1.01|34,0.99|45,0.98 Any pointers would be appreciated. Note the number of ratings is variable and not just 3.
has comment: http://stackoverflow.com/comment/83738759
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/48382192

http://stackoverflow.com/comment/83949823
type: Comment
type: QuestionComment
has text: @John Gordon: I added call to check() function. Also, my full code is too long, so this snippet shows what is happening. Please let me know if you have clarifying questions.
comment on: http://stackoverflow.com/q/48478068
score: 0

http://stackoverflow.com/a/48382266
type: Answer
has comment: http://stackoverflow.com/comment/83751260
answers question: http://stackoverflow.com/q/48382219
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: Option 1 Using str.split, but don't expand the result. You should end up with a column of lists. Next, use df.assign, assign columns to return a new DataFrame object. v = df['name'].str.split('/') df.assign( main=v.str[ 0], sub=v.str[ 1], leaf=v.str[-1] ) name leaf main sub a 1 a/b/c c a b 2 w/x/y/z z w x 3 q/w/e/r/t t q w Details This is what v looks like: a 1 [a, b, c] 2 [w, x, y, z] 3 [q, w, e, r, t] Name: name, dtype: object This is actually a lot easier to handle, because you have greater control over elements with the .str accessor. If you expand the result, you have to snap your ragged data to a tabular format to fit into a new DataFrame object, thereby introducing Nones. At that point, indexing (finding the ith or ith-last element) becomes a chore. Option 2 Using direct assignment (to maintain order) - df['main'] = v.str[ 0] df['sub' ] = v.str[ 1] df['leaf'] = v.str[-1] df name main sub leaf a 1 a/b/c a b c 2 w/x/y/z w x z 3 q/w/e/r/t q w t Note that this modifies the original dataframe, instead of returning a new one, so it is cheaper. However, it is more intractable if you have a large number of columns. You might instead consider this alternative which should generalise to many more columns: for c, i in [('main', 0), ('sub', 1), ('leaf', -1)]: df[c] = v[i] df name main sub leaf a 1 a/b/c a b c 2 w/x/y/z w x z 3 q/w/e/r/t q w t Iterate over a list of tuples. The first element in a tuple is the column name, and the second is the corresponding index to pick the result from v. You still have to assign each one separately, whether you like it or not. Using a loop would probably be a clean way of doing it.
has comment: http://stackoverflow.com/comment/83751534
score: 2
has comment: http://stackoverflow.com/comment/83751290
has comment: http://stackoverflow.com/comment/83751421
accepted answer of: http://stackoverflow.com/q/48382219

http://stackoverflow.com/comment/83696240
has text: The immediate problem is that you're passing a values_list to the modelchoicefield, rather than a proper queryset. But I can't understand why you're using a modelform and why you're saving it, even with commit=False, if all you want is two selected countries.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48354764

http://stackoverflow.com/q/48461371
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48497876
tagged with: pygame
has comment: http://stackoverflow.com/comment/83926356
tagged with: pygame-surface
has comment: http://stackoverflow.com/comment/83926200
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/40966994
has title: Copying python's pygame surface objects
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83927391
upvote count: 1
tagged with: python
has body: I have an issue regarding copy.deepcopy and pygame surface objects. Regularly, I use WSL and python to execute python (because I have to run windows on my machine but I hate the commandline interface of windows). I'm learning pygame - making a simple game. Everything is working fine, but I tried to launch it with my regularly installed python3 and pygame in AppData, which normally works, but this time it returns an error which doesn't happen in the WSL. The error is: TypeError: can't pickle pygame.Surface objects Here's the code regarding the error. player = Player(start) temp = deepcopy(player) and here's the class itself: class Player(pygame.sprite.Sprite): def __init__(self, pos): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(os.path.join('img','player.png')) self.r = 17 self.rect = self.image.get_rect() self.rect.center = (pos[0] + 8.5, pos[1] + 8.5) self.rect.inflate_ip(-2,-2) self.vel = Vector(0,0) Now why am I doing what I'm doing. I'm making stuff from scratch, I didn't look up a similar game or anything, I just went. The point is, on the game field, there's a player and there's walls. The player can not move through walls. The way I do that is - before moving, I make a deepcopy of the player and the copy makes the move instead. Then I check for wall collision and if the copy didn't hit a wall, I move the original player. Then I delete the copy. This is a very sloppy way, but I wasn't able to come up with a better idea. I want to make this work. I don't mind if anyone advises me a better way to copy the player or just implement the movement in a different way. Should anyone want to see more of the code, tell me and I'll happily give you more snippets :) Thanks for any help in advance. P.S. This is not a homework, it actually is procrastinating from homework lol
score: 1

http://stackoverflow.com/comment/83840248
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48425028
has text: Thanks for your reply. In the code, I need to do a global sort through set_index(). Can I still process it in chunks?

http://stackoverflow.com/comment/83768655
type: Comment
has text: Your link uses a `sympy` tool (`autowrap`), http://docs.sympy.org/latest/modules/utilities/autowrap.html. That's not the same as compiling your own code as `pyx`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48389750
score: 1

http://stackoverflow.com/q/48414513
tagged with: list
has comment: http://stackoverflow.com/comment/83818901
has answer: http://stackoverflow.com/a/48414620
accepted answer: http://stackoverflow.com/a/48414620
has comment: http://stackoverflow.com/comment/83819077
has comment: http://stackoverflow.com/comment/83819427
type: Question
has answer: http://stackoverflow.com/a/48414635
has comment: http://stackoverflow.com/comment/83819035
possible better answer: http://stackoverflow.com/a/48414635
answer count: 2
tagged with: for-loop
tagged with: python
has body: why if from_unit ==unit[0] will return found unit, in? isn't the unit[0]==['cm',0.01]? this should not equal to in, right?** Image Following is my code: def converter(value, from_unit='cm',to_unit='m'): units = [['m',1],['cm',0.01],['in',0.0254]] if from_unit != units[0][0]: print("conver to base unit") for unit in units[1:]: if from_unit == unit[0]: print("found unit ", unit[0]) print(converter(10,'in','cm'))
has title: python coding issue for length converter
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/48420702
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48414823
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: This is a simpler way, using only openCV and numpy. Since the size of your query image was much less than the train image size, I first downsized the train image by a factor of 0.33 to fit on my screen, and then created a function to iterate through various sizes of the query image because for this method you have to match sizes too. You can, of course adjust the variable fx and fy, mult and threshold to see how many of the Xs you can get. My highest number was 3 from rough iterations, but this setting below achieves 2: import cv2 import numpy as np originalPicRead = cv2.imread('originalPic.jpg') img_bgr = cv2.resize(originalPicRead, (0,0), fx=0.33, fy=0.33) img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) templateR = cv2.imread('template.jpg',0) w,h = templateR.shape[::-1] for magn in range(1,11): mult = magn*0.35 w,h = int(mult*w),int(mult*h) template = cv2.resize(templateR, (0,0), fx=mult, fy = mult) res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) threshold = 0.35 loc = np.where(res &gt;= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2) cv2.imshow('Detected', img_bgr) cv2.waitKey(0) cv2.destroyAllWindows()
accepted answer of: http://stackoverflow.com/q/48414823

http://stackoverflow.com/q/48428838
downvote count: 0
tagged with: python
tagged with: amazon-web-services
possible better answer: http://stackoverflow.com/a/50275428
tagged with: aws-lambda
favorite count: 0
type: AnsweredQuestion
tagged with: aws-iot
has body: I am trying to learn AWS greengrass and so I was following this tutorial https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-gs.html which explains step by step on setting up with greengrass on raspberry pi and publishing some messages using a lambda function. A simple lambda function is as following : import greengrasssdk import platform from threading import Timer import time # Creating a greengrass core sdk client client = greengrasssdk.client('iot-data') # Retrieving platform information to send from Greengrass Core my_platform = platform.platform() def greengrass_hello_world_run(): if not my_platform: client.publish(topic='hello/world', payload='hello Sent from Greengrass Core.') else: client.publish(topic='hello/world', payload='hello Sent from Greengrass Core running on platform: {}'.format(my_platform)) # Asynchronously schedule this function to be run again in 5 seconds Timer(5, greengrass_hello_world_run).start() # Execute the function above greengrass_hello_world_run() # This is a dummy handler and will not be invoked # Instead the code above will be executed in an infinite loop for our example def function_handler(event, context): return Here this works but I am trying to understand it better by having a lambda function to do some extra work for example opening a file and writing to it. I modified the greengrass_hello_world_run() function as following def greengrass_hello_world_run(): if not my_platform: client.publish(topic='hello/world', payload='hello Sent from Greengrass Core.') else: stdout = "hello from greengrass\n" with open('/home/pi/log', 'w') as file: for line in stdout: file.write(line) client.publish(topic='hello/world', payload='hello Sent from Greengrass Core running on platform: {}'.format(my_platform)) I expect upon deploying, the daemon running on my local pi should create that file in the given directory coz I believe greengrass core tries to run this lambda function on local device. However it doesnt create any file nor it…
tagged with: aws-iot-greengrass
type: Question
has answer: http://stackoverflow.com/a/50275428
has title: Execute lambda function on local device using greengrass
answer count: 2
accepted answer: http://stackoverflow.com/a/48468006
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48468006

http://stackoverflow.com/q/48454151
has comment: http://stackoverflow.com/comment/83901618
type: Question
has comment: http://stackoverflow.com/comment/83902018
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83902218
has answer: http://stackoverflow.com/a/48454704
has answer: http://stackoverflow.com/a/48455218
has body: I am determined to try get all the other users that replied to the same comment as a given reply. I have come up with the following python, however I am concerned this will do more than one DB call. other_repliers = [other_reply.user for other_reply in my_reply.comment.replies.filter()] I'm looking for a one-db-call fix. The Psuedo-SQL logic would be something like: SELECT u.* FROM users AS u INNER JOIN replies AS r ON r.user = user.id WHERE r.comment = {my_reply.comment} AND r.user != {my_reply.user} Does anyone know a way that I can do the above SQL in a python django command chain? Edit: My models look like this when you ignore the anything that is not a relationship: class Comment(models.Model): user = models.ForeignKey(User, related_name='comments') listing = models.ForeignKey(Listing, related_name='comments') class CommentReply(models.Model): user = models.ForeignKey(User, related_name='replies') comment = models.ForeignKey(Comment, related_name='replies') class User(models.Model): pass Edit: I am looking to collect this final column in the following graph: /--- r4 --- u4 / r1 --- c1 --- r3 --- u3 \ \--- r2 --- u2 * ** r1 Where r* are requests and c* are comments and u* are users and the starred line indicates the r1 is ignored (as it was used to find the other r*s).
tagged with: django
tagged with: django-models
tagged with: python
has title: How to access the a reverse relation of a reverse relation django
has comment: http://stackoverflow.com/comment/83902257
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48471704
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48471704
has comment: http://stackoverflow.com/comment/83902199
answer count: 3
downvote count: 0
tagged with: django-queryset
possible better answer: http://stackoverflow.com/a/48455218
has comment: http://stackoverflow.com/comment/83901488
favorite count: 0

ibm-cloud
tags question: http://stackoverflow.com/q/48356280
type: Tag
tag name: ibm-cloud

http://stackoverflow.com/q/48360735
answer count: 1
tagged with: django
tagged with: python
tagged with: static
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48360868
has answer: http://stackoverflow.com/a/48360868
has title: How to assign Foreign Key static in Django Post Model
tagged with: post
type: Question
has body: I want to add static user my Foreign Key field because of guest's post, but i can't. I try to add first id like 1, "1", "id=1" but no result. Can you help me pls? Here is my model.py; class Post(models.Model): user = models.ForeignKey('auth.User', related_name='posts') title = models.CharField(max_length=120) views.py; post = form.save(commit=False) post.user = request.user if request.user == '': post.user = 1 post.save() else: post.save() return HttpResponseRedirect(post.get_absolute_url()) etc. Thanks.
tagged with: return

http://stackoverflow.com/a/48464780
accepted answer of: http://stackoverflow.com/q/48464231
has comment: http://stackoverflow.com/comment/83923113
answers question: http://stackoverflow.com/q/48464231
type: Answer
has body: I managed to get it work by moving your dowork2 outside the class. If you declare dowork2 as a function before Test class and call it as results.append(pool.apply_async(dowork2, (queue, shared_queue))) it works as expected. I am not 100% sure but it probably goes wrong because your Test class is already subclassing Process. Now when your pool creates a subprocess and initialises the same class in the subprocess, something gets overridden somewhere. Overall I wonder if Pool is really what you want to use here. Your worker seems to be in an infinite loop indicating you do not expect a return value from the worker, only the result in the return queue. If this is the case, you can remove Pool. I also managed to get it work keeping your worker function within the class when I scrapped the Pool and replaced with another subprocess: foo = mp.Process(group=None, target=self.dowork2, args=(queue, shared_queue)) foo.start() # results.append(pool.apply_async(Test.dowork2, (queue, shared_queue))) while True: .... (you need to add self to your worker, though, or declare it as a static method:) def dowork2(self, queue, shared_queue):
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83869173
has text: This does not answer the question, but thanks anyway -- it may come in handy for me in the future HAHAHAHA.
comment on: http://stackoverflow.com/a/48438961
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84103914
comment on: http://stackoverflow.com/q/48482265
type: Comment
type: QuestionComment
score: 0
has text: I have downgraded my numpy version to 1.3.0 and I am using python 2.7 You think I also need to go to Matlab2013a?? Because I used to have this working on Ubuntu 14.04 with latest numpy and Matlab, but now I have shifted to Ubuntu 17.10 and it stopped working.

http://stackoverflow.com/comment/83811669
comment on: http://stackoverflow.com/a/48409555
type: AnswerComment
has text: Remember that you can post your code on [*Code Review*](https://codereview.stackexchange.com) to get this sort of assessment.
score: 0
type: Comment

http://stackoverflow.com/comment/83843280
has text: If `a==0` you are printing `many solutions` because your first conditional tells the program to print that! And it's incorrect since `a==0` should display `no solution` Also the last `elif a != 0` is redundant
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48425626

scroll
type: Tag
tag name: scroll
tags question: http://stackoverflow.com/q/48389719

http://stackoverflow.com/comment/83666996
type: Comment
type: QuestionComment
has text: Are these matrices always distance matrices?
score: 1
comment on: http://stackoverflow.com/q/48336165

http://stackoverflow.com/a/48396191
has body: You can use first merge for add column vocab to first DataFrame: import re df = df.groupby'key1','key2'['document'].apply(vocab).reset_index() df = pd.merge(df1, df2, on=['key1','key2'], how='left') #another theoretical solution #df['vocab'] = df.groupby'key1','key2'['document'].transform(vocab) Then extract all words by findall, re.I is for ignore case and last remove column vocab: df['document'] = df['document'].str.findall('\w+', flags=re.I) Last get intersection between sets and convert to strings by str.join: df['document'] = df.apply(lambda x: set(x['document']) &amp; x['vocab'], axis=1).str.join(' ') df = df.drop('vocab', axis=1) print (df) key1 key2 document 0 aa bb evening went dinner 1 aa bb sit down dinner 2 cc mm restaurant people 3 aa bb chef culinary 4 cc mm home people sleep dinner
has comment: http://stackoverflow.com/comment/83780152
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48395721

http://stackoverflow.com/comment/83956248
score: 0
has text: Hm. What apout `res.headers`?
comment on: http://stackoverflow.com/q/48470241
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83816369
comment on: http://stackoverflow.com/q/48413192
score: 0
has text: if lxml is an option then I would use that instead and use its xpath functionality, its easier and straightforward
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87370354
type: Comment
has text: Best I can suggest is roll this as a Google AppEngine or AWS app. There are several libraries around designed to work on these platforms for generating notifications, and they provide very easy to use app hosting options. You can go through registering and get a POC app up and running in under an hour, and your Pythonista code should be highly portable to them, except for the notification API calls.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48362944

http://stackoverflow.com/a/48438029
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48437889
has body: y_true is the variable containing the class/labels that your algorithm is trying to predict for your test set. I assume that you are facing a supervised learning problem: in that case, y_true is known and contained in your test set. Using your conventions: y_pred = clf.predict(features_test) #without labels_test! accuracy_score(labels_test, y_pred)
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48437889
downvote count: 0

http://stackoverflow.com/comment/83693007
type: AnswerComment
comment on: http://stackoverflow.com/a/48339861
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163527/discussion-between-buhtz-and-spectras).
score: 0

http://stackoverflow.com/comment/83782325
type: Comment
type: AnswerComment
has text: After casting the column that way it works, thanks a lot. Quick question though: I was convinced that the `holding_time` column was an numeric, since: 1, can compute its mean when not grouping, 2. `dtype` is displyed to be "int64" when I group and call e.g., `sum`. Where am I wrong?
score: 0
comment on: http://stackoverflow.com/a/48397259

http://stackoverflow.com/comment/83944589
has text: The last one is the one I wanted! Thank you very much!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48470791
type: AnswerComment

http://stackoverflow.com/q/48485293
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/48489739
score: 0
answer count: 2
tagged with: google-cloud-endpoints-v2
upvote count: 1
has body: How to decode messages.Message to JSON in python 2.7 for Google Cloud Endpoints Frameworks ? Especially when we have some nested messages. Endpoints version : google-endpoints==2.4.5 and google-endpoints-api-management==1.3.0 from protorpc import messages # messsage definition class GPSCoord(messages.Message): """ GPS data obj """ latitude = messages.FloatField(1) longitude = messages.FloatField(2) class Address(messages.Message): """ Address objectt """ type = messages.StringField(1) name = messages.StringField(2) number = messages.StringField(3) city = messages.StringField(4) zip_code = messages.IntegerField(5) gps_coord = messages.MessageField(GPSCoord, 6) I tried to add a method "to_json" to messages definition but I had "MessageDefinitionError: May only use fields in message definitions. " exception. It looks like a rudimentary operation but it's not that easy. Python SDK needs a huge improvement for this part.
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48509913
has title: google cloud endpoints messages.Message to json python

http://stackoverflow.com/comment/83672919
has text: Another one is `float("nan")`
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/48343387

http://stackoverflow.com/q/48370560
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83870886
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83881491
type: UnansweredQuestion
tagged with: math
tagged with: arrays
has body: I was trying to answer a question called "lightgremlins" on IEEEXTREME. given a array number of gremlins and the prime numbers each chose return the numbers in range that are still on after all gremlins toggled there prime multiplied numbers. given the input: 30 3 2 3 5 output: 15 case consists of a hallway of length 30, and three gremlins. The action of the gremlins is as follows: The first gremlin flips switches {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}. All of these switches were previously off, so they are now on. The second gremlin flips switches {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}. Of these, {6, 12, 18, 24, 30} were previously on, so they are now off. This results in the following switches being on: {2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 21, 22, 26, 27, 28}. The third gremlin flips switches {5, 10, 15, 20, 25, 30}. Of these, {10, 15, 20} were previously on, so they are now off. This results in the following switches being on: {2, 3, 4, 5, 8, 9, 14, 16, 21, 22, 25, 26, 27, 28, 30}. Thus, there are 15 switches on at the end of the night. Now my code is very straight forward: testcases=int(input()) for i in range(0,testcases): array = input().split(' ') arrayofnumbers = [int(x) for x in array] #print(arrayofnumbers) onCount=0 for j in range(1,arrayofnumbers[0]+1): primeCount=0 for p in arrayofnumbers[2:len(arrayofnumbers)]: if j%p == 0: primeCount += 1 if primeCount % 2 == 1: onCount += 1 print(onCount) now this seems to work ok for small arrays or i think. i'm failing half of the test cases and i don't really understand why. perhaps this doesn't hold for very large arrays? perhaps my entire approach is wrong? i have changed my code to use LCM and count amount of iterations but still this didn't solve the rest of the test cases pretty much stayed the same. this is my code: from math import gcd testcases=int(input()) for i in range(0,testcases): array = input().split(' ') arrayofnumbers = [int(x) for x in array] #print(arrayofnumbers) lcm = 1 for i i…
has comment: http://stackoverflow.com/comment/83881593
tagged with: python
score: -1
has title: light gremlins - finding all the multiplication numbers of a prime in a range
has answer: http://stackoverflow.com/a/48371297
upvote count: 0
has comment: http://stackoverflow.com/comment/83880992
has comment: http://stackoverflow.com/comment/83881184
answer count: 1
has comment: http://stackoverflow.com/comment/83854822
downvote count: 1
has comment: http://stackoverflow.com/comment/83882366

http://stackoverflow.com/comment/83701972
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48357619
has text: This is trivial. Next time try to search better...
score: 3

http://stackoverflow.com/comment/83736999
has text: Show the code also that you have tried
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48374960

http://stackoverflow.com/q/48431036
has title: How are the abstract classes implemented which in collection.abc.* module?
has body: I was wondering that how the implementation mechanism work for tuple, list, or set data types. When I have checked the tuple data type with help() function, I can't see any inherited class from collection.abc module. help(tuple) Help on class tuple in module builtins: class tuple(object) # omitting the other details When I was checking: import collections issubclass(tuple, collections.abc.MutableSequence) # False issubclass(tuple, collections.abc.Sequence) # True issubclass(list, collections.abc.MutableSequence) # True issubclass(list, collections.abc.Sequence) # True Both of two lines for list are correct because I know that MutableSequence is also subclass of Sequence abstract class. I'm getting confused because as I mentioned above I couldn't see any inherited class from the collection.abc module within concrete tuple or list implementation. Long story short I try to find an explanation about implementation of abstract base classes for Python data types.
has comment: http://stackoverflow.com/comment/83853265
has comment: http://stackoverflow.com/comment/83853109
score: 2
upvote count: 4
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83853327
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/48431082
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48431082
tagged with: python

http://stackoverflow.com/comment/83938191
type: Comment
has text: I was thinking more along the lines of: "can we easily rewire the `pandas` group indexer for categoricals" so that all these mappings are not necessary.
score: 0
comment on: http://stackoverflow.com/a/48472095
type: AnswerComment

http://stackoverflow.com/a/48404756
has comment: http://stackoverflow.com/comment/83799427
type: Answer
has comment: http://stackoverflow.com/comment/83806238
score: 3
has comment: http://stackoverflow.com/comment/83806174
has comment: http://stackoverflow.com/comment/83799854
upvote count: 3
answers question: http://stackoverflow.com/q/48404505
type: AcceptedAnswer
downvote count: 0
has body: Your code is really close, but you took it just one step further than you needed to. # creates a slice of the dataframe where the row is at iloc 5 (row number 5) and where the slice includes all columns slice_of_df = cacs.iloc[5, :] # returns the index of the slice # this will be an Index() object index_of_slice = slice_of_df.index From here we can use the documentation on the Index object: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html # turns the index into a list of values in the index index_list = index_of_slice.to_list() # gets the first index value first_value = index_list[0] The most important thing to remember about the Index is that it is an object of its own, and thus we need to change it to the type we expect to work with if we want something other than an index. This is where documentation can be a huge help. EDIT: It turns out that the iloc in this case is returning a Series object which is why the solution is returning the wrong value. Knowing this, the new solution would be: # creates a Series object from row 5 (technically the 6th row) row_as_series = cacs.iloc[5, :] # the name of a series relates to it's index index_of_series = row_as_series.name This would be the approach for single-row indexing. You would use the former approach with multi-row indexing where the return value is a DataFrame and not a Series. Unfortunately, I don't know how to coerce the Series into a DataFrame for single-row slicingbeyond explicit conversion: row_as_df = DataFrame(cacs.iloc[5, :]) While this will work, and the first approach will happily take this and return the index, there is likely a reason why Pandas doesn't return a DataFrame for single-row slicing so I am hesitant to offer this as a solution.
accepted answer of: http://stackoverflow.com/q/48404505

http://stackoverflow.com/a/48432749
has comment: http://stackoverflow.com/comment/89323365
score: 14
has comment: http://stackoverflow.com/comment/83857080
type: Answer
has body: s = ttk.Style() s.configure('Treeview', rowheight=40) # repace 40 with whatever you need
has comment: http://stackoverflow.com/comment/89309728
upvote count: 14
has comment: http://stackoverflow.com/comment/83857755
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48432506
has comment: http://stackoverflow.com/comment/83857500
answers question: http://stackoverflow.com/q/48432506
has comment: http://stackoverflow.com/comment/89311423

http://stackoverflow.com/comment/83964243
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48465739
type: Comment
has text: Thanks Mark Setchell

http://stackoverflow.com/comment/83936133
has text: I'd say only use the prefix for the strings where you need to. It looks cleaner.
comment on: http://stackoverflow.com/q/48471086
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48373637
has comment: http://stackoverflow.com/comment/83741458
score: 0
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83750171
tagged with: python-2.7
has body: For work I use some software for analysing data bus messages and i need to display some of that data in an x,y plot. The software has a python interpreter but unfortunately it doesn't play nice with threads/processes and interactive pyplot's cause it to crash. I thought maybe i could use a localhost TCP server to pass data between the software and an external pyplot process. Iv'e been hacking my way through some of the simple multiprocessing TCP server/client examples online and have so far come up with whats posted below. The problem i have is that the figure (although it does update) is unresponsive and that is no good. I tried to play around with running the plot in its own Process and use a global Queue to get the data, but the plot couldn't see the global Queue used by the client thread even when passed as an argument, but i was able to run the plot in interactive mode. Anyway, i abandoned that and iv'e ended up with this. Can anybody help me fix this or provide a better solution? Server.py import socket import sys import traceback from threading import Thread import matplotlib.pyplot as plt import json from multiprocessing import Process class Figure(object): def __init__(self): self.fig = plt.figure() proc = Process(target=start_server, args=(self,)) proc.start() def Plot(self, data): f = self.fig.add_subplot(111) d = json.loads(data) print "Plot data: ", d f.plot(d[0], d[1], d[2]) self.fig.canvas.draw() plt.ion() plt.show() #plt.show(block=False) #plt.draw() def start_server(fig): host = "localhost" port = 8888 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: soc.bind((host, port)) except: print("Bind failed. Error : " + str(sys.exc_info())) sys.exit() soc.listen(5) # queue up to 5 requests print("Awaiting Connection...") while True: connection, address = soc.accept() ip, port = str(address[0]), str(address[1]) print("Connected with " + ip + ":" + port) try: Thread(target=client_thread, ar…
tagged with: matplotlib
tagged with: tk-toolkit
has title: matplotlib drawing dynamic plots from TCP data
has comment: http://stackoverflow.com/comment/83741608
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/83749835

http://stackoverflow.com/comment/83877846
type: Comment
type: QuestionComment
score: 1
has text: string.replace("\n" , " ")?
comment on: http://stackoverflow.com/q/48443294

http://stackoverflow.com/comment/83901838
has text: This is rather a question for [Code Review](https://codereview.stackexchange.com/).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48454251
score: 3

http://stackoverflow.com/comment/83773106
has text: Hello again! You can find the answer here : https://stackoverflow.com/questions/14117945/too-many-different-python-versions-on-my-system-and-causing-problems?answertab=votes#tab-top
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48392546
type: AnswerComment

http://stackoverflow.com/comment/83754200
type: QuestionComment
comment on: http://stackoverflow.com/q/48383549
score: 1
has text: Why wouldn't it? You set the timezone to UTC? Your client (the browser) is in GMT+7, but Django doesn't know that.
type: Comment

http://stackoverflow.com/a/48474188
has comment: http://stackoverflow.com/comment/83942321
accepted answer of: http://stackoverflow.com/q/48474108
has body: The error you are seeing says it all : for row in table.find_element_by_xpath("//td[@data-live='false']"): AttributeError: 'list' object has no attribute 'find_element_by_xpath' The following line is error prone : for row in table.find_element_by_xpath("//td[@data-live='false']"): As per your previous line : table = driver.find_elements_by_xpath("//table[@class='foot-market']") table is a List and you can't invoke find_element_by_xpath() on a List. find_element_by_xpath() can be invoked either on webdriver instance or on a webelement. Your working code will be as follows : all_tds = driver.find_elements_by_xpath("//table[@class='foot-market']//td[@class='today-name']") for tds in all_tds : tds.click() #try for one row first and break out break Note : This is a basic solution to overcome your error AttributeError: 'list' object has no attribute 'find_element_by_xpath' and to try for one row first Update If you intend to loop through all the td elements of the table, then you have to capture the base url so we can revert back to the main page to find and click the subsequent elements as follows : base_url = driver.current_url count_all_tds = len(driver.find_elements_by_xpath("//table[@class='foot-market']//td[@class='today-name']")) for td in range(count_all_tds): driver.find_elements_by_xpath("//table[@class='foot-market']//td[@class='today-name']")[td].click() # code block for other required actions and finally redirect to base_url driver.get(base_url)
type: Answer
answers question: http://stackoverflow.com/q/48474108
has comment: http://stackoverflow.com/comment/83942105
has comment: http://stackoverflow.com/comment/83941967
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83941944
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83942316
has comment: http://stackoverflow.com/comment/83942373

timer
tag name: timer
tags question: http://stackoverflow.com/q/48487623
type: Tag

http://stackoverflow.com/q/48419506
type: Question
has body: I have a data that looks like this that I get from an API (of course in JSON form): 0,1500843600,8872 1,1500807600,18890 2,1500811200,2902 . . . where the second column is the date/time in ticks, and the third column is some value. I basically have the data for every hour of the day, for every day for a couple of months. Now, what I want to achieve is that I want to get the minimum value for the third column for every week. I have the code segment below, which correctly returns the minimum value for me, but apart from returning the minimum value, I also want to return the specific Timestamp as which date/time the lowest that week occurred. How can I modify my code below, so I can get also the Timestamp along with the minimum value. df = pandas.DataFrame(columns=['Timestamp', 'Value']) # dic holds the data that I get from my API. for i in range(len(dic)): df.loc[i] = [dic[i][1], dic[i][2]] df['Timestamp'] = pandas.to_datetime(df['Timestamp'], unit='s') df.sort_values(by=['Timestamp']) df.set_index(df['Timestamp'], inplace=True) df.groupby([pandas.Grouper(key='Timestamp', freq='W-MON')])['Value'].min()
tagged with: datetime
tagged with: python
has title: Using GroupBy with DateTime in Pandas (Python)
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48419614
upvote count: 1
has answer: http://stackoverflow.com/a/48419614
favorite count: 0

http://stackoverflow.com/comment/83920345
type: AnswerComment
comment on: http://stackoverflow.com/a/48463233
type: Comment
score: 0
has text: What do you mean by "mix"?

http://stackoverflow.com/q/48336963
has body: I am trying to make a program to break a Hill Cipher with a known Key Matrix, and when I enter the ciphertext, and convert the letters into numbers, I use this for loop: letters = 'abcdefghijklmnopqrstuvwxyz' ciphertext = input('Enter your ciphertext') ciphertext = list(ciphertext.lower()) for symbol in ciphertext: num = int(letters.find(symbol)) print(num) and I am wondering if there is a way to transfer the numbers that are printed into an array, which I am using to represent the matrices that are involved in Hill ciphers, as I need to insert every block of 2 letters into a 2x1 matrix, in order to perform a matrix multiplication on each, in order to get the plaintext. Basically, I am trying to get the numbers from the for loop into arrays, in the most efficient way possible, but I am very new to coding in python, so I have no idea how I would do it. Also, is there just an easier way altogether to use matrices in python that I don't know about that would make this whole thing easier?
score: 1
has comment: http://stackoverflow.com/comment/83659193
tagged with: python
has comment: http://stackoverflow.com/comment/83659364
has comment: http://stackoverflow.com/comment/83659739
favorite count: 0
has comment: http://stackoverflow.com/comment/83659068
type: Question
has comment: http://stackoverflow.com/comment/83659475
has comment: http://stackoverflow.com/comment/83659424
has comment: http://stackoverflow.com/comment/83659118
has comment: http://stackoverflow.com/comment/83659064
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83659637
has title: Is it possible to get values from a for loop into a list?
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/48337209
has comment: http://stackoverflow.com/comment/83659435
has answer: http://stackoverflow.com/a/48337133
has comment: http://stackoverflow.com/comment/83659814
answer count: 3
has answer: http://stackoverflow.com/a/48337080

http://stackoverflow.com/comment/83926687
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48427385
score: 0
has text: thanks i figures that out..i appreciate it.

http://stackoverflow.com/comment/83851122
comment on: http://stackoverflow.com/a/48428956
type: AnswerComment
has text: Eliakin ! Eureka !! I found a bug.... In detale_bajki.html i had but i change it to and its working !!!
score: 0
type: Comment

http://stackoverflow.com/comment/83855084
comment on: http://stackoverflow.com/q/48431456
type: QuestionComment
has text: Fair point @juanpa.arrivillaga
score: 0
type: Comment

http://stackoverflow.com/comment/83959736
comment on: http://stackoverflow.com/q/48483398
type: Comment
score: 0
has text: can you show an example of the file you want to sort?
type: QuestionComment

http://stackoverflow.com/comment/83752435
type: Comment
type: AnswerComment
has text: "it's typical to define the n to be number of nodes visited": with such a definition, searching a binary search tree would be O(n) ! You probably mean the total number of nodes in the tree ?
score: 0
comment on: http://stackoverflow.com/a/48382792

http://stackoverflow.com/comment/83698533
has text: you can simply iterate the array and match the criteria
comment on: http://stackoverflow.com/q/48355264
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48470916
has comment: http://stackoverflow.com/comment/83935802
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/1132941
has title: How to create instance attribute?
type: Question
has body: I have some problem with understandig how to declare object instance attribute. Here is my code: class TestItem(object): def __init__(self): super(TestItem, self).__init__() def import_(self, value): self.value = value class TestItems(object): def __init__(self, items=[]): super(TestItems, self).__init__() self.items = items def __getitem__(self, index): return self.items[index] def __len__(self): return len(self.items) def import_from_list(self, data): for i in data: item = TestItem() item.import_(i) self.items.append(item) data = [] data.append(TestItems()) data[-1].import_from_list(['A', 'B']) for i, j in enumerate(data): print('Size of data[%i] - %i' % (i, len(j))) data.append(TestItems()) data[-1].import_from_list([1, 2]) for i, j in enumerate(data): print('Size of data[%i] - %i' % (i, len(j))) print('First element of data[%i] - %s' % (i, j[0].value)) print(data[0]) print(data[1]) Here is output: Size of data[0] - 2 Size of data[0] - 4 First element of data[0] - A Size of data[1] - 4 First element of data[1] - A &lt;__main__.TestItems object at 0x000002C0765F51D0&gt; &lt;__main__.TestItems object at 0x000002C0765F52B0&gt; It looks like array items is shared between all instances of TestsItem but it shouldn't. What am I doing wrong? UPD: I fixed it like this: class TestItems(object): def __init__(self, items=None): super(TestItems, self).__init__() self.items = items or []
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/83935786

http://stackoverflow.com/a/48382314
score: 1
answers question: http://stackoverflow.com/q/48381870
has body: Your approach is about as good as it will get, you need to poll the sequence/iterable and build the chunks, but in any case, here is a lazy version that works with iterables and uses a deque for performance: from collections import deque def split_overlap(iterable, size, overlap=0): size = int(size) overlap = int(overlap) if size &lt; 1 or overlap &lt; 0 or overlap &gt;= size: raise ValueError() pops = size - overlap q = deque(maxlen=size) for elem in iterable: q.append(elem) if len(q) == size: yield tuple(q) for _ in range(pops): q.popleft() # Yield final incomplete tuple if necessary if len(q) &gt; overlap: yield tuple(q) &gt;&gt;&gt; list(split_overlap(range(10), 4, 2)) [(0, 1, 2, 3), (3, 4, 5, 6), (6, 7, 8, 9)] &gt;&gt;&gt; list(split_overlap(range(10), 5, 2)) [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (6, 7, 8, 9)] Note: as it is, the generator yields one last incomplete tuple if the input does not produce an exact number of chunks (see second example). If you want to avoid this remove the final if len(q) &gt; overlap: yield tuple(q).
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48367549
has title: Flask - getting error when trying to config an app
tagged with: python
accepted answer: http://stackoverflow.com/a/48367612
tagged with: flask
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48367612
has body: I have the following directory structure: app.py config __init__.py settings.py instance __init__.py settings.py app.py looks like this: app = Flask(__name__) debug_toolbar = DebugToolbarExtension() mail = Mail() csrf = CsrfProtect() app.config.from_object('config.settings') app.config.from_pyfile('settings.py', silent=True) @app.route('/') def hello_world(): return "hey" debug_toolbar.init_app(app) mail.init_app(app) csrf.init_app(app) app.run(port=8000) and my settings.py file in both folders looks like this: DEBUG = False SERVER_NAME = 'localhost:8000' SECRET_KEY = 'insecurekeyfordev' # Flask-Mail. MAIL_DEFAULT_SENDER = 'contact@local.host' MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USE_SSL = False MAIL_USERNAME = 'you@gmail.com' MAIL_PASSWORD = 'awesomepassword' # Celery. CELERY_BROKER_URL = 'redis://:devpassword@redis:6379/0' CELERY_RESULT_BACKEND = 'redis://:devpassword@redis:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_REDIS_MAX_CONNECTIONS = 5 If i remove the 2 lines in app.py that take care of the configuration, my app works fine and i get hey when i try to access 127.0.0.1:8000. If i keep those lines in the file, i get a 404 error when i try to access that address. What could be the problem?

http://stackoverflow.com/comment/83821881
type: AnswerComment
comment on: http://stackoverflow.com/a/48415889
has text: I tried this...but its giving error as IndexError: tuple index out of range
type: Comment
score: 0

http://stackoverflow.com/a/48475929
type: Answer
has comment: http://stackoverflow.com/comment/83945146
score: 0
answers question: http://stackoverflow.com/q/48475746
has body: First of all, I recommend to think on this problem one more time; in most cases global state is not the thing you need. On high level, you want a singleton On one way, you can implement this by hand within __new__ method, but I'd not recommend this. Python import system machinery is heavily cached. Meaning, only one instance of every module (together with all classes inside) exists at time. So, if you feel that such functionality really needed, you can put your state in module scope, like _path = '../folder' class Cache: def do_some(self, arg): return arg * _path And once per app you just call `cache_module._path = '../other' Other dirty way is to put this path inside class, like class attribute class Cache: path = '../folder' @classmethod def do_some(cls, arg): return arg * cls.path And once per app you setup cache with Cache.path = '../other'. Cache class and cache module will be the same across all codebase per single python interpreter.

http://stackoverflow.com/a/48974082
type: Answer
accepted answer of: http://stackoverflow.com/q/48333694
has body: As stated in the documentation, message.author is a Member object, not a string. Comparing a member to a string will always result in False. Since Member is a subclass of User, you can use the id attribute to identify the author: @client.event async def on_message(message): if message.author.id == "some_id": await client.send_message(message.channel, "success") This article describes how to find a user's ID. To sum it up: Enable Developer Mode under Settings -> Appearance -> Advanced Right click a user and hit "copy ID"
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48333694
score: 0

http://stackoverflow.com/a/48631708
upvote count: 3
downvote count: 1
has body: Your eg works for me if give a fully qualified file name for simple as '/home/me/simple.htm' . Or if simple.htm is in same directory where I am running the python I do import sys,os fname = os.getcwd()+ '/simple.html' url = QUrl.fromLocalFile(fname) This is with the pyqt that comes with Debian that I am running under python 2.
type: Answer
answers question: http://stackoverflow.com/q/48405646
score: 2

http://stackoverflow.com/q/48458326
downvote count: 1
has comment: http://stackoverflow.com/comment/83909530
has comment: http://stackoverflow.com/comment/83909555
favorite count: 0
type: Question
tagged with: numpy
has body: Please pardon me if it is a dumb question. I was just exploring numpy in python shell and I ran these lines &gt;&gt;&gt; from numpy.linalg import inv &gt;&gt;&gt; from numpy import dot, transpose &gt;&gt;&gt; a = np.matrix('1,2;3,4') &gt;&gt;&gt; print a [[1 2] [3 4]] &gt;&gt;&gt; print inv(a) [[-2. 1. ] [ 1.5 -0.5]] &gt;&gt;&gt; print a.dot(inv(a)) [[1.0000000e+00 0.0000000e+00] [8.8817842e-16 1.0000000e+00]] In the last line I was expecting value [[1,0] [0,1]] (identity matrix), however I got some non-zero value at (1,0) pos.
has answer: http://stackoverflow.com/a/48458388
accepted answer: http://stackoverflow.com/a/48458388
has title: Numpy matrix multiplication with it's inv
tagged with: python
linked to: http://stackoverflow.com/q/15707215
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/83912479
duplicate of: http://stackoverflow.com/q/15707215
type: AnsweredQuestion
score: 0
tagged with: matrix
upvote count: 1
answer count: 1
tagged with: floating-point
has comment: http://stackoverflow.com/comment/83909589

http://stackoverflow.com/q/48359761
tagged with: python-3.x
tagged with: python-sockets
answer count: 1
accepted answer: http://stackoverflow.com/a/48359916
type: AnsweredQuestion
score: 0
tagged with: network-programming
tagged with: sockets
has title: Why Python Socket works only on local network?
tagged with: python
has comment: http://stackoverflow.com/comment/83706361
has answer: http://stackoverflow.com/a/48359916
has body: I'm trying to send a text file trhough Python sockets and it works but only on local network. Why is that?(I'm working with Python 3.6) This is the server.py: import socket HOST = '0.0.0.0' PORT = 80 ADDR = (HOST,PORT) BUFSIZE = 4096 print(socket.gethostbyname(socket.gethostname())) serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.bind(ADDR) serv.listen(5) print ('listening ...') while True: conn, addr = serv.accept() print ('client connected ... ', addr) myfile = open('asd.txt', 'w') while True: data = conn.recv(BUFSIZE) if not data: break myfile.write(data.decode("utf-8")) print ('writing file ....') myfile.close() print ('finished writing file') conn.close() print ('client disconnected') This is the client.py: import socket HOST = '192.168.2.109' PORT = 80 ADDR = (HOST,PORT) BUFSIZE = 4096 textfile = "C:/Users/Public/asd.txt" bytes = open(textfile, "r").read() print (len(bytes)) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect_ex(ADDR) client.send(bytes.encode()) client.close() I've tried this and it worked on local network, but when I sent to my friend the client to try it, it just printed out the bytes but didn't connect to my server.(The server was running on my pc)
type: Question
has comment: http://stackoverflow.com/comment/83706297

http://stackoverflow.com/q/48387602
has comment: http://stackoverflow.com/comment/83763409
has comment: http://stackoverflow.com/comment/83764632
downvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48448962
has title: Multi-Task Learning: Train a neural network to have different loss functions for the two classes?
score: 1
upvote count: 7
answer count: 1
tagged with: keras
has body: I have a neural net with two loss functions, one is binary cross entropy for the 2 classes, and another is a regression. Now I want the regression loss to be evaluated only for class_2, and return 0 for class_1, because the regressed feature is meaningless for class_1. How can I implement such an algorithm in Keras? Training it separately on only class_1 data doesn't work because I get nan loss. There are more elegant ways to define the loss to be 0 for one half of the dataset and mean_square_loss for another half?
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/83767782
type: Question
has answer: http://stackoverflow.com/a/48448962
has comment: http://stackoverflow.com/comment/83765681
has comment: http://stackoverflow.com/comment/83764472
has comment: http://stackoverflow.com/comment/83767504
tagged with: python

http://stackoverflow.com/comment/83737365
has text: `healthy_kibble = (int(kibble) + 1 + 100)`
comment on: http://stackoverflow.com/q/48375167
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48339145
has comment: http://stackoverflow.com/comment/83664234
has body: I am creating very simply building game. I want to click on button in tkinter, which open a new window. In this window you would choose type of building, which you use in previous window, so both windows should be linked in this way. Do you now ho to simply create this type of window? Thank you.
tagged with: python
has title: How to create new window linked to previous? - python
tagged with: tkinter
upvote count: 0
tagged with: window
answer count: 1
tagged with: button
has answer: http://stackoverflow.com/a/48339795
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
downvote count: 2

http://stackoverflow.com/q/48360628
has body: I want to rename a long list of file names to make them more searchable. The names where auto generated so there is some odd spacing issues. I wrote a little python script that does what I want. But I don't want to remove white spaces between words. For instance I have two names: 0 130 — HG — 1500 — 12" (Page 1 of 2) 01 30 — HD LOW POINT DRAIN They should read : 0130-HG-1500-12" 0130-HD LOW POINT DRAIN My code so far : import os import re for filename in os.listdir("."): if not filename.endswith(".py"): os.replace(filename, re.sub("[(].*?[)]", "", # Remove anything between () "".join(filename.split() # Remove any whitespaces ).replace("—", "-"))) # Replace Em dash with hyphen Everything is working except I cant figure out how to not strip white spaces between words only.
type: Question
has comment: http://stackoverflow.com/comment/83799275
has comment: http://stackoverflow.com/comment/83755594
has answer: http://stackoverflow.com/a/48360737
tagged with: python
has comment: http://stackoverflow.com/comment/83709568
tagged with: regex
has comment: http://stackoverflow.com/comment/83722346
has comment: http://stackoverflow.com/comment/83709985
has comment: http://stackoverflow.com/comment/83710449
has title: How to ignore white space inbetween words but not other characters?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48360737
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83807493

http://stackoverflow.com/a/48389502
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48384420
has body: I think you either need multi-threading, or swap your file contents. Nothing runs after mainloop until the Tk instance is destroyed. Alternatively, you could structure your ticket.py in OOP, and fetch GUI object from it by your othermodule to use it as you please. Below is an example: ticket.py: #import tkinter as tk import Tkinter as tk class Window(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Entry") self.resizable(False, False) # create widgets self.frame = tk.Frame(self) self.value = tk.Entry(self.frame) self.btn_stage = tk.Button(self.frame, text="ACTION") # widgets layout self.frame.pack(padx=10, pady=10) self.btn_stage.pack(side='right', padx=2) self.value.pack(side='left') if __name__ == "__main__": root = Window() root.mainloop() and othermodule.py: import ticket def put(): global my_var_in_othermodule my_var_in_othermodule = ticket_GUI.value.get() ticket_GUI.destroy() my_var_in_othermodule = "" ticket_GUI = ticket.Window() ticket_GUI.btn_stage['command'] = put ticket_GUI.mainloop() print(my_var_in_othermodule) input()

http://stackoverflow.com/q/48418169
has body: I have task, which generates which files should be processed: class TaskA(luigi.Task): def run(self): # some code which generates list of files into output() def output(self): return luigi.LocalTarget(filepath='/path/to/process_these_files.json') And I have wrapper task, which should run TaskA, get parameters, and run processing task with values, which I put into process_these_files.json class RunAll(luigi.WrapperTask): def requires(self): files = json.load(TaskA().open('r')) for file in files: yield ProcessFileTask(file=file) Any ideas how to do it?
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48630754
type: Question
tagged with: luigi
has title: Run taskA and run next tasks with parameters, that returned taskA in luigi
favorite count: 0
tagged with: pipeline
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48630754

http://stackoverflow.com/q/48339120
has comment: http://stackoverflow.com/comment/83663645
downvote count: 2
has answer: http://stackoverflow.com/a/48339619
has title: HP - EnemyAttack Throws error at me :L
score: -2
accepted answer: http://stackoverflow.com/a/48339619
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83663561
answer count: 1
has comment: http://stackoverflow.com/comment/83663384
tagged with: python
has body: This is the code I am using: def EnemyAttack(): print("The enemy",enemy, "Attacked!") HP - EnemyAttack if HP &lt; 0 or HP == 0: print("You Were torn to pieces by the",enemy,".") else: print("You managed to withstand the attack by the",enemy, "It growls in frustration.") BattleChoice() ... and the error I receive when running: Traceback (most recent call last): File "python", line 83, in File "python", line 62, in EnemyAttack TypeError: unsupported operand type(s) for -: 'int' and 'function'
type: Question
upvote count: 0

http://stackoverflow.com/q/48393590
has comment: http://stackoverflow.com/comment/83775164
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83775054
answer count: 1
type: Question
has title: how to generate multiple txt file based on months/year?
has answer: http://stackoverflow.com/a/48399148
score: 0
has comment: http://stackoverflow.com/comment/83775185
has comment: http://stackoverflow.com/comment/83775534
has comment: http://stackoverflow.com/comment/83774990
tagged with: python
has body: I have a large txt file (log file), where each entry starts with timestamp such as Sun, 17 Mar 2013 18:58:06 I want to split the file into multiple txt by mm/yy and and sorted The general code I planned is below, but I do not know how to implement such. I know how to split a file by number of lines etc, but not by specified timestamp import re f = open("log.txt", "r") my_regex = re.compile('regex goes here') body = [] for line in f: if my_regex.match(line): if body: write_one(body) body = [] body.append(line) f.close() example of lines from txt 2Sun, 17 Mar 2013 18:58:06 Pro IDS2.0 10E22E37-B2A1-4D55-BE20-84661D420196 nCWgKUtjalmYx053ykGeobwgWW V3 3Sun, 17 Mar 2013 19:17:33 &lt;AwaitingDHKey c i FPdk 1:0 pt 0 Mrse&gt; 0000000000000000000000000000000000000000 wo&gt; HomeKit keychain state:HomeKit: mdat=2017-01-01 01:41:47 +0000,cdat=2017-01-01 01:41:47 +0000,acct=HEDF3,class=genp,svce=AirPort,labl=HEDF3 4Sun, 13 Apr 2014 19:10:26 values in decoded form... oak: &lt;C: gen:'[ 21:10 5]' ak&gt; &lt;PI@0x7fc01dc05d90: [name: Bourbon] [--SrbK-] [spid: zP8H/Rpy] [os: 15G31] [devid: 49645DA6] [serial: C17J9LGKDTY3] - 5Sun, 16 Feb 2014 18:59:41 tLastKVSKeyCleanup: ak|nCWgKUtjalmYx053ykGeobwgWW:sk1Kv+37Clci7VwR2IGa+DNVEA: DHMessage (0x02): 112
has comment: http://stackoverflow.com/comment/83774954
has comment: http://stackoverflow.com/comment/83775387

http://stackoverflow.com/comment/83755796
score: 0
type: Comment
type: QuestionComment
has text: See [`tkinter`](https://stackoverflow.com/tags/tkinter/info) tag info for more resources, tutorials etc.
comment on: http://stackoverflow.com/q/48376528

http://stackoverflow.com/a/48472705
type: Answer
score: 2
has body: Short answer, no. Use a dictionary. def rock_paper_scissors_lizard_spock(player1, player2): # each variable stores what it can defeat mapper = {'scissors': ['paper', 'lizard'], 'rock': ['lizard', 'scissors'], 'paper': ['rock', 'spock'], 'lizard': ['spock', 'paper'], 'spock': ['scissors', 'rock']} print('player %s wins' %(1 if player2 in mapper[player1] else 2)) rock_paper_scissors_lizard_spock('paper', 'rock') # player 1 wins
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48472683

http://stackoverflow.com/comment/83922738
score: 0
comment on: http://stackoverflow.com/a/48457837
type: AnswerComment
has text: But somehow both Logger.log(new RegExp("\\.").exec(".")); and Logger.log(new RegExp("\.").exec(".")); Match the dot! This is very confusing!
type: Comment

http://stackoverflow.com/a/48413443
score: 1
answers question: http://stackoverflow.com/q/48412871
has body: I'm not sure about the L or the Decimal notation, but here is something you could do to get the desired results: from collections import defaultdict lis = [ {'price': 45.00, 'total': '1L', 'quantity': 1}, {'price': 45.00, 'total': '1L', 'quantity': 1}, {'price': 45.00, 'total': '2L', 'quantity': 1}, {'price': 40.00, 'total': '1L', 'quantity': 1}, {'price': 40.00, 'total': '1L', 'quantity': 1}, {'price': 49.00, 'total': '1L', 'quantity': 1}, ] results = defaultdict(lambda: {'price':0, 'total':0, 'quantity':1}) for i in lis: results[i['price']]['price'] += i['price']*int(i['total'].strip('L')) results[i['price']]['total'] += int(i['total'].strip('L')) print(list(results.values())) This results in: [{'price': 180.0, 'total': 4, 'quantity': 1}, {'price': 80.0, 'total': 2, 'quantity': 1}, {'price': 49.0, 'total': 1, 'quantity': 1}]
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/48398998
score: 0
accepted answer of: http://stackoverflow.com/q/48365093
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48365093
has body: i was uploading a corrupted .gz file. The code is fine and is working well now.
type: Answer

http://stackoverflow.com/comment/83900547
has text: So the merge sort algorithm says basically "to sort an array, split it in half, sort each part, then merge it together". And a one-element array is already sorted by default. 1. Your analysis of what happens with `left` and `right` is correct. 2. `mergesort([3])` does return `[3]`; what makes you think it doesn't? 3. The first `merge` will happen after the first time both `left` and `right` are calculated, which will be `merge([1], [23])`, resulting in `[1, 23]`.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48453373
type: Comment

http://stackoverflow.com/a/48373846
answers question: http://stackoverflow.com/q/48373812
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/83734887
has body: try: import sys sys.setrecursionlimit(10000) 10 000 recursions should be enough What happened is that somewhere someplace , something is calling itself over and over again. Each time, thats called one recursion. Python has a limit to prevent a program running infinitely. While this is usually a sign of an error, you can increase the limit to how you see fit, as your program might recurse for an unusually big amount.
type: Answer
accepted answer of: http://stackoverflow.com/q/48373812
upvote count: 6

http://stackoverflow.com/q/48378468
has comment: http://stackoverflow.com/comment/83744201
has comment: http://stackoverflow.com/comment/83743733
tagged with: python
linked to: http://stackoverflow.com/q/31397373
has answer: http://stackoverflow.com/a/48378633
answer count: 4
has comment: http://stackoverflow.com/comment/83743789
accepted answer: http://stackoverflow.com/a/48378552
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83743795
has answer: http://stackoverflow.com/a/48378552
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83743829
has title: Python nested for loops output unpredictable?
downvote count: 0
has comment: http://stackoverflow.com/comment/83744208
favorite count: 0
has answer: http://stackoverflow.com/a/48379041
type: Question
possible better answer: http://stackoverflow.com/a/48378618
type: AnsweredQuestion
has body: I have the following code which I wrote for the project Euler question #4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. def foo(): for x in xrange (999,100,-1): for y in xrange (999,100,-1): product= (x*y) if str(product)== str(product)[::-1]: print product foo() This code generates a continuous output of all palindromes since i have omitted a break. However the output is as follows: 580085 514415 906609 119911 282282 141141 853358 650056 601106 .. .. I can't figure out why the largest number doesn't print out first. A similar code in C gives the largest number on the very top. Is there something about Python for loops I'm missing?
has answer: http://stackoverflow.com/a/48378618

http://stackoverflow.com/comment/83943496
score: 1
has text: @MikeMüller I've simplified the argument to `np.exp`. The purpose of the answer was to illustrate how you can write two loops in a single line expression.
type: Comment
comment on: http://stackoverflow.com/a/48474930
type: AnswerComment

http://stackoverflow.com/q/48464861
has answer: http://stackoverflow.com/a/48467880
accepted answer: http://stackoverflow.com/a/48467880
tagged with: python
has title: numpy vectorize dimension increasing function
has answer: http://stackoverflow.com/a/48465092
possible better answer: http://stackoverflow.com/a/48465092
type: AnsweredQuestion
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/83928136
has comment: http://stackoverflow.com/comment/83927136
has body: I would like to create a function that has input: x.shape==(2,2), and outputs y.shape==(2,2,3). For example: @np.vectorize def foo(x): #This function doesn't work like I want return x,x,x a = np.array([[1,2],[3,4]]) print(foo(a)) #desired output [[[1 1 1] [2 2 2]] [[3 3 3] [4 4 4]]] #actual output (array([[1, 2], [3, 4]]), array([[1, 2], [3, 4]]), array([[1, 2], [3, 4]])) Or maybe: @np.vectorize def bar(x): #This function doesn't work like I want return np.array([x,2*x,5]) a = np.array([[1,2],[3,4]]) print(bar(a)) #desired output [[[1 2 5] [2 4 5]] [[3 6 5] [4 8 5]]] Note that foo is just an example. I want a way to map over a numpy array (which is what vectorize is supposed to do), but have that map take a 0d object and shove a 1d object in its place. It also seems to me that the dimensions here are arbitrary, as one might wish to take a function that takes a 1d object and returns a 3d object, vectorize it, call it on a 5d object, and get back a 7d object.... However, my specific use case only requires vectorizing a 0d to 1d function, and mapping it appropriately over a 2d array.
has comment: http://stackoverflow.com/comment/83926178
has answer: http://stackoverflow.com/a/48467516
downvote count: 1
has comment: http://stackoverflow.com/comment/83927005
has comment: http://stackoverflow.com/comment/83927025
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83924666
has comment: http://stackoverflow.com/comment/83926014
has comment: http://stackoverflow.com/comment/83926950
upvote count: 2
linked to: http://stackoverflow.com/q/35215161

http://stackoverflow.com/comment/83652330
type: QuestionComment
has text: @user1767754 basically i have a service where i want to take in a class as a "processor" that would get executed in each worker process. it would be nice if the class could maintain state in each process. ideally i could use the initializer argument to call a "start" instance method on the class instance as well.
score: 0
comment on: http://stackoverflow.com/q/48332391
type: Comment

http://stackoverflow.com/q/48481929
type: Question
has body: I'm trying to find the roots of a function from scipy.optimize import brentq import matplotlib.pyplot as plt from numpy.polynomial import Polynomial,Legendre def f(): return Legendre.basis(3).linspace() brentq(f,1,2) but i keep getting the error TypeError: f() takes 0 positional arguments but 1 was given I have no idea whats wrong with it since as far as I can tell, the format of brentq is correct.
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48482087
score: 0
has title: python SciPy error brentq
tagged with: scipy

http://stackoverflow.com/a/48374096
has body: There's no need for an apply here. It would be a lot faster to groupby, calculate the sum and divide directly, as pandas vectorises these operations. Borrowing from @Wen's setup, this is how I'd do it - v = df.groupby('A')'A', 'B'.sum() v['B'] /= v['A'] del v['A'] B A 1 2.500000 3 1.333333 4 1.250000
has comment: http://stackoverflow.com/comment/83735548
has comment: http://stackoverflow.com/comment/83735535
answers question: http://stackoverflow.com/q/48373984
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83737076
downvote count: 0

http://stackoverflow.com/q/48383549
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48383752
tagged with: django
has comment: http://stackoverflow.com/comment/83754200
has comment: http://stackoverflow.com/comment/83754563
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/17646662
has answer: http://stackoverflow.com/a/50546278
tagged with: postgresql
has body: I'm using PostgreSQL to store an object with a DateTimeField. The DateTimeField is using auto_now_add options. And it is created automatically from serializer in Django Rest Framework. As described in Django docs, I tried to get local timezone and activate it. from django.utils.timezone import localtime, get_current_timezone tz = get_current_timezone() timezone.activate(tz) session.started_at = localtime(session.started_at) In template index.html, I also try to load timezone. {% localtime on %} Session: start time {{ item.session.started_at }} {% endlocaltime %} In settings.py USE_TZ = True TIME_ZONE = 'UTC' I'm using GMT+7 timezone but it still shows UTC time on template. I'm using Django development server to test. Am I missing something?
has answer: http://stackoverflow.com/a/64721811
score: 3
has answer: http://stackoverflow.com/a/48390518
tagged with: python
linked to: http://stackoverflow.com/q/10235956
linked to: http://stackoverflow.com/q/14657173
has title: How to show local time in template
answer count: 4
has comment: http://stackoverflow.com/comment/83754716
upvote count: 3

http://stackoverflow.com/a/48477554
answers question: http://stackoverflow.com/q/48477484
type: Answer
has comment: http://stackoverflow.com/comment/83981460
has body: Try to import cv2 package in command line. If it executes without any error than it should work. Have you pasted the cv2.pyd file in lib/site-packages folder?
score: 0
has comment: http://stackoverflow.com/comment/83952927

http://stackoverflow.com/a/48471831
has body: David here, from the Zapier Platform team. Marc, your main problem is that you're using a PHP snippet in our Python interpreter, which is probably why it's giving you trouble. If you have specific questions or there's something we can improve about our documentation, definitely let me know! I'd check out the python re.sub() function instead. There's a great answer about it here. You'll also want to be able test your regex, for which there's a great site (as there are some sleight differences between PHP and Python regex. There's also a great language resource here if you want to learn more about the Python language. ​Let me know if you've got any other questions!
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48436769

http://stackoverflow.com/q/48480053
has answer: http://stackoverflow.com/a/48480133
has comment: http://stackoverflow.com/comment/83953153
upvote count: 0
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/83953221
has comment: http://stackoverflow.com/comment/83953108
downvote count: 1
tagged with: vectorization
favorite count: 0
has comment: http://stackoverflow.com/comment/83953073
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83953092
tagged with: python
score: -1
has title: Python - Fastest / Best way to apply a function to each element of a numpy.array
accepted answer: http://stackoverflow.com/a/48480133
has body: I am wondering what is the fastest (or "best" due to some reason) method to apply a function to each element of a numpy array. I tried this method with a larger data set and it takes quite a while... Post your answer with the results (time in milliseconds) you got on my implementation and yours,as different HW will give different results on the same code Please share your implementation between the 2 commented lines import numpy as np import time # Some random data x = np.random.rand(5,32,32,3)*255 x = x.astype(int) # Defining some function def normalize(x, a=0, b=1, x_min=0, x_max=255): return a + (x - x_min)*(b - a)/(x_max-x_min) ## Start timer start_time = time.time() # ---------------------IMPLEMENTATION--------------------- # Apply Normalize function to each element in the array n = np.vectorize(normalize) x = n(x) #_________________________________________________________ # Stop timer and show time in milliseconds elapsed_time = time.time() - start_time print("Time [ms] = " + str(elapsed_time*1000))
type: Question
tagged with: numpy

http://stackoverflow.com/q/48331931
possible better answer: http://stackoverflow.com/a/48331947
has comment: http://stackoverflow.com/comment/83649654
upvote count: 2
score: 1
has title: Python - Looping over selected indexes in a list
has body: Let's say I have a list of 10 numbers: a = [0,1,2,3,4,5,6,7,8,9] I want to get the 2nd digit, the 5-8th digits, and the last digit. Something like: for i in (a[1], a[4:7], a[9]): print(i) How would I do this?
has answer: http://stackoverflow.com/a/48331959
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48331953
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48332023
has answer: http://stackoverflow.com/a/48331947
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48331964
accepted answer: http://stackoverflow.com/a/48332023

instantiation
tags question: http://stackoverflow.com/q/48341893
type: Tag
tag name: instantiation

http://stackoverflow.com/comment/83733654
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48373267
has text: Could you provide the corresponding source?

http://stackoverflow.com/q/48454720
tagged with: python-3.x
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83902504
has comment: http://stackoverflow.com/comment/83904520
has body: I have two big dataframes. “gene” has structure like this (more than three columns though): Mutation ID CDS Mutation AA COSM1000525 123 V617A COSM1003371 234 S517A COSM1003372 456 T417A COSM1004880 567 K317A COSM1004881 1234 R610A COSM1004883 1234 V617A COSM1004884 543 W617A COSM1006396 132 Y617A COSM1007340 7654 V617A “output” is part of "gene" and only has one column Mutation ID: Mutation ID COSM1000525 COSM1003372 COSM1004881 I want to make a new dataframe that has two columns (Mutation ID and Mutation AA) of the “gene’ when Mutation ID matches with those in the “output”. How to implement this in python?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48454855
has title: Creat a new dataframe that has two columns of one dataframe when some rows matches with another dataframe
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/89009201
comment on: http://stackoverflow.com/a/48489815
type: AnswerComment
has text: It should be the answer because we don't have to modify the length of our data
score: 1
type: Comment

http://stackoverflow.com/comment/84132426
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48477528
has text: How are you running the code on PythonAnywhere? Are you sure you're using Python 3.x? The command `python` in bash will launch Python 2.7. you need to use `python3.6` or equivalent to use Python 3.

http://stackoverflow.com/q/48360675
has comment: http://stackoverflow.com/comment/83710098
has body: I'm having a problem with the player class I've created. To create it I was inspired by how I was doing on Pygame, so maybe that's why I'm getting the error here on Pyglet. class player(pyglet.sprite.Sprite): def __init__(self, x, y, game): self.game = game self.groups = self.game.spritesPlayer pyglet.sprite.Sprite.__init__(self, self.groups) self.image = pyglet.resource.image("white_square.png") self.rect.x = x * self.game.tilesize self.rect.y = y * self.game.tilesize The class is called from the main class with self.player = player(self, 0, 0) And this is the Player group contained in the main class: self.spritesPlayer = OrderedDict() The error I'm getting is this: File "C:/Users/BlackFenix06/Desktop/pk.py/c.py", line 464, in __init__ pyglet.sprite.Sprite.__init__(self, self.groups) File "C:\Python34\lib\site-packages\pyglet\sprite.py", line 243, in __init__ self._texture = img.get_texture() AttributeError: 'OrderedDict' object has no attribute 'get_texture' What am I doing wrong? I'm working for 2D, not for 3D
tagged with: pyglet
has comment: http://stackoverflow.com/comment/83956140
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83965674
score: 0
has title: AttributeError: 'OrderedDict' object has no attribute 'get_texture'
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83711135
has comment: http://stackoverflow.com/comment/83718743

http://stackoverflow.com/a/48334837
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48334761
has comment: http://stackoverflow.com/comment/83654832
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48334761
has comment: http://stackoverflow.com/comment/83654847
type: Answer
has body: Numpy solution. Use broadcasted comparison, followed by a cumsum operation along the first axis. Finally, extract the diagonal elements and assign to df. v = (df.invoice_date[:, None] &gt; df.payment_date.values).cumsum(1) df['num_pay_dates_less_than_inv_date'] = v[np.diag_indices_from(v)] df id invoice_date payment_date num_pay_dates_less_than_inv_date 0 1 2017-03-01 2017-03-03 0 1 1 2017-03-04 2017-03-06 1 2 1 2017-03-04 2017-03-11 1 3 1 2017-03-15 2017-03-16 3 4 1 2017-03-21 2017-03-31 4 5 2 2017-01-22 2017-01-22 0 6 2 2017-01-24 2017-01-25 1 This requires both columns to be in datetime format (otherwise, the comparison is lexicographical, which is usually okay, but it would depend on your date format at that point).
score: 2
has comment: http://stackoverflow.com/comment/83654875

http://stackoverflow.com/a/48402388
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83793144
has body: You are computing the first 4 million fibonacci numbers. It's going to take a while. It took me almost 5 minutes to compute the result, which was about 817 KB of digits, after I replaced fibn % 2 == 0 with fibn &amp; 1 == 0 - an optimization that makes a big difference on such large numbers. In other words, your code will eventually finish - it will just take a long time. Update: your version finished after 42 minutes.
answers question: http://stackoverflow.com/q/48402048
has comment: http://stackoverflow.com/comment/83800199
has comment: http://stackoverflow.com/comment/83798334
type: Answer
has comment: http://stackoverflow.com/comment/83795333
has comment: http://stackoverflow.com/comment/83792974
score: 2
has comment: http://stackoverflow.com/comment/83793228

http://stackoverflow.com/q/48350693
has body: I've seen np.int0 used for converting bounding box floating point values to int in OpenCV problems. What exactly is np.int0? I've seen np.uint8, np.int32, etc. I can't seem to find np.int0 in any online documentation. What kind of int does this cast arguments to?
tagged with: python
accepted answer: http://stackoverflow.com/a/48350735
tagged with: int
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83688068
answer count: 3
has comment: http://stackoverflow.com/comment/83688228
has comment: http://stackoverflow.com/comment/83688197
has comment: http://stackoverflow.com/comment/83688157
has title: What is numpy method int0?
has comment: http://stackoverflow.com/comment/83726126
downvote count: 2
has comment: http://stackoverflow.com/comment/83688360
has answer: http://stackoverflow.com/a/48352025
tagged with: methods
has comment: http://stackoverflow.com/comment/83690481
has answer: http://stackoverflow.com/a/48350735
has comment: http://stackoverflow.com/comment/83688177
favorite count: 0
has comment: http://stackoverflow.com/comment/83688586
type: Question
tagged with: numpy
upvote count: 40
has answer: http://stackoverflow.com/a/48350713
possible better answer: http://stackoverflow.com/a/48350713
score: 38
has comment: http://stackoverflow.com/comment/83726293

http://stackoverflow.com/a/48467337
type: Answer
accepted answer of: http://stackoverflow.com/q/48447427
score: 2
upvote count: 2
type: AcceptedAnswer
has body: (Answer mostly summarises a bunch of comments) The immediate issue you were having was that Python has no real way to handle C structs. To get around this, Cython tries to convert structs to dictionaries when they are passed to Python (if possible). In this particular case, mpz_t is treated as "opaque" by C (and thus Cython) so you aren't supposed to know about its members. Therefore Cython "helpfully" converts it to an empty dictionary (a correct representation of all the members it knows about). For an immediate fix I suggested using the gmpy library, which is an existing Python/Cython wrapping of GMP. This is probably a better choice than repeating the effort to wrap it. As a general solution to this sort of problem there are two obvious options. You could create a cdef wrapper class. The documentation I have linked is for C++, but the idea could be applied to C as well (with new/'del' replaced with 'malloc'/'free'). This is ultimately a Python class (so can be returned from Cython to Python) but contains a C struct, which you can manipulate directly in Cython. The approach is pretty well documented and doesn't need repeating here. You could convert the mpz_t back to a Python integer at the end of the function. I feel this makes most sense, since ultimately they represent the same thing. The code shown below is a rough outline and hasn't been tested (I don't have gmp installed): cdef mpz_to_py_int(mpz_t x): # get bytes that describe the integer cdef const mp_limb_t* x_data = mpz_limbs_read(x) # view as a unsigned char* (i.e. as bytes) cdef unsigned char* x_data_bytes = &lt;unsigned char*&gt;x_data # cast to a memoryview then pass that to the int classmethod "from_bytes" # assuming big endian (python 3.2+ required) out = int.from_bytes(&lt;unsigned char[:mpz_size(x):1]&gt;x_data_bytes,'big') # correct using sign if mpz_sign(x) &lt; 0: return -out else return out
downvote count: 0
answers question: http://stackoverflow.com/q/48447427

http://stackoverflow.com/q/48455204
downvote count: 0
upvote count: 1
has title: 'ascii' codec can't decode byte 0xe2 in position 81: ordinal not in range(128)
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am trying to send the following JSON object to a webservice api and ran into Error1 below,then I added .encode("utf-8").strip() to the title(see code snippet) below and then ran to Error1,now am lost as to how to fix this?any one provide pointers? {"component":{"name":"comp chip PCIe", "version":"X"},"assignee":123449612,"milestone":"Internal Tools - Mile","priority":2,"state":"Analyze","substate":"Nominate","title":"[Cloning for automation checkin]SVT:UDM:4364B2::SITM: Observing few instances of “CW Firmware Requested Dump PCIe~reason=(0x6)” followed by “watchdog@CW Chip Trap~Type=4,PC=0x1666F0,LR=0xEEEEEEEE” during SITM test."} Code Snippet: title = "[" + sys.argv[5] +"]" + orgRadar['title'].encode("utf-8").strip() Error1: 'ascii' codec can't encode character u'\u201c' in position 253: ordinal not in range(128) Error2: 'ascii' codec can't decode byte 0xe2 in position 81: ordinal not in range(128)
has answer: http://stackoverflow.com/a/48456235
score: 1
answer count: 1

http://stackoverflow.com/a/48378884
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83803811
downvote count: 0
has comment: http://stackoverflow.com/comment/83760925
has comment: http://stackoverflow.com/comment/140158359
answers question: http://stackoverflow.com/q/48377685
type: Answer
has body: You should be able to traverse the chunks the same way you traverse the layers. With a method like: def expand(pkt): payload = [] for p in pkt.payload: payload+=expand(p) return [pkt.name, payload] print(expand(pkt)) print(pkt.payload.payload.payload.name) I get, for an SCTP package: ['Ethernet', ['IP', ['SCTP', ['SCTPChunkSACK', []]]]] SCTPChunkSACK edit: For the content: &gt;&gt;&gt; print(pkt[SCTP][1]) b'\x03\x00\x00\x10\x7f\x8cD\x18\x00\x01\xa0\x00\x00\x00\x00\x00' &gt;&gt;&gt; print(pkt[SCTP][1].show()) ###[ SCTPChunkSACK ]### type = sack flags = 0x0 len = 16 cumul_tsn_ack= 0x7f8c4418 a_rwnd = 106496 n_gap_ack = 0 n_dup_tsn = 0 gap_ack_list= [] dup_tsn_list= [] So you already have your (nested) list of chunks at pkt[SCTP][1:].

http://stackoverflow.com/comment/83649250
score: 1
has text: @Null-Hypothesis, you mean those rows where all columns (except first two) are NaN's or any?
comment on: http://stackoverflow.com/a/48331482
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83713298
comment on: http://stackoverflow.com/q/48363203
has text: this is too many threads per block: `threadsperblock = 16,16,16` That is 16x16x16 = 4096 threads total. But CUDA is limited to 1024 total threads per block. Try `threadsperblock = 8,8,8`
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48487936
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83968769
has comment: http://stackoverflow.com/comment/83968751
has answer: http://stackoverflow.com/a/48487979
answer count: 2
possible better answer: http://stackoverflow.com/a/48487979
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48488024
accepted answer: http://stackoverflow.com/a/48488024
has title: Calculating when the amount will be doubled using while loop
has comment: http://stackoverflow.com/comment/83968746
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1832940
has body: This is a simple exercise found in a book, which asks us to determine how long it takes for an amount to double at a given interest rate. My code is like this: def main(): x = eval(raw_input("Initial Principal: ")) y = eval(raw_input("Interest rate: ")) count = 0 while x &lt; 2*x: x = x * (1 + y) count = count + 1 print (x) print (count) main() What it returns is: Initial Principal: 1000 Interest rate: 0.5 inf 1734 What's wrong with my code? Also I wonder if the above code would work if my amount and interest is small, e.g. amount = 1 and interest rate = 0.05, since there would include some floating point arithmetic I guess. Thank you!
tagged with: python

http://stackoverflow.com/comment/83751247
type: Comment
type: QuestionComment
has text: Sorry, in the interview I did this: `path[:]`, `two_nodes` should be `two_paths`, sorry, I typed this up on SO quickly, should have proof-read.
comment on: http://stackoverflow.com/q/48382047
score: 0

http://stackoverflow.com/q/48372508
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48372745
has body: I have the following HTML code: &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;a href="/block_explorer/address/1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"&gt;1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="/block_explorer/address/hash/62e907b15cbf27d5425399ebf6f0fb50ebb88f18/"&gt;62e907b15cbf27d5425399ebf6f0fb50ebb88f18&lt;/a&gt;&lt;/td&gt; &lt;td class="num"&gt;66.6771&lt;small class="b-blockExplorer__small"&gt;1246&lt;/small&gt;&amp;nbsp;BTC&lt;/td&gt; &lt;td class="num"&gt;66.6771&lt;small class="b-blockExplorer__small"&gt;1246&lt;/small&gt;&amp;nbsp;BTC&lt;/td&gt; &lt;td class="num"&gt;1089&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;a href="/block_explorer/address/12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"&gt;12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="/block_explorer/address/hash/119b098e2e980a229e139a9ed01a469e518e6f26/"&gt;119b098e2e980a229e139a9ed01a469e518e6f26&lt;/a&gt;&lt;/td&gt; &lt;td class="num"&gt;50.0572&lt;small class="b-blockExplorer__small"&gt;3154&lt;/small&gt;&amp;nbsp;BTC&lt;/td&gt; &lt;td class="num"&gt;50.0572&lt;small class="b-blockExplorer__small"&gt;3154&lt;/small&gt;&amp;nbsp;BTC&lt;/td&gt; &lt;td class="num"&gt;55&lt;/td&gt; &lt;/tr&gt; &lt;!--- SNIP ---&gt; &lt;/tbody&gt; I want to parse it to get something like: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa,62e907b15cbf27d5425399ebf6f0fb50ebb88f18,66.6771,66.6771 12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX,119b098e2e980a229e139a9ed01a469e518e6f26,50.0572,50.0572 Tried with BeautifulSoup: soup.select('tbody &gt; tr &gt; td')[rowcount].get_text(strip=True) I get only the fist &lt;td&gt;*&lt;/td&gt; What am I doing wrong?
has answer: http://stackoverflow.com/a/48372745
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48374367
has answer: http://stackoverflow.com/a/48374367
has title: Parse " / / " with python's BeautifulSoup
type: AnsweredQuestion
score: 3
answer count: 2
upvote count: 3
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/a/48481632
downvote count: 1
has body: The reason for your error is you are attempting to do a row-wise (vectorised calculation), but in fact in your function diff() ratings[ratings.downloaded &gt; 0] returns a subset of the dataframe and preceding it by if is ambiguous. The error message reflect this. You may wish to review Indexing and Selecting Data. The below solution sets the default value 0 by setting it at the beginning. import pandas as pd df = pd.DataFrame([[2, 2, 5.0], [12, 12, 4.5], [10, 5, 3.0], [20, 2, 3.5], [3, 0, 0.0], [0, 0, 0.0]], columns=['total', 'downloaded', 'avg_rating']) df['Pct Diff'] = 0 df.loc[df['downloaded'] &gt; 0, 'Pct Diff'] = (df['total'] - df['downloaded']) / df['total'] # total downloaded avg_rating Pct Diff # 0 2 2 5.0 0.0 # 1 12 12 4.5 0.0 # 2 10 5 3.0 0.5 # 3 20 2 3.5 0.9 # 4 3 0 0.0 0.0 # 5 0 0 0.0 0.0
score: 1
type: Answer
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48481223
accepted answer of: http://stackoverflow.com/q/48481223

http://stackoverflow.com/a/48484327
answers question: http://stackoverflow.com/q/48484256
accepted answer of: http://stackoverflow.com/q/48484256
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: MATLAB has its own interpreter, so it can interpret the ; etc to suit its needs. numpyuses the Python interpreter, so can't use or reuse basic syntactic characters like [],;. So the basic array constructor wraps a nested list of lists (takes a list as argument): np.array([[1,2,3], [4,5,6]]) But that nesting can be carried to any depth, np.array([]), np.array(['foo']), because arrays can have 0,1, 2 etc dimensions. MATLAB initially only had 2d matrices, and still can't have 1 or 0d. In MATLAB that matrix is the basic object (cell and struct came later). In Python lists are the basic object (with tuples and dicts close behind). np.matrix takes a string argument that imitates the MATLAB syntax. np.matrix('1 2; 3 4'). But np.matrix like the original MATLAB is fixed at 2d. https://docs.scipy.org/doc/numpy/reference/arrays.classes.html#matrix-objects https://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html#numpy.bmat But seriously, who makes real, useful matrices with the 1, 2; 3, 4 syntax? Those are toys. I prefer to use np.arange(12).reshape(3,4) if I need a simple example. numpy has added a np.stack which gives more ways of joining arrays into new constructs. And a np.block: https://docs.scipy.org/doc/numpy/reference/generated/numpy.block.html#numpy.block
score: 2
type: Answer

http://stackoverflow.com/q/48470964
has body: I am trying to extract phone numbers from a web page using Python &amp; RegEx Australian number format +61 (international code - shown below as 'i') 02, 03, 07 or 08 (state codes - shown below as 's') 1234-5678 (8 digit local number - shown below as 'x') Common variations of format (in order of commonality): Format 1: ss xxxx xxxx (e.g. 02 1234 5678) Format 2: +ii s xxxx xxxx (e.g. +61 2 1234 5678) (note the first 's' digit is removed here) Format 3: (seen rarely) +ii (s)s xxxx-xxxx (e.g. +61 (0)2 1234 5678 My RegEx: re.findall(r'[0][2]\d{8}|[0][3]\d{8}|[0][7]\d{8}|[0][8]\d{8}|[6][1][2]\d{8}|[6][1][3]\d{8}|[6][1][7]\d{8}|[6][1][8]\d{8}|[0][4]\d{8}|[6][1][4]\d{8}|[1][3][0][0]\d{6}|[1][8][0][0]\d{6}', re.sub(r'\W+', '', sample_text)) works well on a simple sample_text: sample_text = "610212345678ABC##610312345678ABC##610712345678ABC##610812345678ABC##0212345678ABC##0312345678ABC##0712345678ABC##0812345678ABC##61212345678ABC##61312345678ABC##61712345678ABC##61812345678ABC##0412345678ABC##61412345678ABC##130012345678ABC##180012345678ABC##" Result: ['0212345678', '0312345678', '0712345678', '0812345678', '0212345678', '0312345678', '0712345678', '0812345678', '61212345678', '61312345678', '61712345678', '61812345678', '0412345678', '61412345678', '1300123456', '1800123456'] The Goal Using http://www.outware.com.au/contact as an example ... The 2 actual numbers on the page are: +61 (0)3 8684 9912 and +61 (0)2 8064 7043 (both numbers appear twice - once in the main section of the page and once in the footer) The Problem #take HTML markup from body tags b = driver.find_element_by_css_selector('body').text #remove all non-alpha + white space. b = re.sub(r'\W+', '', b) Result: "PORTFOLIOINNOVATIONSERVICESCAREERSINSIGHTSNEWSABOUTCONTACTCONTACTOUTWAREMelbourneLe......AFRFast100Nov92017EXPLOREOUTWAREPortfolioInnovationWorkingatOutwareAboutSitemapCONNECTMELBOURNELevel3469LaTrobeStMelbourneVIC3000610386849912SYDNEYLevel41SmailStUltimoNSW2007610280647043" Now if I apply my regex to…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48471027
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/48471027
has comment: http://stackoverflow.com/comment/83935967
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48471080
has answer: http://stackoverflow.com/a/48474595
has title: Python RegEx for Australian Phone Numbers - False negative - 2 matches in the same substring
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48471080

http://stackoverflow.com/comment/84167162
score: 0
has text: @Alfe I guess I should ask a separate question :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48454604

http://stackoverflow.com/comment/83665981
has text: You should try to understand what `SRT_stocFund.Export()` does and work from there.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48340352

http://stackoverflow.com/comment/83900047
has text: could you make some executable script with just one textfield. It will be easier for me to help you
type: Comment
comment on: http://stackoverflow.com/a/48453159
score: 0
type: AnswerComment

http://stackoverflow.com/a/48374368
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83736112
downvote count: 0
answers question: http://stackoverflow.com/q/48374345
type: AcceptedAnswer
has body: TensorFlow versions 1.1.0 and higher have been compiled for Python 3.6 (as well as 3.5 in most cases). You can check the current installation of TensorFlow using command: python -c "import tensorflow as tf; print(tf.__version__)"
accepted answer of: http://stackoverflow.com/q/48374345
upvote count: 3

depth-first-search
tags question: http://stackoverflow.com/q/48350916
tags question: http://stackoverflow.com/q/48333927
type: Tag
tag name: depth-first-search

http://stackoverflow.com/q/48372210
type: Question
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48372641
answer count: 1
downvote count: 0
upvote count: 1
has body: I was testing how difflib works for per-character diffing of some random inputs, and was surprised to find out the following: Consider a snippet: import difflib a = """kydropqfp tpssubdbw tzibqyqvp llmpwtekn xmubmrjch vcojgxxil vdrsqhzag xlcldqabb ujccweoha dsooqyyve khilgzjue jignrbela glvvueqqb qlfehmlkm brkleswiq vvsplffjf yjuoivyjr wtfueypmo pkvlmbcnh tesuistya zbf""" blist = list(a) blist[23] = 'a' b = ''.join(blist) print('\n'.join(difflib.unified_diff(a, b))) It provides the expected result: --- +++ @@ -21,7 +21,7 @@ t z i -b +a q y q However, if we add only a single n character at the end of the input: a = """kydropqfp tpssubdbw tzibqyqvp llmpwtekn xmubmrjch vcojgxxil vdrsqhzag xlcldqabb ujccweoha dsooqyyve khilgzjue jignrbela glvvueqqb qlfehmlkm brkleswiq vvsplffjf yjuoivyjr wtfueypmo pkvlmbcnh tesuistya zbfn""" Then, for some reason, the context after the found diff is not limited to 3 chars: --- +++ @@ -21,184 +21,184 @@ t z i -b -q -y -q -v -p - -l -l -m -p -w -t -e -k -n - -x -m -u -b -m -r -j -c -h - -v -c -o -j -g -x -x -i -l - -v -d -r -s -q -h -z -a -g - -x -l -c -l -d -q -a -b -b - -u -j -c -c -w -e -o -h -a - -d -s -o -o -q -y -y -v -e - -k -h -i -l -g -z -j -u -e - -j -i -g -n -r -b -e -l -a - -g -l -v -v -u -e -q -q -b - -q -l -f -e -h -m -l -k -m - -b -r -k -l -e -s -w -i -q - -v -v -s -p -l -f -f -j -f - -y -j -u -o -i -v -y -j -r - -w -t -f -u -e -y -p -m -o - -p -k -v -l -m -b -c -n -h - -t -e -s -u -i -s -t -y -a - -z -b -f -n +a +q +y +q +v +p + +l +l +m +p +w +t +e +k +n + +x +m +u +b +m +r +j +c +h + +v +c +o +j +g +x +x +i +l + +v +d +r +s +q +h +z +a +g + +x +l +c +l +d +q +a +b +b + +u +j +c +c +w +e +o +h +a + +d +s +o +o +q +y +y +v +e + +k +h +i +l +g +z +j +u +e + +j +i +g +n +r +b +e +l +a + +g +l +v +v +u +e +q +q +b + +q +l +f +e +h +m +l +k +m + +b +r +k +l +e +s +w +i +q + +v +v +s +p +l +f +f +j +f + +y +j +u +o +i +v +y +j +r + +w +t +f +u +e +y +p +m +o + +p +k +v +l +m +b +c +n +h + +t +e +s +u +i +s +t +y +a + +z +b +f +…
favorite count: 0
tagged with: diff
has title: Python difflib produces weird result on certain inputs
tagged with: difflib
tagged with: python

http://stackoverflow.com/comment/83845255
type: QuestionComment
comment on: http://stackoverflow.com/q/48427224
score: 0
has text: I added what i'm attempting to do if that makes sense. I thought i clarified that in the text above. I'm sorry.
type: Comment

http://stackoverflow.com/comment/83738879
score: 0
type: Comment
type: QuestionComment
has text: can you just check your code indentation and make changes ?
comment on: http://stackoverflow.com/q/48375937

http://stackoverflow.com/comment/83892266
type: AnswerComment
has text: Actually, this only works if I set the tuple as a single character, e.g. 'a' but not its something like an actual postcode 'SW10 5LX' (made up postcode)
comment on: http://stackoverflow.com/a/48449203
type: Comment
score: 0

http://stackoverflow.com/q/48461770
has answer: http://stackoverflow.com/a/48465034
has body: I have two list, and I have to extract the items from the first list, from which the first element is present in the second. The code I have pasted bellow works perfectly but as I am operating with several million records, it is painfully slow. Does any one have any idea how it can be optimized? a = [[1,0],[2,0],[3,0],[4,0]] b = [2,4,7,8] same_nums = list(set([x[0] for x in a]).intersection(set(b))) result = [] for i in a: if i[0] in same_nums: result.append(i) print(result)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48461918
has answer: http://stackoverflow.com/a/48461809
score: 3
tagged with: list
tagged with: element
has answer: http://stackoverflow.com/a/48461918
upvote count: 3
has title: find common elements from sublist in list
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48462317
tagged with: python-3.x
answer count: 5
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48461809
has answer: http://stackoverflow.com/a/48462308

http://stackoverflow.com/a/48350640
score: 0
answers question: http://stackoverflow.com/q/48350505
type: Answer
has body: you mean you uninstalled python 3 and installed python2? Assuming this is what you did right click on anacona prompt and run as administrator try running this after running command prompt in admin mode python2 -m pip install ipykernel or python2 -m ipykernel install --user

http://stackoverflow.com/comment/83927166
comment on: http://stackoverflow.com/q/48466840
type: Comment
has text: Too many `=`. Do `printline = False`.
type: QuestionComment
score: 1

http://stackoverflow.com/a/48401634
upvote count: 1
has comment: http://stackoverflow.com/comment/83833058
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83791248
answers question: http://stackoverflow.com/q/48398726
has comment: http://stackoverflow.com/comment/83832868
has body: So I figured it out and both Thomas Kühn and and ImportanceOfBeingErnest helped me see the errors: First off, I changed the question to be replicable and with a mappable instead of ax[1,1]. Once doing that, I could see how it was actually directly transferrable to the question I had linked to, in my question. Here is my result: import numpy as np import matplotlib.pyplot as plt import matplotlib import matplotlib.colors as colors import matplotlib.cm as cmx import os import random fnames = np.random.rand(100, 10) fig, ax = plt.subplots(nrows=2,ncols=2, sharex=True, figsize=(4,4)) parameters = np.linspace(0,len(fnames[0,:]), len(fnames[0,:])) norm = matplotlib.colors.Normalize( vmin=np.min(parameters), vmax=np.max(parameters)) c_m = matplotlib.cm.cool s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm) s_m.set_array([]) for filename, parameter in zip(xrange(0,len(fnames[0,:])), parameters): try: no = random.randint(0,1) no2 =random.randint(0,1) ax[no,no2].plot(fnames[:, filename], c=s_m.to_rgba(parameter)) except IOError as error: print error for ax1 in ax.flatten(): ax1.set_xlabel('Y') ax1.set_ylabel('X') plt.title('Title') fig.subplots_adjust(bottom=0.2) cbar_ax = fig.add_axes([0.13, 0.08, 0.74, 0.03]) cbar = fig.colorbar(s_m, cax=cbar_ax, orientation='horizontal') cbar.set_label('Focus: ') plt.show() Which gave this plot. Thanks for the tips. Would you recommend changing the grid structure from plt.subplots, to AxesGrid, found in mpl_toolkits.axes_grid1?
type: Answer

http://stackoverflow.com/comment/83773243
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48392501
type: AnswerComment
has text: Thank you for your answer. do you know how to save the number to text or excel?

http://stackoverflow.com/a/48434925
downvote count: 0
answers question: http://stackoverflow.com/q/48434059
has body: Come a bit late to the party. The idea is that we can sort an array based on sorted indices of another array. y = np.arange(x.shape[0]) # y for preserving the indices mask = x &gt; thresh y = y[mask] x = x[mask] ans = y[np.argsort(x)] # change order of y based on sorted indices of x The method is to add an array y that is just for recording the indices of x. We then filter out both arrays based on the boolean indexes x &gt; thresh. Then, sort x with argsort. Finally, use the indices return by argsort to change the order of y!
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/83862029

http://stackoverflow.com/a/48362701
has body: The problem is on line if os.path.isdir(item): You don't add pervious path, so instead of checking pics for other_pics, the program checks . for other_pics Also, much nicer way to create path is os.path.join if os.path.isdir(os.path.join(dir, item)): Than to design: It may be better not to pass dictionary and write to it, but return it insted. Also to check type of file, use split, if you will want to add not-3-chars-long type My code: from pygame.image import load import os def gather_pics(dir='.'): dictionary = {} print(dir) for item in os.listdir(dir): if os.path.isdir(os.path.join(dir, item)): dictionary[item] = gather_pics(os.path.join(dir, item)) elif item.split(".")[-1] in ('png', 'jpg'): dictionary[item.split('.')[0]] = load(os.path.join(dir, item)) return dictionary if __name__ == '__main__': dict = gather_pics() print(dict) EDIT Just noticed you are using "dict" as variable, careful, it is type
has comment: http://stackoverflow.com/comment/83712357
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48362570
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48362570
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48443698
has body: I would like to create a column in a data frame that contains a list of filenames based on certain sequence number. I have the main data frame that looks like this: num letter 0 0 I 1 1 P 2 2 I 2 3 B 2 4 P 2 5 B 2 6 I and the filenames I have are: I-0001.jpg, I-0002.jpg, I-0003.jpg, P-0001.jpg, P-0002.jpg, B-0001.jpg, B-0002.jpg The final result I would like is: num letter file 0 0 I I-0001.jpg 1 1 P P-0001.jpg 2 2 I I-0002.jpg 2 3 B B-0001.jpg 2 4 P P-0002.jpg 2 5 B B-0002.jpg 2 6 I I-0003.jpg So basically, the column file should be such, that any time I, or P, or B in "letter" column is found it picks that file name having I, P or B in the file name based on the numbering in each file. Any help?
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: pattern-matching
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48443736
tagged with: python
has answer: http://stackoverflow.com/a/48443736
tagged with: string-matching
type: AnsweredQuestion
has title: Python pandas : column with ordered file names based on given sequence
tagged with: pandas

http://stackoverflow.com/comment/136162821
type: Comment
has text: @kmario23 Do not include solution to question please (post a separate answer instead).
comment on: http://stackoverflow.com/q/48471852
score: 0
type: QuestionComment

http://stackoverflow.com/q/48399828
possible better answer: http://stackoverflow.com/a/48399953
has answer: http://stackoverflow.com/a/48400090
has answer: http://stackoverflow.com/a/48399953
type: AnsweredQuestion
has title: PythonChallenge. Find rare characters in the mess below
upvote count: 1
has comment: http://stackoverflow.com/comment/83787874
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83787643
accepted answer: http://stackoverflow.com/a/48400090
answer count: 2
has comment: http://stackoverflow.com/comment/83788607
downvote count: 5
score: -4
has comment: http://stackoverflow.com/comment/83788808
has comment: http://stackoverflow.com/comment/83789020
tagged with: python
has comment: http://stackoverflow.com/comment/83787979
has comment: http://stackoverflow.com/comment/83787536
has body: I'm trying to learn programming via PythonChallenge (I have no background in programming at all) and now I'm stuck on this challenge, which requires me to find rare characters in the mess. The mess is in the source code of that page, which I've put in the file 'py.txt'. I've tried this code below and it prints just this: [('t', 2), ('e', 1), ('x', 1)], but the most interesting part is that isn't the right answer i think. from collections import Counter with open('C:/py.txt', 'r') as f: text = f.read() c = Counter("text") print(c.most_common()) When you look at the source code on the page and search for some characters (let's say 'a') image here it shows you that 'a' is in the list but it doesn't appear in the code output. Please, help, I need to find all of those 'rare' characters. Thanks! Oh, and also, I want to ask you how to learn Python from scratch. Maybe you have some good books to recommend or some online-resources (it would be better if it had some practical-homework stuff like doing small projects which don't require much math). Thanks a lot.

shapely
tags question: http://stackoverflow.com/q/48358037
tags question: http://stackoverflow.com/q/48413271
tags question: http://stackoverflow.com/q/48462044
tag name: shapely
type: Tag
tags question: http://stackoverflow.com/q/48487482

http://stackoverflow.com/comment/83692443
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48352791
score: 0
has text: @James The third, too.

http://stackoverflow.com/q/48397717
accepted answer: http://stackoverflow.com/a/48402787
type: Question
has answer: http://stackoverflow.com/a/48402787
has title: pyodbc and sql server, apply datetime.date to DATE column
tagged with: python
has body: pyodbc handles well datetime.datetime objects with DATETIME column. No special formatting needed. But it fails with datetime.date objects and DATE column:[HY004] [FreeTDS][SQL Server]Invalid data type (0) (SQLBindParameter) One way is to insert datetime.date object as string, with .isoformat() method. But: d1 = dt.date.today() d2 = dt.datetime.now() print(isinstance(d1, dt.date)) print(isinstance(d1, dt.datetime)) print(isinstance(d2, dt.date)) print(isinstance(d2, dt.datetime)) returns True False True True isn't there a better way than testing like that? if isinstance(d1, dt.date) and not isinstance(d1, dt.datetime): d1 = d1.isoformat()
has comment: http://stackoverflow.com/comment/83790185
tagged with: sql-server
tagged with: freetds
has comment: http://stackoverflow.com/comment/83796932
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-datetime
downvote count: 0
has comment: http://stackoverflow.com/comment/83792354
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48400514
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83792410
downvote count: 2
has comment: http://stackoverflow.com/comment/83790648
has comment: http://stackoverflow.com/comment/83789926
has comment: http://stackoverflow.com/comment/83789416
has comment: http://stackoverflow.com/comment/83791588
has comment: http://stackoverflow.com/comment/83788958
has comment: http://stackoverflow.com/comment/83791154
tagged with: regex
has comment: http://stackoverflow.com/comment/83789227
has answer: http://stackoverflow.com/a/48402990
accepted answer: http://stackoverflow.com/a/48402990
has comment: http://stackoverflow.com/comment/83790112
has comment: http://stackoverflow.com/comment/83793728
favorite count: 0
type: Question
upvote count: 0
has body: in my test log file, i want to find all the line between these two it can occur more than once also i did not want to exclude these two match from output --- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- *** [atf-run.log] Error code where the first line pattern will always start like "--- /b/act-builder/sandboxes/" and end like "Linux ---" and the second patern will be "Error code" My Solution Which is not working:- file = open('atf_log_28378.txt', "r") for result in re.findall('^--- /b/act-builder/(.*?)Error code', file.read(), re.S): print 'Failed test cases:' + result + '\n' Expected Output will be the one or more combination of these:- --- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- test1: [0.040247s] Failed: Test program received signal 6 test2: [0.039347s] Failed: Test program received signal 6 [0.079804s] scu_dcu_test (12/12): 1 test cases test1: [0.039158s] Failed: Test program received signal 6 [0.039262s] Failed test cases: aspath_test:test1, aspath_test:test2, aspath_test:test3, aspath_test:test4, cbf_test:test1, com_test:test1, com_test:test2, cmgr_test:test1, cmgr_test:test2, lsp_regex_test:test1, match_cache_test:test1, match_cache_test:test2, match_cache_test:test3, match_cache_test:test4, match_cache_test:test5, mt_test:test1, path_attr_err_test:test1, path_attr_err_test:test2, plist_test:test1, policy_namelist_test:test1, policy_te_test:test1, policy_te_test:test2, scu_dcu_test:test1 Summary for 12 test programs: 0 passed test cases. 23 failed test cases. 0 expected failed test cases. 0 skipped test cases. *** [atf-run.log] Error code 1 (ignored)
has comment: http://stackoverflow.com/comment/83794189
has title: Python regex to find all between two patterns
score: -2
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83788965
has comment: http://stackoverflow.com/comment/83790767

http://stackoverflow.com/comment/83953748
type: Comment
score: 0
has text: That specific error tells you that one of your `raw_box` variables is `None`, which means that the string you're trying to `find` is not present (at least, not in the kind of element you're searching). It may be that not finding any matches is an expected situation, in which case you should probably put an `if raw_box is None` check and handle that case differently. If it is unexpected, you need to investigate further to find out why you're not getting the results you expect (and we can't really help with the limited information you've provided).
type: QuestionComment
comment on: http://stackoverflow.com/q/48480345

http://stackoverflow.com/a/48487716
answers question: http://stackoverflow.com/q/48487401
has comment: http://stackoverflow.com/comment/83968708
has comment: http://stackoverflow.com/comment/83969163
type: Answer
has comment: http://stackoverflow.com/comment/83979488
has body: One potential issue here could be how you're trying to store NULL values with the database. In Django/Python, you pass in the NULL values using None. This needs to be converted to NULL when you execute your actual SQL statement, which Django should handle under-the-covers. That may be the reason for your initial syntax error above. If you get past the syntax error, try changing this line: total_fee = int(result[0].get('total_fee')) / 100 Instead of 100 try using 100.00 and see if that retains your decimal precision when you update the DB. If that doesn't work, then look at this line: total_fee = models.DecimalField('订单金额', default=0, decimal_places=0, max_digits=7) Try changing "default=0" to "default=999". If you run your code and see the value set to 999, then that means no value was passed in and that gives a place to start looking.
has comment: http://stackoverflow.com/comment/83969035
has comment: http://stackoverflow.com/comment/83969070
has comment: http://stackoverflow.com/comment/83969788
has comment: http://stackoverflow.com/comment/83969120
score: 0

http://stackoverflow.com/a/50153262
has body: If I am not too late, To identify a question or answer I have recently done this using fasttext. If you have big enough dataset, fasttext will give you best results with smallest model that can run on any machine. To determine whether the statement is providing answer or not you have to build an NER(kind of thing) which will look for some specific things like phone numbers, emails, names etc for every message that is coming in. output with my model for your questions.
answers question: http://stackoverflow.com/q/48343084
upvote count: 0
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/83854779
score: 0
has text: maybe you should take a look at a https://docs.python.org/2/tutorial/datastructures.html#dictionaries Dictionaries?
comment on: http://stackoverflow.com/q/48427802
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83898126
has text: So what does your `b` look like? Its initial values is an object array filled with `None`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48452399
type: QuestionComment

http://stackoverflow.com/a/48480922
has comment: http://stackoverflow.com/comment/84017081
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48480523
has comment: http://stackoverflow.com/comment/84015814
has body: pip install --user installs your packages into a user-specific directory that Apache doesn't know about. I would recommend you use a virtualenv but you can still use your user's site-packages if you can find its path: python -c 'import site; print(site.USER_BASE)' Then you configure mod_wsgi to use the path: WSGIDaemonProcess hello python-home=/path/to/your/env Although it is recommended that you use a virtual environment and not a per user site-packages directory, if you really must use the per user site-packages directory, use something like: WSGIDaemonProcess hello python-path=/home/user/.local/lib/python2.7/site-packages
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48481700
score: 3
has answer: http://stackoverflow.com/a/48481793
possible better answer: http://stackoverflow.com/a/48481793
tagged with: python
has title: Which is the better way to handle ImportError - Raise error or import chain?
accepted answer: http://stackoverflow.com/a/48481789
has body: Question When encounter ImportError in python, should I directly raise the error and ask the user to install it, or should I use import chain? Description I came across this question when I tried to use lxml package to parse xml file in python. In its official documentation, it says: If your code only uses the ElementTree API and does not rely on any functionality that is specific to lxml.etree, you can also use (any part of) the following import chain as a fall-back to the original ElementTree: try: from lxml import etree print("running with lxml.etree") except ImportError: try: import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: ... It seems to me that it's a bad idea to import a substitution since: if you can import another library as a substitution, which may not have all the methods as lxml, then all your script can only based on those available methods in all the packages. Then it make less sense to import the most powerful package (e.g. lxml here), we could directly import the least functional one, and save a lot codes. Or if we want to use additional methods later, we then should directly raise the ImportError. However, as answered in Error handling when importing modules , I find this approach seems to be used frequently in python programming: it's useful to define multi-level functionality based on what library has been imported in runtime. But it seems to me that, the multi-level functionality can only be achieved by constantly checking whether one library has been imported, which makes the whole codes complicated and ugly. As a result, I just wondered why people sometimes use such structure, instead of raise the error directly?
upvote count: 4
type: AnsweredQuestion
tagged with: python-import
answer count: 2
linked to: http://stackoverflow.com/q/3131217
tagged with: error-handling
has answer: http://stackoverflow.com/a/48481789
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/83687065
type: Comment
score: 0
type: AnswerComment
has text: @Hippolippo Changing the layout manager has nothing to do with that error. It is simply because `myAnswer` is not an `Entry` object. It is the `return`ed object of method `place` used on `myanswer` object, which is `None`. See https://stackoverflow.com/q/21592630/7032856.
comment on: http://stackoverflow.com/a/48349601

http://stackoverflow.com/comment/83690606
comment on: http://stackoverflow.com/q/48351902
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yes that's what I need. You should write it as an answer.
type: QuestionComment
score: 0

http://stackoverflow.com/a/48371126
score: 0
accepted answer of: http://stackoverflow.com/q/48370952
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48370952
has body: Your DieShaker class should just be a wrapper around a list of Die objects. class Die(object): 'a class representing a Die' def __init__(self, sides=6): 'initialize a die, default 6 sides' self.sides = sides # You should make sure that by the time someone has created a Die object, # all the attributes they might want to access have been defined self.roll() def roll(self): 'roll the dice' self.dieRoll = random.randint(1, self.sides) # Note I got rid of Die.get # Anyone who can call Die.get can see Die.dieRoll class DiceShaker(object): def __init__(self, dice=()): # Note we avoid mutable default arguments self.dice = list(dice) # Presumably it would be nice to add/remove dice def shake(self): for die in self.dice: die.roll() # return self.get_dice() # It doesn't really make sense for this to return anything def get_dice(self): return [die.dieRoll for die in self.dice]
type: Answer

http://stackoverflow.com/comment/83962050
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48474991
type: Comment
has text: @Joel thanks for your clarification. my links are not correct, i got that wrong. but the problem is still there, as i checked my built version and the PDF version im looking at right now, they both state version 2.0 and both are released in 2017. but still they don't match in some cases, like my example. thanks again.

http://stackoverflow.com/comment/83750118
type: QuestionComment
has text: What is the behaviour you're actually trying to test with this? *"I need to redefine `MagicMock`'s magic method in the child class and then use child class for testing"* - why?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48381711

http://stackoverflow.com/comment/83756235
has text: Please explain what you did. Answers consisting of 100% code are most likely not to be understood.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48384560
type: AnswerComment

http://stackoverflow.com/comment/83842551
has text: I have difficulties imagining this. Can you provide us with a `print(repr(labelStr))` so we can see the actual content? Escaping should normally not be necessary.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48425994

http://stackoverflow.com/a/48391278
type: Answer
has comment: http://stackoverflow.com/comment/83770838
score: 0
answers question: http://stackoverflow.com/q/48391021
has body: You can replace that last print statement with: print 'RESULTS:', # last comma prevents newline for key,val in value[1]: print key+':'+str(val), print '' # newline for python3: print('RESULTS:',end='') for key,val in value[1]: print(key+':'+str(val),end='') print('') # newline
has comment: http://stackoverflow.com/comment/83895656

http://stackoverflow.com/comment/83809008
type: Comment
score: 2
has text: Aside from the error message, another thing is that the OP is checking if `str` value of `x` is not on `d` rather than the length of `x`. This in-turn reassigns the value of `len(x)` to a new list, since `x` never exists as a key
type: AnswerComment
comment on: http://stackoverflow.com/a/48409688

http://stackoverflow.com/comment/83789227
type: Comment
comment on: http://stackoverflow.com/q/48400514
type: QuestionComment
has text: i did try that but still not working and yes there are more than one matches expected
score: 0

http://stackoverflow.com/a/48480837
score: 13
answers question: http://stackoverflow.com/q/48466151
accepted answer of: http://stackoverflow.com/q/48466151
type: Answer
has comment: http://stackoverflow.com/comment/84019778
upvote count: 13
has comment: http://stackoverflow.com/comment/84005149
has body: Renaming of variables is not a native Visual Studio Code feature for languages other than JavaScript and TypeScript. It is specific to each language, and functionality is provided by separate extensions, specific to each language. The Python extension you have installed, uses the Rope library to perform refactoring/renaming of python variables and the like. So yes, you'll need to install it by closing in the Install rope button. If you don't have the Install rope button, you can just go to cmd and type pip install rope. That should do the job as well. If it doesn't work even after installing it, please could you file an issue on the Python extension GitHub repository.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84020048
downvote count: 0

http://stackoverflow.com/comment/83710596
comment on: http://stackoverflow.com/a/48338439
has text: @tomoc4 my answer gives the same thing that the accepted answer does. Are you saying my answer isn't working? Specifically, what part is wrong? If you can explain in more detail, I'll see if I can give you an alternative.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83841669
type: QuestionComment
comment on: http://stackoverflow.com/q/48425672
score: 0
has text: @Daninel Roseman The list and tags are generated dynamically and I want to add ids to both the anchor tag and the division respectively so they will work as tabs as in this example https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_nav_tabs&stacked=h
type: Comment

http://stackoverflow.com/a/48383157
type: Answer
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Methods decorated by @property are instances of property: &gt;&gt;&gt; [name for name in dir(C) if isinstance(getattr(C, name), property)] ['x', 'y']
answers question: http://stackoverflow.com/q/48383082
accepted answer of: http://stackoverflow.com/q/48383082

http://stackoverflow.com/q/48439854
has comment: http://stackoverflow.com/comment/83873686
has comment: http://stackoverflow.com/comment/83871387
has comment: http://stackoverflow.com/comment/83871064
has comment: http://stackoverflow.com/comment/83871884
has body: I have a dataframe column1 dtype obj in format of: ==> this is one column of the dataframe Col1 02.11.2017 11.11.2017 02.12.2017 25.12.2017 this colum i want to convert to dates column by adding a new column to the df: ==> this is the code to convert the dataframe col1 to a new df column NewDate that generate the error below df['NewDate'] = pd.to_datetime(df['Col1'], format='%d.%m.%Y') I want my results to be: ==> this is what i want my result to look like. Col1 NewDate 02.11.2017 2017-11-02 11.11.2017 2017-11-11 02.12.2017 2017-12-02 25.12.2017 2017-12-25 But my ERROR is: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead But when i try this I still get the same error: ==> this is the code i tried because of the warning/error above but get the same warning/error doing so df.loc[:, 'NewDate'] = pd.to_datetime(df['Col1'].values, format='%d.%m.%Y') Can someone point me in the right direction? Any help is much appriciated! PS: Very new to python and pandas. Thanks alot!
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83870847
has comment: http://stackoverflow.com/comment/83871436
has answer: http://stackoverflow.com/a/48440368
has answer: http://stackoverflow.com/a/48440363
has comment: http://stackoverflow.com/comment/83870925
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83873934
linked to: http://stackoverflow.com/q/46728120
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83871280
has comment: http://stackoverflow.com/comment/83873736
tagged with: python-3.6
has title: Dataframe column str to Dataframe column date
linked to: http://stackoverflow.com/q/20625582
has comment: http://stackoverflow.com/comment/83873336
has comment: http://stackoverflow.com/comment/83871761
answer count: 2
has comment: http://stackoverflow.com/comment/83870902
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/83873871

http://stackoverflow.com/a/48461200
upvote count: 8
has body: What an excellent opportunity to explore some Boolean Logic. Adding binary like this can be done with two "half adders" and an "or" First of all the "Half Adder" which is a XOR to give you a summed output and an AND to give you a carry. [EDIT as per comments: python does have an XOR implemented as ^ but not as a "word" like and not or. I am leaving the answer as is, due to the fact it is explaining the Boolean logic behind a binary add] As python doesn't come with a XOR, we will have to code one. XOR itself is two AND's (with reversed inputs) and an OR, as demonstrated by this: This would result is a simple function, like this: def xor(bit_a, bit_b): A1 = bit_a and (not bit_b) A2 = (not bit_a) and bit_b return int(A1 or A2) Others may want to write this as follows: def xor(bit_a, bit_b): return int(bit_a != bit_b) which is very valid, but I am using the Boolean example here. Then we code the "Half Adder" which has 2 inputs (bit_a, bit_b) and gives two outputs the XOR for sum and the AND for carry: def half_adder(bit_a, bit_b): return (xor(bit_a, bit_b), bit_a and bit_b) so two "Half Adders" and an "OR" will make a "Full Adder" like this: As you can see, it will have 3 inputs (bit_a, bit_b, carry) and two outputs (sum and carry). This will look like this in python: def full_adder(bit_a, bit_b, carry=0): sum1, carry1 = half_adder(bit_a, bit_b) sum2, carry2 = half_adder(sum1, carry) return (sum2, carry1 or carry2) If you like to look at the Full Adder as one logic diagram, it would look like this: Then we need to call this full adder, starting at the Least Significant Bit (LSB), with 0 as carry, and work our way to the Most Significant Bit (MSB) where we carry the carry as input to the next step, as indicated here for 4 bits: This will result is something like this: def binary_string_adder(bits_a, bits_b): carry = 0 result = '' for i in range(len(bits_a)-1 , -1, -1): summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry) result += str(summ) result += str(carry…
type: Answer
answers question: http://stackoverflow.com/q/48459361
has comment: http://stackoverflow.com/comment/83916863
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/83943867
has comment: http://stackoverflow.com/comment/83916714

http://stackoverflow.com/q/48383759
has comment: http://stackoverflow.com/comment/83754389
has answer: http://stackoverflow.com/a/48384330
has comment: http://stackoverflow.com/comment/83754416
type: UnansweredQuestion
tagged with: python
score: 0
has title: parsing of javascript objects using python
answer count: 1
tagged with: parsing
type: Question
has body: friends! I'm starting to learn python. I have a problem with obtaining the required value from javascript text. Here is the code, which I managed to download from website: [&lt;script src="//maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=false&amp;amp;key=ABQIAAAAOjFUxXImJbfYejRUbw0-uBSoJppdodHXaiZe2O5Byw3T7kzYihSys_Exmi235-oDCy6xEhVelBMhBQ" type="text/javascript"&gt;&lt;/script&gt;, &lt;script type="text/javascript"&gt; var map_shop = null; var marker_shop = null; function google_maps_shop_initialize() { if (GBrowserIsCompatible()) { map_shop = new GMap2(document.getElementById("map_canvas_shop")); point_center = new GLatLng(51.6663267, 39.1898874); marker_shop = new GMarker(point_center); map_shop.addOverlay(marker_shop); map_shop.setCenter(point_center, 13); //Create new Tile Layer var gTileUrlTemplate = '//mt1.google.com/vt/lyrs=m@121,transit|vm:1&amp;hl=ru&amp;opts=r&amp;x={X}&amp;y={Y}&amp;z={Z}'; var tileLayerOverlay = new GTileLayerOverlay( new GTileLayer(null, null, null, { tileUrlTemplate: gTileUrlTemplate, isPng:true, opacity:1 }) ); map_shop.addOverlay(tileLayerOverlay); } } google_maps_shop_initialize(); &lt;/script&gt;] I want to print only one line from text, which contains coordinates point_center = new GLatLng(51.6663267, 39.1898874); I'm trying decide it using re module, but the problem is that number of line may vary and I get empty output with this code: if re.match("point_center = new GLatLng", line): print (line) Desirable output looks like this: 51.6663267, 39.1898874

http://stackoverflow.com/comment/83987539
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48456280
score: 3
has text: @ThunderFlash I may have been too harsh, but SO has a serious problem with poorly researched questions. SO is here to help people, but not on any terms they want. SO is designed to provide a specific kind of help: it is designed to aid you [when you hit a wall in your own research](https://meta.stackoverflow.com/a/261593/1394393). The OP here shows no signs of engaging in their own research. Even a Google search was more than they were willing to do. We do not want such questions answered because rewarding them tends to draw even more, eventually drowning out good questions (Slashdot effect).

http://stackoverflow.com/q/48398229
has title: Efficient alternative to np.piecewise in Tensorflow
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am currently in the process of porting my NumPy code to Tensorflow, for the sake of efficiently applying it to neural networks. While Tensorflow covers some of the basic NumPy functions, it obviously does not provide complete coverage. Right now I am a little bit stuck trying to translate the beautiful numpy.piecewise function to Tensorflow. The goal is to check whether each element in the input matrix (tensor?) will exceed the given boundaries if a certain step is added, and if so, to modify the accompanying element in the mask matrix of the same size. This is how the function looks in NumPy: def bounds_check(inputs, mask, step, bounds): conds = [np.absolute(inputs + step) &gt; bounds, np.absolute(inputs + step) &lt;= bounds] funcs = [lambda mask: -mask, lambda mask: mask] return np.piecewise(mask, conds, funcs) # return mask What would be a logical Tensorflow alternative? This has to be an op in the graph, as each epoch will involve making the next step through the search space and checking against the boundaries.
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48398435
has answer: http://stackoverflow.com/a/48398435
tagged with: arrays
tagged with: python
type: AnsweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/48399306
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has title: python distribution build with specific wxpython library version
answer count: 1
has answer: http://stackoverflow.com/a/48402782
tagged with: wxpython
tagged with: libraries
has body: I am trying to create a python software distribution depending on wxpython library. The thing is that I have two different versions in my PC: 2.8 and 3.0. The tool I use for exe creation is py2exe and the following content in setup.py : from distutils.core import setup import py2exe setup( name='Grabador tarjetas', version='0.0', description='Grabador Mifare', author='siteco.desarrollo', author_email='siteco.desarrollo@gmail.com', url='http://www.sitecosl.net', scripts=["GrabadorTarjetaMifareSiteco.py"], windows=["GrabadorTarjetaMifareSiteco.py"], data_files=[('', ['config.cfg'])], install_requires=["wxpython=wx-2.8-msw-unicode"] ) Each time I generate exe file, instead of including wxpython 2.8 library, it gets 3.0 library, regarding wxpython. Then, when I launch exe application, I get an error due to the difference between included library and needed library. In my python distribution folder, inside lib/site-packages, I have two folders for wxpython distributions: wx-2.8-msw-unicode and wx-3.0-msw. Besides, wx.pth is pointing to wx-2.8-msw-unicode. Running from pydev in eclipse works fine, but I get errors when executing generated exe from "dist" folder. Obviously something is wrong.... ¿Could you give me any tips? Thanks a lot.
tagged with: py2exe

http://stackoverflow.com/comment/83783584
has text: This may work. I will test soon and confirmed and mark as answered. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/48397873
score: 0
type: AnswerComment

http://stackoverflow.com/a/48451374
type: Answer
answers question: http://stackoverflow.com/q/48451231
has body: Another way is to define the function you want to apply, then applymap it to the columns you're interested in. You can then set those same columns to be overridden by the new values. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD')) def function(value): if value &lt;= 2: return 'a' if 2 &lt; value &lt;= 5: return 'b' if value &gt; 5: return 'c' df'A', 'B' = df'A', 'B'.applymap(function)
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/48431295
has comment: http://stackoverflow.com/comment/83869211
has body: The following seems fairly readable to me (and is also fairly efficient): from itertools import chain sb = [11, 12, 21, 22, 31, 32]*4 # stream buffer, e.g. 4 identical frames ci = 1 # 1-indexed channel index cs = 2 # channel size nc = 3 # number of channels in each frame fs = nc*cs # frame size result = list(chain.from_iterable(sb[i: i+cs] for i in xrange(ci-1, len(sb), fs))) print(result) # -&gt; [11, 12, 11, 12, 11, 12, 11, 12]
has comment: http://stackoverflow.com/comment/83855814
has comment: http://stackoverflow.com/comment/83854272
answers question: http://stackoverflow.com/q/48430081
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83869076
has comment: http://stackoverflow.com/comment/83856999
score: 2
has comment: http://stackoverflow.com/comment/83869543
type: Answer

http://stackoverflow.com/comment/83951618
has text: Please provide a [mcve].
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48477268

http://stackoverflow.com/comment/83743955
comment on: http://stackoverflow.com/q/48377317
has text: Also see this question: https://stackoverflow.com/questions/15111408/how-does-sklearn-svm-svcs-function-predict-proba-work-internally
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83891396
comment on: http://stackoverflow.com/a/48449227
has text: You might to reference the actual column name instead of the alias, ie. F('username') would be F('SamAccountName')
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48424956
has comment: http://stackoverflow.com/comment/84092726
tagged with: windows
tagged with: python
type: UnansweredQuestion
tagged with: pyusb
tagged with: drive
has body: I have the device ID of a removable drive. How can I use this to identify the drive letter of the device on windows with Python? Non python answers may help.
has comment: http://stackoverflow.com/comment/83952977
score: 0
answer count: 0
tagged with: deviceid
has comment: http://stackoverflow.com/comment/84006768
has title: Drive letter from device ID on Windows with Python
has comment: http://stackoverflow.com/comment/84011807
type: Question

http://stackoverflow.com/q/48404347
tagged with: qsub
has body: I have tensorflow 1.4.1 installed by pip, but the system-default gcc libs are not latest, that running import tensorflow will cause this error ImportError: /lib64/libc.so.6: version 'GLIBC_2.16' not found Since I don't have root permission, I built the gcc libs, and use alias python_cpu='/path/ld-linux-x86-64.so.2 --library-path /path/other_libs /path/python' to run tensorflow on CPU. Now I've generated thousands of bash scripts and want to run them with qsub within each script oo.sh writes #!/usr/bin/bash python_cpu python_script.py different_params I've tried the below ideas but all failed. Use qsub -V oo.sh to pass the alias into oo.sh. Use alias python_cpu=&quot;&quot; within the bash script. Without alias, use '/path/ld-linux-x86-64.so.2 --library-path /path/other_libs /path/python' python_script.py params. By the way the alias of TF works well with the bash shell command line. Any suggestions of what to do now?
tagged with: python
type: Question
answer count: 2
tagged with: bash
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48405501
downvote count: 0
has title: How to use ld-linux-x86-64.so.2 in bash script for qsub
tagged with: shell
upvote count: 1
has answer: http://stackoverflow.com/a/48405314
favorite count: 0
tagged with: linux

http://stackoverflow.com/comment/83817688
score: 0
has text: @jp_data_analysis as far as I can tell, that doesn't make a distinction between "error" and "exception"
type: Comment
comment on: http://stackoverflow.com/q/48413843
type: QuestionComment

http://stackoverflow.com/q/48354259
upvote count: 1
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48354336
tagged with: python
tagged with: subtraction
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48354336
has body: I have two Numpy arrays which look like this: a = [[ [1,2,3], [4,5,6] ], [ [7,8,9], [10,11,12] ]] b = [[ [1,1,1], [0,0,0] ], [ [3,3,3], [4,4,4] ]] I want to perform c = a - b with condition that c = 255 if b&gt;0 else a So c should be like this: c = [[ [255,255,255], [4,5,6] ], [ [255,255,255], [255,255,255] ]] How to do it efficiently without any loop?
type: AnsweredQuestion
has title: Subtract 2 Numpy arrays with condition

http://stackoverflow.com/a/48365911
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48365860
score: 0
has body: Print will not show quotes by default in a string. You will have to add them by concatenation. Print("\""+str0+"\"")
upvote count: 1

http://stackoverflow.com/a/48457485
answers question: http://stackoverflow.com/q/48456624
downvote count: 1
has comment: http://stackoverflow.com/comment/83908132
score: 0
type: Answer
has body: css_locator = 'div.quote-header-section span[data-reactid="35"]' price = driver.find_element_by_css_selector(css_locator).text print price
upvote count: 1

http://stackoverflow.com/comment/83696390
has text: @Rawing : ofcourse. Its assuming that the list only contains elements with values `yes` and `no`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48354865
score: 1

http://stackoverflow.com/comment/83968010
has text: And / or filter out empty strings.
type: Comment
comment on: http://stackoverflow.com/a/48487608
score: 5
type: AnswerComment

http://stackoverflow.com/comment/83715694
type: QuestionComment
score: 0
has text: yes, there are a lot of examples there, but I still can't how can the lambda use itself (like a recursion) - as happening in the first two rows.
comment on: http://stackoverflow.com/q/48364382
type: Comment

http://stackoverflow.com/a/48430683
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48430589
downvote count: 0
score: 3
has body: It seems like you could convert your dataframe to a 2-tuple Series and group that with something similar (groupby + apply + tolist) - df.apply(tuple, 1)[:stop]\ .groupby(mask.cumsum())\ .apply(lambda s: s[s.str[0] !='stop'].tolist()) a 0 [(a1, 1), (a2, 2)] 1 [(a2, 4), (a4, 5), (a5, 6)]
type: Answer
accepted answer of: http://stackoverflow.com/q/48430589

http://stackoverflow.com/a/48331767
accepted answer of: http://stackoverflow.com/q/48331736
has body: We can leverage broadcasting - (arr1[:,None] + arr2).reshape(-1,arr1.shape[1]) For large arrays, we can gain some further speedup with numexpr to transfer the broadcasting part - import numexpr as ne arr1_3D = arr1[:,None] out = ne.evaluate('arr1_3D + arr2').reshape(-1,arr1.shape[1]) Runtime test - In [545]: arr1 = np.random.rand(500,500) In [546]: arr2 = np.random.rand(500,500) In [547]: %timeit (arr1[:,None] + arr2).reshape(-1,arr1.shape[1]) 1 loop, best of 3: 215 ms per loop In [548]: %%timeit ...: arr1_3D = arr1[:,None] ...: out = ne.evaluate('arr1_3D + arr2').reshape(-1,arr1.shape[1]) 10 loops, best of 3: 174 ms per loop
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83650020
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48331736
has comment: http://stackoverflow.com/comment/83650029

http://stackoverflow.com/q/48486776
has comment: http://stackoverflow.com/comment/83966582
has answer: http://stackoverflow.com/a/48487724
type: AnsweredQuestion
tagged with: python-3.x
has body: I want to be able to this with other formulas as well. input = "3x+7-2x" # output = ["3x", "+7", "-2x"]
answer count: 5
upvote count: 1
has answer: http://stackoverflow.com/a/48487058
has comment: http://stackoverflow.com/comment/83966401
has comment: http://stackoverflow.com/comment/83966456
favorite count: 0
has title: how to divide a formula in its terms in python?
type: Question
linked to: http://stackoverflow.com/q/45126448
has comment: http://stackoverflow.com/comment/83966412
downvote count: 3
has comment: http://stackoverflow.com/comment/83966637
has comment: http://stackoverflow.com/comment/83967200
has comment: http://stackoverflow.com/comment/83966714
possible better answer: http://stackoverflow.com/a/48487126
score: -2
has answer: http://stackoverflow.com/a/48487215
has comment: http://stackoverflow.com/comment/83966416
has answer: http://stackoverflow.com/a/48487258
has answer: http://stackoverflow.com/a/48487126
tagged with: python
accepted answer: http://stackoverflow.com/a/48487258

http://stackoverflow.com/a/48489444
score: 0
answers question: http://stackoverflow.com/q/48484103
has body: I hesitate to even answer, as you have not responded to answers in your last question. We are not here to write your code for you. But, you are fortunate that SO users are generous with their time. Following up on my last answer: from google.appengine.ext import ndb class UserCurrencies(ndb.Model): user_email = ndb.StringProperty() currencies = ndb.JsonProperty(indexed=False)
type: Answer

http://stackoverflow.com/comment/83694314
has text: Cannot EAN13s have check digits as well ("X") as the last character?
comment on: http://stackoverflow.com/q/48353884
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48366740
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 3
tagged with: python
has title: Multiple Video Display using Tkinter in Python for GUI design
accepted answer: http://stackoverflow.com/a/48459316
has answer: http://stackoverflow.com/a/48367244
possible better answer: http://stackoverflow.com/a/48367244
type: Question
has answer: http://stackoverflow.com/a/54512546
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83720153
answer count: 3
upvote count: 1
score: -2
has body: My task is to display a webcam stream and its black&amp;white stream in two different frames on a single GUI using Tkinter on python. I have seen some examples on google, but they are of images not videos as in the link here. Example of image display in 2 panes on a single GUI I need exactly the same thing but for the real time video through my webcam.
has answer: http://stackoverflow.com/a/48459316

http://stackoverflow.com/q/48359295
has answer: http://stackoverflow.com/a/48359399
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
has title: python 3.6 Tkinter Label attribute error when using .grid
type: Question
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48359399
has body: I am beginning to get the hang of tkinter, but I have run into a problem. I want to create a label that displays an appropriate message according to the values of an Entry field, checked by a button. When this is used repeatedly, using just the tk.Label command will just overlay on top of the existing label, So I am trying to assign the label to a variable: messagebox=tk.Label(root2,text=" ",font(style,font).grid(row=1,column=0,columnspan = 50)) I want to later on use the .configure command to change this text, However I get this error: Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:[CENSORED BY POSTER (me), It was just the file directory]", line 84, in Checkpass messagebox = tk.Label(root2,text=" ",font=(style,font).grid(row=1,column=0,columnspan = 50)) AttributeError: 'tuple' object has no attribute 'grid' Can anyone please tell me what I am doing wrong and explain why it wont work. Thank you, Tava

http://stackoverflow.com/a/48387515
type: Answer
has comment: http://stackoverflow.com/comment/83783434
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83776371
type: AcceptedAnswer
downvote count: 0
has body: I am still not sure what exactly the problem is but changing: subprocess.run(['find', '/i', '"error"', '*.txt', '&gt;Errors.log'], shell=True, cwd=r'S:\ome\directory') to: subprocess.run('find /i "error" *.txt &gt;Errors.log', shell=True, cwd=directory) does the trick. As it appears, manually stitching the command works. If anybody has more info on the matter, I would be very grateful.
accepted answer of: http://stackoverflow.com/q/48387241
has comment: http://stackoverflow.com/comment/83776396
has comment: http://stackoverflow.com/comment/83762734
answers question: http://stackoverflow.com/q/48387241

http://stackoverflow.com/q/48406295
tagged with: pandas
type: Question
possible better answer: http://stackoverflow.com/a/48406469
has answer: http://stackoverflow.com/a/48406469
has answer: http://stackoverflow.com/a/48406377
tagged with: python
has body: I have the following dataframe: item_id bytes value_id value 1 0 2.0 year 2017 2 0 1.0 month 04 3 0 1.0 day 12 4 0 1.0 time 07 5 0 1.0 minute 13 6 1 2.0 year 2017 7 1 1.0 month 12 8 1 1.0 day 19 9 1 1.0 time 09 10 1 1.0 minute 32 11 2 2.0 year 2017 12 2 1.0 month 04 13 2 1.0 day 17 14 2 1.0 time 14 15 2 1.0 minute 24 I want to be able to calculate the time for each item_id. How do I use group by here or anything else to achieve the following? item_id time 0 2017/04/12 07:13 1 2017/12/19 09:32 2 2017/04/17 14:24
has title: Read values from multiple rows and combine them in another row in pandas dataframe
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48406377
answer count: 2

http://stackoverflow.com/comment/86589338
type: QuestionComment
comment on: http://stackoverflow.com/q/48430052
has text: If you are using Pycharm as your IDE then there is a duplicate answer here https://stackoverflow.com/questions/19885821/how-do-i-import-modules-in-pycharm This may also help answer your question if you aren't using Pycharm
score: 0
type: Comment

http://stackoverflow.com/q/48417561
has comment: http://stackoverflow.com/comment/83825136
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/83825644
downvote count: 3
has comment: http://stackoverflow.com/comment/83826686
has title: python extract songs from radio streaming
has comment: http://stackoverflow.com/comment/83825446
has comment: http://stackoverflow.com/comment/83836113
has answer: http://stackoverflow.com/a/48418721
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83836783
type: UnansweredQuestion
answer count: 1
has body: My task is to extract full songs from radio streaming using python 2.7. I have managed to record radio streaming, but I can't find a good way to detect if the audio that I record is music, ads, or just talking. I tried to detect by threshold, but it wasn't good because there are not enough silence between the talking or the ads to the songs. If someone knows a good solution for me I would love to hear about it. import pydub streamAudio = pydub.AudioSegment.from_mp3("justRadioStream.mp3") listMp3 = pydub.silence.detect_silence(streamAudio, min_silence_len=400, silence_thresh=-38) print listMp3 I tried to play with the min_silence_len and silence_thresh, but there is not enough time of silence between songs and ads or talking, or louder voice to detect properly thanks a lot!
has comment: http://stackoverflow.com/comment/83826169
tagged with: python

http://stackoverflow.com/q/48445050
has comment: http://stackoverflow.com/comment/83882252
has title: How to order a list of lists and merge consecutive elements in Python
answer count: 1
has body: I have a list of lists like this: ['lion', '23', '35'] ['lion', '24', '68'] ['elephant', '23', '34'] ['monkey', '4', '20'] ['monkey', '5', '25'] ['monkey','28', '90'] ['lion', '33', '2'] and I want to sort them out and merge the ones with the same type of animal that have consecutive values (23-34) and merge as well its adjacent values (i.e. 35-68 for lion) , like this: ['lion', '23-24', '35-68'] ['lion', '33', '2'] ['elephant', '23', '34'] ['monkey', '4-5', '20-25'] ['monkey', '28', '90'] Notice that the consecutive values for lion and monkey were merged and separated with a dash as well as the sequence next to it. The ones that were not consecutive remained alone: lion 33 and monkey 28. I have tried some code with itertools and groupby as well as labda sorting to no avail. For instance strings.sort(key=lambda element: (element[0], element[1])) Sorts them by animal name and consecutive numbers but I would not know how to merge them. What I want is order them alphabetically by the name of the animal and merge the ones that have a consecutive second value and create a new list with that output. Any ideas?
has comment: http://stackoverflow.com/comment/83906122
type: Question
has comment: http://stackoverflow.com/comment/83882458
linked to: http://stackoverflow.com/q/2154249
type: AnsweredQuestion
score: 0
tagged with: python-itertools
accepted answer: http://stackoverflow.com/a/48456188
has comment: http://stackoverflow.com/comment/83881820
has answer: http://stackoverflow.com/a/48456188
tagged with: python
has comment: http://stackoverflow.com/comment/83882034
has comment: http://stackoverflow.com/comment/83881762
has comment: http://stackoverflow.com/comment/83905572

http://stackoverflow.com/a/48362765
type: AcceptedAnswer
downvote count: 0
score: 2
has body: May be problem with client-side support Send a base64 image in HTML email
accepted answer of: http://stackoverflow.com/q/48362667
type: Answer
answers question: http://stackoverflow.com/q/48362667
has comment: http://stackoverflow.com/comment/83712608
upvote count: 2
has comment: http://stackoverflow.com/comment/83712586

http://stackoverflow.com/a/48378541
type: AcceptedAnswer
has body: import boto3 alone is enough to connect with a bucket. botocore.session was used during for the previous boto 1.8 and is not accepted by boto3. you can refer the following boto3 documents http://boto3.readthedocs.io/en/latest/reference/services/s3.html#client . Here is boto 1.8 documents that mentions the use of botocore.session http://botocore.readthedocs.io/en/latest/tutorial/
answers question: http://stackoverflow.com/q/48377297
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/83799425
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48377297

http://stackoverflow.com/comment/83981661
comment on: http://stackoverflow.com/a/48490163
score: 0
has text: Thank you. I guess I was trying to take too much control of what I was doing. I appreciate it! :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83919681
type: Comment
type: QuestionComment
has text: You probably want to use a custom logger for that. Maybe decorate the view and log what you need manually. But what exactly you want to see, what do you think is really missing here?
comment on: http://stackoverflow.com/q/48463349
score: 0

http://stackoverflow.com/q/48432016
answer count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/12309269
favorite count: 0
type: Question
tagged with: ajax
has comment: http://stackoverflow.com/comment/83855500
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83855345
tagged with: javascript
tagged with: python
tagged with: jquery
tagged with: flask
has body: Trying to understand how to send post requests to my backend (flask). In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below. $(document).ready(function() { $("#loadData").click(getChecked); }); function getChecked() { event.preventDefault(); var checkboxes = $(".form-check input[type=checkbox]:checked"); //toArray: convert checkboxes object to javascript array var labels = checkboxes.toArray().map(checkbox =&gt; checkbox.value); $.ajax({ url: 'api/regions', type: "POST", data: JSON.stringify(labels), processData: false, contentType: "application/json; charset=UTF-8", success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); } In my app.py I have a route for my endpoint api: @app.route('/api/regions', methods=['POST']) def regions(): regions = request.json with open("C:\\test.txt", 'w') as f: f.write(regions) if __name__ == "__main__": app.run(debug=True) I understand there is no return statement, I'm just trying to write the data I get from regions = request.json to a file. "C:\test.txt" The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.
upvote count: 2
has title: AJAX Post Request to Python Flask
has answer: http://stackoverflow.com/a/48432158
score: 1

http://stackoverflow.com/comment/83955097
comment on: http://stackoverflow.com/q/48481041
score: 0
type: Comment
type: QuestionComment
has text: Doesn't this depend on the ability of your IDE to interpret type annotations, which is unrelated to the way you wrtie the code (except for the fact that you will have to annotate code then...) ?

http://stackoverflow.com/comment/83717502
comment on: http://stackoverflow.com/a/48365433
type: Comment
has text: You can also create a function that handles the boolean condition
score: 0
type: AnswerComment

http://stackoverflow.com/comment/131435848
comment on: http://stackoverflow.com/a/48438829
score: 2
type: Comment
has text: Did anyone get any idea how to make voice less robotic or more like human?
type: AnswerComment

http://stackoverflow.com/q/48412684
has body: Quick example of code: import requests import re for pages in range(1,10): post = 0 myfile = open('posts.txt') data=myfile.read().splitlines() poster=data[post] postersend = {'param1': poster} try: resp = requests.get('http://www.postexample.com/pages={}'.format(pages), params=postersend).text except: //change post from 0 to 1 using + 1 // tried post = post + 1 ( didn't work ) continue so what I'm trying to do is if except: is triggered then change post = 0 to post = 1 by adding + 1 each time we receive a exception
score: 0
has comment: http://stackoverflow.com/comment/83815301
has answer: http://stackoverflow.com/a/48412712
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83815286
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83815243
has comment: http://stackoverflow.com/comment/83815271
has title: Python add to existing variable in except
tagged with: python
has comment: http://stackoverflow.com/comment/83815274
has comment: http://stackoverflow.com/comment/83815265
type: Question

http://stackoverflow.com/q/48349364
score: 1
has body: I have a MongoClient instance that is connected to a database. I would like to get the connection information (such as the host IP). How would I do this? (I cannot for the life of me find it in the docs)
downvote count: 0
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/78227908
type: Question
accepted answer: http://stackoverflow.com/a/48349448
has answer: http://stackoverflow.com/a/48349448
tagged with: python
has comment: http://stackoverflow.com/comment/83685127
type: AnsweredQuestion
tagged with: mongodb
has answer: http://stackoverflow.com/a/78227908
answer count: 2
has title: Get the Mongo hosts from a client

http://stackoverflow.com/comment/83917527
type: Comment
comment on: http://stackoverflow.com/q/48461003
score: 0
type: QuestionComment
has text: Hi everyone, thanks for your quick reply. I get my problem solved!! The extension follows the Python version(32bit/64bit) cause I couldn't install 32-bit extension on 64-bit Python and only can install 32-bit extension on 32-bit Python. Actually I successfully installed both but the keylogger python file doesn't record character well so I thought is extension version wrong. After that I just found out the keylogger python code doesn't have any problem but the first line lacking of "# -*- coding: utf-8 -*-" and cause the logging of key became some unreadable character.

http://stackoverflow.com/q/48447812
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has title: python pandas merge_asof groupby
favorite count: 0
accepted answer: http://stackoverflow.com/a/48449252
type: AnsweredQuestion
tagged with: dataframe
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/48453289
possible better answer: http://stackoverflow.com/a/48453289
has body: I have a merged dataframe as follows: &gt;&gt;&gt; merged_df.dtypes Jurisdiction object AdjustedVolume float64 EffectiveStartDate datetime64[ns] VintageYear int64 ProductType object Rate float32 Obligation float32 Demand float64 Cost float64 dtype: object The below groupby statement returns the correct AdjustedVolume values by Jurisdiction/Year: &gt;&gt;&gt; merged_df.groupby(['Jurisdiction', 'VintageYear'])['AdjustedVolume'].sum() When including ProductType: &gt;&gt;&gt; merged_df.groupby(['Jurisdiction', 'VintageYear','ProductType'])['AdjustedVolume'].sum() AdjustedVolume by Year is correct if the Jurisdiction contains only one ProductType, but for any Jurisdiction with two or more ProductTypes, the AdjustedVolumes are getting split up such that they sum to the correct value. I was expecting each row to have the total AdjustedVolume, and am unclear on why it's being split up. example: &gt;&gt;&gt; merged_df.groupby(['Jurisdiction', 'VintageYear'])['AdjustedVolume'].sum() Jurisdiction VintageYear AdjustedVolume CA 2017 3.529964e+05 &gt;&gt;&gt; merged_df.groupby(['Jurisdiction', 'VintageYear','ProductType'])['AdjustedVolume'].sum() Jurisdiction VintageYear ProductType AdjustedVolume CA 2017 Bucket1 7.584832e+04 CA 2017 Bucket2 1.308454e+05 CA 2017 Bucket3 1.463026e+05 I suspect the merge_asof is being done incorrectly: &gt;&gt;&gt; df1.dtypes Jurisdiction object ProductType object VintageYear int64 EffectiveStartDate datetime64[ns] Rate float32 Obligation float32 dtype: object &gt;&gt;&gt; df2.dtypes Jurisdiction object AdjustedVolume float64 EffectiveStartDate datetime64[ns] VintageYear int64 dtype: object Because df2 has no ProductType field, the below merge is breaking up the total volume into whatever ProductTypes are under each Jurisdiction. Can I modify the below merge so each ProductType has the total AdjustedVolume? merged_df = pd.merge_asof(df2, df1, on='EffectiveStartDate', by=['Jurisdiction','VintageYear'])
type: Question
has answer: http://stackoverflow.com/a/48449252
answer count: 2

http://stackoverflow.com/comment/84004432
type: QuestionComment
comment on: http://stackoverflow.com/q/48476162
has text: Delete any instance of the Adafruit_DHT folder on your machine and re-clone it from Git. After, make sure you cd into the new directory and use SUDO to install it. `sudo python setup.py install` Note that the python3 declaration is not needed. Also, there's no need to copy/paste the directory. Just cd to any directory you want and run `git clone https://github.com/adafruit/Adafruit_Python_DHT.git`
score: 0
type: Comment

http://stackoverflow.com/q/48465408
has comment: http://stackoverflow.com/comment/83924594
tagged with: structure
tagged with: parsing
tagged with: hex
has title: Formatting a string for Python c-type structure and substructure
has comment: http://stackoverflow.com/comment/83929955
score: 0
has body: I get a traceback whenever the string function in main_structure starts parsing the info in sub_structure. I got a TypeError saying, "not all my arguments were converted during string formatting." In another attempt, I got a TypeError saying, "%X format: a number is required, not sub_structure." I was able to successfully parse all other fields before including sub_structure in the main_structure fields. new_sys = 0xFE class sub_structure(Structure): _pack_ = 1 _fields_ = [ ("Block", c_uint16), ("Count", c_uint32) ] def __str__(self): retStr = "" retStr += "Block: %8.8Xh\n" % self.Block retStr += "Count: %8.8Xh\n" % self.Count return retStr class main_structure(Structure): _pack_ = 1 _fields_ = [ ("System", c_uint8 * total), ("Erase", c_uint32), ("Global", c_uint32), ("Offset", c_uint32), ("Start", c_uint16), ("SysCnt", sub_structure * 6) ] def __str__(self): retstr = "Parsing Buffer Data:\n" for idx, sys in enumerate(self.System): sysStr = "0x%d" % sys if sys == new_sys: sysStr = "0 -- (New System)" retstr += "System[" + str(idx) + "]: " + sysStr + "\n" retstr += "Erase: 0x%08X\n" % self.Erase retstr += "Global: 0x%08X\n" % self.Global retstr += "Offset: 0x%08X\n" % self.Offset for idx, itm in enumerate(self.SysCnt): retstr += "SysCnt%d: 0x%08X\n" % (idx, itm) return retstr
answer count: 0
has comment: http://stackoverflow.com/comment/83925581
type: Question
tagged with: ctypes
has comment: http://stackoverflow.com/comment/83926785
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48444552
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83880642
tagged with: raspberry-pi3
tagged with: python
has title: Having problems configuring GPIO pins on rpi with python
score: 0
type: Question
has comment: http://stackoverflow.com/comment/83883541
has body: I am trying to control the fan speed of a fan connected to the rpi via 5V power, 3.3V control and GND. This is my simple code: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(1,GPIO.OUT) GPIO.PWM(1, 50) I am getting a "The channel sent is invalid on a Raspberry Pi". Everything is up to date and i can't seem to find a solution online.
answer count: 0

http://stackoverflow.com/comment/83923108
comment on: http://stackoverflow.com/a/48451101
score: 0
type: AnswerComment
type: Comment
has text: @Hana this cause you have subgroup(depends on how many true you have within one UPC) with each group UPC, The New para here , is to setting the subgroup Id :-)

http://stackoverflow.com/q/48461297
score: 0
has answer: http://stackoverflow.com/a/48461509
accepted answer: http://stackoverflow.com/a/48461509
answer count: 1
has title: Expected 2D array error not getting resolved
tagged with: svm
type: Question
has comment: http://stackoverflow.com/comment/83915439
has comment: http://stackoverflow.com/comment/83915616
has body: i am trying to use my machine learning model on dataset where i have only two columns while standard scaling them,i got the error expected 2D array but got 1 . Below is the code: import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].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 = 0.2, random_state = 0)""" # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() X = sc_X.fit_transform(X) y = sc_y.fit_transform(y) # Fitting SVR to the dataset from sklearn.svm import SVR regressor = SVR(kernel = 'rbf') regressor.fit(X, y) # Predicting a new result y_pred = regressor.predict(6.5) y_pred = sc_y.inverse_transform(y_pred) # Visualising the SVR results plt.scatter(X, y, color = 'red') plt.plot(X, regressor.predict(X), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() when i try to put y = sc_y.fit_transform([y]) like this i received no error but when i execute next 3 lines i receive another error. which is bad input shape (1, 10) can anyone help me on this?
tagged with: arrays
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83706118
type: QuestionComment
comment on: http://stackoverflow.com/q/48359619
score: 1
has text: That's a powershell command. Are you sure you opened the powershell?
type: Comment

http://stackoverflow.com/a/48348399
has comment: http://stackoverflow.com/comment/83691240
has comment: http://stackoverflow.com/comment/83683161
type: Answer
has body: I'm not an expert with PyInstaller and I get the same warning on a Qt dll that I explicitly include. However, my exe runs on other computers. Does your code add sys._MEIPASS to the python-vlc search path for libvlc.dll? Something to the affect of: # handle pyInstaller temp directory if hasattr(sys, '_MEIPASS'): # add to your python-vlc search path Does the machine you're testing on have VLC installed? Can you give the exact error you're seeing when trying to run on the other machine?
has comment: http://stackoverflow.com/comment/83691235
answers question: http://stackoverflow.com/q/48336981
score: 0
has comment: http://stackoverflow.com/comment/83690111

http://stackoverflow.com/a/64486726
answers question: http://stackoverflow.com/q/48446351
has comment: http://stackoverflow.com/comment/117553660
type: Answer
has comment: http://stackoverflow.com/comment/116882502
has body: I realize that this is an old question, but I just had the same problem and I think I found a neat solution; however it currently works only for the Qt backend (similar solutions might exist for other backends too). The idea is that matplotlib changes the cursor shape while zooming or panning, so you can check for that. This is the adapted code: import numpy as np import matplotlib matplotlib.use('qt5agg') import matplotlib.pyplot as plt def onclick(event, ax): # Only clicks inside this axis are valid. try: # use try/except in case we are not using Qt backend zooming_panning = ( fig.canvas.cursor().shape() != 0 ) # 0 is the arrow, which means we are not zooming or panning. except: zooming_panning = False if zooming_panning: print("Zooming or panning") return if event.inaxes == ax: if event.button == 1: print(event.xdata, event.ydata) # Draw the click just made ax.scatter(event.xdata, event.ydata) ax.figure.canvas.draw() elif event.button == 2: # Do nothing print("scroll click") elif event.button == 3: # Do nothing print("right click") else: pass fig, (ax1, ax2) = plt.subplots(1, 2) # Plot some random scatter data ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10)) fig.canvas.mpl_connect( 'button_press_event', lambda event: onclick(event, ax2)) plt.show()
score: 7
downvote count: 0
upvote count: 7

exception
tags question: http://stackoverflow.com/q/48382879
tags question: http://stackoverflow.com/q/48423848
tags question: http://stackoverflow.com/q/48430792
tags question: http://stackoverflow.com/q/48429925
tags question: http://stackoverflow.com/q/48353538
tags question: http://stackoverflow.com/q/48334703
tag name: exception
tags question: http://stackoverflow.com/q/48459235
type: Tag
tags question: http://stackoverflow.com/q/48474056
tags question: http://stackoverflow.com/q/48451662

http://stackoverflow.com/comment/83964233
type: QuestionComment
has text: @skrx: of course that's only half of the answer (though it's a fairly important half).
comment on: http://stackoverflow.com/q/48475586
score: 0
type: Comment

http://stackoverflow.com/comment/83681737
type: AnswerComment
has text: @F.F. sample is random pick , if you want just first half you can using index to slice
comment on: http://stackoverflow.com/a/48347368
type: Comment
score: 0

http://stackoverflow.com/a/48374509
score: 4
has comment: http://stackoverflow.com/comment/83741224
answers question: http://stackoverflow.com/q/48371199
has body: Because your source image is cleaner than the link your post, so you can do approx on the max-area-contour, then get half number of points, the result is 84. Sample code: #!/usr/bin/python3 # 2018.01.22 11:53:24 CST import cv2 import myutils ## Read img = cv2.imread("img13_2.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ## threshold and find contours ret, threshed = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV) cnts= cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2] ## Find the max-area-contour cnt = max(contours, key=cv2.contourArea) ## Approx the contour arclen = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.002*arclen, True) ## Draw and output the result for pt in approx: cv2.circle(img, (pt[0][0],pt[0][1]), 3, (0,255,0), -1, cv2.LINE_AA) msg = "Total: {}".format(len(approx)//2) cv2.putText(img, msg, (20,40),cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2, cv2.LINE_AA) ## Display cv2.imshow("res", img);cv2.waitKey() Result:
type: Answer
accepted answer of: http://stackoverflow.com/q/48371199
has comment: http://stackoverflow.com/comment/83741578
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83811349
comment on: http://stackoverflow.com/q/48410264
has text: @CristiFati - Possibly, though aside from the pyded.py being called with some extra flags (--multiproc --qt-support = auto --client 127.0.0.1 --port 5727) I'm not seeing much difference. The problem seems to stem from the breakpoints; it runs successfully in "Run" mode and "Debug" mode as long as when in debug mode there are zero breakpoints (which kinda defeats the purpose of debug).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48357440
has body: I begin to use pyQT5 with python 3.5 on Ubuntu 16.04. I installed the package pyqt5-examples that provides a lot of examples that can be run individually. Does somebody know where I could find a global demo launcher from which I could access to all the demo items ? Such a thing exists for wxWidgets and it is really helpful. A README file says: The source code for the launcher can be found in the examples/demos/qtdemo directory in the PyQt package. I don't find this directory on my installation.
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83718866
has comment: http://stackoverflow.com/comment/83706980
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: pyqt5 demo launcher: does it exists ? Where to find it?
downvote count: 0
tagged with: pyqt5
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48456899
answers question: http://stackoverflow.com/q/48376664
has body: http://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html I solve it when i set the close-on-exec option to my uwsgi setting
type: Answer
score: 0

http://stackoverflow.com/comment/83798327
type: Comment
type: QuestionComment
has text: I've tried changing images, but still showing the same error. Can you tell solution for it.
comment on: http://stackoverflow.com/q/48404783
score: 0

http://stackoverflow.com/q/48459357
has title: JSON Parser Python Script Issues
tagged with: debugging
has comment: http://stackoverflow.com/comment/83911632
has comment: http://stackoverflow.com/comment/83911598
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83911560
has comment: http://stackoverflow.com/comment/83911794
tagged with: python
has body: I'm a first year student in CS, attempting to debug a simple Python script. The script is attempting to parse a directory of JSON files, aka an AWS bucket. I can't figure out where these errors come from, however: import json import os from pprint import pprint jsonDirectory = "/path/to/dir/" targetRegion = "-insert-region-here" print("Searching for records with AWS Region: " + targetRegion) print("") for filename in os.listdir(jsonDirectory): print("Reading: " + filename) data = json.dumps(open(jsonDirectory + filename)) for i in range(len(data["Records"])): if data["Records"][i]["awsRegion"] == targetRegion: print("---------------------------") print("Record #" + str(i)) print("Username: " + data["Records"][i]["userIdentity"] ["userName"]) print("Event name: " + data["Records"][i]["eventName"]) print("Event time: " + data["Records"][i]["eventTime"]) print("---------------------------") print("") print("Completed reading files.") The errors: Traceback (most recent call last): File "/path/to/file.py", line 13, in data = json.dumps(open(jsonDirectory + filename)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py", line 231, in dumps return _default_encoder.encode(obj) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default o.class.name) TypeError: Object of type 'TextIOWrapper' is not JSON serializable
has answer: http://stackoverflow.com/a/48459583
downvote count: 0
has comment: http://stackoverflow.com/comment/83911741
upvote count: 1
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: error-handling
has comment: http://stackoverflow.com/comment/83911611
favorite count: 0
has comment: http://stackoverflow.com/comment/83911756
type: Question

http://stackoverflow.com/q/48336986
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83659486
tagged with: django
has comment: http://stackoverflow.com/comment/83659063
has answer: http://stackoverflow.com/a/48337600
type: Question
score: 0
has title: Error 1054 from database when I am trying to access model in admin panel
tagged with: python
has comment: http://stackoverflow.com/comment/83659014
has answer: http://stackoverflow.com/a/48339033
has body: So I was trying to modify my models a bit and now I can't get rid of this error. I tried to delete all my data, but it doesn't help. I think it has to do with my database, but before, everything used to work fine. I get this error: (1054, "Unknown column 'courses_course.course_category_id' in 'field list'") And here are my models: class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies"))) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Meta: verbose_name = "Study Programme" verbose_name_plural = 'Study Programmes' def __str__(self): return self.name class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE) course_category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE, default='', related_name='categories') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Course.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() class CourseCategory(models.Model): course_category = models.CharField(max_length=50, unique=True) def __str__(self): return self.course_category class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', relat…
answer count: 2
has comment: http://stackoverflow.com/comment/83659091

http://stackoverflow.com/q/48339675
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/84311381
has comment: http://stackoverflow.com/comment/83820721
has comment: http://stackoverflow.com/comment/83665607
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83773873
has title: how to use keycondition in Query method from DynamoDb Table using boto3
tagged with: python
has comment: http://stackoverflow.com/comment/83830235
type: Question
answer count: 0
has body: ' I am trying to query the Dynamodb table to display the items from the table. I am using a table.query with some conditions such as projectionexpression etc. Since we knew that scan Method scans the whole table which is time-consuming, so im trying to use a query where i am getting an issue with putting key conditions as it is mandatory criteria. So can you help me in this code. using this URL :http://localhost:0000/rsi/hotels My Repository.py -> def list_items(self): ProjectionExpression = "Id,#Name,Description" ean = {"#Name": "Name"} # Using this URL: http://localhost:0000/rsi/hotels # how can I use keycondition for this in below table esk = Key('Id').gt(0) # stuck here dono what exact condition to give limit = settings.AWS_SCAN_LIMIT items = [] tableResponse = table.query( ProjectionExpression=ProjectionExpression, ExpressionAttributeNames=ean, KeyConditionExpression = esk, Limit=limit ) items.extend(tableResponse['Items']) while 'LastEvaluatedKey' in tableResponse: tableResponse = table.query( ProjectionExpression=ProjectionExpression, ExpressionAttributeNames=ean, ExclusiveStartKey=tableResponse['LastEvaluatedKey'], KeyConditionExpression=esk, Limit = limit ) items.extend(tableResponse['Items']) return items ERROR: ERROR - An error occurred (ValidationException) when calling the Query operation: Query key condition not supported Actually, my table consists of id name description 1 hai des 09 bye des2 123 there des3 etc...... So, i am not able to get of any other option on how to use parallel scan and query effectively, So,i have approached you, people. Please help me on this!
type: UnansweredQuestion
score: 0
tagged with: amazon-dynamodb
tagged with: boto3
has comment: http://stackoverflow.com/comment/83830098

http://stackoverflow.com/q/48333752
type: Question
tagged with: anaconda
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83654125
has title: Python 3 can't run after installing anaconda2
linked to: http://stackoverflow.com/q/5694706
tagged with: python
has body: I am using MacOS. First, I installed anaconda3 to install python3.6. And then, i need python2.7 to be installed. Then i installed anaconda2. After the installation, I can't run python 3.6. I installed Anaconda2 and 3 in different folder. The error appears Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding Current thread 0x00007fffb3c0c3c0 (most recent call first): Abort trap: 6 How to fix it? Thank you so much
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83671544
has comment: http://stackoverflow.com/comment/83979851

http://stackoverflow.com/a/48396583
answers question: http://stackoverflow.com/q/48393976
has body: I have figured out the answer. The problem was with the pd.to_datetime('today') part. This had to be changed to reflect the data types of the other datetime parts loan_plans['final_date'] = np.where( (loan_plans.days_since_end.astype('timedelta64[D]')&gt;=0) &amp; (loan_plans.principal_outstanding.astype('float')&lt;1000), pd.to_datetime(loan_plans['max_repaid_date']), np.where( (loan_plans.days_since_end.astype('timedelta64[D]')&gt;0) &amp; (loan_plans.principal_outstanding.astype('float')&gt;1000), np.datetime64('today'), np.where( loan_plans.days_since_end.astype('timedelta64[D]')&lt;0, pd.to_datetime(loan_plans['final_repayment_date']), pd.to_datetime(loan_plans['final_repayment_date']))))
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48393976
upvote count: 1
type: Answer

http://stackoverflow.com/q/48431774
has comment: http://stackoverflow.com/comment/83857229
score: 1
has body: I was curious at how pandas dataframe handles calculating the upper and lower whiskers, with outliers. Normally it's 1.5IQR-Q1, 1.5IQR+Q3. However, the problem I can't understand, or maybe I'm wrong on how the whiskers are calculated. It shows the same problems in the boxplot section of https://pandas.pydata.org/pandas-docs/stable/visualization.html Here's a sample of code I've randomly selected: ray1=[0.217766,0.691315,0.289239,0.239135,0.161341,0.364297,0.373284,0.323216] df = pd.DataFrame(ray1, dtype = float) If I used the df.describe() it gives me the stats of that array. count 8.000000 mean 0.332449 std 0.162374 min 0.161341 25% 0.233793 50% 0.306227 75% 0.366544 max 0.691315 But according to the upper whisker, lower whisker from the normal 1.5IQR-Q1, 1.5IQR+Q3, it should be around .565 and .035. If I plot this with df.boxplot() it shows the upper whisker as 0.373 and the lower whisker as .161. I've tried other variations (2.698σ) and the medcouple and those don't equal either. So how is it getting those values, when outliers are present?
answer count: 1
downvote count: 0
has title: Python Dataframe boxplot, wisker caluclation with outliers
upvote count: 1
has comment: http://stackoverflow.com/comment/83856889
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51669575
type: UnansweredQuestion
tagged with: boxplot
has comment: http://stackoverflow.com/comment/83856594
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83856927

http://stackoverflow.com/a/48474357
has body: You were right, the line: except (optparse.BadOptionError, optparse.OptionValueError), err: is not Python3 compatible (according to [Python]: The try statement). According to [GitHub]: volatilityfoundation/volatility - (2.6) volatility/README.txt:126+ (as it is at this point): Requirements ============ - Python 2.6 or later, but not 3.0. http://www.python.org Note: The stacktrace is still incomplete (missing the last line - should be SyntaxError); that would have cleared things up much sooner So, you have to run it with Python2.6+ (of course you could also modify the code (at least the part that you need) to be Python3 compatible, but I doubt that's feasible).
downvote count: 0
answers question: http://stackoverflow.com/q/48474056
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48474056
type: AcceptedAnswer

http://stackoverflow.com/comment/83767837
score: 0
type: Comment
type: QuestionComment
has text: @chris-crush-code. I'm talking about recaptcha v2. I'm not a robot select and manually solving the images. :)
comment on: http://stackoverflow.com/q/48389786

http://stackoverflow.com/comment/83803764
type: Comment
type: QuestionComment
has text: What you trying to do is usually done with `logger = logging.getLogger(__name__)`. This will use the dotted name of the module and create and hierarchical structure in the logging system. [details](https://docs.python.org/3/library/logging.html#logger-objects)
comment on: http://stackoverflow.com/q/48407358
score: 1

http://stackoverflow.com/q/48355680
favorite count: 0
has comment: http://stackoverflow.com/comment/83701594
has answer: http://stackoverflow.com/a/48355724
type: Question
tagged with: http://stackoverflow.com/tag/csv
has body: I am collecting Data from twitter for data analysis using python tweepy. code is: Data is saved in json format.But i need to convert it in .csv format. Data sample is: But it is showing error that json is invalid. Can you tell me how can i convert this data in .csv format.
has title: Tweet collection using Python Tweepy
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: twitter
type: UnansweredQuestion
downvote count: 4
upvote count: 0
score: -4
answer count: 1

http://stackoverflow.com/comment/83732019
comment on: http://stackoverflow.com/q/48372449
type: Comment
type: QuestionComment
score: 0
has text: `my_command`, `my_command.py`, and `$my_command` are three different things, or do you have a symbolic link? This is not Windows, it does not add the extension automagically, or are you using an alias in the shell?

http://stackoverflow.com/comment/83779436
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48378081
has text: This solution is appropriate. The question shows the op is just starting to learn the language (maybe programming). Solutions with advanced language constructs or even worse external packages while correct may (nay, will) not provide any enlightenment to the OP.
score: 1

http://stackoverflow.com/q/48460460
has comment: http://stackoverflow.com/comment/83917669
tagged with: gunicorn
tagged with: python
has title: gunicorn running with flask in python hangs when started?
score: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83917173
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48462997
has comment: http://stackoverflow.com/comment/83916615
tagged with: keras
tagged with: flask
has body: I am running a Python script containing keras models which should be run with a flask app and gunicorn. The flask server on it's own runs fine, but when I try to integrate gunicorn with it, the worker hangs after boot. These are the last 2 statements that I see : [2018-01-26 12:17:35 +0000] [32225] [INFO] Booting worker with pid: 32225 2018-01-26 12:17:36.651087: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA I can no longer access flask in the browser after integrating gunicorn. This is the main problem. I tried lowering the timeout for workers but it did not make a difference.
favorite count: 0
type: Question

http://stackoverflow.com/comment/83827551
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48418556
has text: You should convert the things that aren't dates into dates, then sort. I.e. `Win 2009` would be whatever month winter starts in your hemisphere.

http://stackoverflow.com/q/48418499
has answer: http://stackoverflow.com/a/58127317
has comment: http://stackoverflow.com/comment/114114784
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/65162149
upvote count: 5
has body: I have defined a variable T_0 at the top of a python code, and want to change this variable by F2 of MS VS Code. T_0 = 10 T_1 = T_0 + 1 print(T_1) But first, I got an error message Refactoring library rope is not installed. Then I found an answer to this at here. After appropriately changed this, I got a new error message Refactor failed. Rename refactoring should be performed on resolvable python identifiers.. How can I rename a variable in a python code on MS VS Code? I am using Python 3.6, VS Code 1.19.2.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84016887
has title: Renaming a variable in a Python code in MS VS Code
score: 5
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/61115516
answer count: 3
linked to: http://stackoverflow.com/q/59508959

http://stackoverflow.com/q/48392381
has answer: http://stackoverflow.com/a/48392444
accepted answer: http://stackoverflow.com/a/48393096
has comment: http://stackoverflow.com/comment/83772669
has answer: http://stackoverflow.com/a/48393096
tagged with: python
linked to: http://stackoverflow.com/q/973473
has body: I need to recursively find all paths below a folder with names that contain the substring "Bar". In Python 2.7 That is for the folder structure Foo | ------ Doug | | | --------CandyBar | ---------MilkBar I need to get the list ["Foo/Doug/CandyBar", "Foo/MilkBar"] Now I can use os.walk and glob.glob and write a bunch of loops to get this list but I'm wondering if I'm missing a simpler technique.
has title: How can I get folder names that match a substring?
has comment: http://stackoverflow.com/comment/83773129
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83772699
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/83773324
score: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/2186525
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48392444

http://stackoverflow.com/comment/83924133
type: AnswerComment
score: 0
has text: I do not need to simply repeat the value into another dimension, that was merely an example...
type: Comment
comment on: http://stackoverflow.com/a/48465092

http://stackoverflow.com/q/48361380
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48362088
has title: How do I take the end of a message on discord and make my bot repeat it?
type: Question
has answer: http://stackoverflow.com/a/48361415
has body: How do I have my bot take the end of a message and repeat it with a message behind it? Here's my code: elif message.content.startswith('/ban'): bant = message.content.endswith('') and ('has been bant') await client.send_message(message.channel, bant) If I say for example /ban chiken I want it to say: chiken has been bant Or if I say /ban jeff I want it to say: jeff has been bant
type: UnansweredQuestion
tagged with: python
tagged with: discord

http://stackoverflow.com/comment/83933053
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48469597
score: 0
has text: You are comparing a series `df[string_col]` to a string 'some string'. Therefore, the output will be a series. As the error message says, you need to be specific about what you are testing, e.g. are all or any of the Boolean series output meant to be True?

http://stackoverflow.com/comment/83927440
has text: So, apparently, my instance of Spyder 3.6 is using those directories instead of what I thought it was using (C:\Python27\). I copied it over to the site-packages in anaconda3 and the error has changed to a different missing module. So, that was it. Thanks @cowbert
comment on: http://stackoverflow.com/q/48454161
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83716611
has text: I have edited my answer above. You can use `if round(t) % 6 == 0: `
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48364945
score: 0

http://stackoverflow.com/comment/90043773
type: Comment
comment on: http://stackoverflow.com/a/48384553
type: AnswerComment
has text: You should probably ask that as a new question on stackoverflow.
score: 1

http://stackoverflow.com/q/48364139
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83735745
tagged with: python
has title: Flask url_for adding trailing slash with gunicorn
tagged with: flask
score: 0
answer count: 0
has body: I am using Flask and when developing locally, all this works fine. However, when deployed using nginx with a proxy pass through gunicorn, the url_for seems to be adding a trailing / to the url which is causing errors when pulling the json data off the url. Here's the relevant code: @app.route('/save', methods=['POST']) def save(): name = request.form['name']; email = request.form['email'] data = json.dumps({"name": name, "email": email}) return redirect(url_for('.record', data=data)) @app.route("/record") def record(): // error here because of trailing / data = json.loads(request.args['data']) //... more code I'm pretty new to using Flask and super new to gunicorn so if I'm missing any required info to get help, just let me know. Here's the proxy_pass config in nginx: location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } And then I'm just running gunicorn as a service with: gunicorn --bind 0.0.0.0:8000 app:app Example breaking URL https://&lt;ipaddress&gt;/record?data=%7B%22name%22%3A+%22fdaf%22%2C+%22email%22%3A+%22fsd%40sfd.com%22%7D/
has comment: http://stackoverflow.com/comment/83718366
has comment: http://stackoverflow.com/comment/83715275
type: Question
tagged with: gunicorn
tagged with: nginx

http://stackoverflow.com/comment/83744320
type: AnswerComment
comment on: http://stackoverflow.com/a/48378730
type: Comment
has text: <tf.Tensor 'Shape_6:0' shape=(?,) dtype=int32>
score: 0

http://stackoverflow.com/comment/83792801
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48402329
has text: `[23/Jan/2018 12:59:04] "GET /home/ HTTP/1.1" 302 0` `Not Found: /accounts/login/` `[23/Jan/2018 12:59:04] "GET /accounts/login/?next=/home/ HTTP/1.1" 404 2650` I have used that exact syntax, but it doesn't redirects.
score: 1

http://stackoverflow.com/a/48350565
accepted answer of: http://stackoverflow.com/q/48349052
type: Answer
answers question: http://stackoverflow.com/q/48349052
type: AcceptedAnswer
has body: You have to use $filter operator in $expr expression. You can't use query operator ($elemMatch) in $expr. $expr only allows aggregation operators. Outer $gt to check when $size of matching records is greater than 0 Something like db.servers.find( {"$expr":{ "$gt":[ {"$size":{ "$filter":{ "input":"$disk", "as":"item", "cond":{ "$gt":[ {"$divide":["$$item.used","$$item.capacity"]}, 0.9 ] } } }}, 0 ] }})
score: 0

http://stackoverflow.com/q/48470823
accepted answer: http://stackoverflow.com/a/48470882
has answer: http://stackoverflow.com/a/48470882
possible better answer: http://stackoverflow.com/a/48470979
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48470979
has title: How to take log of a unit with dimensions?
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83935614
type: AnsweredQuestion
has body: I have a temperature variable with Kelvin units. I need to take log10 of it with np.log10, but it does not work if a number has dimensions. What is the easiest way to remove dimensions from the variable so I can take a log of it? Example import astropy.units as u import numpy as np temp = 6000 * u.K np.log10(temp) Shows the error message: UnitTypeError: Can only apply 'log10' function to dimensionless quantities
tagged with: python
tagged with: astropy

http://stackoverflow.com/comment/132017238
has text: Does this answer your question? [Dynamically adding @property in python](https://stackoverflow.com/questions/2954331/dynamically-adding-property-in-python)
comment on: http://stackoverflow.com/q/48448074
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83818805
has text: OK. Another question: your outputs have different lengths. Does the function choose each value with a certain probability or does it choose a certain number of values with equal probability?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48414404

http://stackoverflow.com/comment/83802636
type: QuestionComment
comment on: http://stackoverflow.com/q/48405225
type: Comment
has text: Consider using only a small sample of the data set first, or some dummy data of smaller size. Although it's hard to be use with that information alone, it looks odd that you are creating a data set for each image. Wouldn't you rather insert all features into a single row-indexed data-set?
score: 0

http://stackoverflow.com/comment/83756063
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48384376
has text: @AndyG there are around 10000 records with dates ranging from 01/01/2000 - 12/01/2018 in multiple date formats..
score: 0

http://stackoverflow.com/comment/83837716
type: AnswerComment
comment on: http://stackoverflow.com/a/48388405
type: Comment
has text: I get "Requirement already satisfied", but then if I run a Python script using the Automator or via /usr/bin/python, I keep getting "ImportError: No module named ..."
score: 0

http://stackoverflow.com/comment/83666628
has text: A quick test of performance puts as the fastest out of all of these (including the `find` method) (all splitting on `' (file no'`)
comment on: http://stackoverflow.com/q/48340340
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/94768249
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48350671
has text: See [Pygame OpenGL init causes an X Error](https://gamedev.stackexchange.com/questions/166421/pygame-opengl-init-causes-an-x-error). The issue has nothing to do with your code. It is causes by your system or graphics driver or possibly you have to update pygame.
score: 0

http://stackoverflow.com/a/48359307
answers question: http://stackoverflow.com/q/48359091
score: 2
upvote count: 2
downvote count: 0
has body: My standard method is to combine series.replace / series.fillna with series.map(dict). fill_dict = dataframe2.set_index('Col1')['Col2'].to_dict() dataframe1['Col2'] = dataframe1['Col2'].replace('Null', dataframe1['Col1'].map(fill_dict))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48359091
type: Answer

http://stackoverflow.com/a/48461881
answers question: http://stackoverflow.com/q/48461814
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/84008374
upvote count: 0
has comment: http://stackoverflow.com/comment/83930900
has body: Sure, the variable is declared AFTER it's used, exactly what Python complains about. Move the top-level text assignment to before the function definition.

http://stackoverflow.com/q/48351518
favorite count: 0
has comment: http://stackoverflow.com/comment/83693804
score: 9
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/75736729
has body: Boto3 has a managed copy method, which works pretty nicely for individual objects. Similarly, it seems to have a delete() method that works on a collection. But if I have a collection of objects (see objects below), it seems like the only way I can do a bulk operation is to use my own thread/process pool (I'm using multiprocessing for simplicity, but concurrent.futures would likely be better for error handling). import boto3 import multiprocessing bucket_name = '1000genomes' prefix = 'changelog_details/' bucket = boto3.resource('s3').Bucket(bucket_name) objects = bucket.objects.filter(Prefix=prefix).limit(30) sources = [{'Bucket': o.bucket_name, 'Key': o.key} for o in objects] target_bucket = 'my-bucket' # fill in bucket here! def copy_to_bucket(src, bucket=target_bucket): # client is not thread-safe according to docs s3 = boto3.resource('s3') return s3.meta.client.copy(src, bucket, src['Key']) pool = multiprocessing.Pool(20) results = pool.map(copy_to_bucket, sources) print('Copied %d results' % len(results)) Have I missed something about how to do this in bulk? I was attempting to look through the aws-cli codebase and/or the S3Transfer class, but both of them seem to be focused on uploading or downloading files. Failing that, any thoughts on whether threads or processes are the better choice here? (I'd think the majority of a server-side copy would be just waiting for network I/O regardless).
type: UnansweredQuestion
tagged with: boto3
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/66008004
type: Question
upvote count: 9
tagged with: amazon-s3
tagged with: python
has title: Bulk copy with boto3

http://stackoverflow.com/q/48434159
tagged with: python-module
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
score: 1
has body: First post hear and relatively new coder. Trying to get this package: https://pypi.python.org/pypi/sgp4/ to work, only I have no idea what I'm doing. I'm not familiar with the file extension (.tar.gz) and I don't know if this is a module or what and how to install it and get it to work. I am using python 3.6.4 currently. Apologies that this is a pretty dumb question, but I'm trying to learn towards the goal of adding to this script so that I can build a tracking capable ground station. Any and all help appreciated. Thank you for your time, Lorcan.
linked to: http://stackoverflow.com/q/8548030
has answer: http://stackoverflow.com/a/48444750
accepted answer: http://stackoverflow.com/a/48444750
tagged with: sgp4
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24691654
tagged with: orbital-mechanics
has answer: http://stackoverflow.com/a/71584170
possible better answer: http://stackoverflow.com/a/71584170
has title: How to install SGP4 V 1.4 package in Python 3.6

http://stackoverflow.com/a/48345324
has body: elif choice == "5": print("\nOto wszystkie terminy znajdujace sie w slowniku:") for i in dictionary.keys(): print(i) thats what i've been looking for :) Now it works how it supposed to, thank you for your help :) I just started learning python so all those small things are still making me a problem :)
answers question: http://stackoverflow.com/q/48343965
type: Answer
score: 0

http://stackoverflow.com/comment/123937155
has text: what is `bigquery_client` ? It's not clear from your code.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48399955

http://stackoverflow.com/comment/84078069
score: 0
type: Comment
has text: Also, why is your data a list of lists? I was assuming that the input data were feature vectors of the type ` <index:value> <index:value> ...` (cf. my OP)
type: AnswerComment
comment on: http://stackoverflow.com/a/48526540

http://stackoverflow.com/q/48487570
tagged with: tensorflow
type: Question
has title: Low accuracy in neural network with Tensorflow
type: AnsweredQuestion
score: 0
has body: I was following a Google code lab on neural networks and I decided to use the Cifar10 dataset instead of the MNIST dataset to make a simple image classifier, but for some reason I have very low accuracy and high cross-entropy. After training the accuracy is around 0.1 (never more than 0.2) and cross-entropy doesn't go below 230. My code: import tensorflow as tf import numpy as np import matplotlib as mpt # Just disables the warning, doesn't enable AVX/FMA import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def returnMiniBatch(dictionary,start,number): matrix=np.zeros([number,3072],dtype=np.int) labels=np.zeros([number],dtype=np.int) for i in range(0,number): matrix[i]=dictionary[b'data'][i+start] labels[i]=dictionary[b'labels'][i+start] return matrix,labels def formatLabels(labels,number): lab=np.zeros([number,10]) for i in range(0,number): lab[i][labels[i]]=1 return lab data='D:/cifar-10-python/cifar-10-batches-py/data_batch_1' dictionary=unpickle(data) tf.set_random_seed(0) L = 200 M = 100 N = 60 O = 30 X=tf.placeholder(tf.float32,[None,3072]) Y_=tf.placeholder(tf.float32,[None,10]) W1 = tf.Variable(tf.truncated_normal([3072,L],stddev=0.1)) B1 = tf.Variable(tf.ones([L])/10) W2 = tf.Variable(tf.truncated_normal([L, M], stddev=0.1)) B2 = tf.Variable(tf.ones([M])/10) W3 = tf.Variable(tf.truncated_normal([M, N], stddev=0.1)) B3 = tf.Variable(tf.ones([N])/10) W4 = tf.Variable(tf.truncated_normal([N, O], stddev=0.1)) B4 = tf.Variable(tf.ones([O])/10) W5 = tf.Variable(tf.truncated_normal([O, 10], stddev=0.1)) B5 = tf.Variable(tf.ones([10])) Y1 = tf.nn.relu(tf.matmul(X, W1) + B1) Y2 = tf.nn.relu(tf.matmul(Y1, W2) + B2) Y3 = tf.nn.relu(tf.matmul(Y2, W3) + B3) Y4 = tf.nn.relu(tf.matmul(Y3, W4) + B4) Ylogits = tf.matmul(Y4, W5) + B5 Y = tf.nn.softmax(Ylogits) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Ylogits, labels=Y_) cross_entropy = tf.re…
has answer: http://stackoverflow.com/a/48622865
tagged with: python
has answer: http://stackoverflow.com/a/48490995
tagged with: python-3.x
answer count: 2
tagged with: classification
accepted answer: http://stackoverflow.com/a/48622865
tagged with: neural-network
possible better answer: http://stackoverflow.com/a/48490995

http://stackoverflow.com/comment/83766798
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48389450
has text: Exactly ['/Member1'] or ['@Member1'] in order to scrap their followers and friend after to create a network

http://stackoverflow.com/a/48358838
has comment: http://stackoverflow.com/comment/83704662
type: Answer
has body: The uploaded file is in request.FILES. You are not passing files to the form. Try this. form = DocumentUpload(request.POST, request.FILES)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48358774
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48358774

http://stackoverflow.com/comment/83743829
comment on: http://stackoverflow.com/q/48378468
score: 0
type: QuestionComment
type: Comment
has text: If you want your palindromes sorted, store them in a list during the for loops, then sort and print them a the end.

http://stackoverflow.com/q/48462044
favorite count: 0
type: Question
tagged with: geometry
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: shapes
upvote count: 7
tagged with: plot
has answer: http://stackoverflow.com/a/48465221
has answer: http://stackoverflow.com/a/69624322
has comment: http://stackoverflow.com/comment/125280813
has title: shapely parallel_offset sometimes does not generate closed ring
tagged with: shapely
score: 7
has body: I am using the parallel_offset function of the shapely package to get offset structures to some polygons that are closed rings. I have several polygons at once, many with similar shapes. Around 10-25% of them, however, do not generate a closed ring from the parallel_offset. Here is a MWE of a shape that does not work: import matplotlib.pyplot as plt from shapely.geometry.polygon import LinearRing def plot_line(ax, ob, color): x, y = ob.xy ax.plot(x, y, color=color, alpha=0.7, linewidth=3, solid_capstyle='round', zorder=2) polygon = [[-29.675, -30.675], [-28.4094, -29.4094], [-28.325, -29.325], [-28.325, -29.764], [-28.325, -29.7933], [-28.4587, -29.8274], [-28.4676, -29.8297], [-28.5956, -29.8814], [-28.6041, -29.8848], [-28.724, -29.953], [-28.732, -29.9576], [-28.8417, -30.0413], [-28.849, -30.0469], [-28.9466, -30.1445], [-28.9531, -30.151], [-29.0368, -30.2607], [-29.0424, -30.268], [-29.1106, -30.3879], [-29.1152, -30.3959], [-29.1669, -30.5239], [-29.1703, -30.5324], [-29.2044, -30.6661], [-29.2067, -30.675], [-29.6457, -30.675], [-29.675, -30.675]] poly_line = LinearRing(polygon) poly_line_offset = poly_line.parallel_offset(0.05, side="left", resolution=16, join_style=2, mitre_limit=1) fig = plt.figure() ax = fig.add_subplot(111) plot_line(ax, poly_line, "blue") plot_line(ax, poly_line_offset, "green") plt.show() As you can see, the green offset polygon does not close at the point that is first/last in the list of vertices. Other very similar shapes, however, do work as intended. They have the same data structure and also have the same start/end point, as does my example above. The join_style attribute does not change the outcome to what I want. Changing the resolution or distance does not help either. The documentation also does not address this issue. Do you have any guidance? I am using shapely 1.6.3.
tagged with: python

http://stackoverflow.com/a/48434543
has comment: http://stackoverflow.com/comment/83977503
upvote count: 3
answers question: http://stackoverflow.com/q/48434492
has comment: http://stackoverflow.com/comment/83977520
has comment: http://stackoverflow.com/comment/83977536
has comment: http://stackoverflow.com/comment/83979391
downvote count: 0
type: Answer
has body: If filenameis relative, the current working directory (available with os.getcwd()) is used. PYTHONPATH is only used when importing modules.
score: 3

http://stackoverflow.com/comment/84294249
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48449611
has text: any positive updates on this issue?
type: Comment

http://stackoverflow.com/a/48452190
has comment: http://stackoverflow.com/comment/104184907
accepted answer of: http://stackoverflow.com/q/48446351
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/104185071
score: 11
has comment: http://stackoverflow.com/comment/104184427
has body: You may check if the mouse button is released after the mouse has previously been moved. Since for zooming and panning, this would be the case you may call the function to draw a new point only when no previous movement has happened. import numpy as np import matplotlib.pyplot as plt class Click(): def __init__(self, ax, func, button=1): self.ax=ax self.func=func self.button=button self.press=False self.move = False self.c1=self.ax.figure.canvas.mpl_connect('button_press_event', self.onpress) self.c2=self.ax.figure.canvas.mpl_connect('button_release_event', self.onrelease) self.c3=self.ax.figure.canvas.mpl_connect('motion_notify_event', self.onmove) def onclick(self,event): if event.inaxes == self.ax: if event.button == self.button: self.func(event, self.ax) def onpress(self,event): self.press=True def onmove(self,event): if self.press: self.move=True def onrelease(self,event): if self.press and not self.move: self.onclick(event) self.press=False; self.move=False def func(event, ax): print(event.xdata, event.ydata) ax.scatter(event.xdata, event.ydata) ax.figure.canvas.draw() fig, (ax1, ax2) = plt.subplots(1, 2) # Plot some random scatter data ax2.scatter(np.random.uniform(0., 10., 10), np.random.uniform(0., 10., 10)) click = Click(ax2, func, button=1) plt.show()
answers question: http://stackoverflow.com/q/48446351
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/104184967

http://stackoverflow.com/q/48483832
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has title: Extraction of tables from PDF
upvote count: 2
has answer: http://stackoverflow.com/a/48483966
answer count: 2
downvote count: 5
type: UnansweredQuestion
tagged with: pdf-scraping
score: -3
has answer: http://stackoverflow.com/a/48484409
favorite count: 0
has comment: http://stackoverflow.com/comment/83960436
type: Question
tagged with: http://stackoverflow.com/tag/r
has body: I have a pdf file containing text, images and tables.I want to extract just the tables from that pdf file using either Python or R.
has comment: http://stackoverflow.com/comment/83961072
has comment: http://stackoverflow.com/comment/83960755

http://stackoverflow.com/comment/83732725
comment on: http://stackoverflow.com/a/48372768
score: 0
has text: `mypackage` is just a name for the package. The difference here is the file `__init__.py`. It's a convention that every folder contains that file, even just an empty one, is considered as a Python package. `foo.py`, `spam.py` are modules in this package.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83675075
has text: you need to give your counter an initial value: `sales = 0`
comment on: http://stackoverflow.com/q/48344562
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/a/66199162
type: Answer
has body: What you have highlighted in red is the area in which the Treeview's indicator resides -- the open or close toggle icon -- that is shown if any of the Item objects contain subitems of their own. One way to accomplish removing that area would be to just remove the indicator altogether while using a ttk theme that allows you to do so. s = ttk.Style() s.theme_use('default') s.configure('Treeview.Item', indicatorsize=0) This approach seems to only work for the default, clam and classic themes on Windows 10. For other themes, Ron's answer may be your best bet.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48358096

http://stackoverflow.com/a/48415889
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83821881
downvote count: 0
has comment: http://stackoverflow.com/comment/83825941
answers question: http://stackoverflow.com/q/48415782
type: Answer
has body: You initialized variable merged_meetings as a single tuple, however it should be a list of tuples. Thus, you have to modify the initialization of merged_meetings to merged_meetings = [sorted_meetings[0]] and the result of your testcase will be [(1, 3), (5, 17)]

http://stackoverflow.com/comment/83965420
has text: By an arc length of `S`, I assume you mean that the length of the arc formed by `0, 0` and `x0, y0` is `S`?
type: QuestionComment
comment on: http://stackoverflow.com/q/48486254
score: 0
type: Comment

http://stackoverflow.com/comment/84003320
type: Comment
type: AnswerComment
has text: Oh, I am sorry I have misunderstood your question.
comment on: http://stackoverflow.com/a/48488611
score: 0

http://stackoverflow.com/comment/83785889
comment on: http://stackoverflow.com/q/48398486
type: Comment
has text: I think need `decimal` in `read_csv` like `df=pd.read_csv("C:/Users/PD/Desktop/Finanzblick Dokumente/2017_11/2017_11- DB.csv", sep=';',usecols=(0,1,2,3,4), encoding='utf-8', decimal=',')` - it convert `,` to `.` and numbers to numeric floats.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83651416
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163449/discussion-between-alwaysaskingquestions-and-julian-rachman).
comment on: http://stackoverflow.com/q/48332632
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83746645
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48378996
has text: Please edit your question instead of hiding additional, unformatted information in the comments.
type: Comment

http://stackoverflow.com/comment/83852984
has text: OK, so with a little testing I figured out my mistake. The fit=sp.stats.norm does normalize my values. If I remove it, my graphs look like I expect them to.
score: 0
comment on: http://stackoverflow.com/q/48424096
type: QuestionComment
type: Comment

visual-glitch
tags question: http://stackoverflow.com/q/48392263
type: Tag
tag name: visual-glitch

http://stackoverflow.com/q/48473602
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: What is given: Office consists of 3 types of buildings: building A, B, C. Employees work in 3 departments: IT, Marketing, Management There is a pass system that records time, department, building_type, gender(m/f) The goal is to count number of male employees for each department-building_type pair for each 30 minute segment. Here's a piece of CSV data to process: time,department,building_type,gender 2017-09-07 14:46:14,018,management,b,m 2017-09-07 14:49:14,081,it,a,m 2017-09-07 14:55:14,127,management,c,f 2017-09-07 15:40:16,318,marketing,c,m 2017-09-07 16:01:14,018,it,a,m 2017-09-07 16:10:14,081,it,a,m 2017-09-07 17:46:14,127,marketing,c,m 2017-09-07 17:49:16,318,management,c,m 2017-09-07 18:00:14,018,it,c,f 2017-09-07 18:02:14,081,management,a,m 2017-09-07 18:33:14,127,marketing,b,m 2017-09-07 18:56:16,318,marketing,a,m The main time period to process is 2017-09-07 14:46:14,018 thru 2017-09-07 18:56:16,318. Inside this main time period 30 minute segments should be defined and the number of male employess for each department-building_type pair should be calculated for every 30 minute segment. The output should include a column start_time that denotes the beginning of a 30 minute segment inside which the number of male employees for each department-building pair should be calculated. Output should be displayed in terminal (csv format is not needed) Example of an output: start_time,department,building_type,num_of_m_employees 2017-09-07 14:46:14,018,management,b,2 2017-09-07 14:46:14,018,it,a,1 2017-09-07 15:40:16,318,marketing,c,1 2017-09-07 15:40:16,318,it,a,2 2017-09-07 17:46:14,127,marketing,c,1 2017-09-07 17:46:14,127,management,a,1 2017-09-07 18:33:14,127,marketing,b,1 2017-09-07 18:33:14,127,marketing,a,1 I have written a program that counts the number of male employees for each department-building pair in general, but I can't do the same for each 30 minute segment. How am I to edit it?: import csv from collections import Counter with open('test.csv') as f: cn…
has comment: http://stackoverflow.com/comment/83940910
tagged with: datetime
has title: Python, CSV: count number of male employees for each 30 min segment
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48521379
has comment: http://stackoverflow.com/comment/83940948

http://stackoverflow.com/a/48459055
has comment: http://stackoverflow.com/comment/83911415
has comment: http://stackoverflow.com/comment/83910994
upvote count: 3
downvote count: 0
has body: Option 1 Parse your string column with ast.literal_eval/pd.eval (it's the easiest first step). import ast df['values'] = df['values'].apply(ast.literal_eval) Next, flatten the last column and concatenate with the remaining n - 1 columns. i = df.iloc[:, :-1] j = pd.DataFrame(df.iloc[:, -1].tolist()) pd.concat([i, j], 1) col1 col2 0 1 2 3 0 Col1Val Col2Val 3 31.1 -341.4 54.13 Here's an improved version for efficiency. Use del for inplace deletion of columns, and cut out all the slicing operations (they create copies, and are wasteful). j = pd.DataFrame(df['values'].tolist()) del df['values'] pd.concat([df, j], 1) col1 col2 0 1 2 3 0 Col1Val Col2Val 3 31.1 -341.4 54.13 Option 2 str.extractall (can't guarantee performance). df = df.set_index(['col1', 'col2'])['values']\ .str.extractall('(\d+(?:\.\d*)?)')\ .unstack() df.columns = df.columns.droplevel(0) df.reset_index() match col1 col2 0 1 2 3 0 Col1Val Col2Val 3 31.1 341.4 54.13
has comment: http://stackoverflow.com/comment/83913995
has comment: http://stackoverflow.com/comment/83913887
score: 3
has comment: http://stackoverflow.com/comment/83914023
type: Answer
has comment: http://stackoverflow.com/comment/83911111
answers question: http://stackoverflow.com/q/48458706
has comment: http://stackoverflow.com/comment/83913810

http://stackoverflow.com/comment/83845723
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48427501
has text: Thanks, but it still isn't [mcve] to the problem you're having. You can narrow it down more.
type: Comment

http://stackoverflow.com/comment/125079412
comment on: http://stackoverflow.com/q/48340463
type: Comment
score: 0
has text: I think this is happening because you are resampling using '3T' which indicates a 3 minutes period for each sample and not 3 rows
type: QuestionComment

http://stackoverflow.com/comment/83765871
type: QuestionComment
has text: Rodger. I'll give that a go
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48388550

http://stackoverflow.com/comment/83809764
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48398923
has text: @ImportanceOfBeingErnest thanks ernest, first i don't get the importance of being ernest , secondly, thanks for your help, i will clear my exact problem up in next comment
score: 0

http://stackoverflow.com/comment/83858778
has text: like the Time items are all like 2016-10-19 21:58:13-04:00, and are 20, 21, 22, 23 ish not its UTC equivalent
comment on: http://stackoverflow.com/a/48429323
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48430360
type: AnsweredQuestion
tagged with: list
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/48430430
downvote count: 0
possible better answer: http://stackoverflow.com/a/48439584
upvote count: 1
has answer: http://stackoverflow.com/a/48430430
has answer: http://stackoverflow.com/a/48439584
favorite count: 0
type: Question
has body: I am trying to fina all numbers b/1 1 and 1000 that contain 7. Tried: lst=[y for y in range(1,1000) if 7 in y] print (lst) Got below error: TypeError: argument of type 'int' is not iterable Tried: lst=[y for y in range(1,1000)] newlst=[] str1=list(map(lambda x:str(x),lst)) for i in str1: if any('7') in i: newlst.append(i) print (newlst) This gives if any('3') in i: TypeError: 'in &lt;string&gt;' requires string as left operand, not bool Process finished with exit code 1 Any idea to accomplish this with list comprehension?
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/83851868
has title: List comprehension to find all numbers between 1 and 1000 which contains 7

http://stackoverflow.com/comment/83889748
has text: Do you understand why the program behaves the way it does? You need to tell the green_foreground function to use the logger defined in first.py. How might you do that?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48448501

http://stackoverflow.com/q/48361637
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/48362215
type: AnsweredQuestion
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48362215
has comment: http://stackoverflow.com/comment/83710519
has comment: http://stackoverflow.com/comment/83710083
favorite count: 0
tagged with: numpy
tagged with: python-3.x
has title: Fit straight line on semi-log scale with Matplotlib
type: Question
tagged with: matplotlib
tagged with: python
has body: I have been struggling with fitting a straight line on a semi-log plot made with Matplotlib and Python 3. I have seen many examples of log-log scale figures, but none of the solutions I tried worked (using numpy). The line always ends up being crooked somewhere. The following is what I have thus far: import os import matplotlib import matplotlib.pyplot as plt import numpy as np base_path = os.path.dirname(os.path.realpath(__file__)) fig = plt.figure() ax = fig.add_subplot(111) # Plot data. location = os.path.join(base_path, "data.csv") data = np.genfromtxt(location, delimiter=',', names=['year', 'bw']) ax.plot(data['year'], data['bw']) # Fit test. x = data['year'] y = data['bw'] y_ln = np.log10(y) n = data.shape[0] A = np.array(([[x[j], 1] for j in range(n)])) B = np.array(y_ln[0:n]) B = np.array(y[0:n]) X = np.linalg.lstsq(A, B)[0] a = X[0] b = X[1] fit = a * x + b p = np.polyfit(x, np.log(y), 1) ax.semilogy(x, p[0] * x + p[1], 'g--') ax.set_yscale('log') The associated data.csv file looks as follows: 2016, 68.41987090116676 2017, 88.9788618486191 2018, 90.94850458504749 2019, 113.20946182004333 2020, 115.71547492850719 The figure I obtain looks as following, where the fitted line is crooked. Feedback and suggestions are very much appreciated.
has comment: http://stackoverflow.com/comment/83710292
has comment: http://stackoverflow.com/comment/83710212

http://stackoverflow.com/q/48381085
tagged with: python
linked to: http://stackoverflow.com/q/427453
has answer: http://stackoverflow.com/a/48381266
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48381266
upvote count: 3
score: 3
has body: Background: I'd like to slice a pandas dataframe in elements of a given row length, and perform calculations on them. pandas.DataFrame.rolling will let me do that, but seemingly only with built-in functions like sum() in the example df.rolling(2, win_type='triang').sum(). I would also like to plot these subsets (I'm able to do that by slicing and some For Loops, but it's a bit slow). What I've found out: From How can I get the source code of a Python function? I've learnt that I can read source code using pandas.DataFrame.rolling?? which will give me this: But trying to dig deeper from here using for example rolling?? seems futile: So, is it possible to reference the underlying functions of pandas.DataFrame.rolling somehow, or is this where it ends using Python? I guess so since the docs state that pandas is written in Cython or C, but I'm really curious about this so I'd like to ask about this here as well. Thank you for any suggestions!
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48381684
downvote count: 0
has comment: http://stackoverflow.com/comment/83748749
has answer: http://stackoverflow.com/a/48381111
has title: Is it possible to read source code from the pandas library and use that in my own functions?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48381684
has comment: http://stackoverflow.com/comment/83748748

http://stackoverflow.com/q/48391733
tagged with: python
has answer: http://stackoverflow.com/a/64986416
score: 0
has comment: http://stackoverflow.com/comment/83773515
answer count: 1
tagged with: twitter
has comment: http://stackoverflow.com/comment/83773169
has title: User authentication for Twitter API using Python application
tagged with: twython
tagged with: twitter-oauth
type: Question
has body: I am working on a module for an application written in Python (it is open-source). I want the module to allow a user to log into Twitter and update status (post a tweet). I have Python script I wrote using the twitter import that requires a developer (me) to put in consumer/authentication token/secrets. I don't want to have the tokens pre-programmed into the module, but rather have a user log in to update THEIR status (obviously). I need a general direction to pursue. I envision the user clicking on a Share! menu option, a browser popping up with the Twitter login page, a user logging in and the application storing the credentials, and then updating the status from there. I have the module working, but like I said before, I need to input token information from my application's apps.twitter.com page. I want the user to be able to log in. Here is a snip of code using the twython library: from twython import Twython #APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET OAUTH_TOKEN = '...' OAUTH_TOKEN_SECRET = '...' APP_KEY = '...' APP_SECRET = '...' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) if (twitter.update_status(status='The status is updated from Python!')): print("Working!") else: print("Not working!") The code above works and updates my Twitter status, but I do not want other users of this module to be updating my status, but rather have them log in and update their status. Thanks in advance. EDIT What I have now: import urllib.parse import oauth2 as oauth consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXX' consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' request_token_url = 'https://api.twitter.com/oauth/request_token' access_token_url = 'https://api.twitter.com/oauth/access_token' authorize_url = 'https://api.twitter.com/oauth/authorize' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) resp, content = client.request(request_token_url, "GET") if resp['status'] != '200': raise Except…
type: UnansweredQuestion

http://stackoverflow.com/a/76465311
has body: To handle this situation, you can override the clean_username method in your UsersForm class and customize the validation logic to suit your requirements. Here's an example of how you can modify your form to display a custom error message instead of the default validation error: def clean_username(self): username = self.cleaned_data['username'] existval = User.objects.filter(username=username) if self.instance: existval = existval.exclude(pk=self.instance.pk) if existval.exists(): raise forms.ValidationError("This username is already taken !!") return username
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48475039

http://stackoverflow.com/q/48475071
answer count: 1
tagged with: django
has body: My models.py is like this: My python's version is 3.5.x and django version is 2.0.1, and when I went to admin's page, I got this page:
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83943532
accepted answer: http://stackoverflow.com/a/48475275
has title: django(v2.0.1) -- _str_() method shows Object but not notes in self.text(python3.5)
has answer: http://stackoverflow.com/a/48475275
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83943569
score: 0

pivottable.js
tag name: pivottable.js
type: Tag
tags question: http://stackoverflow.com/q/48415690

http://stackoverflow.com/comment/83903676
comment on: http://stackoverflow.com/q/48455129
type: QuestionComment
has text: No. But you may have multiple instance of `python` or `PYTHONPATH`.
score: 0
type: Comment

http://stackoverflow.com/q/48463442
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network
upvote count: 1
tagged with: python
has title: tensorflow parallelize training in 1 computer
has body: I have a computer with one cuda enabled gpu and one 8 core cpu. I'm trying to implement the A3C algorithm for reinforcement learning, which parallelizes the graph and the training environment and syncs the gradient updates to a global graph. I'm trying to use the distributed tensorflow api to do this: # Hyperparameter definition ############################################################ epochs = 100000 # Global steps t_max = 1000 # Thread steps max_grad_norm = 0.5 alpha = 0.99 gamma = 0.99 ############################################################# ckpt_path = 'ckpt/checkpoints' log_path = 'logs' def test(ac, load_path, sess): ac.load(load_path) env = gym.make('Breakout-v0') while True: obs = env.reset() state_c, state_h = ac.init_lstm_c, ac.init_lstm_h done = False while not done: action, _, state_c, state_h = ac.step(sess, obs, state_c, state_h) obs, _, done, _ = env.step(action) def train(n_epochs, t_max, gamma, ac, sess): env = gym.make("Breakout-v0") save_dir = os.path.join(log_path) writer = tf.summary.FileWriter(save_dir) for ep in range(n_epochs): ep_obs, ep_disc_rew, m_rew, ep_act, ep_vals, state_c, state_h = process_episode(sess, ac, env, t_max, gamma) log = ac.learn(sess, ep_obs, state_c, state_h, ep_disc_rew, m_rew, ep_act, ep_vals) step = tf.train.get_global_step().eval(session=sess) writer.add_summary(log, global_step=step) def process_episode(sess, ac, env, t_max, gamma): ep_observations, ep_rewards, ep_actions, ep_values = [], [], [], [] done = False t = 0 observation = env.reset() state_c, state_h = ac.c_init, ac.h_init while t &lt; t_max and not done: action, value, state_c, state_h = ac.step(sess, observation, state_c, state_h) ep_observations.append(observation) ep_values.append(value) ep_actions.append(action) observation, reward, done, _ = env.step(action) ep_rewards.append(reward) ep_disc_rewards = discount_rewards(ep_rewards, gamma) t_rew = np.sum(ep_rewards) return ep_observations, ep_disc_rewards, t_rew, ep_actions, ep_values, state_c, …
tagged with: reinforcement-learning
score: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/48472331
tagged with: statistics
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48475821
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83940781
has title: Evaluating a classifier in TensorFlow
has body: I was walking through this tutorial. I couldn't figure out how to evaluate the classifier, especially finding its sensitivity, specificity, AUC, ...etc. I found those in the TensorFlow documentation (this, and this), but couldn't figure how to use it with the code shown in the article. How can I find such measures for the code shown in the article?
tagged with: auc
tagged with: evaluation
tagged with: python

http://stackoverflow.com/q/48376000
type: Question
has comment: http://stackoverflow.com/comment/83738886
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48376078
accepted answer: http://stackoverflow.com/a/48376078
downvote count: 0
tagged with: python
has body: Example Plot that needs to format date I am trying to plot stock prices against time (see above). The code below does plot the "OPEN" prices but as I try to format the X-axis dates from ordinal to ISO dates, it throws AttributeError. The same code worked while plotting the OHLC graph, but somehow this doesn't work now. AttributeError: 'list' object has no attribute 'xaxis' df_copy = read_stock('EBAY') fig = plt.figure(figsize= (12,10), dpi = 80) ax1 = plt.subplot(111) ax1 = plt.plot(df_copy['Date'], df_copy['Open'], label = 'Open values' ) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
tagged with: plot
favorite count: 0
has title: Matplotlib Plotting: AttributeError: 'list' object has no attribute 'xaxis'
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48376060
possible better answer: http://stackoverflow.com/a/48376060
tagged with: pandas
upvote count: 5
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83738973

http://stackoverflow.com/comment/83945224
type: QuestionComment
score: 0
has text: `poly.split()` will also return a list, so wrapping it in `list()` is also unnecessary. As is `int(12-i)` (since all the components are already ints).
type: Comment
comment on: http://stackoverflow.com/q/48475989

http://stackoverflow.com/q/48367882
has body: I'm trying to implement a scan algorithm (Hillis-Steele) and I'm having some trouble understanding how to do it properly on CUDA. This is a minimal example using pyCUDA: import pycuda.driver as cuda import pycuda.autoinit import numpy as np from pycuda.compiler import SourceModule #compile cuda code mod = SourceModule(''' __global__ void scan(int * addresses){ for(int idx=1; idx &lt;= threadIdx.x; idx &lt;&lt;= 1){ int new_value = addresses[threadIdx.x] + addresses[threadIdx.x - idx]; __syncthreads(); addresses[threadIdx.x] = new_value; } } ''') func = mod.get_function("scan") #Initialize an array with 1's addresses_h = np.full((896,), 1, dtype='i4') addresses_d = cuda.to_device(addresses_h) #Launch kernel and copy back the result threads_x = 896 func(addresses_d, block=(threads_x, 1, 1), grid=(1, 1)) addresses_h = cuda.from_device(addresses_d, addresses_h.shape, addresses_h.dtype) # Check the result is correct for i, n in enumerate(addresses_h): assert i+1 == n My question is about __syncthreads(). As you can see, I'm calling __syncthreads() inside the for loop and not every thread will execute that code the same number of times: ThreadID - Times it will execute for loop 0 : 0 times 1 : 1 times 2- 3 : 2 times 4- 7 : 3 times 8- 15 : 4 times 16- 31 : 5 times 32- 63 : 6 times 64-127 : 7 times 128-255 : 8 times 256-511 : 9 times 512-896 : 10 times There can be threads in the same warp with different number of calls to syncthreads. What will happen in that case? How can threads that are not executing the same code be synchronized? In the sample code, we start with an array full of 1's and we get in the output the index+1 as value for each position. It is computing the correct answer. Is it "by chance" or the code is correct? If this is not a proper use of syncthreads, how could I implement such algoritm using cuda?
tagged with: cuda
accepted answer: http://stackoverflow.com/a/48372995
has title: How to use syncthreads in CUDA for a scan algorithm (Hillis-Steele)
tagged with: parallel-processing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48372995
score: 0
answer count: 1
tagged with: synchronization
type: Question
tagged with: pycuda
has comment: http://stackoverflow.com/comment/83729691
tagged with: python

http://stackoverflow.com/comment/83814204
type: AnswerComment
comment on: http://stackoverflow.com/a/48411715
score: 0
has text: @sagar, i don't think it's easy to prevent it and make it generic at the same time...
type: Comment

http://stackoverflow.com/comment/83953668
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48479964
type: Comment
has text: I have read the op several times, and it doesn't say anything about not wanting an alternative solution. Could be a misunderstanding on part tho.

http://stackoverflow.com/comment/104184427
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48452190
type: Comment
has text: In my experience, this works very well when using a trackpad. However, in practice, when I run my tkinter app with a sensitive mouse, it is difficult to click without also incorporating a subtle motion prior to releasing the button. Any suggestions?

http://stackoverflow.com/q/48412010
tagged with: discord
tagged with: embed
has body: I want to put the avatar and nick of the person who ran a command in the embed, something like this: requested by: (avatar) (nick) but I do not know how to start....
has title: How do I put a member's image and nick on embed? (w/ discord.py)
has answer: http://stackoverflow.com/a/48451550
possible better answer: http://stackoverflow.com/a/48451550
type: AnsweredQuestion
answer count: 3
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/48424456
tagged with: python
has answer: http://stackoverflow.com/a/48481861
accepted answer: http://stackoverflow.com/a/48481861

http://stackoverflow.com/a/48380500
downvote count: 0
answers question: http://stackoverflow.com/q/48380425
upvote count: 1
type: Answer
has body: First, split on comma and expand words into their own cells. v = df['keys'].str.split(',',expand=True) Next, form two masks, one for actual and another for syn, using isin + any. These will be used to label the rows. m1 = v.isin(["one","two"]).any(1) m2 = v.isin(["four","five"]).any(1) Finally, use np.select or np.where to label the rows based on the masks computed. df['val'] = np.select([m1, m2], ['actual', 'syn'], default='') Or, df['val'] = np.where(m1, 'actual', np.where(m2, 'syn', '')) df keys val 0 one actual 1 two,one actual 2 3 five,one actual 4 5 two,four actual 6 four syn 7 four,five syn Details v 0 1 0 one None 1 two one 2 None 3 five one 4 None 5 two four 6 four None 7 four five m1 0 True 1 True 2 False 3 True 4 False 5 True 6 False 7 False dtype: bool m2 0 False 1 False 2 False 3 True 4 False 5 True 6 True 7 True dtype: bool np.select([m1, m2], ['actual', 'syn'], default='') array(['actual', 'actual', '', 'actual', '', 'actual', 'syn', 'syn'], dtype='&lt;U6')
score: 1

http://stackoverflow.com/comment/83663384
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48339120
has text: I really dont get this -_-
type: Comment

http://stackoverflow.com/comment/83767878
type: AnswerComment
comment on: http://stackoverflow.com/a/48389805
score: 0
has text: @iamuser : Just started on that journey. Is it a matter of pulling each one (like python-libs) and running #2 to find additional dependencies? No way to do transitive closure... I guess that's why we have yum.
type: Comment

http://stackoverflow.com/comment/83710788
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48338439
type: AnswerComment
has text: Would it be possible to create a list of all last_traded_price rows relating to the selection_id instead?

http://stackoverflow.com/q/48446047
upvote count: 1
tagged with: flask
tagged with: event-sourcing
has comment: http://stackoverflow.com/comment/83885953
score: 1
has title: Python flask stream not updating
tagged with: python
has body: I'm trying to stream some data, to update progress bar on my website. For testing I'm running this: @application.route('/api/stream', methods=['GET', 'POST']) def stream(): def event_stream(): n = 0 while True: yield "data: %s\n\n" % n n += 1 time.sleep(1) return Response(event_stream(), mimetype='text/event-stream') @application.route('/api/output') def index(): return """ Data """ and on my website I've got post function: $.post("//mywebsite.com/api/stream", {"some": 'ss'}, function(data) { alert(data) }) And when I run this POST (above) then I'm opening mywebsite.com/api/output and it displays only: Data But when after a while I stop my flask app, on the website I'm getting: Data 0 1 2 Why It's not updating live but only when I stop flask app?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83902277
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83957397
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48481958
has text: @briancaffey Probably "python" not recognized. Try Anaconda Promt. Assuming Windows.
type: Comment

http://stackoverflow.com/q/48418105
has title: Python exec in function scope cannot set value
has body: import re value = eval("'Hello「World」'") c = [ "g = re.search('.*「(.*)」', value, re.IGNORECASE)", "print(value)", "value = g.group(1)", "print(value)" ] if c is not None: for d in c: exec(d) def test(): value2 = eval("'Hello「World」'") c2 = [ "g2 = re.search('.*「(.*)」', value2, re.IGNORECASE)", "print(value2)", "value2 = g2.group(1)", "print(value2)" ] if c2 is not None: for d2 in c2: exec(d2) test() Expect result: Hello「World」 World Hello「World」 World Actual result: Hello「World」 World Hello「World」 Hello「World」 I am running in Python 3.6.2. My question is why cannot exec set the value when it is inside the function? However, it can set on a new variable. def test2(): value2 = eval("'Hello「World」'") c2 = [ "g2 = re.search('.*「(.*)」', value2, re.IGNORECASE)", "print(value2)", "value3 = g2.group(1)", "print(value3)" ] if c2 is not None: for d2 in c2: exec(d2) test2() Result: Hello「World」 World Hello「World」 World How can I make test() change value2 inside exec?
has comment: http://stackoverflow.com/comment/83825940
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83825871
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83825804
has comment: http://stackoverflow.com/comment/83826007
type: UnansweredQuestion
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/1463306
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83825872
downvote count: 0
has comment: http://stackoverflow.com/comment/83826029
duplicate of: http://stackoverflow.com/q/1463306
has comment: http://stackoverflow.com/comment/83825915
has comment: http://stackoverflow.com/comment/83825950
tagged with: exec

http://stackoverflow.com/q/48342384
has answer: http://stackoverflow.com/a/48351421
tagged with: reinforcement-learning
linked to: http://stackoverflow.com/q/37524472
upvote count: 2
answer count: 1
downvote count: 0
has title: Q-Learning Table converges to -inf
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/83672667
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/33011825
tagged with: q-learning
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83679259
tagged with: python
has body: I tried to solve the aigym mountain-car problem with my own q-learning implementation. After trying around different things it started to work really good, but after a while (20k Episodes * 1000 Samples per Episode) I noticed that my the values stored in my Q-table got to big and so it stored the value -inf. During the simulation I used to following code: for t in range(SAMPLE_PER_EPISODE): observation, reward, done, info = env.step(action) R[state, action] = reward history.append((state,action,reward)) max_indexes = np.argwhere(Q[state,] == np.amax(Q[state,])).flatten() action = np.random.choice(max_indexes) For learning I used the following code after each episode: #train latest_best = 0 total_reward = 0 for entry in reversed(history): Q[entry[0],entry[1]] = Q[entry[0],entry[1]] + lr * (entry[2] + latest_best * gamma) latest_best = np.max(Q[entry[0],:]) total_reward += entry[2] I got really good results with that algorithm but the problem was - as explained above - that the Q-Values went really fast to -inf I think I implemented the Q-Algorithm wrong, but after changing it to the following implementation, it doesn't work anymore (nearly as good as it did before): #train latest_best = 0 total_reward = 0 for entry in reversed(history): # Here I changed the code Q[entry[0],entry[1]] = Q[entry[0],entry[1]] + lr * (entry[2] + latest_best * gamma - Q[entry[0],entry[1]]) latest_best = np.max(Q[entry[0],:]) total_reward += entry[2] What am I doing wrong?
score: 2

http://stackoverflow.com/a/48480875
has body: Here's how it should look. This stops the code from initializing a new board object in each loop. def ref_scr(brd): cls() # Not sure what this is. It doesn't appear anywhere else. header() brd.display() if __name__ == "__main__": brd = Board() while True: ref_scr(brd) cell_in = int(input("enter cell between 1 and 9: ")) player = 'X' brd.update_cell(cell_in, player) Edit: Went ahead and changed the ref_scr func as well. This should now work.
has comment: http://stackoverflow.com/comment/83955001
type: Answer
has comment: http://stackoverflow.com/comment/83954862
accepted answer of: http://stackoverflow.com/q/48480786
score: 0
answers question: http://stackoverflow.com/q/48480786
has comment: http://stackoverflow.com/comment/83954979
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83955087

http://stackoverflow.com/q/48451231
tagged with: python
has answer: http://stackoverflow.com/a/48451374
possible better answer: http://stackoverflow.com/a/48451284
has body: Given the following df: Name Id v1 v2 v3 ... A 1 1 3 5 ... B 2 2 4 6 ... I want to apply these condition for the columns v1 to v3...: if value &lt;= 2 then a if 2&lt; value &lt;= 5 then b if value > 5 then c Name Id v1 v2 v3 ... A 1 a b b ... B 2 a b c ... I would use something like df[v1] = np.where(df[v1] &lt;= 2, a, np.where(df[v1] &lt;= 5, b, c)) then repeat the same for df[v2] df[v3]... Is there a more efficient way to handle this?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48451284
answer count: 3
accepted answer: http://stackoverflow.com/a/48451288
tagged with: pandas
tagged with: matrix
score: 1
has answer: http://stackoverflow.com/a/48451288
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Pandas apply if-then statement to a matrix df

http://stackoverflow.com/q/48361516
tagged with: google-cloud-datalab
has comment: http://stackoverflow.com/comment/83709979
tagged with: python
has body: I am trying to utilize the H2O package in a Jupyter notebook running in the Google Datalab hosted on GCP and am getting the error that Java isn’t installed. I’ve searched the documentation but haven’t found any solutions. Appreciate any ideas. Thanks
type: AnsweredQuestion
has title: Google Datalab: Java not installed
score: 0
has comment: http://stackoverflow.com/comment/83711286
has comment: http://stackoverflow.com/comment/83711271
has comment: http://stackoverflow.com/comment/83709887
tagged with: java
answer count: 1
accepted answer: http://stackoverflow.com/a/48387457
type: Question
has answer: http://stackoverflow.com/a/48387457

http://stackoverflow.com/comment/118853383
comment on: http://stackoverflow.com/a/48847588
type: AnswerComment
score: 0
has text: how can i convert .traineddata to tflite extension? thanks in advance
type: Comment

http://stackoverflow.com/q/48370588
has comment: http://stackoverflow.com/comment/83727962
has answer: http://stackoverflow.com/a/48370634
linked to: http://stackoverflow.com/q/16932825
score: 0
answer count: 1
has title: SyntaxError: non-default argument follows default argument; __init__ related
upvote count: 1
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/16932825
type: Question
has comment: http://stackoverflow.com/comment/83734547
type: UnansweredQuestion
tagged with: python
has body: This is my last resort. I've searched everywhere, but it's always pertaining to it being re-written by another function or something. I assure you there is no other function that uses this init thing. I'm a beginner. The error is that I get this: SyntaxError: non-default argument follows default argument. It points towards __init__([here]self, ...etcetc). class book: def __init__(self, bookId, nextBook=None, name, author, ageGroup): self.bookId = bookId self.nextBook = nextBook self.name = str(name) self.author = str(author) self.ageGroup = str(ageGroup) def getInfo(self): return self.bookdId def setInfo(self, bookId, bookName, authorName, ageGroup): self.bookId = bookId self.name = bookName self.author = authorName self.ageGroup = ageGroup def getNextBook(self): return self.nextBook def setNextBook(self,val): self.nextBook = val class bookCollection: def __init__(self,head = None): self.head = head self.size = 0 def getSize(self): return self.size def addBookToFront(self,bookId): newBook = book(bookId,self.head) self.head = newBook self.size+=1 return True def listAllBooks(self): curr = self.head while curr: print(curr.data) print(curr.name) curr = curr.getNextBook() def deleteBook(self,value): prev = None curr = self.head while curr: if curr.getInfo() == value: if prev: prev.setNextBook(curr.getNextBook()) else: self.head = curr.getNextBook() return True prev = curr curr = curr.getNextBook() return False def addBookAtPosition(self, newBookId, position): counter = 1 if position == 0: newBookId.setNextBook(self.head) self.head = newBookId else: book = self.head while book.getNextBook() is not None: if counter == position: newBookId.setNextBook(book.getNextBook()) book.setNextBook(newBookId) book = book.getNextBook() counter = counter + 1 def removeBookAtPosition(self, removedBookId, position): counter = 1 if position == 0: self.head = removedBookId.getNextBook() else: book = self.head while book.getNextBook() is not None: if counter == position - 1: book.setNextBook…

http://stackoverflow.com/q/48385165
favorite count: 0
has title: Web scraping using beautifulsoup, output keep varying
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83758186
has answer: http://stackoverflow.com/a/48387059
tagged with: django
has answer: http://stackoverflow.com/a/48385527
tagged with: python
has answer: http://stackoverflow.com/a/48386580
has body: I'm currently want to scrape the review from the website foursquare.com. I used the following code to do it url = "https://foursquare.com/v/pantai-klebang/4c7c12d22d3ba14318e595d0" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") containers = soup.findAll("li", {"class": "tip"}) filename = "review.csv" f = open(filename, 'w') for container in containers: review = container.find("div", {"class": "tipText"}).text print(review.decode('unicode_escape').encode('ascii','ignore')) I should get 144 data when I run the above code. Sometimes I get all of the data and sometime i get only 56 of the data Why does the output keep varying? Is it the issue with the code or the internet connectivity?
has comment: http://stackoverflow.com/comment/83758477
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/48386580
score: 1
possible better answer: http://stackoverflow.com/a/48385527
downvote count: 0
tagged with: web-scraping
upvote count: 1

http://stackoverflow.com/a/48431377
type: Answer
has body: The files argument is meant for file uploads. You probably want to use data instead here. r = requests.post( BASE_PATH + '/games/181/mods'.format(self.id), data = dict, headers = headers ) You get this error because requests expects the value of name_id to be a file pointer with a read() method. But in your payload it's None. And don't use dict as a variable name.
has comment: http://stackoverflow.com/comment/83858389
score: 1
answers question: http://stackoverflow.com/q/48431187
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83860775
type: AnswerComment
type: Comment
has text: Thank you! Makes perfect sense.
comment on: http://stackoverflow.com/a/48413539
score: 0

http://stackoverflow.com/a/48389354
has comment: http://stackoverflow.com/comment/83766450
has body: Could you post a more complete example? With what you have, the following works for me: a = {'0': 0, '1': 1, '10': 10, '2': 2, '3': 3, '4': 4} b = pd.Series(a).to_frame() b.index = map(int, b.index) # or pd.to_numeric(b.index) b.sort_index()
has comment: http://stackoverflow.com/comment/83767533
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48389141
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48389141
score: 2
has comment: http://stackoverflow.com/comment/83766939
downvote count: 0
has comment: http://stackoverflow.com/comment/83768499

http://stackoverflow.com/q/48342098
tagged with: anaconda
type: Question
has body: I have a Windows 10 PC with python anaconda installed. The latest anaconda version is v5.0.1 I would like to find out whether the PC has the latest version v5.0.1 installed and whether it is 32-bit/64bit or python 2.7/3.6. How do I do that? https://www.anaconda.com/download/
has comment: http://stackoverflow.com/comment/121585789
has comment: http://stackoverflow.com/comment/137624850
score: 83
tagged with: python
upvote count: 83
has answer: http://stackoverflow.com/a/52522740
accepted answer: http://stackoverflow.com/a/52522740
possible better answer: http://stackoverflow.com/a/48342205
has title: How to check python anaconda version installed on Windows 10 PC?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48342205
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/61133190
favorite count: 0

http://stackoverflow.com/a/48405017
has comment: http://stackoverflow.com/comment/83803689
has comment: http://stackoverflow.com/comment/83798866
type: Answer
has comment: http://stackoverflow.com/comment/83803347
has comment: http://stackoverflow.com/comment/83803803
accepted answer of: http://stackoverflow.com/q/48404881
upvote count: 19
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48404881
score: 19
has comment: http://stackoverflow.com/comment/83798693
has body: Python converts all identifiers to their NFKC normal form; from the Identifiers section of the reference documentation: All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC. The NFKC form of both the super and subscript characters is the lowercase u: &gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.normalize('NFKC', 'Xᵘ Xᵤ') 'Xu Xu' So in the end, all you have is a single identifier, Xu: &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile('Xᵘ = 42\nprint((Xu, Xᵘ, Xᵤ))', '', 'exec')) 1 0 LOAD_CONST 0 (42) 2 STORE_NAME 0 (Xu) 2 4 LOAD_NAME 1 (print) 6 LOAD_NAME 0 (Xu) 8 LOAD_NAME 0 (Xu) 10 LOAD_NAME 0 (Xu) 12 BUILD_TUPLE 3 14 CALL_FUNCTION 1 16 POP_TOP 18 LOAD_CONST 1 (None) 20 RETURN_VALUE The above disassembly of the compiled bytecode shows that the identifiers have been normalised during compilation; this happens during parsing, any identifiers are normalised when creating the AST (Abstract Parse Tree) which the compiler uses to produce bytecode. Identifiers are normalized to avoid many potential 'look-alike' bugs, where you'd otherwise could end up using both ﬁnd() (using the U+FB01 LATIN SMALL LIGATURE FI character followed by the ASCII nd characters) and find() and wonder why your code has a bug.

http://stackoverflow.com/q/48419373
upvote count: 2
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
has body: i want to know how i can display a vertical header in a tableview. The vertical header should display the index. I've created a dataframe of stock prices. The date is the index of the dataframe (i.e. 2017-12-06) and the close price is the value of the dataframe (i.e. 50$). I wrote a model class that uses the QAbstractTabelModel. My headerData method is the following: def headerData(self, rowcol, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return self._data.columns[rowcol] if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return self._data.index[rowcol] return None But there is no index in the displayed tableview. Screenshot of the displayed TableView The whole source code is the following: from PyQt5 import QtCore class PandasModel(QtCore.QAbstractTableModel): def __init__(self, data, parent=None): QtCore.QAbstractTableModel.__init__(self, parent) self._data = data def rowCount(self, parent=None): return len(self._data.values) def columnCount(self, parent=None): return self._data.columns.size def data(self, index, role=QtCore.Qt.DisplayRole): if index.isValid(): if role == QtCore.Qt.DisplayRole: return str(self._data.values[index.row()][index.column()]) return None def headerData(self, rowcol, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return self._data.columns[rowcol] if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return self._data.index[rowcol] return None I have the code from stackoverflow reference Edit: My dataframe sourcecode attachement dates = pd.date_range(start_date, end_date) df = pd.DataFrame(index=dates) df_temp = pd.read_csv(directory, index_col='Date', parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan']) df = df.join(df_temp) df = df.dropna(axis=0, how='any') return df Edit 2: Screenshot of the csv file
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83873499
accepted answer: http://stackoverflow.com/a/48443262
has comment: http://stackoverflow.com/comment/83832825
has answer: http://stackoverflow.com/a/48443262
tagged with: python
has comment: http://stackoverflow.com/comment/83866160
has comment: http://stackoverflow.com/comment/83875491
linked to: http://stackoverflow.com/q/31475965
has title: PyQt display tableview vertical header of dataframe
type: AnsweredQuestion
score: 2
tagged with: pandas

http://stackoverflow.com/q/48356671
has body: Here I have films grouped by year, but I need to have a year value filled for each film respectively. Could you please suggest how can I do that? cast.groupby(['year','name']).size() year name 1894 Blanche Bayliss 1 Chauncey Depew 1 William Courtenay 1 1900 Orrie Perry 1 Reg Perry 1 1905 Armand Dranem 1 1906 Battling Nelson 1 E.J. Tait 1 Elizabeth Tait 1 Frank (VI) Mills 1 Frank Tait 1 Helfrid Lambert 1 Jack (II) Ennis 1 Joe Gans 1 John (III) Forde 1 John Tait 1 Knut Lambert 1 Mr. Marshall 1 Mr. McKenzie 1 Norman (II) Campbell 1 Sam Crewes 1 Tollie Zellman 1 Will Coyne 1 1907 Arthur Guest 1 Thanks!
accepted answer: http://stackoverflow.com/a/48356777
tagged with: python
linked to: http://stackoverflow.com/q/20110170
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/20110170
tagged with: pandas
has answer: http://stackoverflow.com/a/48356777
answer count: 1
has title: Groupby transformation
type: Question

http://stackoverflow.com/q/48372019
has answer: http://stackoverflow.com/a/49223210
has comment: http://stackoverflow.com/comment/83731226
has answer: http://stackoverflow.com/a/48474539
score: 32
downvote count: 0
has answer: http://stackoverflow.com/a/51051124
answer count: 6
has body: I update the Jupyter notebook from the old version to latest 5.3.1. However, when I try to launch the notebook from anaconda, it throws an import error: I tried to remove and install Jupyter package, still, the issue persists. Traceback (most recent call last): File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\__init__.py", line 25, in from .nbextensions import install_nbextension File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\nbextensions.py", line 27, in from jupyter_core.utils import ensure_dir_exists ImportError: cannot import name 'ensure_dir_exists'
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48474539
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48373567
has answer: http://stackoverflow.com/a/49156585
has title: ImportError: cannot import name 'ensure_dir_exists'
has answer: http://stackoverflow.com/a/48373567
tagged with: python
upvote count: 32
has answer: http://stackoverflow.com/a/49644389
tagged with: jupyter-notebook

http://stackoverflow.com/a/48418143
upvote count: 2
has comment: http://stackoverflow.com/comment/83854109
has body: Use strptime: import datetime today = datetime.datetime.now().date() parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date() print(today &lt; parsed) # True
has comment: http://stackoverflow.com/comment/83826063
score: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48417802

max
tags question: http://stackoverflow.com/q/48440514
tags question: http://stackoverflow.com/q/48397061
tags question: http://stackoverflow.com/q/48433694
tags question: http://stackoverflow.com/q/48454918
tags question: http://stackoverflow.com/q/48412362
tag name: max
tags question: http://stackoverflow.com/q/48355809
type: Tag

http://stackoverflow.com/q/48331449
tagged with: rest
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51223137
score: 0
tagged with: mongodb
answer count: 1
has body: Following the Basic Usage example at http://django-rest-elasticsearch.readthedocs.io/en/latest/ from app.serializers import BlogSerializer from app.models import Blog from rest_framework_elasticsearch import (es_views, es_client, es_pagination, es_filters) from .search_indexes import BlogIndex class BlogView(es_views.ListElasticAPIView): es_client = es_client es_model = BlogIndex es_pagination_class = es_pagination.ElasticLimitOffsetPagination es_filter_backends = ( es_filters.ElasticFieldsFilter, es_filters.ElasticFieldsRangeFilter, es_filters.ElasticSearchFilter, es_filters.ElasticOrderingFilter, ) es_ordering = 'created_at' es_filter_fields = ( es_filters.ESFieldFilter('tag', 'tags'), ) es_range_filter_fields = ( es_filters.ESFieldFilter('created_at', 'created_at'), ) es_search_fields = ( 'tags', 'title', ) Gives me the stacktrace: `Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x10de071e0&gt; Traceback (most recent call last): File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Users/andrew/projects/drfmonoengine/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.u…
type: Question
has title: MongoDB with Django Rest Elasticsearch?

http://stackoverflow.com/comment/83861485
type: Comment
comment on: http://stackoverflow.com/a/48423573
score: 0
type: AnswerComment
has text: If possible, do you have any similar demo for real image. Thanks Tonechas alots.

http://stackoverflow.com/a/48418849
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48411386
score: 6
downvote count: 0
has body: If you download the API from the official website and you the zip file, you will find an "examples" folder which has plenty of examples. Then there's the core developer guide if you need help on the schemas.
answers question: http://stackoverflow.com/q/48411386
type: Answer
has comment: http://stackoverflow.com/comment/83861166
has comment: http://stackoverflow.com/comment/132732262
upvote count: 6
has comment: http://stackoverflow.com/comment/138669686

http://stackoverflow.com/a/61825907
answers question: http://stackoverflow.com/q/48465737
has body: The GMM module's score_sample from sklearn gives the probability density and they won't sum to 0, rather integrate to 1. data = 10 * np.random.rand(100) model = mixture.GMM(n_components=1).fit(data[:, None]) xfit = np.linspace(-5, 15, 5000) logprob, _ = model.score_samples(xfit[:, None]) dx = xfit[1] - xfit[0] print(dx * np.sum(np.exp(logprob))) # 0.999773872653 You can also calculate the probability of a data point belonging to a multivariate normal distribution., Source: https://github.com/scikit-learn/scikit-learn/issues/4202
type: Answer
upvote count: 4
score: 4
downvote count: 0

http://stackoverflow.com/a/48444272
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48444067
type: Answer
has body: One easy solution is check only in strings before last /: df = pd.DataFrame({'SOURCEURL':['http://au/news/nat/cit/news-story/b2ecb', 'http://au/news/nat/cit/news-story/b2d88ecb494']}) print (df) SOURCEURL 0 http://au/news/nat/cit/news-story/b2ecb 1 http://au/news/nat/cit/news-story/b2d88ecb494 filter3 = ['ecb'] df['new'] = (df['SOURCEURL'].str.rsplit('/', 1).str[0] .str.extract("(" + "|".join(filter3) +")", expand=False)) Another similar solution: filter3 = ['ecb'] df['new'] = (df['SOURCEURL'].str.extract('(.*)/', expand=False) .str.extract("(" + "|".join(filter3) +")", expand=False)) print (df) SOURCEURL new 0 http://au/news/nat/cit/news-story/b2ecb NaN 1 http://au/news/nat/cit/news-story/b2d88ecb494 NaN
accepted answer of: http://stackoverflow.com/q/48444067

http://stackoverflow.com/comment/83776245
score: 1
has text: @sudonym Yes, because it doesn't take `Item` into account. Add an extra row: `Bike 2` and try this again.
comment on: http://stackoverflow.com/a/48394338
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83652439
score: 0
has text: @MatteoT. Probably not.
type: Comment
comment on: http://stackoverflow.com/q/48333346
type: QuestionComment

http://stackoverflow.com/comment/83683920
type: Comment
comment on: http://stackoverflow.com/q/48347849
score: 0
type: QuestionComment
has text: Please provide some data, then it is easier to help. And also change the tag, this is a pandas not a scipy question.

http://stackoverflow.com/comment/83721396
has text: @Esha You should replace `super()` with something python2. I've updated above code to work with python2.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48367244
type: AnswerComment

http://stackoverflow.com/comment/132860568
has text: See my answer with a reasonable alternative that works: https://stackoverflow.com/a/75275031/95750
type: Comment
comment on: http://stackoverflow.com/a/54764354
type: AnswerComment
score: 1

http://stackoverflow.com/comment/83801717
comment on: http://stackoverflow.com/q/48404874
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Getting value from radiobox in Tkinter - Python](https://stackoverflow.com/questions/6547355/getting-value-from-radiobox-in-tkinter-python)

http://stackoverflow.com/q/48353565
score: 0
has body: I am trying to make a program that will get and input from the user, place it in an array and then call a function with those 3 values where the calculation will be performed, however I seem to get the following two errors: Traceback (most recent call last): File "..\Playground\", line 14, in quad(p1,p2,p3) File "..\Playground\", line 7, in quad print("Solution 1: " + res1 + "Solution 2: " + res2) TypeError: Can't convert 'complex' object to str implicitly Here is the entire code: import cmath def quad(a,b,c): r = (b ** 2 - 4 * a * c) res1 = ((-b) + cmath.sqrt(r))/2 res2 = ((-b) - cmath.sqrt(r))/2 print("Solution 1: " + res1 + "Solution 2: " + res2) nums = input() param = nums.split() p1 = float(param[0]) p2 = float(param[1]) p3 = float(param[2]) quad(p1,p2,p3)
linked to: http://stackoverflow.com/q/29375970
has comment: http://stackoverflow.com/comment/83693686
has comment: http://stackoverflow.com/comment/83693674
answer count: 1
accepted answer: http://stackoverflow.com/a/48353749
type: Question
has comment: http://stackoverflow.com/comment/83693702
has answer: http://stackoverflow.com/a/48353749
has comment: http://stackoverflow.com/comment/83693795
tagged with: python
has comment: http://stackoverflow.com/comment/83693655
type: AnsweredQuestion
has title: TypeError: Can't convert 'complex' object to str implicitly error quadratic formula function (python)

http://stackoverflow.com/comment/135778620
has text: @user343233 no i don't mean the behavior of `to` the answer is clear if you train on `cpu` there will be memory sharing , if you train on `GPU` there will be not. `device` and `to` not the focus since all the data have to be moved to gpu if you want to train on it even if you set it as default.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/72680694
type: AnswerComment

http://stackoverflow.com/a/48447589
answers question: http://stackoverflow.com/q/48447123
has body: The strptime function (in its various incarnations) isn't designed to perform this sort of task, it's just for parsing valid time / date strings. The simple solution is to write your own code to parse the string and perform the arithmetic. Here's an example that outputs seconds; obviously you can divide by 60 to get minutes. def hms_to_s(s): t = 0 for u in s.split(':'): t = 60 * t + int(u) return t data = ( '10', '0:10', '1:30', '2:1:00', '1000:00:00', '9700:00:00', '15:56:46', '9715:56:46', ) for s in data: print(s, hms_to_s(s)) output 10 10 0:10 10 1:30 90 2:1:00 7260 1000:00:00 3600000 9700:00:00 34920000 15:56:46 57406 9715:56:46 34977406
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48447434
has title: Password check(strong or weak)
has comment: http://stackoverflow.com/comment/83887291
has comment: http://stackoverflow.com/comment/83887487
tagged with: python
has answer: http://stackoverflow.com/a/48447585
answer count: 4
has answer: http://stackoverflow.com/a/48447559
downvote count: 0
score: 1
upvote count: 1
tagged with: function
has comment: http://stackoverflow.com/comment/83887388
has answer: http://stackoverflow.com/a/48447597
has body: Write a function that determines whether or not a password is good. We will define a good password to be a one that is at least 8 characters long and contains at least one uppercase letter, at least one lowercase letter, and at least one number. import string num = [i for i in range(0,10)] letdown = list(string.ascii_lowercase) letup = list(string.ascii_uppercase) def good_password(password): l1=[] l2=[] l3=[] for char in password: if char in num: l1.append(char) elif char in letdown: l2.append(char) elif char in letup: l3.append(char) if len(l1)&gt;=1 and len(l2) &gt;=1 and len(l3) &gt;=1 and len(password) &gt;=8: return True else: return False This is the code that I've come up with. However, it doesn't seems to work and I cannot tell why. Can anyone explain me? I am still a novice in programming.
has answer: http://stackoverflow.com/a/48447724
has comment: http://stackoverflow.com/comment/83887940
favorite count: 0
type: Question
tagged with: passwords
has comment: http://stackoverflow.com/comment/83887251
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83887572

http://stackoverflow.com/q/48477317
has answer: http://stackoverflow.com/a/48477354
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/7053652
linked to: http://stackoverflow.com/q/7664779
possible better answer: http://stackoverflow.com/a/48477347
upvote count: 3
has comment: http://stackoverflow.com/comment/83947842
has answer: http://stackoverflow.com/a/48477347
downvote count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/48477339
type: Question
has answer: http://stackoverflow.com/a/48477363
has answer: http://stackoverflow.com/a/48477339
has body: Why do I get None after each result of the print statement? I have never come across this while using the print statement or class instantiation... Where is None coming from? ​ class Enemy: life = 3 def attack(self): print("ouch!") self.life -= 1 def checkLife(self): if (self.life &lt;= 0): print('dead!') else: print( str(self.life) + " lives left..." ) e1 = Enemy() print( e1.checkLife() ) # 3 lives left... # None print( e1.attack() ) # ouch! # None print( e1.checkLife() ) # 2 lives left... # None
answer count: 5
linked to: http://stackoverflow.com/q/7053652
tagged with: python
has title: None after printing instance variables
has answer: http://stackoverflow.com/a/48477431

http://stackoverflow.com/comment/83856827
type: Comment
score: 3
type: QuestionComment
has text: The [official Django documentation](https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/) shows you the configuration. If you don't get it to work, show us your *.conf* files
comment on: http://stackoverflow.com/q/48432664

file-type
tag name: file-type
tags question: http://stackoverflow.com/q/48346752
type: Tag

linux
tags question: http://stackoverflow.com/q/48398253
tags question: http://stackoverflow.com/q/48433985
tags question: http://stackoverflow.com/q/48451507
tags question: http://stackoverflow.com/q/48449126
tags question: http://stackoverflow.com/q/48402623
tags question: http://stackoverflow.com/q/48469817
tag name: linux
tags question: http://stackoverflow.com/q/48486240
tags question: http://stackoverflow.com/q/48452316
tags question: http://stackoverflow.com/q/48449895
tags question: http://stackoverflow.com/q/48404347
tags question: http://stackoverflow.com/q/48373118
tags question: http://stackoverflow.com/q/48417818
tags question: http://stackoverflow.com/q/48466626
tags question: http://stackoverflow.com/q/48377637
tags question: http://stackoverflow.com/q/48333680
tags question: http://stackoverflow.com/q/48372449
tags question: http://stackoverflow.com/q/48446461
tags question: http://stackoverflow.com/q/48474742
tags question: http://stackoverflow.com/q/48407093
tags question: http://stackoverflow.com/q/48397845
tags question: http://stackoverflow.com/q/48355388
tags question: http://stackoverflow.com/q/48398211
tags question: http://stackoverflow.com/q/48390361
tags question: http://stackoverflow.com/q/48465649
tags question: http://stackoverflow.com/q/48389406
tags question: http://stackoverflow.com/q/48421988
tags question: http://stackoverflow.com/q/48441559
tags question: http://stackoverflow.com/q/48474398
tags question: http://stackoverflow.com/q/48431413
tags question: http://stackoverflow.com/q/48446037
tags question: http://stackoverflow.com/q/48392773
type: Tag
tags question: http://stackoverflow.com/q/48356946
tags question: http://stackoverflow.com/q/48456590
tags question: http://stackoverflow.com/q/48416016
tags question: http://stackoverflow.com/q/48397522
tags question: http://stackoverflow.com/q/48476162
tags question: http://stackoverflow.com/q/48422037
tags question: http://stackoverflow.com/q/48429110
tags question: http://stackoverflow.com/q/48482415
tags question: http://stackoverflow.com/q/48467380
tags question: http://stackoverflow.com/q/48460140
tags question: http://stackoverflow.com/q/48484240

http://stackoverflow.com/comment/83958563
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48480570
type: Comment
has text: Thanks for the clarification @VivekKumar.

http://stackoverflow.com/q/48353899
linked to: http://stackoverflow.com/q/44397105
has title: How to plot triangles using coordinates in python?
score: 0
duplicate of: http://stackoverflow.com/q/44397105
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have some sample coordinates like (0,0) (0,1) (1,0). how can i Plot multiple triangles in a same graph in python using coordinates only ?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48354257
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83738049
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48375511
has text: For starters, your code is incorrectly indented. Please fix the indentation.
score: 0

http://stackoverflow.com/comment/83967070
has text: @vildhjarta: A subclass inherits the *implementation*. Registration only makes a statement that the right methods are present and implemented correctly.
score: 0
comment on: http://stackoverflow.com/a/48431082
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83869541
score: 0
comment on: http://stackoverflow.com/q/48437286
type: Comment
type: QuestionComment
has text: it's the last layer of pretrained model, which is listed as "embeddings:0 shape=(?, 128)"

http://stackoverflow.com/a/48400777
answers question: http://stackoverflow.com/q/48400760
has body: Use boolean indexing with s.index: print (s.index[s]) Index(['b', 'd'], dtype='object') print (s.index[s].tolist()) ['b', 'd'] print (', '.join(s.index[s])) b, d A bit overcomplicated solution with np.where, for fun: print (s.index[np.where(s)[0]]) Index(['b', 'd'], dtype='object')
type: Answer
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48400760
upvote count: 2

http://stackoverflow.com/comment/84134294
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48464565
has text: Not a direct solution for your problem, but you may find an alternative approach here: http://dask.pydata.org/ Dask promises to enable parallel computation on dataframe-like objects larger than memory.

iterator
tags question: http://stackoverflow.com/q/48475888
tag name: iterator
tags question: http://stackoverflow.com/q/48375250
tags question: http://stackoverflow.com/q/48403504
type: Tag

http://stackoverflow.com/comment/83755651
score: 0
type: Comment
type: QuestionComment
has text: But how do I get the element xpath?
comment on: http://stackoverflow.com/q/48381258

http://stackoverflow.com/comment/83797952
type: Comment
has text: @umairbutt if this is the correct answer, it should be accepted.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48394087

http://stackoverflow.com/comment/83931709
has text: you could download it and install it manually. wheels are zip files. I've done that a lot of times
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48468975
score: 0

http://stackoverflow.com/comment/83861121
has text: Welcome to SO, please take the time to read [How to Ask](https://stackoverflow.com/questions/how-to-ask)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48434720
score: 0

http://stackoverflow.com/comment/83906036
comment on: http://stackoverflow.com/a/48456267
type: Comment
score: 1
type: AnswerComment
has text: This doesn't answer the question and the question is not about that.

computer-vision
tags question: http://stackoverflow.com/q/48385926
tags question: http://stackoverflow.com/q/48449847
tags question: http://stackoverflow.com/q/48464281
tags question: http://stackoverflow.com/q/48457690
tags question: http://stackoverflow.com/q/48409525
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/48355891

http://stackoverflow.com/comment/83654967
comment on: http://stackoverflow.com/q/48334572
type: QuestionComment
has text: I see. In that case, wouldn't it be better converting everything to ONLY NaNs, or ONLY empty string columns? Why two different things for different data?
score: 0
type: Comment

http://stackoverflow.com/q/48406442
score: 0
tagged with: bash
has body: Given this program named foo.py #! /usr/bin/env python foo = input('input foo: ') print(foo) How do I run this from foo_test.sh?
answer count: 1
has answer: http://stackoverflow.com/a/48406464
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Providing data to Python input() from Bash
tagged with: python

http://stackoverflow.com/comment/83901666
comment on: http://stackoverflow.com/q/48454312
type: Comment
score: 3
type: QuestionComment
has text: How to create a Minimal, Complete, and Verifiable example: https://stackoverflow.com/help/mcve

aggregation-framework
tags question: http://stackoverflow.com/q/48349052
type: Tag
tag name: aggregation-framework
tags question: http://stackoverflow.com/q/48402629
tags question: http://stackoverflow.com/q/48355264

http://stackoverflow.com/a/48465222
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48465027
has body: simply try the line below or use dict update data["new key"] = "some new entry"

google-cloud-platform
tags question: http://stackoverflow.com/q/48409782
tags question: http://stackoverflow.com/q/48437722
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/48413676
tags question: http://stackoverflow.com/q/48480396
tags question: http://stackoverflow.com/q/48449299
tags question: http://stackoverflow.com/q/48449537
tags question: http://stackoverflow.com/q/48389768
tags question: http://stackoverflow.com/q/48386148
tags question: http://stackoverflow.com/q/48459712
type: Tag

http://stackoverflow.com/comment/83656757
has text: Never mind. Before I bother you more, let me do some tests and try to narrow down the problem. Thank you for your help. I partially solved the problem.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48334698

pyopenssl
tag name: pyopenssl
type: Tag
tags question: http://stackoverflow.com/q/48345735
tags question: http://stackoverflow.com/q/48430239

http://stackoverflow.com/q/48335126
has title: Issue around connecting to a MySQL database table
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48335198
has body: I have some code which tries to connect to a mySQL database and retrieve a query. The connection code is in a module called connection and looks like: #!/usr/bin/env python3 import pandas as pd import pymysql from sqlalchemy import create_engine COMPANY_SERVER = create_engine( 'mysql+pymysql://view_user:connectiondetails') def read_sql(query): return pd.read_sql_query(query, COMPANY_SERVER) I have omitted the connection details for security. But this connection has worked in the past. I am trying to connect and query a database table (which is pulled in with variable name table) and trying returning a DESCRIBE of the table in the following way: #!/usr/bin/env python3 import datetime as dt import numpy as np import pandas as pd from copy import copy import pymysql from sql.connection import read_sql class DBSnapData(object): def __init__(self, start_dt, end_dt, start_point, end_point, variables, table, stock_id ): self.start_dt = start_dt self.end_dt = end_dt self.start_point = start_point self.end_point = end_point self.variables = variables self.table = table self.stock_id = stock_id self.schema = self.load_schema() def load_schema(self): return run_schema_sql_query(self.table) def run_schema_sql_query(table): return read_sql('DESCRIBE %s' % table) I am getting the following error output: 2018-01-17 22:34:02,717 (pymysql.err.OperationalError) (1142, "SELECT command denied to user 'view_user'@'192.168.9.132' for table 'TBL_MKTDATA_SNAPS_AUS'") [SQL: 'DESCRIBE TBL_MKTDATA_SNAPS_AUS'] Traceback (most recent call last): File "/usr/local/lib64/python3.5/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib64/python3.5/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) File "/usr/local/lib/python3.5/site-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.5/site-packages/pymysql/cursors.py", line 322, in _query c…
score: 0
has comment: http://stackoverflow.com/comment/83655390
answer count: 1

http://stackoverflow.com/a/48449404
type: Answer
upvote count: 10
accepted answer of: http://stackoverflow.com/q/48448863
has body: Try This: (self.Lines = json.load(open("Data/Lines.json","rb"), encoding="utf-8")) The difference is loading the file in bytes and reading it in utf-8 format (assuming that's the file format).
has comment: http://stackoverflow.com/comment/83891787
answers question: http://stackoverflow.com/q/48448863
type: AcceptedAnswer
downvote count: 0
score: 10

http://stackoverflow.com/q/48463648
has title: convolution matrix filter size vs channel length
tagged with: conv-neural-network
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83923549
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48469687
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83923071
has comment: http://stackoverflow.com/comment/83923529
has body: I am a beginner in computer vision. what I would like to know the relationship between the size of the filter and channel over the output image My aim is to understand the various relation that connect the size and the channels with the Convolutional Neural Network I am using tensorflow library , i have found an example that apply CNN on cifar 10 data-set , data-set consists of :- data -- a 10000x3072 numpy array of uint8s. Each row of the array stores a 32x32 colour image. The first 1024 entries contain the red channel values, the next 1024 the green, and the final 1024 the blue. The image is stored in row-major order, so that the first 32 entries of the array are the red channel values of the first row of the image. labels -- a list of 10000 numbers in the range 0-9. The Code: import tensorflow as tf X = tf.placeholder(tf.float32,shape=[None,32,32,3]) y_true = tf.placeholder(tf.float32,shape=[None,10]) hold_prob = tf.placeholder(tf.float32) # Helper Functions def init_weight(shape,name_W): init_rand_dist = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(init_rand_dist,name=name_W) # init bais def init_bias(shape, name_b): init_bias_vals = tf.constant(value=0.1,shape=shape) return tf.Variable(init_bias_vals,name=name_b) # convolution 2d # Conv2D def conv2d(X,W,name_conv): # X --&gt; [batch,H,W,Channels] # W --&gt; [filter H , filter W , Channel In , Channel Out] return tf.nn.conv2d(X,W,strides=[1,1,1,1],padding='SAME',name=name_conv) # convolutional Layer with activation and bais # Convolutional Layes def convolutional_layer(input_x, shape,name_W,name_b,name_conv): W = init_weight(shape = shape,name_W=name_W) b = init_bias(shape = [shape[3]],name_b = name_b) return tf.nn.relu(conv2d(input_x,W, name_conv =name_conv) + b ) # pooling layer # Pooling def max_pooling_2by2(X): # X --&gt; [batch,H,W,Channels] return tf.nn.max_pool(X,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') # Fully connected Layer # Normal Layer (fully connected Layer) def normal_full_lay…

http://stackoverflow.com/q/48461971
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83917140
tagged with: flask
has comment: http://stackoverflow.com/comment/83917027
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83916985
type: UnansweredQuestion
tagged with: python
has title: ModuleNotFoundError: No module named 'flask_Moment'
has body: Why do i get an error when i try to import a flask extension but when i run the app i get the ModuleNotFoundError i am running flask versionFlask== 0.12.2 this is the app from flask import Flask,request,render_template,send_from_directory from flask_moment import Moment app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True) i then run py -3 app.py using my virtual environment and these are the results (venv1) PS D:\2. Design\Web\FlaskApp\apps\tut1&gt; py -3 app.py Traceback (most recent call last): File "app.py", line 2, in &lt;module&gt; from flask_moment import Moment ModuleNotFoundError: No module named 'flask_moment' (venv1) PS D:\2. Design\Web\FlaskApp\apps\tut1&gt; maybe just to show you the modules i have installed pip freeze returns (venv1) PS D:\2. Design\Web\FlaskApp\apps\tut1&gt; pip freeze click==6.7 dominate==2.3.1 Flask==0.12.2 Flask-Bootstrap==3.3.7.1 Flask-Moment==0.6.0 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 visitor==0.1.3 Werkzeug==0.14.1
score: 2
has answer: http://stackoverflow.com/a/48484931
upvote count: 2

http://stackoverflow.com/a/48436888
has comment: http://stackoverflow.com/comment/83904563
has comment: http://stackoverflow.com/comment/83865127
has comment: http://stackoverflow.com/comment/83868672
has comment: http://stackoverflow.com/comment/83865568
has comment: http://stackoverflow.com/comment/83865087
accepted answer of: http://stackoverflow.com/q/48436712
has comment: http://stackoverflow.com/comment/83865022
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48436712
has body: The major flaw with your proposal is that importing your module will cause the entire interpreter to exit. This means you can't import your module at all. If you try, the program will terminate. Generally the purpose of the if __name__ == "__main__" block is to allow the module to be imported so you can use functions, classes, etc. inside it. This purpose is defeated by having the module exit when imported. In addition, having the "extra indent" for the body of main is not just wasting line space. The body of main will be indented because it is the body of a function, and that function, like any other, can be called from elsewhere if the module is imported. This means someone else can import your module without running main, but later call main explicitly if they want.
has comment: http://stackoverflow.com/comment/83865231
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83865186

http://stackoverflow.com/comment/85363903
has text: It looks like you are timing network access? That's going to vary dramatically based on a lot of factors, most of which have nothing to do with your machine, let alone Python, Jupyter or Visual Studio.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48467587

http://stackoverflow.com/comment/83930627
type: QuestionComment
score: 0
has text: @needalittlehelp Update your last comment details within the question. These bytes may be helpful in constructing an answer.
comment on: http://stackoverflow.com/q/48467961
type: Comment

http://stackoverflow.com/q/48343822
tagged with: date
has title: Sort dates through file name date
has comment: http://stackoverflow.com/comment/83776069
has answer: http://stackoverflow.com/a/48344282
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83673415
upvote count: 1
has body: I have a folder with *.txt files which contain a specific format (c is character and d is digit and yyyy-mm-dd-hh-mm-ss is the date format) cccccd_ddd_cc_ccc_c_dd-ddd_yyyy-mm-dd-hh-mm-ss.txt or cccccd_ddd_cc_ccc_c_dd-dddd_yyyy-mm-dd-hh-mm-ss.txt or cccccd_ddd_cc_ccc_c_d_yyyy-mm-dd-hh-mm-ss.txt when the single digidt d is equal to 0 I would like to create a python script to obtain the dates and sort the files from that specific date. SO far I ahve done import os list_files=[] for file in os.listdir(): if file.endswith(".txt"): #print(file) list_files.append(file) But I am bit new with regular expressions. Thanks
tagged with: sorting
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/77586398
score: 1
tagged with: python

http://stackoverflow.com/q/48384986
score: 2
has answer: http://stackoverflow.com/a/48386099
answer count: 3
tagged with: widget
has comment: http://stackoverflow.com/comment/83757312
tagged with: children
has title: Accessing child widgets of a window by their names?
has comment: http://stackoverflow.com/comment/83825035
has body: Is there any way in Python/tkinter to access child elements referring by their variable names, but from an other function? For example in VBA, it is possible to directly refer to an element of an other window by its name. For example if I have two windows, UserForm1 and UserForm2 I can change the text value of Label1 of UserForm2 by clicking a button on UserForm1. Private Sub CommandButton1_Click() UserForm2.Label1.Caption = "Changed" End Sub In tkinter I have found the winfo_children() to access child elements. Is there any way to access them by their names? See my sample code below: import tkinter from tkinter import * #---------------------------------------------------------------------- def new(parent_window): """""" parent_window.withdraw() global main_window global new_window new_window = tkinter.Tk() new_window.title("My App - New") label1 = tkinter.Label(new_window, text="NEW") label1.grid(row=0,column=0,columnspan=3,pady=10,padx=10, sticky="nsw") b1 = tkinter.Button(new_window, text="Change It", command=lambda: showdashboard(new_window)) b1.grid(row=4,column=1,padx=20,pady=10,sticky="nwse") b2 = tkinter.Button(new_window, text="Quit", command=lambda: quit()) b2.grid(row=5,column=1,padx=20,pady=10,sticky="nwse") #---------------------------------------------------------------------- def dashboard(parent_window): """""" parent_window.withdraw() global main_window global dashboard_window dashboard_window = tkinter.Tk() dashboard_window.title("My App - Dashboard") label1 = tkinter.Label(dashboard_window, text="Dashboard") label1.grid(row=0,column=0,columnspan=3,pady=10,padx=10, sticky="nsw") b1 = tkinter.Button(dashboard_window, text="New", command=lambda: new(dashboard_window)) b1.grid(row=4,column=1,padx=20,pady=10,sticky="nwse") #---------------------------------------------------------------------- def showdashboard(parent_window): """""" parent_window.withdraw() dashboard_window.update() dashboard_window.deiconify() #This way it works &lt;&lt;&lt;&lt;&lt;…
type: Question
linked to: http://stackoverflow.com/q/30004505
has comment: http://stackoverflow.com/comment/127100626
linked to: http://stackoverflow.com/q/71902896
tagged with: tkinter
has answer: http://stackoverflow.com/a/61029093
has answer: http://stackoverflow.com/a/48385894
has comment: http://stackoverflow.com/comment/83757589
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/83947074
score: 3
type: QuestionComment
has text: Why don't you want to define the model (without any conditionals) and tweak your logic in such way that the instances of `ConsumerRegistration` are only created when the `'CONSUMER_REGISTRATION'` is set to True? Because running migrations every single time you change the flag doesn't seem to be the right way to do that
comment on: http://stackoverflow.com/q/48476900
type: Comment

http://stackoverflow.com/comment/83935374
comment on: http://stackoverflow.com/q/48470228
type: Comment
type: QuestionComment
has text: Use str(msg) instead msg in your format string
score: 0

http://stackoverflow.com/comment/83950027
type: Comment
comment on: http://stackoverflow.com/q/48478357
has text: Show your latest code attempt and specify in reference to the code what are you believe the problem lies. The community can then point you in the right direction based on the work you have already started.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83886577
comment on: http://stackoverflow.com/q/48445616
score: 0
has text: thanks it works with colorama
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83813422
type: Comment
type: QuestionComment
score: 0
has text: @Pushk1n Every type has a `__str__` method, and it's responsible for figuring out how those values should be represented as strings.
comment on: http://stackoverflow.com/q/48411539

http://stackoverflow.com/comment/139087088
type: Comment
type: QuestionComment
has text: *"Obviously, one solution is"* - No, obviously that doesn't even work at all.
score: 0
comment on: http://stackoverflow.com/q/48412699

http://stackoverflow.com/q/48353031
has body: from datetime import datetime import datetime import calendar import locale locale.setlocale(locale.LC_ALL, 'srb_srb') def main(): days = list(calendar.day_name) day = input("Input day:") if day in days: print(day) print (days) else: print("Error") main() (this is just experimental code) First I just tryed to print list of days on Serbian. But, when I run the code it print this: ['?????????', '??????','?????','????????','?????','??????','??????'] It's probably because local is on Serbian cyrilic so it's should probably looks like this: ['понедељак','уторак','среда','четвртак','петак','субота','недеља'] But I have to check is inputed day is the same as in text file where days are writen on serbian latin, so is there any way to convert cyrilic to latin? If I input, for example, понедељак in cmd on Serbian cyrilic just to check does my experimental code work it prints ????????? ['?????????', '??????','?????','????????','?????','??????','??????'] *понедељак len = 9 ????????? len = 9* I need some universal solution, because user probably would not run this code on my computer. :D
tagged with: calendar
type: Question
tagged with: setlocale
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/83693614
score: 0
has comment: http://stackoverflow.com/comment/83693443
answer count: 0
has title: Python set locale

http://stackoverflow.com/a/48425218
type: Answer
has body: you can use limit(): session.query(XPAchievement) \ .filter(XPAchievement.XP_required &lt;= xp) \ .order_by(XPAchievement.XP_required.desc()) \ .limit(3) then first and the last are previous and next
score: 0
has comment: http://stackoverflow.com/comment/83840678
has comment: http://stackoverflow.com/comment/83842015
answers question: http://stackoverflow.com/q/48424970

http://stackoverflow.com/comment/83931977
type: QuestionComment
comment on: http://stackoverflow.com/q/48468827
has text: Something is fishy here... This is that rare case where a screenshot would be needed to convince...
score: 3
type: Comment

http://stackoverflow.com/a/48348266
has body: Ok, finally figured out what the issue was after turning verbose debugging on such that I could actually see the queries being sent. The issue was how it was being joined and it was using the pk of Products by default. ProductPositions.objects.filter(product_code__code=product_c‌​ode) Was basically being translated into: ... INNER JOIN.... ON 'ProductPositions'.'product_code' = 'Products'.'id' Which I really did not want. It should have been: ... INNER JOIN.... ON 'ProductPositions'.'product_code' = 'Products'.'code' So the solution was to fix the product_code field in the ProductPositions model by adding to_field. As the documentation says: For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances. https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field product_code = models.ForeignKey(Products, to_field='code', db_column='product_code', null=False) Now data is retrieving as expected and without errors.
type: Answer
answers question: http://stackoverflow.com/q/48344744
score: 0
accepted answer of: http://stackoverflow.com/q/48344744
type: AcceptedAnswer

http://stackoverflow.com/comment/83858746
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48433229
has text: In `pictures.picture[animal_pics]` , `animal_pics` is a list. I think you meant `str_animal`

http://stackoverflow.com/q/48347385
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/53023830
score: 1
tagged with: tensorboard
has answer: http://stackoverflow.com/a/75050972
has answer: http://stackoverflow.com/a/69396014
answer count: 4
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has title: Seeing more than 10 test examples in Tensoboard
downvote count: 0
has body: I am running the Tensorflow Object Detection API on a batch of 1000 labeled images, 80 of which I kept for testing. This is being done using the provided train.py and eval.py scripts, and also using one of the pipelines provided in the repo. After I get train.py and eval.py running, I run Tensorboard to monitor the training progress. However, when I go to the Image tab, I only find 10 out of the 80 examples I saved for training. Is there any way to force Tensorboard to use all the provided examples?
has answer: http://stackoverflow.com/a/48766929
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/84065094
type: AnswerComment
has text: Thank you! I'm trying to do that, but when I measure the angles between a point in the polygon and the two adjacent ones I always get the smallest possible value (I calculated them using vectors in numpy). How can I determine if it's a convex or concave vertex?
type: Comment
comment on: http://stackoverflow.com/a/48432358
score: 0

http://stackoverflow.com/comment/83690200
has text: Thanks! And thanks for your insight about the core Python implementations :)
comment on: http://stackoverflow.com/a/48351533
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48354868
score: 0
has body: Solved removing the db.close and the db.commit at the end of the function.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48353621
type: Answer
answers question: http://stackoverflow.com/q/48353621

http://stackoverflow.com/comment/83659363
type: Comment
comment on: http://stackoverflow.com/a/48337133
type: AnswerComment
has text: Bailey Parker's answer is neater, though
score: 0

data-visualization
tags question: http://stackoverflow.com/q/48439930
tags question: http://stackoverflow.com/q/48344745
tags question: http://stackoverflow.com/q/48379421
tags question: http://stackoverflow.com/q/48470251
tags question: http://stackoverflow.com/q/48465439
tags question: http://stackoverflow.com/q/48430069
tags question: http://stackoverflow.com/q/48415690
tags question: http://stackoverflow.com/q/48385273
tags question: http://stackoverflow.com/q/48440929
type: Tag
tag name: data-visualization

http://stackoverflow.com/q/48331413
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48331482
has body: I have a data frame that has 100 columns where the first column is a unique identifier and the second column is the group that they belong to and rest of the column explains each user's characteristics. user_id, group_id, a, b, c,....,az 0001, 1, 23, pro, 5.5, ......, 234 0002, 1, 32, che, 3.3, ......, 342 0003, 2, NaN, NaN, NaN,......., NaN I want to subset all the records that have NaN(s) all the columns except for column 1 and column 2 (user_id, group_id) One way to do is: df[df['a'].notnull() &amp; (df['b'].notnull()) &amp; (df['c'].notnull())] but writing for 98 columns like this seems inneficient. Is there a betterway?
downvote count: 0
answer count: 3
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48331482
favorite count: 0
possible better answer: http://stackoverflow.com/a/48331470
has title: Pandas better way to get rows that has all columns null except one
has answer: http://stackoverflow.com/a/48331827
has answer: http://stackoverflow.com/a/48331470
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/83648730

http://stackoverflow.com/q/48428669
has body: I have just set up a new Data Science Virtual Machine on Azure. I wanted to run a script FasterRCNN.py from https://github.com/karolzak/CNTK-Hotel-pictures-classificator but received an error: from utils.rpn.rpn_helpers import create_rpn, create_proposal_target_layer ImportError: No module named 'utils.rpn' The environment I am running the script on has Python 3.4 and CNTK 2.1 installed. I tried to add a Detection or Detection/utils directories (by editing ~./bashrc) to PYTHONPATH: export PYTHONPATH="$PYTHONPATH:/home/username/CNTK-Hotel-pictures-classificator/Detection" as described in https://github.com/Microsoft/CNTK/issues/2705 but the error persists. Update: Screenshot
tagged with: python
has title: CNTK on Data Science VM (FasterRCNN): ImportError: No module called 'utils.rpn'
type: AnsweredQuestion
score: 0
tagged with: azure
accepted answer: http://stackoverflow.com/a/48602711
tagged with: cntk
answer count: 1
has answer: http://stackoverflow.com/a/48602711
has comment: http://stackoverflow.com/comment/84133347
tagged with: azure-dsvm
has comment: http://stackoverflow.com/comment/84100468
type: Question

http://stackoverflow.com/a/48439505
answers question: http://stackoverflow.com/q/48439338
has body: The issue is with the same variable repeated twice. Can i suggest you that you use zip instead of using nested for loops. This would be a cleaner and concise implementation. QPA=[4,5,6,7,8,9] MT=[2,3,4,5,6,7] WH=[225,226,230,225,220,222] Prd=[24,24,24,24,24,24] MTBR=[7.5,8,9,7,5,6] for q,m,w,mt in zip(QPA,MT,WH,MTBR): mean_v = q*m*w*24 / (mt*1000) mean_value.append(mean_v)
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83871953
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48439338

http://stackoverflow.com/comment/83934492
comment on: http://stackoverflow.com/a/48458014
type: Comment
type: AnswerComment
score: 1
has text: show the models. maybe there is no related_name in the foreigh key.

gtk
tags question: http://stackoverflow.com/q/48431689
tags question: http://stackoverflow.com/q/48469655
type: Tag
tags question: http://stackoverflow.com/q/48459051
tags question: http://stackoverflow.com/q/48409067
tags question: http://stackoverflow.com/q/48368219
tag name: gtk
tags question: http://stackoverflow.com/q/48392498

http://stackoverflow.com/comment/83950805
comment on: http://stackoverflow.com/a/48461082
type: Comment
has text: Just explained the code. Would be nice to upvote my solution. Maybe someone can take advantage of it. Thanks for your help!
score: 0
type: AnswerComment

http://stackoverflow.com/a/48472274
has body: You were very close. It's split not strip: a, b, c = (int(x) for x in raw_input().split()) This will take exactly 3 integers, no more no less. If you want to take an arbitrary amount into a tuple, try this instead: tup = tuple(int(x) for x in raw_input().split())
upvote count: 8
has comment: http://stackoverflow.com/comment/83938449
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/83938445
answers question: http://stackoverflow.com/q/48472265
downvote count: 0

http://stackoverflow.com/comment/83794110
comment on: http://stackoverflow.com/q/48402887
type: Comment
has text: If you want to retrieve all items that contain `Assembly`: `result = [for i in l if 'Assembly' in i]`
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83731880
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48371975
score: 0
has text: thanks but i am not able to do this. I try to fin another solution or answer

http://stackoverflow.com/q/48448563
has answer: http://stackoverflow.com/a/48448643
has body: I have this view that stores data for 2 forms. The data for my second form is fine. But for the main User form, I just want to store the username, password and have a password confirmation. When a user is created, password gets stored inside the email field for some reason. class UserForm(forms.ModelForm): password = forms.CharField(label='Password', max_length=32, required=True, widget=forms.PasswordInput) confirm_password = forms.CharField(label='Confirm', max_length=32, required=True, widget=forms.PasswordInput, help_text="Passwords must match!") def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) class Meta: model = User fields = ('username', 'password') exclude = ('email',) def student_register(request, user): data = dict() if request.method == 'POST': form1 = UserForm(request.POST) form2 = StudentForm(request.POST, request.FILES) if form1.is_valid() and form2.is_valid(): cd1 = form1.cleaned_data user.username = cd1["username"] user.password = cd1["password"] user.confirm_password = cd1["confirm_password"] new_user = User.objects.create_user(user.username, password, confirm_password) new_user.save() cd2 = form2.cleaned_data name = cd2['name'] surname = cd2['surname'] email = cd2['email'] phone = cd2['phone'] student_id = cd2['student_ID'] photo = cd2['photo'] Student.objects.create(user=new_user, name=name, surname=surname, email=email, phone=phone, student_ID=student_id, photo=photo) return redirect('index') else: form1 = UserForm() form2 = StudentForm() data['form1'] = form1 data['form2'] = form2 return render(request, "student_signup_form.html", data)
has comment: http://stackoverflow.com/comment/83889859
has comment: http://stackoverflow.com/comment/83889843
accepted answer: http://stackoverflow.com/a/48448638
tagged with: python
has answer: http://stackoverflow.com/a/48448638
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
tagged with: django
upvote count: 1
possible better answer: http://stackoverflow.com/a/48448643
favorite count: 0
type: Question
has title: My password is stored inside the email field in Django admin

http://stackoverflow.com/comment/83780230
score: 1
type: Comment
type: AnswerComment
has text: As an FYI: The statement *it still doesn't work* is not terribly illuminative.
comment on: http://stackoverflow.com/a/48395833

http://stackoverflow.com/a/48374123
has body: for i, product in enumerate(products, 1): return HttpResponse(print(str(product))) First of all, you can place HttpResponse inside the loop. The best solution is to generate your response string first and then return that string. Also, remove print. for i, product in enumerate(products, 1): response_string += product return HttpResponse(response_string)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48371873

http://stackoverflow.com/q/48333680
answer count: 0
downvote count: 0
has title: What's the difference between the python[x.x] and python[x.x]-dev packages?
duplicate of: http://stackoverflow.com/q/2358801
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83653844
linked to: http://stackoverflow.com/q/2358801
has comment: http://stackoverflow.com/comment/83653066
tagged with: linux
type: UnansweredQuestion
tagged with: package
tagged with: python
score: 4
upvote count: 4
has body: Appreciate this is a really basic question, but I've read that the dev packages are for headers for building extensions? Is that all? What can I not do without dev packages and vice-versa? If I don't install the dev packages what ramifications will it have? Thanks!
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83653029

http://stackoverflow.com/comment/83707294
comment on: http://stackoverflow.com/a/48360223
type: Comment
has text: Yeah, very good. But you are not helping by spreading this kind sloppiness.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48403239
upvote count: 1
tagged with: scikit-learn
tagged with: oversampling
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/45969390
possible better answer: http://stackoverflow.com/a/48403451
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48403451
tagged with: python
has body: My data consists of 99% target variable = 1, and 1% target variable = '0'. Does stratify guarantee that the train tests and test sets have equal ratio of data in terms of target variable. As in containts, equal amounts of '1' and '0'? Please see below code for clarification X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,stratify=y,random_state=42)
accepted answer: http://stackoverflow.com/a/48403888
type: Question
has title: what is the differene between Stratify and StratifiedKFold in python scikit learn?
answer count: 2
has answer: http://stackoverflow.com/a/48403888
tagged with: machine-learning

http://stackoverflow.com/comment/83935621
comment on: http://stackoverflow.com/a/48470397
score: 1
type: Comment
type: AnswerComment
has text: code-only answers are discouraged. This answer would be much better if you explained what you changed to make it work, so that the OP or anyone else doesn't have to compare your code line-by-line to the original.

http://stackoverflow.com/q/48377703
favorite count: 0
has title: Tensorflow: Canonical method of diagnosing "No gradients provided for any variable..." errors
type: Question
has answer: http://stackoverflow.com/a/48378908
has body: I have a high level question about how to diagnose Tensorflow errors of the form: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables Of course I am interested in solving this for my specific problem, but that is not what this question is about. I would like a more canonical answer on the best way to find the place where the gradients "stop". For instance, it would be nice to have a tool in Tensorboard that showed the parts of the graph which have gradients with respect to certain variables. In the specific example below, I could image the variable being blue, and then all of the lines and scopes that have gradients with respect to the Variable being colored blue. That sure would make it easy to trace such problems for large graphs... Does such a feature exist? Or what is the canonical way of tracing such problems?
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 1
tagged with: tensorboard
upvote count: 1
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/a/48360052
has comment: http://stackoverflow.com/comment/83739216
type: AcceptedAnswer
has body: Ok, so in the future you would be advised to break your question down into smaller parts. The problem you require an answer to in your question is a different one then your current error (as you mentioned only in the comments to your question) is indicating. The error you are getting (python is not recognised) already has an answer [here][1]. Which I will not repeat here since it does not relate to your question. Once you've managed to get Python added to your PATH simply navigate to the folder C:\pyprobml-master (assuming this is indeed the checkout location of the repo on your system? - I am assuming based on the comments to the main question) and execute the demo via python -m examples.mnist1NNdemo. As an alternative you could also navigate to C:\pyprobml-master\examples and run python mnist1NNdemo.py
score: 0
accepted answer of: http://stackoverflow.com/q/48356666
type: Answer
answers question: http://stackoverflow.com/q/48356666

http://stackoverflow.com/q/48473767
tagged with: visual-studio-code
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0
score: 3
has body: I'm using vscode to debug my app. In debug panel, variables with Latin characters are displayed correctly, but encoded string like Chinese are not decoded as expected. s = "测试" and the debug panel and console output(not print) is s: '\xe6\xb5\x8b\xe8\xaf\x95' How can I fix this issue?
has comment: http://stackoverflow.com/comment/83976810
has title: How can I display decoded str or unicode in VSCode console
type: Question

http://stackoverflow.com/comment/83758511
type: AnswerComment
comment on: http://stackoverflow.com/a/48373047
has text: I am trying the Selenium solution as suggested and posted a new question, so I don't know the protocol on what to do with this question. I hesitate to tick it as correct for the code has not worked for me. Should I close it or do something else? Thanks for help.
score: 0
type: Comment

http://stackoverflow.com/comment/83896733
comment on: http://stackoverflow.com/a/48446169
has text: Your justification for claiming "`[] = ()` does not change `[]`" is just testing the type of list literal, which obviously will not change. However, as explained in @glglgl's answer, this syntax exists so that variables specified in the LHS collection can be assigned with values from the RHS iterable, so in that sense, the syntax is meant to "change" the list/tuple. Additionally, you can use multiple assignment to see that the evaluated value of this "assignment from iterable" expression is its own RHS: `a = [] = ()` assigns `()` to `a`.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83956236
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48480501
has text: Yep - that is it! I in fact suspected something like this, but couldn't get past the fact that both `append` and `+=` logically do the same thing (change an existing object). I'll post the solution below.
score: 0

http://stackoverflow.com/q/48376566
downvote count: 2
linked to: http://stackoverflow.com/q/4706499
possible better answer: http://stackoverflow.com/a/48376604
favorite count: 0
type: Question
has body: I have stored the string in a variable. And I want to append it to a text file. How can I achieve this? def readyaml(abs_read_path,): with open(abs_read_path, 'r') as stream, open("instanceinput.txt",'w') as fnew: try: content = yaml.load(stream) instance = content['instance'] dump = instance[0] print dump fnew.write(dump) except yaml.YAMLError as exc: print(exc) stream.close() fnew.close() readyaml(abs_read_path)
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/4706499
has title: How to write in text file by variable using python 2.7
score: -2
has answer: http://stackoverflow.com/a/48376738
tagged with: python
has comment: http://stackoverflow.com/comment/83740598
has answer: http://stackoverflow.com/a/48376604
accepted answer: http://stackoverflow.com/a/48376950
has answer: http://stackoverflow.com/a/48376950
answer count: 3
upvote count: 0

http://stackoverflow.com/q/48434330
tagged with: pandas
tagged with: date-difference
accepted answer: http://stackoverflow.com/a/48434652
has answer: http://stackoverflow.com/a/48434713
upvote count: 1
has body: I want to compute a month difference vector to my given df based on the following rules : Date1 Date2 12/31/2017 1/1/2018 12/31/2017 2/1/2018 12/31/2017 1/15/2018 The logic is as the following: column d1: (Date1+ 1 month) - Date2 column d2: (Date1+ 2 month) - Date2 column d3: (Date1+ 3 month) - Date2 and so on... The output would be: Date1 Date2 d1 d2 d3 ... d10 12/31/2017 1/1/2018 0 1 2 ... 9 12/31/2017 2/1/2018 -1 0 1 ... 8 12/31/2017 1/15/2018 0 1 2 ... 9 What would be best approach for this without manually defying each d1, d2, d3, ...d10 each time? Many thanks!
has answer: http://stackoverflow.com/a/48434652
downvote count: 1
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48434713
has title: Pandas calculating month difference vector
tagged with: python
has comment: http://stackoverflow.com/comment/83860745
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/93218655
type: Comment
score: 0
type: AnswerComment
has text: https://www.youtube.com/watch?v=xvfJXNGCQBM this lecture explains it well for PCA but it should be same logic with SVD.
comment on: http://stackoverflow.com/a/48425000

http://stackoverflow.com/comment/125201600
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/59530481
has text: Having experienced a similar problem, this is actually the better solution in my opinion.

http://stackoverflow.com/comment/83866025
comment on: http://stackoverflow.com/q/48436679
score: 0
type: Comment
type: QuestionComment
has text: Please read why a [**`screenshot of HTML or code or error is a bad idea`**](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Consider updating the Question with formatted text based relevant HTML, code trials and error stack trace.

http://stackoverflow.com/a/48373277
score: -1
downvote count: 1
has body: There are different ways to handle this, one way is to do a for loop for (int i = 0; i &lt; rx.getDataLength(); i++) { Serial.print( rx.getData(i), HEX ); } and extract the data from that string which there are so many ways to do it.
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48370175

http://stackoverflow.com/comment/83660399
comment on: http://stackoverflow.com/a/48337072
type: Comment
has text: Then you need to have some boolean value on user which will indicate that user and then provide some logic in confirmation.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83748300
type: Comment
score: 0
type: AnswerComment
has text: I tried to change something (to perform the dot product at python level) and the interpreter can go forward, but it stuck at the middle saying me "name 'When' is not defined". I have to admit that i don't know that syntax.
comment on: http://stackoverflow.com/a/48375903

http://stackoverflow.com/a/48386303
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48386100
downvote count: 0
upvote count: 1
has body: The only think I can think of is to make a Factory Method: class Fruit(): def __init__(self, color): self.color = color @staticmethod def MakeFruit(aFruit): return Fruit(aFruit.color) usage: an_apple = Apple('red', 42) #assuming Apple as before a_fruit = Fruit('blue') a_red_fruit = Fruit.MakeFruit(an_apple)

http://stackoverflow.com/a/65420453
type: Answer
answers question: http://stackoverflow.com/q/48399871
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/127392482
downvote count: 0
has comment: http://stackoverflow.com/comment/126841607
has body: This should work: bucket = bucketName key = f"{folder}/{filename}" csv_buffer=StringIO() df.to_csv(csv_buffer) content = csv_buffer.getvalue() s3.put_object(Bucket=bucket, Body=content,Key=key) AWS bucket names are not allowed to have slashes ("/"), which should be part of Key. AWS uses slashes to show "virtual" folders in the dashboard. Since csv is a text file I'm using StringIO instead of BytesIO

http://stackoverflow.com/q/48410664
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48410905
downvote count: 0
tagged with: django
tagged with: javascript
tagged with: python
tagged with: jquery
has body: I have an tag on my Django template for an advert that fulfills two functions: When a user clicks it, data is logged about the click (its location on the page, the text of the link, etc.) It is then redirected to an external link on a different website. The way the page template is loaded is that the tag is dynamically filled with the href attribute pointing towards a view function in my views.py : Lawyer Education The problem is that in practice, when a user hovers over my hyperlink, on the bottom left of the browser they see the URL pointing towards the view and its DJango url with arguments is displayed as opposed to the URL they are expecting to be redirected to. Is it possible to have the redirect URL be displayed instead in some way? Or to have the view function be fired as an event while the redirect occurs at the same time? Javascript/jQuery/PHP is not my forte so I am not sure how to proceed if that is the way to go to solve my problem...
has answer: http://stackoverflow.com/a/48410905
type: AnsweredQuestion
has title: Invoke a seperate event when I click on a hyperlink on my Django template page
score: 2

http://stackoverflow.com/q/48444373
score: 16
downvote count: 0
has answer: http://stackoverflow.com/a/66413913
upvote count: 16
favorite count: 0
has title: Convert string to hours and seconds using pd.to_datetime
has answer: http://stackoverflow.com/a/48445423
answer count: 3
tagged with: datetime
tagged with: python
type: Question
has body: I have a pandas DataFrame, with dates in the following format: print(df["date"]) 14/01/18 12:47 14/01/18 12:48 14/01/18 12:50 14/01/18 12:57 14/01/18 12:57 14/01/18 12:57 14/01/18 12:57 14/01/18 12:57 14/01/18 12:58 Specifically, I would like to: Convert it to datetime, using pd.to_datetime Create the following columns: df["month"] df["day"] df["year"] df["hour"] df["minute"] I tried to run: df['date'] = pd.to_datetime(df['date'], format = "%d/%m/%Y %H/%M" ) But I get the error: time data '02/01/18 08:41' does not match format '%d/%m/%Y %H/%M' (match)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48444450

http://stackoverflow.com/q/48425201
has comment: http://stackoverflow.com/comment/83840501
has comment: http://stackoverflow.com/comment/83841004
linked to: http://stackoverflow.com/q/23455728
tagged with: resampling
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/83841434
has title: sample X examples from each class label
has answer: http://stackoverflow.com/a/68035617
has comment: http://stackoverflow.com/comment/83845428
tagged with: random
has answer: http://stackoverflow.com/a/48427561
score: 2
has body: l have a dataset (numpy vector) with 50 classes and 9000 training examples. x_train=(9000,2048) y_train=(9000,) # Classes are strings classes=list(set(y_train)) l would like to build a sub-dataset such that each class will have 5 examples which means l get 5*50=250 training examples. Hence my sub-dataset will take this form : sub_train_data=(250,2048) sub_train_labels=(250,) Remark : we take randomly 5 examples from each class (total number of classes = 50) Thank you
downvote count: 0
has answer: http://stackoverflow.com/a/72477821
favorite count: 0
tagged with: sklearn-pandas
answer count: 4
has comment: http://stackoverflow.com/comment/83840372
has answer: http://stackoverflow.com/a/52776718
type: Question
upvote count: 2

http://stackoverflow.com/comment/130852647
has text: `uuid.uuid4` will generate a value of 36 characters and that field has at most 31 characters (I wasn't the downvoter though).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48438652

http://stackoverflow.com/a/48473125
has comment: http://stackoverflow.com/comment/83939926
has comment: http://stackoverflow.com/comment/83950699
has comment: http://stackoverflow.com/comment/83951708
has comment: http://stackoverflow.com/comment/83950990
answers question: http://stackoverflow.com/q/48473056
type: Answer
has comment: http://stackoverflow.com/comment/83951246
has comment: http://stackoverflow.com/comment/83951036
has comment: http://stackoverflow.com/comment/83951293
has comment: http://stackoverflow.com/comment/83940395
has comment: http://stackoverflow.com/comment/83940047
has comment: http://stackoverflow.com/comment/83939958
has comment: http://stackoverflow.com/comment/83940543
has comment: http://stackoverflow.com/comment/134446998
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83951068
score: 13
has comment: http://stackoverflow.com/comment/83940639
upvote count: 13
has body: Approach #1 One vectorized approach with sorting - In [8]: b = np.sort(a,axis=1) In [9]: (b[:,1:] != b[:,:-1]).sum(axis=1)+1 Out[9]: array([2, 2, 3]) Approach #2 Another method for ints that aren't very large would be with offsetting each row by an offset that would differentiate elements off each row from others and then doing binned-summation and counting number of non-zero bins per row - n = a.max()+1 a_off = a+(np.arange(a.shape[0])[:,None])*n M = a.shape[0]*n out = (np.bincount(a_off.ravel(), minlength=M).reshape(-1,n)!=0).sum(1) Runtime test Approaches as funcs - def sorting(a): b = np.sort(a,axis=1) return (b[:,1:] != b[:,:-1]).sum(axis=1)+1 def bincount(a): n = a.max()+1 a_off = a+(np.arange(a.shape[0])[:,None])*n M = a.shape[0]*n return (np.bincount(a_off.ravel(), minlength=M).reshape(-1,n)!=0).sum(1) # From @wim's post def pandas(a): df = pd.DataFrame(a.T) return df.nunique() # @jp_data_analysis's soln def numpy_apply(a): return np.apply_along_axis(compose(len, np.unique), 1, a) Case #1 : Square shaped one In [164]: np.random.seed(0) In [165]: a = np.random.randint(0,5,(10000,10000)) In [166]: %timeit numpy_apply(a) ...: %timeit sorting(a) ...: %timeit bincount(a) ...: %timeit pandas(a) 1 loop, best of 3: 1.82 s per loop 1 loop, best of 3: 1.93 s per loop 1 loop, best of 3: 354 ms per loop 1 loop, best of 3: 879 ms per loop Case #2 : Large number of rows In [167]: np.random.seed(0) In [168]: a = np.random.randint(0,5,(1000000,10)) In [169]: %timeit numpy_apply(a) ...: %timeit sorting(a) ...: %timeit bincount(a) ...: %timeit pandas(a) 1 loop, best of 3: 8.42 s per loop 10 loops, best of 3: 153 ms per loop 10 loops, best of 3: 66.8 ms per loop 1 loop, best of 3: 53.6 s per loop Extending to number of unique elements per column To extend, we just need to do the slicing and ufunc operations along the other axis for the two proposed approaches, like so - def nunique_percol_sort(a): b = np.sort(a,axis=0) return (b[1:] != b[:-1]).sum(axis=0)+1 def nunique_percol_…
has comment: http://stackoverflow.com/comment/83939965
has comment: http://stackoverflow.com/comment/83951048
accepted answer of: http://stackoverflow.com/q/48473056
has comment: http://stackoverflow.com/comment/83940431

http://stackoverflow.com/comment/83894968
comment on: http://stackoverflow.com/a/48450922
type: Comment
score: 0
type: AnswerComment
has text: don't think so, not sure.

http://stackoverflow.com/comment/83762397
has text: Not really a duplicate, but you're going to want to read this: https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags?rq=1
comment on: http://stackoverflow.com/q/48387448
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83664022
comment on: http://stackoverflow.com/a/48338786
score: 0
type: Comment
has text: @Dyrl I added this to my answer. But did it help to fix the issue?
type: AnswerComment

http://stackoverflow.com/a/48370394
accepted answer of: http://stackoverflow.com/q/48366707
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48366707
has body: It is good practice to do a redirect upon submitting a form. Here's how you can change your code to perform the redirect: from django.shortcuts import render, redirect from django.urls import reverse def create_album(request): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] album.save() return redirect(reverse('detail', kwargs={'album_id':album.id})) context = { "form": form, } return render(request, 'photo/create_album.html', context) This assumes that the url/view is named detail in your url patterns. You could try this first, and if it doesn't work could we see your HTML code for the form?
type: AcceptedAnswer

http://stackoverflow.com/comment/83906890
score: 0
has text: What is your _question_?
type: Comment
comment on: http://stackoverflow.com/q/48457085
type: QuestionComment

http://stackoverflow.com/q/48478798
score: 3
has body: I'm trying to asynchronously download a file in Python, using wget in a subprocess. My code looks like this: async def download(url, filename): wget = await asyncio.create_subprocess_exec( 'wget', url, 'O', filename ) await wget.wait() def main(url): loop = asyncio.get_event_loop() future = asyncio.ensure_future(download(url, 'test.zip'), loop=loop) print("Downloading..") time.sleep(15) print("Still downloading...") loop.run_until_complete(future) loop.close() What I'm trying to do is witness the printing of "Downloading.." then 15 seconds later "Still downloading...", all while the download of the file has started. What I'm actually seeing is that the download of the file only starts when the code hits loop.run_until_complete(future) My understanding is that asyncio.ensure_future should start running the code of the download coroutine, but apparently I'm missing something.
tagged with: python-asyncio
has title: In what condition could ensure_future not actually start the future?
downvote count: 1
has answer: http://stackoverflow.com/a/76078219
possible better answer: http://stackoverflow.com/a/76078219
has comment: http://stackoverflow.com/comment/83950712
favorite count: 0
type: Question
answer count: 2
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/48478856
accepted answer: http://stackoverflow.com/a/48478856
type: AnsweredQuestion

http://stackoverflow.com/q/48362679
has answer: http://stackoverflow.com/a/48367232
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83713008
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83726383
has body: I'm relatively new to web development, but I have a couple years experience working with python, so I figured I would build my first production site using django. I've spent the last few days learning the basics and building a test site running on my local machine. Today, I've been trying to deploy my site to production; however, I've hit a pretty large stumbling block. The django documentation suggests using mod_wsgi for apache deployments. I followed the install instructions here, only to realize that I don't have access to make any changes to apache - I'm currently on a shared hosting plan. Apparently, to perform the install, I would have to upgrade to a VPS plan, which costs a lot more. Any advice for a new web developer trying to get a proof-of-concept web app together (preferably with feedback gathered from real users) on a budget? I think I have two options: Eat the cost on my current web hosting plan. Try to find a cheaper host that specializes in django hosting. I've been looking at the following (suggestions here would be wonderful): Heroku DigitalOcean A2Hosting Try some sort of manual deployment. Is this possible or has anybody ever made this work? I can't seem to find any resources about this. I was able to install django on my web server and my site just seems like a collection of files at this point. Can I simply move this directory tree to my site using an ftp? And handle the database migration manually? Can I just run django on my web server via ssh instead of from my local machine? Essentially just rebuild my site in production? I know this isn't a smart idea with a normal production site, but as a proof of concept, I don't mind some downtime if my code is buggy. Thanks!
tagged with: apache
accepted answer: http://stackoverflow.com/a/48367232
tagged with: django
has title: How to deploy Django without mod_wsgi
tagged with: python
has comment: http://stackoverflow.com/comment/83718422

http://stackoverflow.com/a/48411578
accepted answer of: http://stackoverflow.com/q/48411496
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48411496
has body: Make it an object property and set it in the constructor. def __init__(self): self.val = 0 ... def roll(self): 'primary game play' ds.shake() rolled = ds.getTotalRoll() while True: if self.val == 0: rolled = self.val self.val += 1 return 'You got it! Next value is {}'.format(self.val) break if rolled == self.val: self.val +=1 self.count += 1 return 'You got it! Next value is {}'.format(self.val) else: self.count += 1 return 'You rolled a {} but needed to roll a {}'.format(rolled, self.val)
type: Answer
score: 0

http://stackoverflow.com/a/76575110
type: Answer
answers question: http://stackoverflow.com/q/48415690
upvote count: 2
downvote count: 0
score: 2
has body: See this solution (on https://github.com/nicolaskruchten/pivottable/issues/1269) that worked for me. Hi, I did not find a workaround to use pivottable on vscode. But, if you open the pivottablejs.html that is generated into your folder in a web browser, you're able to use it normally. This is my code that worked. First, I defined my path and saved an HTML file. Then I opened this html file in chrome, and it worked well. #!pip install pivottablejs from pivottablejs import pivot_ui pivot_ui(df, outfile_path=r"D:\XXXXXX\pivot.html")

http://stackoverflow.com/a/48398435
has body: If I understand your code correctly, it should be the same as: new_inputs = inputs + step over_bounds = tf.abs(new_inputs) &gt; bounds new_mask = mask * (1 + (-2) * tf.cast(over_bounds, tf.float32)) return new_mask
score: 0
has comment: http://stackoverflow.com/comment/83791067
has comment: http://stackoverflow.com/comment/83784980
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48398229
has comment: http://stackoverflow.com/comment/83794571
accepted answer of: http://stackoverflow.com/q/48398229
type: Answer

http://stackoverflow.com/comment/83732991
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48372783
score: 0
has text: Thanks a lot for the great answer :) However, this does not seem to work with my real data. My real data includes a `list tuple` instead of the numbers. e.g., [['tim tam'], 0.5], ['pudding', 0.5], ...]. I get an error saying `TypeError: unhashable type: 'list'`. Can you please kindly tell me why that happens? :)

http://stackoverflow.com/comment/84232908
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48398869
has text: The issues I read about were only to do with reading more decimal places than were recorded by c/c++ programs. A very minor problem.
type: Comment

http://stackoverflow.com/q/48408370
has comment: http://stackoverflow.com/comment/83807516
score: 0
has body: in Spyder, I can write code in one window, and when I hit F5 to run it, my console becomes aware of everything that's happened. If I define or import a class in my code (then run the code), I can then create instances of it in the terminal, for example If I try to do this in pycharm (using shift+F10), the code runs, but I can't interact with the window afterwards. If I call up a console (view> tool windows> python console), I can run code interactively, but it is not aware of the code I previously ran (using shift+F10) is there any way around this?
has comment: http://stackoverflow.com/comment/83806855
tagged with: spyder
has title: what is this feature in Spyder called, and how can I do it in pycharm?
type: Question
tagged with: pycharm
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91455907
comment on: http://stackoverflow.com/a/48420423
type: Comment
type: AnswerComment
has text: @kriss Yup, exactly. Or a file may not have a name at all, as in [anonymous inodes](https://stackoverflow.com/questions/4508998/what-is-an-anonymous-inode-in-linux)
score: 1

http://stackoverflow.com/comment/83833947
score: 0
comment on: http://stackoverflow.com/a/48421664
type: AnswerComment
has text: Yes, USERID and Time stamp
type: Comment

http://stackoverflow.com/q/48479065
has comment: http://stackoverflow.com/comment/83951202
duplicate of: http://stackoverflow.com/q/19676538
duplicate of: http://stackoverflow.com/q/2612802
has answer: http://stackoverflow.com/a/48479134
favorite count: 0
has title: why both variables are changed when I change one variable? Python
type: Question
score: 2
possible better answer: http://stackoverflow.com/a/48479123
tagged with: numpy
tagged with: python
accepted answer: http://stackoverflow.com/a/48479134
has body: I have a code given below. when I run the code, all x1,x2 and x3 having same values.As per logic x1 should have random numbers, x2 also random numbers , x3 should have 0s and 1s. import numpy as np def reluDerivative(x): yy=x; yy[yy&lt;=0] = 0 yy[yy&gt;0] = 1 return yy x1=np.random.uniform(-1, 1,10) x2=x1 x3=reluDerivative(x1)
upvote count: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48479123
downvote count: 0
linked to: http://stackoverflow.com/q/19676538
linked to: http://stackoverflow.com/q/2612802

http://stackoverflow.com/comment/83703751
score: 4
comment on: http://stackoverflow.com/q/48358500
has text: In other words, the second parameter is supposed to return a **different** (independently distributed) random number each time. The probability of returning a sequence of 20 equal numbers are extremely unlikely.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86983180
type: AnswerComment
comment on: http://stackoverflow.com/a/48476943
score: 0
has text: @hungnguyen do you mean with `canvas.create_text`?
type: Comment

http://stackoverflow.com/comment/83931217
has text: Try to change the line `'iPlanetDirectoryPro': "token",` to `'iPlanetDirectoryPro': token,` (remove quotation marks around `token`)
type: Comment
comment on: http://stackoverflow.com/q/48468526
type: QuestionComment
score: 0

http://stackoverflow.com/a/48479931
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48479750
answers question: http://stackoverflow.com/q/48479750
upvote count: 7
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/87671616
has body: Yes, it is allowed to pass zero-sized arrays to those intrinsics (and many others) and yes those results are explicitly required by the Fortran standard. For product (F2008, 13.7.133): The result of PRODUCT (ARRAY) has a value equal to a processor-dependent approximation to the product of all the elements of ARRAY or has the value one if ARRAY has size zero. For sum (F2008, 13.7.161): The result of SUM (ARRAY) has a value equal to a processor-dependent approximation to the sum of all the elements of ARRAY or has the value zero if ARRAY has size zero.
downvote count: 0

http://stackoverflow.com/comment/83667544
comment on: http://stackoverflow.com/a/48338878
type: AnswerComment
score: 0
has text: Yeah got it. Thanks.
type: Comment

http://stackoverflow.com/comment/83831962
comment on: http://stackoverflow.com/q/48420405
type: Comment
score: 0
type: QuestionComment
has text: Scipy documentaion lists an example od solving a PDE with `scipy.integrate.odeint`, but in order to do that they: "discretize the x variable by defining the uniformly spaced grid of points " and in fact then, they integrate only in time (so, they are left with one variable). See: https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html

http://stackoverflow.com/q/48411686
upvote count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48411722
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48411722
possible better answer: http://stackoverflow.com/a/48413960
tagged with: python
has title: How to stop python script execution and end up in python shell
has answer: http://stackoverflow.com/a/48413960
score: 2
has body: Octave has a keyboard function that stops the execution of the script and drops you out into an interactive octave shell, so it is possible to inspect variables at that point and carry our other debugging actions. Is there anything similar in python?
answer count: 2

jupyter-notebook
tags question: http://stackoverflow.com/q/48401560
tags question: http://stackoverflow.com/q/48480173
tags question: http://stackoverflow.com/q/48486240
tags question: http://stackoverflow.com/q/48447427
tags question: http://stackoverflow.com/q/48359436
tags question: http://stackoverflow.com/q/48362777
tags question: http://stackoverflow.com/q/48387368
tags question: http://stackoverflow.com/q/48355140
tags question: http://stackoverflow.com/q/48372019
tags question: http://stackoverflow.com/q/48428116
tags question: http://stackoverflow.com/q/48422762
tags question: http://stackoverflow.com/q/48430019
tags question: http://stackoverflow.com/q/48350692
tags question: http://stackoverflow.com/q/48399232
tags question: http://stackoverflow.com/q/48429739
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/48335240
tags question: http://stackoverflow.com/q/48409285
tags question: http://stackoverflow.com/q/48373577
type: Tag
tags question: http://stackoverflow.com/q/48372875
tags question: http://stackoverflow.com/q/48480588
tags question: http://stackoverflow.com/q/48406116
tags question: http://stackoverflow.com/q/48355747
tags question: http://stackoverflow.com/q/48450534
tags question: http://stackoverflow.com/q/48350505
tags question: http://stackoverflow.com/q/48425707
tags question: http://stackoverflow.com/q/48413069
tags question: http://stackoverflow.com/q/48366017
tags question: http://stackoverflow.com/q/48397005
tags question: http://stackoverflow.com/q/48415690
tags question: http://stackoverflow.com/q/48338962
tags question: http://stackoverflow.com/q/48335872
tags question: http://stackoverflow.com/q/48381807
tags question: http://stackoverflow.com/q/48420759
tags question: http://stackoverflow.com/q/48407059
tags question: http://stackoverflow.com/q/48390664

http://stackoverflow.com/a/48415476
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83828481
has comment: http://stackoverflow.com/comment/83828349
answers question: http://stackoverflow.com/q/48414401
type: Answer
has body: Issue is here current_user_courses = Course.objects.filter(users__pk=current_user.pk) Try instead [Old] current_user_courses = Course.objects.filter(users__in=[current_user]) [Now] current_user_courses = Course.objects.filter(users__user=current_user) Because in many to many relationships this creates new mapping table and that doesn't have direct many to many field.
has comment: http://stackoverflow.com/comment/83821096
downvote count: 0

http://stackoverflow.com/q/48370793
favorite count: 0
type: Question
has title: Python colon ":" operator applied to a variable?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83728324
tagged with: python
has body: I received a Python class defining a game "Board" object, as well as a number of members which are initialized within a constructor. Most of this is straightforward, but I don't understand the meaning of the ":" operator in the initialisations of the sets in the last two lines of this snippet: class Board: BLANK = 0 NOT_MOVED = (-1, -1) __active_players_queen1__= None __inactive_players_queen1__= None __active_players_queen2__= None __inactive_players_queen2__= None def __init__(self, player_1, player_2, width=7, height=7): self.width=width self.height=height self.queen_11 = "queen11" self.queen_12 = "queen12" self.queen_21 = "queen21" self.queen_22 = "queen22" self.__board_state__ = [ [Board.BLANK for i in range(0, width)] for j in range(0, height)] self.__last_queen_move__ = {self.queen_11:Board.NOT_MOVED, self.queen_12:Board.NOT_MOVED, self.queen_21:Board.NOT_MOVED, self.queen_22:Board.NOT_MOVED} self.__queen_symbols__ = {Board.BLANK: Board.BLANK, self.queen_11:11, self.queen_12:12, self.queen_21:21, self.queen_22:22} E.g. what does "self.queen_11:11" mean? I'm relatively inexperienced Python, and it looks similar to "dot notation" for member access, or how some languages handle assignment (e.g. ":="), but from my understanding of Python, dot notation is dot notation, and assignment is a single equals sign. My reading is the queen_11 variable (initialized earlier to the string "queen11") is somehow associated with the integer value 11? This doesn't seem to be a variant of list slicing or annotations. This is Python 2.7 code BTW.
has comment: http://stackoverflow.com/comment/83728318
score: 2
upvote count: 4
tagged with: python-2.7
linked to: http://stackoverflow.com/q/48323493
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/48370867
has comment: http://stackoverflow.com/comment/83728370
linked to: http://stackoverflow.com/q/10228655
has answer: http://stackoverflow.com/a/48370867

http://stackoverflow.com/q/48356424
downvote count: 0
tagged with: machine-learning
has body: I'm going to check for grammar in the sentences I give as input. If spaCy identifies PRP and MD and NN in a sentence then it will give me a text output there is a prp, md and nn in the sentence The problem is: how can I tell spaCy to check for PRP, MD and NN and then give me the desired text output? This is the code so far which is able to identify grammar of a text input: import spacy sent=input("insert sentence: \n\n") nlp=spacy.load('en') doc=nlp(sent) for token in doc: print(token.text, token.tag_, token.dep_)
tagged with: python
accepted answer: http://stackoverflow.com/a/48357135
score: 4
has answer: http://stackoverflow.com/a/48357135
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83700710
answer count: 1
has comment: http://stackoverflow.com/comment/83700503
tagged with: artificial-intelligence
has title: processing grammar using spaCY
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
tagged with: spacy

http://stackoverflow.com/q/48386829
linked to: http://stackoverflow.com/q/48399459
tagged with: python-3.x
has title: when and how to use return & print while inter-calling the functions with if __name__ == '__main__': method
has comment: http://stackoverflow.com/comment/83761686
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48433458
tagged with: function
has body: I have a doubt, when and how to use return &amp; print while inter-calling the functions with if __name__ == '__main__': method. For example i have quoted two example codes below the first one while i have used the return keyword into the First Fuction CheckUid(user) and print into second Function CallUid() , So When i ran the programm it runs and gives the ouput but the only the diffrence i see when userid.txt is being called to read the user ID's against the ldapsearch command and if user id doesn't exits then it returns None while otherhand while using the print statement into the First Fuction CheckUid() itself then calling it into second function CallUid() then it doesn't return None statement. Please, suggest how and where to use return keyword while using the if __name__ == '__main__': method. $ cat function1.py #!/usr/bin/python3 import subprocess from subprocess import call def CheckUid(user): proc = subprocess.Popen("ldapsearch -h server1 -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE) info_str = proc.stdout.read().decode('utf8') split_str = info_str.split() if len(split_str) &gt; 1: return {'UserID': split_str[1].split(',')[0].split('=')[1], 'MangerID': split_str[-1]} else: split_str = 'null' def CallUid(): with open('userid.txt', mode='rt', encoding='utf-8') as f: for line in f.readlines(): print(CheckUid(line)) #return CheckUid(line) if __name__ == '__main__': CallUid() output as below: $ ./function1.py None None {'UserID': 'aashishp', 'MangerID': 'rpudota'} {'UserID': 'abaillie', 'MangerID': 'davem'} {'UserID': 'abishek', 'MangerID': 'kalyang'} While Other way around: $ cat function2.py #!/usr/bin/python3 import subprocess from subprocess import call def CheckUid(user): proc = subprocess.Popen("ldapsearch -h server1 -D 'cn=directory manager' -w pass123 -LLLb 'ou=people,o=rraka.com' 'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE) info_str = proc.…
tagged with: python
has comment: http://stackoverflow.com/comment/83764799
has comment: http://stackoverflow.com/comment/83762286
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83761393
type: Question
has comment: http://stackoverflow.com/comment/83775348

http://stackoverflow.com/comment/83860400
type: Comment
has text: @Alex, we were both deleting at the same time! I'm happy if yours is accepted since you've described it better, and came up with the better algorithm for high threshold.
comment on: http://stackoverflow.com/a/48434263
type: AnswerComment
score: 1

http://stackoverflow.com/a/48485858
type: Answer
score: 0
has body: You can do it like this: query = Goods.objects sort_by = request.GET.pop('sort_by', 'id') for k, v in request.GET.items(): query.filter(k=v) result = query.order_by(sort_by)
answers question: http://stackoverflow.com/q/48485546

http://stackoverflow.com/comment/83678240
type: Comment
comment on: http://stackoverflow.com/a/48345992
type: AnswerComment
score: 0
has text: You are not writing enough newlines; remember that `print()` *adds* a newline each time that `file.write()` doesn’t.

string
tags question: http://stackoverflow.com/q/48472123
type: Tag
tags question: http://stackoverflow.com/q/48415006
tags question: http://stackoverflow.com/q/48352791
tags question: http://stackoverflow.com/q/48441382
tags question: http://stackoverflow.com/q/48374437
tags question: http://stackoverflow.com/q/48413706
tags question: http://stackoverflow.com/q/48385609
tags question: http://stackoverflow.com/q/48444067
tags question: http://stackoverflow.com/q/48418556
tags question: http://stackoverflow.com/q/48479039
tags question: http://stackoverflow.com/q/48469884
tags question: http://stackoverflow.com/q/48336963
tags question: http://stackoverflow.com/q/48447123
tags question: http://stackoverflow.com/q/48350061
tags question: http://stackoverflow.com/q/48453806
tags question: http://stackoverflow.com/q/48435051
tags question: http://stackoverflow.com/q/48343033
tags question: http://stackoverflow.com/q/48480352
tags question: http://stackoverflow.com/q/48347331
tags question: http://stackoverflow.com/q/48386742
tags question: http://stackoverflow.com/q/48410832
tags question: http://stackoverflow.com/q/48386339
tags question: http://stackoverflow.com/q/48334596
tags question: http://stackoverflow.com/q/48382219
tags question: http://stackoverflow.com/q/48469254
tags question: http://stackoverflow.com/q/48452274
tags question: http://stackoverflow.com/q/48352745
tags question: http://stackoverflow.com/q/48332599
tags question: http://stackoverflow.com/q/48336724
tags question: http://stackoverflow.com/q/48367128
tags question: http://stackoverflow.com/q/48407191
tags question: http://stackoverflow.com/q/48390258
tags question: http://stackoverflow.com/q/48408866
tags question: http://stackoverflow.com/q/48461131
tags question: http://stackoverflow.com/q/48384402
tags question: http://stackoverflow.com/q/48354561
tags question: http://stackoverflow.com/q/48363627
tags question: http://stackoverflow.com/q/48344676
tags question: http://stackoverflow.com/q/48356973
tags question: http://stackoverflow.com/q/48440007
tags question: http://stackoverflow.com/q/48358348
tags question: http://stackoverflow.com/q/48465368
tags question: http://stackoverflow.com/q/48360661
tags question: http://stackoverflow.com/q/48337735
tags question: http://stackoverflow.com/q/48353766
tags question: http://stackoverflow.com/q/48455895
tags question: http://stackoverflow.com/q/48334703
tags question: http://stackoverflow.com/q/48333346
tags question: http://stackoverflow.com/q/48408751
tags question: http://stackoverflow.com/q/48433734
tags question: http://stackoverflow.com/q/48428804
tags question: http://stackoverflow.com/q/48421142
tag name: string
tags question: http://stackoverflow.com/q/48358326
tags question: http://stackoverflow.com/q/48473646
tags question: http://stackoverflow.com/q/48351145
tags question: http://stackoverflow.com/q/48363477
tags question: http://stackoverflow.com/q/48363913
tags question: http://stackoverflow.com/q/48451909
tags question: http://stackoverflow.com/q/48425228
tags question: http://stackoverflow.com/q/48363461
tags question: http://stackoverflow.com/q/48477136
tags question: http://stackoverflow.com/q/48475377
tags question: http://stackoverflow.com/q/48426462

http://stackoverflow.com/comment/83678943
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48345711
has text: "he dataset consists of 500 images of 5 classes (100 each)" - seems that you may need more data to generalize better
type: Comment

http://stackoverflow.com/a/48394887
score: 1
has body: This line: loot = {'lock pick': 3, 'potion' : 1, 'lock pick': 4, 'potion' : 1, 'sword': 1} isn't doing what you expect, the second instance of lock pick is overwriting the first. Since loot is a dictionary, it can only have one instance of each key. If you want to allow multiple instances of a type of loot, consider a list of tuples: loot = [('lock pick', 3), ('potion', 1), ('lock pick', 4)] And then your function would look almost the same: def addToInventory(inventory, addedItems): for item, quantity in addedItems: inventory.setdefault(item, 0) inventory[item] += quantity
accepted answer of: http://stackoverflow.com/q/48394789
answers question: http://stackoverflow.com/q/48394789
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84021814
has text: You're welcome. If helpful, please consider checking this answer as resolved.
type: AnswerComment
comment on: http://stackoverflow.com/a/48490085
score: 0
type: Comment

http://stackoverflow.com/a/48468898
has body: Tkinter only supports 3 file formats off the bat which are GIF, PGM, and PPM. You will need to convert the files to .GIF then load them in using tkinter. There are libraries such as Python Imaging Library (PIL), however it might not be allowed in your school to use it. Hopefully your school allows Photoshop, GIMP or any image editing software to allow you to convert, but I am sure there are plenty of online programs.
score: 0
has comment: http://stackoverflow.com/comment/83932223
answers question: http://stackoverflow.com/q/48468536
type: Answer

http://stackoverflow.com/comment/83888048
has text: I like the first part of this answer. But since a character cannot be a digit, uppercase letter, and lowercase letter at the same time, the second part is incorrect.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48447597
type: AnswerComment

http://stackoverflow.com/comment/83748071
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yeah there are a lot of questions regarding NaNs having no len() but it is hard to find a canonical one as it can appear for everything. Let me know if you can find it.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48380586

http://stackoverflow.com/comment/83915658
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48461081
type: QuestionComment
has text: `timedelta` has no `__init__`. Why do you need it if you only call the base initializer inside? I think that if you need to do some custom initialization, you should override the *ctor* (`__new__`).

http://stackoverflow.com/comment/83730620
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48371821
score: 0
has text: Nice catch.. Totally missed that. *face-palm*

http://stackoverflow.com/comment/83779264
score: 1
comment on: http://stackoverflow.com/q/48395849
has text: How exactly are you trying it?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48367201
tagged with: python
has body: I'm trying to send an email using smtplib for python 3, but i get this error message when sending. File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 854, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-7: ordinal not in range(128)
tagged with: gmail
tagged with: python-3.x
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83721007
has title: Python 3 smtp error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83720950
tagged with: smtp
type: Question

http://stackoverflow.com/comment/83767440
comment on: http://stackoverflow.com/q/48389655
has text: @Hamoudaq given the specific nature of the actual file, I need to be able to search for the entirety of "|75=". Would regex allow me to do that where split is failing?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48474924
has title: Faster way to check for all numbers in a string
has body: I have a string that holds numbers. I want to check if the string has all the numbers between 0-9. Currently, the way I am checking is pretty slow and it will definitely be useless for large strings. Here is my code below: import sys # check if all numbers (0-9) exist in a string num = "31586055033755830765" for i in num: if int(i) not in [0, 1, 2 ,3 ,4 ,5 ,6, 7, 8, 9]: print("The string doesn't have all the numbers") sys.exit(1) The code works fine but is pretty slow. Is there a faster way to accomplish the task?
has answer: http://stackoverflow.com/a/48475010
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48475263
accepted answer: http://stackoverflow.com/a/48474973
has answer: http://stackoverflow.com/a/48474985
has answer: http://stackoverflow.com/a/48485888
has answer: http://stackoverflow.com/a/48474973
has answer: http://stackoverflow.com/a/48475248
possible better answer: http://stackoverflow.com/a/48475010
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/48464062
tagged with: python
answer count: 6
has comment: http://stackoverflow.com/comment/83948933

http://stackoverflow.com/comment/83829127
type: Comment
has text: @JimmyCarlos: "nothing added", yeah so I noticed. You could have added "1920x1080, 8-bit palette, non-interlaced", which is *exactly* what I had to guess.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48376967

http://stackoverflow.com/comment/83896040
type: AnswerComment
comment on: http://stackoverflow.com/a/48451344
score: 0
has text: on the machine I do current reviewing Tkinter isn't installed. So I can't check the script on functionality. OP could implement a threshold warning for debugging purpose. Something like: print value bx1, bx2 and see what happens. Something with swapping values back and forth.
type: Comment

http://stackoverflow.com/q/48486757
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84018607
has comment: http://stackoverflow.com/comment/83978595
answer count: 1
tagged with: textblob
has title: Can NLTK Data be installed in AWS Redshift environment?
type: Question
has body: I am trying to create a Python user defined scalar (UDF) function in an AWS Redshift DB. The UDF wraps the following Python code: CREATE or replace library nltk language plpythonu from 's3://xxx/dev/python-libraries/nltk-3.2.1.zip' credentials 'aws_access_key_id=xxx;aws_secret_access_key=yyy' region as 'eu-west-1'; CREATE or replace library textblob language plpythonu from 's3://xxx/dev/python-libraries/textblob-0.15.1-py2.py3-none-any.zip' credentials 'aws_access_key_id=xxx;aws_secret_access_key=yyy' region as 'eu-west-1'; CREATE or replace FUNCTION f_sentiment_polarity (comment varchar(1000)) RETURNS float IMMUTABLE as $$ from textblob import TextBlob return TextBlob(comment).sentiment.polarity $$ LANGUAGE plpythonu; SELECT f_sentiment_polarity('this would be very useful if the corpora were loaded'); f_sentiment_polarity -------------------- 0 The result of the select statement gives me 0 When I run the same Python code in a local environment (Python 2.7 on Windows with NLTK v3.2.5, I get 0.39: Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from textblob import TextBlob &gt;&gt;&gt; TextBlob('this would be very useful if the corpora were loaded').sentiment.polarity 0.39 &gt;&gt;&gt; I presume that this is because the various NLTK Corpora have not been loaded in the AWS Redshift Python environment. Creating another Redshift UDF as follows seems to bear this out: CREATE or replace FUNCTION f_num_brown_words () RETURNS int IMMUTABLE as $$ from nltk.corpus import brown return len(brown.words()) $$ LANGUAGE plpythonu; select f_num_brown_words(); ERROR: XX000: LookupError: ********************************************************************** Resource u'corpora/brown' not found. Please use the NLTK Downloader to obtain the resource: &gt;&gt;&gt; nltk.download() Searched in: - "'/'/nltk_data" - '/usr/shar Question: Is there a way of loading the NLTK Co…
tagged with: amazon-redshift
tagged with: nltk
has answer: http://stackoverflow.com/a/48489197
tagged with: python
tagged with: amazon-web-services
score: 0

http://stackoverflow.com/q/48439709
has answer: http://stackoverflow.com/a/48470722
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I have an Eleaticsearch index named 'demoadmin' with type named 'billing'. I have executed this following query body using POST successfully . {"query": { "filtered":{ "query" : {"match_all": {}}, "filter": { "bool": { "must":[{ "term": { "Month": "01" }}, { "term": { "Year": "2018" }}] } } } }, "size": 0, "aggregations": { "Total Cost": { "sum": { "field": "UnBlendedCost" } } } } this query returns the output like the following { "took": 16, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 503206, "max_score": 0, "hits": [ ] }, "aggregations": { "Total Cost": { "value": 5849.867677253019 } } } The query and the outputs looks like the following in Elasticsearch-head Query and output in Elasticsearch - head When I am trying to converting this code to python using elasticsearch python API ,the code is like the following and it returns the same output. ADMIN_INDEX_NAME ='demoadmin' es_client = get_es_client() def get_aggregated_total_cost_for_current_month(month,year): '''Get Aggregated total cost for the current month''' body = '{"query": { "filtered":{ "query" : {"match_all": {}}, "filter": { "bool": { "must":[{ "term": { "Month": "' + month + '" }}, { "term": { "Year": "' + year + '" }}] } } } }, "size": 0, "aggregations": { "Total Cost": { "sum": { "field": "UnBlendedCost" } } } }' total_cost_result = es_client.search(index=ADMIN_INDEX_NAME, doc_type="billing", body=body) raw_total_cost = total_cost_result['aggregations']['Total Cost']['value'] total_cost = float("%.2f" % raw_total_cost) print(str(total_cost)) return total_cost I am trying to convert the code in elasticsearch-dsl and got stuck. I have completed up to applying the filter but after that getting confused on what to do. So far I have implemented the code in elasticsearch-dsl like the following def get_aggregated_total_cost_for_current_month_new(month,year): '''Get Aggregated total cost for the current month''' s = Search(using=es_client, index=ADMIN_INDEX_…
tagged with: python
tagged with: elasticsearch-dsl
has title: sum calculation using elasticsearch-dsl python client
tagged with: elasticsearch-py
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48470722
tagged with: elasticsearch-dsl-py

http://stackoverflow.com/a/48355765
score: 1
has body: qrs1 = [1, 2, 3, 5, 9] qrs2 = [1, 4, 2, 5] list(set(qrs1).intersection(qrs2)) you just need an intersection of the querysets
type: Answer
answers question: http://stackoverflow.com/q/48355734
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/83795015
has text: @mai: This is basically what I do. I just need a way to (somehow externally to the rest of the source code) inject the decode key.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48400682
type: QuestionComment

http://stackoverflow.com/q/48462442
has answer: http://stackoverflow.com/a/48462578
score: 3
tagged with: python
has title: How to avoid Sympify to drop parentheses automatically
has body: Let's say I have the following string str1 = "a*(-d*(b+d)+d*(e*f))" If I sympify it the result is a*(d*e*f - d*(b + d)) But I don't want that Sympy drop those parenthesis. I want the final expression to be a*(d*(e*f) - d*(b + d)) How can this be done?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48462578
upvote count: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/48530973
downvote count: 0
tagged with: sympy
has answer: http://stackoverflow.com/a/48530973
favorite count: 0
type: Question

http://stackoverflow.com/q/48449578
type: Question
tagged with: python-3.x
has title: running python for multipul urls get no output
accepted answer: http://stackoverflow.com/a/48451198
tagged with: python
has body: I am trying to run a scraper for this website the code works when i just use one url but when i add multi it gives me no output. I need it to run thru the different urls and scrape the information. &gt; Blockquote &gt;`import requests &gt;import csv &gt;from bs4 import BeautifulSoup &gt;from html.parser import HTMLParser &gt;from time import sleep from random import randint &lt;import urllib.request r=requests.get('https://www.qiagen.com/us/products/a-z-list/#&amp;&amp;s=Ascending&amp;pg=55&amp;q=&amp;l=') c=r.content s=BeautifulSoup(c,"html.parser") product_urls = ['https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-precursor-assays/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assay-plate/#orderinginformation', 'https://www.qiagen.com/us/shop/pcr/primer-sets/miscript-primer-assays/#orderinginformation', 'https://www.qiagen.com/us/shop/genes-and-pathways/technology-portals/browse-qpcr/mirna-gene-expression/mirna-isolation/miscript-single-cell-qpcr-kit/#orderinginformation'] for url in product_urls: page = urllib.request.urlopen(url) s = BeautifulSoup(page,"html.parser") getall = s.find_all("div",{"class":"gene_globe_segment_0_OrderingInfoPane"}) getall for i in getall: product_name = (i.find('div',{'class':'title'}).text.strip()) product_discription = (i.find('div',{'class': 'copy'}).text.strip()) product_number = (i.find('td',{'class': 'textLeft paddingTopLess'}).text.strip()) cat_number = (i.find('td',{'class': 'textRight paddingTopLess'}).text.strip()) product_price = (i.find('td',{'class': 'textRight paddingTopLess priceSingle'}).text.strip()) for i in getall: print(i.find('div',{'class':'title'}).text.strip()) #product name print(i.find('div',{'class': 'copy'}).text.strip()) #product discription print(i.find('td',{'class': 'textLeft paddingTopLess'}).text.strip()) #product number print(i.find('td',{'class': 'textRight paddingTopLess'}).text.strip()) #cat number print(i.find('td',{'class': 'textRight paddingTopLess …
has comment: http://stackoverflow.com/comment/83894022
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83894231
has answer: http://stackoverflow.com/a/48451198

http://stackoverflow.com/comment/83882518
type: Comment
type: QuestionComment
has text: @Alfe adding nsmap = {...} solved the problem - thank you
score: 1
comment on: http://stackoverflow.com/q/48442556

http://stackoverflow.com/q/48407657
has answer: http://stackoverflow.com/a/48409055
tagged with: nawk
score: 0
has answer: http://stackoverflow.com/a/48426453
answer count: 3
has title: replace specific fields in file with fields from other file,fields which needs to be replaced will be found by matching different fields of samefiles
has body: I want to replace specific fields in file (separated by ,) with fields from other file Fields which needs to be replaced will be found after matching different fields of same files. e.g. cat test1.dat 12345,98765,aaaa,bbbbb 12346,98766,cccc,ddddd cat test2.dat 12345,something,something,something,something,something,98765,something,something,somethi 12345,something,something,something,something,something,45655,something,something,somethi 12346,something,something,something,something,something,98766,something,something,somethi 12346,something,something,something,something,something,44556,something,something,something Output file cat test3.dat aaaa,something,something,something,something,something,bbbbb,something,something,somethi 12345,something,something,something,something,something,45655,something,something,somethi cccc,something,something,something,something,something,ddddd,something,something,somethi 12346,something,something,something,something,something,44556,something,something,somethi in above example we are checking if ($1 of test2.dat == $1 of test1.dat &amp;&amp; $7 of test2.dat == $2 of test1.dat ) then ($1 of test2.dat = $3 of test1.dat) ($7 of test2.dat = $4 of test1.dat) test1.dat will have distinct values of $1 and $2 test2.dat will be a huge file having millions of records I am looking for solution which is fastest (we can even iterate through test1.dat and check for each row in test3.dat if it is fastest solution)
tagged with: awk
upvote count: 1
has answer: http://stackoverflow.com/a/48407903
downvote count: 1
favorite count: 0
type: Question
tagged with: sed
type: UnansweredQuestion
tagged with: perl
tagged with: python

http://stackoverflow.com/a/48418009
has comment: http://stackoverflow.com/comment/83985799
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: This answer is effectively identical to PaulPanzer's answer once you look at how the specific algorithms I use are coded in networkx: G=nx.Graph() G.add_edges_from([(1,2), (2,3), (4,5), (5,6)]) list(nx.connected_components(G)) &gt; [{1,2,3},{4,5,6}] #we're done setting G up. Let's do it. CCs = nx.connected_components(G) complete_subgraphs = (nx.complete_graph(component) for component in CCs) H=nx.compose_all(complete_subgraphs) Here we first find the connected components (technically we create a generator for them). Then we find all the complete graphs using nx.complete_graph(nodes) for each of those components. Finally we join all the graphs together with compose_all.
answers question: http://stackoverflow.com/q/48416445

http://stackoverflow.com/a/58963587
type: Answer
has body: Just wanted to add that this can be done for datasets where each element is a dictionary as well. For example, if one element of the input dataset looks like { 'feat1': [2,4], 'feat2': [3]} And for each element you want to split into to elements based on the elements in feat1, you could write: def split(element): dict_of_new_elements = { 'feat1': [ element['feat1'][:, 0], element['feat1'][:, 1]] 'feat2': [ element['feat2'], element['feat2']] } return tf.data.Dataset.from_tensor_slices(dict_of_new_elements) dataset.flat_map(split) Which would yield [ {'feat1': 2, 'feat2': 3}, {'feat1': 4, 'feat2': 3}, ]
answers question: http://stackoverflow.com/q/48471926
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48472947
score: 0
answers question: http://stackoverflow.com/q/48472352
type: Answer
has body: If your json is loaded into a variable named dic: print(dic['main']['temp'] * (9/5) - 459.67) Kelvin to fahrenheit formula from wikipedia.

http://stackoverflow.com/comment/83721478
type: Comment
score: 0
type: AnswerComment
has text: Better: use `if command not in {'l', 'h', 'c'}:`; Python optimises that case and you get a O(1) test.
comment on: http://stackoverflow.com/a/48367451

http://stackoverflow.com/a/48414403
type: Answer
answers question: http://stackoverflow.com/q/48413991
score: 0
has body: If you want to use a collections.defaultdict(), you can do this: from collections import defaultdict from pprint import pprint scores = [{'name': 'Joe', 'score': 98, 'subject': 'Math'}, {'name': 'Bob', 'score': 90, 'subject': 'Math'}, {'name': 'Bill', 'score': 88, 'subject': 'English'}, {'name': 'Jane', 'score': 95, 'subject': 'English'}] result = defaultdict(list) for score in scores: temp = {k: _ for k, _ in score.items() if k != 'subject'} result[score['subject']].append(temp) pprint([{'subject' : k, 'Results': v} for k, v in result.items()]) Which gives: [{'Results': [{'name': 'Joe', 'score': 98}, {'name': 'Bob', 'score': 90}], 'subject': 'Math'}, {'Results': [{'name': 'Bill', 'score': 88}, {'name': 'Jane', 'score': 95}], 'subject': 'English'}]

pre-commit-hook
tag name: pre-commit-hook
tags question: http://stackoverflow.com/q/48352771
type: Tag

http://stackoverflow.com/comment/83891318
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48449217
has text: @Piinthesky I'll upload my code now

http://stackoverflow.com/a/48368974
answers question: http://stackoverflow.com/q/48368952
type: Answer
has body: Here is the function that prints the the length: def print_length(): if time in line and failedPass in line: if dateHour == 'Feb 3 08': countAttack1.append(time) length1 = len(countAttack1) print(length1) print_length() &gt;&gt;&gt;Print length of the List.
score: 0

http://stackoverflow.com/comment/83922608
type: Comment
score: 0
type: QuestionComment
has text: How general of an answer are you looking for? Should it work with any class? Or do you want something that will work only with `Event`.
comment on: http://stackoverflow.com/q/48464321

http://stackoverflow.com/q/48465737
has comment: http://stackoverflow.com/comment/83932787
upvote count: 16
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48465822
tagged with: gmm
tagged with: gaussian
has title: How to convert log probability into simple probability between 0 and 1 values using python
tagged with: python
has body: I am using Gaussian mixture model for speaker identification. I use this code to predict the speaker for each voice clip. for path in file_paths: path = path.strip() print (path) sr,audio = read(source + path) vector = extract_features(audio,sr) #print(vector) log_likelihood = np.zeros(len(models)) #print(len(log_likelihood)) for i in range(len(models)): gmm1 = models[i] #checking with each model one by one #print(gmm1) scores = np.array(gmm1.score(vector)) #print(scores) #print(len(scores)) log_likelihood[i] = scores.sum() print(log_likelihood) winner = np.argmax(log_likelihood) #print(winner) print ("\tdetected as - ", speakers[winner]) and it gives me the output like this: [ 311.79769716 0. 0. 0. 0. ] [ 311.79769716 -5692.56559902 0. 0. 0. ] [ 311.79769716 -5692.56559902 -6170.21460788 0. 0. ] [ 311.79769716 -5692.56559902 -6170.21460788 -6736.73192695 0. ] [ 311.79769716 -5692.56559902 -6170.21460788 -6736.73192695 -6753.00196447] detected as - bart Here score function gives me the log probability for each speaker. Now i want to decide threshold value, for that i need these log probability value into simple probability value (between 0 to 1). How can i do that? I am using python software.
tagged with: logarithm
answer count: 2
has comment: http://stackoverflow.com/comment/83932757
has answer: http://stackoverflow.com/a/61825907
tagged with: probability-distribution
type: UnansweredQuestion
downvote count: 0
score: 16

websocket
tags question: http://stackoverflow.com/q/48394405
tags question: http://stackoverflow.com/q/48481246
tag name: websocket
tags question: http://stackoverflow.com/q/48407093
type: Tag
tags question: http://stackoverflow.com/q/48459764

http://stackoverflow.com/comment/83954434
score: 1
type: QuestionComment
has text: Depends on what do you understand by encryption. There are encryption methods invented thousands years ago, but now it's child play breaking them. One such method is `xor`ing each char in the string with the corresponding char in the password (the drawback is that the same algorithm applied to the encrypted text restores it).
type: Comment
comment on: http://stackoverflow.com/q/48480667

http://stackoverflow.com/q/48364250
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83715715
tagged with: tmp
has body: Goal I'm trying to write a zip file to the /tmp folder in a python aws lambda, so I can extract manipulate before zipping, and placing it in s3 bucket. Problem Os Errno30 Read Only FileSystem This code was tested locally on my computer to make sure the file would write to my working directory before I uploaded it to aws. This is the code i'm trying to use. file = downloadFile() #This is api call that returns binary zip object newFile = open('/tmp/myZip.zip','wb') newFile.write(file) extractAll('/tmp/myZip.zip') here is the code that is trying to extract the zip file def extractAll(self,source): with zipfile.ZipFile(source, 'r') as archive: archive.extractall() here is the trace [Errno 30] Read-only file system: '/var/task/test-deploy': OSError Traceback (most recent call last): File "/var/task/web.py", line 31, in web performAction(bb, eventBody) File "/var/task/src/api/web.py", line 42, in performAction zipHelper.extractAll('/tmp/myZip.zip') File "/var/task/src/shared/utils/zipfilehelper.py", line 24, in extractAll archive.extractall() File "/var/lang/lib/python3.6/zipfile.py", line 1491, in extractall self.extract(zipinfo, path, pwd) File "/var/lang/lib/python3.6/zipfile.py", line 1479, in extract return self._extract_member(member, path, pwd) File "/var/lang/lib/python3.6/zipfile.py", line 1538, in _extract_member os.mkdir(targetpath) OSError: [Errno 30] Read-only file system: '/var/task/test-deploy'
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83715619
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
has comment: http://stackoverflow.com/comment/83715605
type: Question
accepted answer: http://stackoverflow.com/a/48364639
has comment: http://stackoverflow.com/comment/83715550
has answer: http://stackoverflow.com/a/48364639
tagged with: errno
score: 26
has comment: http://stackoverflow.com/comment/83715599
tagged with: python
has title: Write to /tmp directory in aws lambda with python
upvote count: 26
has comment: http://stackoverflow.com/comment/83715901

http://stackoverflow.com/comment/83680825
comment on: http://stackoverflow.com/q/48347290
score: 0
type: Comment
type: QuestionComment
has text: @CharlesDuffy: That’s what the separate function to request without exceptions would be for =)

http://stackoverflow.com/q/48415382
tagged with: python
has comment: http://stackoverflow.com/comment/83826468
score: -1
has answer: http://stackoverflow.com/a/48425354
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83820543
has comment: http://stackoverflow.com/comment/83820658
possible better answer: http://stackoverflow.com/a/48425354
downvote count: 2
has body: Hi I was wondering if anyone could answer my question, how would I go about making a game with graphics in python instead of text based games. I'm only new though so if it involves another programming language then I'm probably can't do it yet.
upvote count: 1
has title: How to make games that use graphic instead of text?
accepted answer: http://stackoverflow.com/a/48415512
tagged with: graphics
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48415512

http://stackoverflow.com/comment/83693587
has text: Python 2 or 3? Add that to the question please.
score: 0
comment on: http://stackoverflow.com/q/48353538
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83859250
score: 0
type: Comment
type: AnswerComment
has text: @barmar yes, I forgot the FROM in the SQL statement. my bad.
comment on: http://stackoverflow.com/a/48433723

http://stackoverflow.com/q/48479115
accepted answer: http://stackoverflow.com/a/48479671
downvote count: 0
has comment: http://stackoverflow.com/comment/83951302
has comment: http://stackoverflow.com/comment/83951336
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/48479671
has comment: http://stackoverflow.com/comment/83951516
has comment: http://stackoverflow.com/comment/83951655
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83951463
has comment: http://stackoverflow.com/comment/83951279
score: 1
answer count: 1
tagged with: twitter
has body: I have tried to scrape twitter account followers list. For that, authentication is required. So i used requests library for authentication purpose. The problem i am getting is, when i try to authenticate, I am getting 200 response but authentication is not done. The code is: import requests from bs4 import BeautifulSoup import json payload={ "session[username_or_email]":"*****************", "session[password]":"**********************", "authenticity_token":"aa3520020157738bdabb6d60f2e02894c6c85689", "ui_metrics":'{"rf":{"a67dd0828000993f688a64a8238f647dd8ef987feb0db5979725fc7e304c3989":-250,"a4cd98aa5fd1d026bfded286fc24eb6ac9cf01a65b789ade51b68558cb0f6ae0":-21,"a88c7b5bdeb04ce3cf55df08c0f981f99df760b9348680c735fbff5b60ad054f":51,"a5e59c69fb04ab30f2f8468030c31ca1150f4265e4c2a35dbb1b67b85be6954f":-68},"s":"QdcvZJ9RhjLcVcW2N_pDt5j5AKQJCkqnh9caYV5ykW35tRpQc_RN5s_VefN2uVCONpXf-qZa-fr8VtCAFrtiOf2f6PhloU2GyxLDN38wGppFNWhb4psCr7x-kibioS9PDxWZF1pe3FM-MOz9YtIQrWxbmEAWnRTK3gUn-1nv4kTFDa159YxJoXiYt43g41sRUJWezJI2yJaECnO1ARbkNAPKrMndxRAcq_5qSFpT8CqzEUvBKPMdFMKeUrzeEecqmx632lTV1NlucVIvV9co3Y3Rk7CtURoaiCwsjTED1brU4XAY3VwsTEuNRUYZqirRNZrYQBCHqsMh5FV_UHpO2QAAAWE40pmN"}', "scribe_log":"", "redirect_after_login":"", "authenticity_token":"aa3520020157738bdabb6d60f2e02894c6c85689", "return_to_ssl":"", "remember_me":"1", "lang":"", "redirect":"" } headers={ "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding":"gzip, deflate, br", "accept-language":"en-US,en;q=0.9", "cache-control":"max-age=0", "cookie":'moments_profile_moments_nav_tooltip_self=true; syndication_guest_id=v1%3A150345116906281638; eu_cn=1; kdt=QErLcBT9OjM5gjEznmsRcHlMTK6biDyAw4gfI5ro; _ga=GA1.2.1923324433.1496571570; tfw_exp=0; __utma=43838368.1923324433.1496571570.1516764481.1516764481.1; __utmz=43838368.1516764481.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); remember_checked_on=0; personalization_id="v1_Iq7dc3Mq746/e91mchhhJg=="; guest_id=v1%3A1516985040…
has comment: http://stackoverflow.com/comment/83951480
has title: Getting 200 response but not logging in using python requests library
tagged with: post
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/q/48466293
score: 1
has body: i try add my model into admin. but error run while i create class for model.admin i don't know why my class read is not defined. i using python 3.6 and Django 2.0 from django.contrib import admin from .models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') raw_id_fields = ('author') date_hierarchy = ('publish') ordering = ['status', 'publish'] admin.site.register(Post, PostAdmin) here my debug error : "C:\Program Files\JetBrains\PyCharm 2017.3\bin\runnerw.exe" C:\Users\FIANUAENA\PycharmProjects\mysite\venv\Scripts\python.exe C:/Users/FIANUAENA/PycharmProjects/mysite/manage.py runserver 8000 Unhandled exception in thread started by .wrapper at 0x05E1EE88> Traceback (most recent call last): File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\FIANUAENA\PycharmProjects\mysite\venv\l…
tagged with: python
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48466881
type: UnansweredQuestion
tagged with: django
has title: Admin class not defined in django
has answer: http://stackoverflow.com/a/48466392
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83891208
has text: When I try to use concat, it gives me the following AttributeError: can't set attribute [25/Jan/2018 12:06:25] "GET /account/profile/ HTTP/1.1" 500 96620 probably because i'm not trying to filter down to a single username, but a list.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48449227

http://stackoverflow.com/q/48333140
tagged with: loops
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48430611
has answer: http://stackoverflow.com/a/48430611
tagged with: python
has title: openpyxl write multiple rows in Excel
has body: I am trying to write multiple rows to Excel. "Containers" has an index/len of 10. Although I loop through it, I only get one row when I run the script. Can anyone help me with this? # define first empty row start_row = sheet.max_row + 1 #write to excel for container in containers: #Company name company_container = container.div.h2 company = company_container.text.strip() #City city = container.div.a["title"] #URL url = container.div.div.a["href"] #Title title_container = container.findAll("div", {"class":"info"}) title = title_container[0].img["alt"] #Description description = title_container[0].p.text #Programming language hardskill = "Java" #Vervolgactie (Teamleader) vervolgactie = "Nieuw" companyinfo = [company, city, url, title, description, hardskill, vervolgactie] for i in range(0,len(companyinfo)): e=sheet.cell(row=start_row,column=1+i) e.value=companyinfo[i] wb.save("vacatures.xlsx")
type: AnsweredQuestion
score: 1
tagged with: openpyxl
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83677210
has text: Thanks for the suggestion, but I'm not sure what you mean by "check it once again." I did try it again and once again it did not work (as described above).
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48340185

http://stackoverflow.com/comment/83827403
has text: `find_all` returns list. It's better you go through doc than I explain it here. https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48415135
type: AnswerComment

http://stackoverflow.com/a/53681271
has body: I had a similar issue where I was trying to add a group when a user instance was saved. The anwer why this is happening is at the docs and more explicitly (using code) at this ticket. When saving a ModelForm() (hitting save in the admin), first an instance of the object is saved, then all its signals are triggered etc. The third step is to save all m2m relations using ModelForm().cleaned_data. If ModelForm().cleaned_data['tags'] is None, all the relations created from your signal, will be deleted. A hackish solution, is to use a post_save signal with transaction.on_commit() which will execute the relevant code after the existing transaction (which includes the procedure of saving all m2m relations) is committed to the database. def on_transaction_commit(func): ''' Create the decorator ''' def inner(*args, **kwargs): transaction.on_commit(lambda: func(*args, **kwargs)) return inner @receiver(post_save, sender=Photo) @on_transaction_commit def tags(instance, raw, **kwargs): """ Create the relevant tags after the transaction of instance is committed, unless the database is populated with fixtures. """ if not raw: update_tags(instance) A more sound solution if your many to many relation has not blank=True is to use a m2m_changed() signal, as explained in this post or the before mentioned ticket. The best of all, is to ditch the signals and override the ModelForm().clean() method for the case where a ModelForm() is used, and also override the Model().save() method in case the model is directly saved. A ModelForm().instance.my_flag will be useful so you can check for an existing Model().my_flag in Model().save() to avoid accessing twice the database.
answers question: http://stackoverflow.com/q/48450004
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83681143
score: 1
type: QuestionComment
has text: @JulianRachman use `io`
type: Comment
comment on: http://stackoverflow.com/q/48347497

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48405228
tags question: http://stackoverflow.com/q/48362364
tags question: http://stackoverflow.com/q/48453231
tags question: http://stackoverflow.com/q/48473110
tags question: http://stackoverflow.com/q/48408370
tags question: http://stackoverflow.com/q/48362903
tags question: http://stackoverflow.com/q/48481958
tags question: http://stackoverflow.com/q/48333923
tags question: http://stackoverflow.com/q/48419029
type: Tag
tags question: http://stackoverflow.com/q/48389667
tags question: http://stackoverflow.com/q/48421596
tags question: http://stackoverflow.com/q/48430380
tags question: http://stackoverflow.com/q/48358997

http://stackoverflow.com/comment/83724922
has text: You have a conflict between `df1` and `df2` for the file `6.txt` in `is_about_pony`
comment on: http://stackoverflow.com/q/48369117
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83884364
type: AnswerComment
has text: Thanks for the info, I think I can find a way to incorporate this into my processes. However, my main focus (and I apologize for not providing the necessary emphasis) is to pass information dynamically into the included file. Your comment regarding __file__ will allow the ability to pass the name of my script to a specific log file, but I find I have to use nearly twenty lines of code (practically all the same boilerplate) for every script I would like to provide logging for.
comment on: http://stackoverflow.com/a/48428185
score: 0
type: Comment

http://stackoverflow.com/comment/83709559
type: Comment
score: 0
has text: Afaik [`uint64`/`int64` and `float64`/`complex128` are the largest numbers](https://docs.scipy.org/doc/numpy/user/basics.types.html), `numpy` can work with. One of the aspects, numpy is not consistent with Python 3 declarations.
type: QuestionComment
comment on: http://stackoverflow.com/q/48361124

http://stackoverflow.com/comment/114238836
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48430736
type: Comment
has text: to whom this may concern: this helped me in django1.11 (python2.7) to django3.1 (python3.6) migration

http://stackoverflow.com/a/48455240
type: Answer
has comment: http://stackoverflow.com/comment/83926221
upvote count: 4
has body: You need to call makeChoice. In Python, functions are objects, and transmitting the function (without calling it) to various parts of the program is sending the entire function object to be called later. In this case, you need to access the returned object, the integer: while True: choiceMade(makeChoice()) Also, note that you need to use == instead of = in makeChoice. = is for assignment, while == is for comparison only: new makeChoice: def makeChoice(): c = 0 if input=='yes': return int(c) Additionally, a : is needed at the end of the function header choiceMade: def choiceMade(c): if c == 1: print('finally this damn thing works')
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48455207
has comment: http://stackoverflow.com/comment/83903683

http://stackoverflow.com/comment/83776640
type: Comment
type: QuestionComment
has text: As for the Unicode error, look here https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20.
comment on: http://stackoverflow.com/q/48394439
score: 0

http://stackoverflow.com/comment/84811487
type: Comment
score: 0
type: AnswerComment
has text: Also using 0.8.1
comment on: http://stackoverflow.com/a/48884632

http://stackoverflow.com/comment/126414883
type: Comment
type: AnswerComment
has text: You're right. I edited my answer accordingly.
score: 0
comment on: http://stackoverflow.com/a/48457078

http://stackoverflow.com/a/48335834
has comment: http://stackoverflow.com/comment/83656706
type: Answer
has body: def conti(): c=raw_input('Do You Wana Continue y/n....') if c=='y': main() else: break You can use return statement in place of break because break will come outside the loop whereas return will return you to main function else if you want to come out of program you can simply use exit()
score: 0
answers question: http://stackoverflow.com/q/48335655

http://stackoverflow.com/q/48486071
type: Question
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83964790
has answer: http://stackoverflow.com/a/48486257
answer count: 1
accepted answer: http://stackoverflow.com/a/48486257
has body: for v in enumerate (["20170106", "20170113", "20170127", "20170203", "20170210", "20170224", "20170303", "20170310", "20170324", "20170331"]) Year17 = "/Users/Name/Desktop/Datas/" + v csvFiles = glob.glob (os.path.join (Year17, "*.csv")) df = (pd.read_csv(i) for i in csvFiles) df = pd.concat (df, ignore_index=True) The subfolders "20170106", "20170113", "20170127", etc... which are inside the folder "Year17" This code works good, but: How can I avoid writing all the subfolders names "20170106", "20170113", "20170127", etc... in the for sentence? Maybe os.walk? How it would be?
linked to: http://stackoverflow.com/q/973473
favorite count: 0
type: AnsweredQuestion
has title: Folder and subfolders
score: -2
tagged with: python

http://stackoverflow.com/q/48408270
answer count: 2
has comment: http://stackoverflow.com/comment/83805887
upvote count: 3
has answer: http://stackoverflow.com/a/48420397
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/11949808
favorite count: 0
tagged with: class
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83828049
has title: How can I call a method stored in a variable?
tagged with: methods
accepted answer: http://stackoverflow.com/a/48412328
type: Question
has answer: http://stackoverflow.com/a/48412328
has body: If I have a class Foo with the method method1, is there a way to store this method in a variable before instantiation, which I then could call after this class is instantiated? For example: class Foo: def method1(self, arg): print(self, arg) # something like this variable, but which can be called with instantiated class func = Foo.method1 foo = Foo() foo.func(1) # I want to call it in a similar way to this
possible better answer: http://stackoverflow.com/a/48420397

http://stackoverflow.com/q/48479215
favorite count: 0
has body: Question I'd like for all the documents created by a single DocuSign Template/PowerForm to be configured with a webhook so that I don't need to continuously poll every 15 minutes to get completed documents. I've done a lot of reading, and want to know if this is even possible in the DocuSign API. Background I have a self-service waiver document: Users navigate to a URL, fill out their contact information (i.e. define a Recipient role), and expect that their completed waiver is recognized by a linked system. I have a DocuSign template that is being used in a PowerForm: Users navigate to the PowerForm's URL, and the PowerForm will let them create a new Envelope from the associated Template. I'd like for the documents created by this setup to automatically notify an HTTPS endpoint upon completion, via a standard webhook. Attempted solutions The Envelopes::create method (POST /v2/accounts/{accountId}/envelopes) accepts an eventNotification parameter that can be used to configure webhooks. The webhook recipe covers usage of this endpoint quite nicely. This would solve my problem, if I were creating every Envelope via an API request, but I like the ease of a copy-pastable URL that comes with a PowerForm. It's not documented, but it appears that Envelopes::update (PUT /v2/accounts/{accountId}/envelopes/{envelopeId}) may support configuring notifications on an already-created envelope. I could repeatedly query the most current envelopes for my template, update the notifications on in-progress envelopes and process the completed ones, but that's no better than polling. I browsed the REST API, specifically the Templates and PowerForms categories, but I don't see any obvious way to configure either resource to set eventNotification on created envelopes. Here's a quick code dump of some of the API exploration I've done: #!/usr/bin/env python3 import requests username = 'user@example.com' password = 'some-sensitive-password' integrator_key = 'abcdef01-2345-6789-0abcdef0123456789…
tagged with: rest
type: Question
tagged with: python
tagged with: docusignapi
accepted answer: http://stackoverflow.com/a/48503474
has title: How to configure eventNotification on DocuSign PowerForms/Templates
has answer: http://stackoverflow.com/a/48503474
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/135193654
upvote count: 1
answer count: 1
downvote count: 1

oauth
tags question: http://stackoverflow.com/q/48343024
tags question: http://stackoverflow.com/q/48408230
tag name: oauth
type: Tag
tags question: http://stackoverflow.com/q/48471093
tags question: http://stackoverflow.com/q/48433331

http://stackoverflow.com/comment/83855375
comment on: http://stackoverflow.com/q/48432090
score: 0
type: Comment
type: QuestionComment
has text: Python *always* passes by reference.

http://stackoverflow.com/comment/83889925
comment on: http://stackoverflow.com/a/48448679
score: 0
type: AnswerComment
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html
type: Comment

http://stackoverflow.com/comment/83705804
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48355267
has text: What kind of image do you want to create? A geometric model (like STL)? A 3D-volumen, like medical CT?
type: Comment

http://stackoverflow.com/q/48361886
tagged with: pandas
has title: Drop specific row from a DataFrame with a MultiIndex
accepted answer: http://stackoverflow.com/a/48361928
has comment: http://stackoverflow.com/comment/83711002
answer count: 1
has answer: http://stackoverflow.com/a/48361928
tagged with: multi-index
downvote count: 1
has comment: http://stackoverflow.com/comment/83710738
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83710848
has comment: http://stackoverflow.com/comment/83710950
score: 3
has comment: http://stackoverflow.com/comment/83710831
tagged with: python
has comment: http://stackoverflow.com/comment/83711026
upvote count: 4
type: AnsweredQuestion
has body: I have a Dataframe with 2 data columns and a multiindex for every month and every day in a month, so something like: temperatureMax temperatureMin time time 1 1 14.167500 7.744167 2 13.735000 7.480833 3 14.228333 7.901667 4 13.891667 7.350833 5 13.735833 6.903333 6 13.670000 6.494167 7 13.642500 7.040000 8 13.005000 6.175000 9 13.034167 5.253333 10 13.260833 5.628333 11 13.783333 5.511667 12 13.823333 6.630000 13 13.265833 6.712500 14 13.112500 6.130000 15 12.355833 7.213333 16 13.032500 6.533333 17 13.175833 7.030000 18 13.184167 8.225000 19 13.896667 6.658333 20 13.711667 5.693333 21 13.442500 5.944167 22 13.245000 6.468333 23 13.765000 5.555833 24 14.260000 5.212500 25 13.523333 5.850000 26 13.000000 5.519167 27 12.554167 5.264167 28 12.806667 5.311667 29 12.755000 6.012500 30 13.240833 6.136667 ... ... ... 12 2 13.545000 5.855833 3 14.380833 6.214167 4 14.502500 7.610833 5 15.379167 8.201667 6 15.161667 8.593333 7 15.101667 8.940833 8 14.886667 7.217500 9 14.701667 7.680000 10 14.756667 7.160000 11 14.575000 6.057500 12 14.172500 7.138333 13 14.360833 7.244167 14 14.285833 7.430000 15 13.545000 6.167500 16 14.082500 5.516667 17 13.780833 5.871667 18 13.345833 5.357500 19 13.909167 5.682500 20 13.264167 5.570833 21 14.828333 6.620833 22 14.431667 6.689167 23 13.564167 6.491667 24 14.343333 6.074167 25 13.470000 5.594167 26 13.468333 4.400833 27 13.403333 5.600833 28 14.506667 7.085833 29 14.173333 6.999167 30 14.211667 7.810000 31 13.604167 7.382500 [366 rows x 2 columns] How can I remove a specific day of the month? Namely, I want to remove the 29th of February from this list. The only thing I can do is to remove every 29th day of every 12 month with daily_mean.drop(29, level=1), but I want to do that only for February.

http://stackoverflow.com/comment/83665619
has text: Okay. Finally figured the problem. Need to add the inbound and outbound TCP rule and restart the system
type: Comment
comment on: http://stackoverflow.com/q/48334579
type: QuestionComment
score: 0

http://stackoverflow.com/a/48454831
score: 0
has body: Forgot to add the header row when creating the csv on application start, that resolved all of it. writer.writeheader() That's all it needed.
type: Answer
answers question: http://stackoverflow.com/q/48454312

http://stackoverflow.com/q/48406572
has comment: http://stackoverflow.com/comment/83802137
has comment: http://stackoverflow.com/comment/83805355
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83803391
tagged with: io
has comment: http://stackoverflow.com/comment/83804415
has comment: http://stackoverflow.com/comment/84446396
has body: I have 4 Python scripts / processes running in parallel, each one appending text to a file every ~30 seconds: while True: id = processing_job() # 30 seconds long with open('log.txt', 'a+') as f: f.write('Job number #%i done.' % id) Is there a risk, when using open(..., 'a+') that 2 processes want to write exactly at the same time, and then some text cannot be written in the log.txt and is lost? Note: I'm using Windows platform.
tagged with: python
has comment: http://stackoverflow.com/comment/83803494
has comment: http://stackoverflow.com/comment/83802351
score: 0
linked to: http://stackoverflow.com/q/3032482
has comment: http://stackoverflow.com/comment/83805966
linked to: http://stackoverflow.com/q/1154446
answer count: 1
has comment: http://stackoverflow.com/comment/84098393
tagged with: file
has comment: http://stackoverflow.com/comment/84097953
has answer: http://stackoverflow.com/a/48406667
tagged with: multiprocessing
type: Question
has title: Four processes appending text to the same file

http://stackoverflow.com/a/48455803
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48441193
type: Answer
has body: @cezar Thank you very much! The solution is so simple! I was confused at the early time. Because the given solutions are using ModelSerializer by that you have to put fields and coupling with model properties. In my example is bare plain Serializer I don't need any of them. From now on I would attacking this kind of problem by Serializer class class FacebookReactionSerializer(serializers.Serializer): """ value serializer the inner most of the payload """ item = serializers.CharField() verb = serializers.CharField() reaction_type = serializers.CharField() created_time = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(4086831600)] ) # Limit the maximum epoch to 2099 July 4th 7:00AM post_id = serializers.CharField(max_length=40) parent_id = serializers.CharField() def create(self, validated_data): pass def update(self, instance, validated_data): pass FacebookReactionSerializer._declared_fields["from"] = FromSerializer() Here is my debugging lines (Pdb) serializer FacebookReactionSerializer(data={'item': 'reaction', 'verb': 'add', 'reaction_type': 'like', 'created_time': 1516183830, 'post_id': '1331351323541869_1844740022202994', 'from': {'name': 'Krittuch Onnom', 'id': '1639217166122728'}, 'parent_id': '1331351323541869_1844740022202994'}): item = CharField() verb = CharField() reaction_type = CharField() created_time = IntegerField(validators=[&lt;rest_framework.compat.MinValueValidator object&gt;, &lt;rest_framework.compat.MaxValueValidator object&gt;]) post_id = CharField(max_length=40) parent_id = CharField() from = FromSerializer(): name = CharField() id = CharField() (Pdb) serializer.is_valid() True
accepted answer of: http://stackoverflow.com/q/48441193
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/116883159

http://stackoverflow.com/comment/83849278
score: 0
type: AnswerComment
has text: how can i do this in a dataframe?
comment on: http://stackoverflow.com/a/48429063
type: Comment

http://stackoverflow.com/comment/83728021
has text: You have to pass two *sprites* to `checkCollision` instead of two rects. It would also make sense to change it, so that the method takes only the other sprite as an argument and then pass `self` to `collide_rect`: `col = pygame.sprite.collide_rect(self, other_sprite)`. `collide_rect` could also be replaced by `pygame.Rect.colliderect`. BTW, the `Vehicle` class should inherit from `pygame.sprite.Sprite`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48369730
type: Comment

http://stackoverflow.com/comment/83961127
comment on: http://stackoverflow.com/q/48479032
type: Comment
score: 0
has text: The second thing to try is https://rudd-o.com/linux-and-free-software/how-to-make-pulseaudio-run-once-at-boot-for-all-your-users
type: QuestionComment

http://stackoverflow.com/a/48917417
downvote count: 0
score: 1
upvote count: 1
has body: I'm using anaconda and just pip installed it. Any particular reason you need it installed by Conda?
answers question: http://stackoverflow.com/q/48434325
type: Answer

http://stackoverflow.com/a/48395833
score: 1
type: Answer
has body: An else would useful here: if x == 0: print("Undefined") else: yx = y/x yx = int (slope) if yx != 0: print ("%d"%yx) else: print ("Undefined")
has comment: http://stackoverflow.com/comment/83780230
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83780108
has comment: http://stackoverflow.com/comment/83780213
answers question: http://stackoverflow.com/q/48395742

http://stackoverflow.com/q/48377998
tagged with: python
has answer: http://stackoverflow.com/a/48378081
has answer: http://stackoverflow.com/a/48378305
accepted answer: http://stackoverflow.com/a/48378081
has answer: http://stackoverflow.com/a/48378159
possible better answer: http://stackoverflow.com/a/48378159
has body: How to add the current list item with the previous 1st list item using python. &gt;&gt;&gt; l = [4,2,1,3] If I perform the below I get cumulative sum &gt;&gt;&gt; new_l = np.cumsum(l) But I want to add the current list only with the previous 1st list, the desired output should be like this one. &gt;&gt;&gt; new_l [4, 6, 3, 4]
has answer: http://stackoverflow.com/a/48380487
type: AnsweredQuestion
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/83742907
has answer: http://stackoverflow.com/a/48378329
downvote count: 1
has answer: http://stackoverflow.com/a/48378220
has title: How to add the current item with the previous item in a list using python
has answer: http://stackoverflow.com/a/48378202
has comment: http://stackoverflow.com/comment/83742753
favorite count: 0
has comment: http://stackoverflow.com/comment/83743551
type: Question
tagged with: numpy
answer count: 8
has comment: http://stackoverflow.com/comment/83743049
has answer: http://stackoverflow.com/a/48378306
has comment: http://stackoverflow.com/comment/83743947

http://stackoverflow.com/a/48411293
has comment: http://stackoverflow.com/comment/86160995
upvote count: 6
has body: The ends of the whiskers are configurable via the upper_head and lower_head properties, which are ArrowHead objects that have their own line_color, etc. The easiest way to configure them is probably like this: w = Whisker(source=source_error, base="base", upper="upper", lower="lower", line_color='red') w.upper_head.line_color = 'red' w.lower_head.line_color = 'red' p.add_layout(w) Though it's also be possible to pass an explicitly configured TeeHead to Whisker if you really want to do everything in one expression: Whisker(..., upper_head=TeeHead(line_color='red'), lower_head=TeeHead(line_color='red'))
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48405055
has comment: http://stackoverflow.com/comment/83868103
has comment: http://stackoverflow.com/comment/86206809
type: Answer

http://stackoverflow.com/comment/83668085
has text: What does it mean *Is there a better way of doing this?* ? If it does not say which parameter is better this question tends to be based on opinions making it off-topic
type: QuestionComment
comment on: http://stackoverflow.com/q/48341411
type: Comment
score: 1

http://stackoverflow.com/comment/83750139
comment on: http://stackoverflow.com/q/48378702
score: 0
type: QuestionComment
has text: Yes but only one command like adb shell (cd /data/) works. I want to enter multiple lines of code as explained above. I am using Python 2.7.12
type: Comment

http://stackoverflow.com/comment/83727671
type: QuestionComment
score: 0
has text: It's better use `requests` module for getting html
type: Comment
comment on: http://stackoverflow.com/q/48370348

http://stackoverflow.com/a/48384275
has body: Since Go supports vendoring, you can use an utility like https://github.com/golang/dep to have all dependencies in the project.
type: Answer
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48382330
has comment: http://stackoverflow.com/comment/127545870

http://stackoverflow.com/a/48459262
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83911638
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48459191
has body: A topping can have many pizzas. A topping is not specific to a particular pizza - pepperoni can be on as many pizzas as you like, and you don't want a separate instance of Topping with name "pepperoni" for each pizza it is on. So many-to-many is the appropriate structure here. If you did have a ForeignKey though, it is more idiomatic to access the toppings through the pizza itself: my_pizza = Pizza.objects.get(order_id=order_id) toppings = my_pizza.topping_set.all()
has comment: http://stackoverflow.com/comment/83911580
accepted answer of: http://stackoverflow.com/q/48459191

http://stackoverflow.com/comment/83931561
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48468846
has text: your question is different. Other questions address only windows. Macintosh is a different beast.

http://stackoverflow.com/a/48469402
answers question: http://stackoverflow.com/q/48469254
upvote count: 3
downvote count: 1
has body: Edited with what the OP really wanted: &gt;&gt;&gt; from functools import partial &gt;&gt;&gt; lst = ['10_file', '11_file', '1_file', '20_file', '21_file', '2_file'] &gt;&gt;&gt; sorted(lst, key=partial(str.split, sep='_', maxsplit=1)) ['1_file', '10_file', '11_file', '2_file', '20_file', '21_file']
type: Answer
score: 2

http://stackoverflow.com/a/48482636
has comment: http://stackoverflow.com/comment/83958496
has comment: http://stackoverflow.com/comment/83958453
has body: Here's one way. Note this requires structure, i.e. room, then size sequentially. I don't think that's a bad idea, since you should be using a dictionary or list of tuples anyway. my_list = ['room', 10, 'chamber', 23, 'kitchen', 8] pos = my_list.index(max(my_list[1::2])) # 23 print('The biggest room is ' + my_list[pos-1]) # chamber
type: Answer
has comment: http://stackoverflow.com/comment/83979660
has comment: http://stackoverflow.com/comment/83959882
score: 0
has comment: http://stackoverflow.com/comment/83959061
has comment: http://stackoverflow.com/comment/83972622
has comment: http://stackoverflow.com/comment/83974851
accepted answer of: http://stackoverflow.com/q/48481022
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83958504
upvote count: 1
has comment: http://stackoverflow.com/comment/83965127
downvote count: 1
answers question: http://stackoverflow.com/q/48481022

http://stackoverflow.com/q/48352616
has title: Python: Keep track of which dictionary paths were accessed
has comment: http://stackoverflow.com/comment/83692038
score: 5
answer count: 0
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/113759187
has comment: http://stackoverflow.com/comment/100442035
upvote count: 5
has body: I have a huge python dictionary (few gigs when written to a JSON). Before writing the dictionary to the disk, there are a bunch of routines that take this dictionary and use information in certain paths (legacy code). I'd like to keep track of which paths are accessed / used. One way is to go through this legacy code and I am looking for a way that avoids this. I can instrument the code before calling into these legacy routines. Is there anything I can do that can result in tracking/logging the paths in the huge dictionary that are being accessed. e.g. { "a": { "b": { "c": "d" } } "e": { "f": { "g": "h" } } Lets say the legacy code accessed the key "g", I need to log the path (e:f:g). I'd like to do this without touching/modifying the legacy code.
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/48391502
has comment: http://stackoverflow.com/comment/83771133
upvote count: 2
possible better answer: http://stackoverflow.com/a/48391592
downvote count: 0
accepted answer: http://stackoverflow.com/a/48391580
has title: Python dictionary update only if value is defined
has answer: http://stackoverflow.com/a/48391592
tagged with: data-structures
has answer: http://stackoverflow.com/a/48391580
type: Question
has answer: http://stackoverflow.com/a/48391599
answer count: 3
has body: If I run the following code: import json foo = [ { "name": "Bob", "occupation": "", "standing": "good", "locations": ["California"], "meta": { "last_updated": "2018-01-15" } }, { "name": "", "occupation": "Carpenter", "standing": "bad", "locations": ["Arizona"], "meta": { "last_updated": "2018-01-15", "email": "bob@domain.com" } }, ] output = {} for i in foo: output.update(i) print json.dumps(output) The final output is: { "locations": [ "Arizona" ], "meta": { "email": "bob@domain.com", "last_updated": "2018-01-15" }, "name": "", "occupation": "Carpenter", "standing": "bad" } That's pretty good. However, I'm trying to figure out how I can pass a function to the update method that basically says, "Only update if the value is defined/not empty." Therefore, on the first iteration name is "Bob", and on the second iteration name remains Bob since name is essentially undefined. The final output would look like this: { "locations": [ "Arizona" ], "meta": { "email": "bob@domain.com", "last_updated": "2018-01-15" }, "name": "Bob", "occupation": "Carpenter", "standing": "bad" }
tagged with: python
tagged with: dictionary
favorite count: 0
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83733803
score: 0
has text: Specifically once I get to the download page and click download it doesn't seem to produce any requests in the dev tools. Prior to clicking the download link it produces a request and shows the raw HTML with the fist page of results. I am trying to grab all of the results, preferably in the csv that downloads after you click the download button. It does look like the request method is a GET though.
type: Comment
comment on: http://stackoverflow.com/q/48373164
type: QuestionComment

http://stackoverflow.com/a/48410044
type: Answer
answers question: http://stackoverflow.com/q/48409782
accepted answer of: http://stackoverflow.com/q/48409782
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: According to this issue, the back-end API doesn't support batching "media" operations

http://stackoverflow.com/q/48369929
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48369943
accepted answer: http://stackoverflow.com/a/48369943
has answer: http://stackoverflow.com/a/48369991
has title: Creating a new column based on the values of other columns
possible better answer: http://stackoverflow.com/a/48369949
tagged with: python
score: 4
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/48370076
type: AnsweredQuestion
has body: I wanted to create a "High Value Indicator" column, which says "Y" or "N" based on two different value columns. I want the new column to have a "Y" when Value_1 is > 1,000 or Value_2 > 15,000. Bellow is the table, the desired output would include the indicator column based on the or condition about. ID Value_1 Value_2 1 100 2500 2 250 6250 3 625 15625 4 1500 37500 5 3750 93750
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48369949

http://stackoverflow.com/q/48475970
tagged with: flatten
has title: How can I calculate the run-time complexity of this flatten array function if number of items is unknown?
tagged with: big-o
type: Question
has body: I have a function flattens given array. def flatten(items): results = [] for i in items: if isinstance(i, list): results += flatten(i) else: results.append(i) return results It works great. It is not possible to know how many times it will run when I give an input as shown below. There are a lot of nested arrays. data = [1, 2, 3, [4], [5, 6], [[7, 8, 9], 10, 11, 12], [13, 14, 15, [[[16], 17], 18, 19], [[[20, 21]]]], [[[22], 23, [[24]]]]] data_flatten = flatten(data) print(data_flatten) I have no idea how can I calculate the run-time complexity of this function?
answer count: 2
upvote count: 3
type: UnansweredQuestion
tagged with: arrays
has answer: http://stackoverflow.com/a/48476050
tagged with: python
downvote count: 1
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/48476306

http://stackoverflow.com/q/48357989
has body: I'm using MicroPython with two NodeMCU ESP8266 dev boards. My goal is to connect one to the other, so they can interchange information. One of the boards is running a server program and its AP is up. The other connects to the other board's AP and try to connect. The server is running fine, and I can connect to it with Kitty using a RAW connection (connecting my PC to the ESP8266 AP). The client, instead, fails in socket.connect() and throws a ECONNABORTED exception. I've used differents settings, but none of them seems to work. How can I connect my two boards? I'm a newbie with sockets, so this may be not a MicroPython specific problem but a Python one. EDIT: There's no problem when connecting from a PC using the same code. The problem seems to be exclusive of a client ESP8266 connecting to a server ESP8266 through the server Access Point. Maybe a MicroPython bug? Server code: import network import socket def runServer(): try: ap_if = network.WLAN(network.AP_IF) ap_if.active(True) ap_if.config(essid='MicroPy-AP', password='micropythoN') s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind( ('', 8266) ) s.listen(1) print("Waiting for a client...") client, client_ip = s.accept() print("Connected!") finally: print("Closing socket...", end=' ') s.close() print("Done.") Client code: import network import socket def runClient(): try: sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('MicroPy-AP', 'micropythoN') while not sta_if.isconnected(): pass sta_if.ifconfig() s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print("Connecting...") s.connect( ('192.168.4.1', 8266) ) finally: print("Closing socket...", end=' ') s.close() print("Done.")
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/48413162
has title: Socket error ECONNABORTED connecting two MicroPython boards
tagged with: esp8266
score: 0
tagged with: micropython
answer count: 1
type: Question

http://stackoverflow.com/q/48342073
answer count: 0
tagged with: triangulation
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83677992
tagged with: rssi
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83670998
has body: I am working on Beacon Triangulation Algorithm using Python. I have beacon data from the reader and calculating the distance using RSSI value. can anyone please guide me how to approach this method? I am reading a text file which has large no of RSSI values. I am unable to process these large no of values. Let say I have 30 RSSI values in a file. How can I calculate 30 distance values using these values? Any method to calculate the centroid of the intersection of three circles? Thanks
type: UnansweredQuestion
has title: Beacon_Triangulation_python_centroid
tagged with: python
tagged with: beacon
score: 0

http://stackoverflow.com/comment/123308943
type: Comment
score: 0
type: AnswerComment
has text: `print(whatever.encode('ascii', 'ignore'))`
comment on: http://stackoverflow.com/a/48347549

http://stackoverflow.com/comment/83938005
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48471274
has text: Note that the reference warns about using this code in production. For the purpose you describe I don't see why not to stick with the clean solution described above **KILLING IT**
type: Comment

http://stackoverflow.com/q/48430597
upvote count: 1
score: 1
tagged with: image-processing
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to make a sobel filter and apply partial derivatives and magnitude to an image
tagged with: sobel
type: UnansweredQuestion
tagged with: python
tagged with: image
has body: I'm currently trying to implement sobel filter in python, in the code below i attempted to as wikipedia explained how sobel filter worked, hoever i haven't understood what the magnitude does to the image, and how to apply it G_x = np.array([[1,0,-1], [2,0,-2], [1,0,-1]]) //Gx G_y = np.array([[1,2,1], [0,0,0], [-1,-2,-1]]) //Gy Gx = sg.convolve2d(f, G_x, "same", "symm") //f is a loaded image Gy = sg.convolve2d(f, G_y, "same", "symm") magnitude = np.sqrt(Gx**2 + Gy**2) Sorry if this has been asked before, however the only questions i could find about this did not prove me any help While on the topic, i've also been doing the same but with finite approximations, however i don't understand exactly how they differ as a result (maybe i will once i get sobel filter working), but if someone could explain that aswell i would be very happy.
answer count: 0
downvote count: 0

http://stackoverflow.com/q/48336820
tagged with: python
accepted answer: http://stackoverflow.com/a/48339861
tagged with: python-decorators
has answer: http://stackoverflow.com/a/56408968
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48339861
score: 2
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44499490
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/53404074
tagged with: observer-pattern
has comment: http://stackoverflow.com/comment/83664707
has answer: http://stackoverflow.com/a/53404074
favorite count: 0
has body: This question is not in general about the observer pattern. It is focused on the use of decorators in that pattern. The question is based on the answer of a similar question. #!/usr/bin/env python3 class Observable: """ The object that need to be observed. Alternative names are 'Subject'. In the most cases it is a data object. """ def __init__(self): self._observers = [] def register_observer(self, callback): self._observers.append(callback) return callback def _broadcast_observers(self, *args, **kwargs): for callback in self._observers: callback(*args, **kwargs) class TheData(Observable): """ Example of a data class just for demonstration. """ def __init__(self, data): Observable.__init__(self) self._data = data @property def data(self): return self._data @data.setter def data(self, data): self._data = data self._broadcast_observers() class TheGUIElement: """ Example of a gui class (Widget) just for demonstration. e. g. it could be a text field in GUI. """ def __init__(self, data): self._data = data #data.register_observer(self._data_updated) self._redraw() def _redraw(self): print('in _redraw(): ' + data.data) @Observable.register_observer def _data_updated(self, **kwargs): """ This is the callback that is called by the Observable if the data changed. """ print('in _data_updated() - kwargs: {}'.format(kwargs)) self._redraw() if __name__ == '__main__': data = TheData('DATA') gui = TheGUIElement(data) data.data = 'SECOND DATA' This code doesn't work because of this error. Traceback (most recent call last): File "./o.py", line 42, in &lt;module&gt; class TheGUIElement: File "./o.py", line 55, in TheGUIElement @Observable.register_observer TypeError: register_observer() missing 1 required positional argument: 'callback' It is unclear to me how to use a decorator for to register the observers (e.g. TheGUIElement).
has title: Using decorators to implement Observer Pattern in Python3
type: Question
has comment: http://stackoverflow.com/comment/83658864

http://stackoverflow.com/q/48354366
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83695455
tagged with: logic
type: AnsweredQuestion
has body: import collections class MyStack: def __init__(self): self._data = [] def push(self, value): self._data.append(value) def size(self): #Return the number of elements in the stack return len(self._data) def toString(self): #Return a string representing the content of this stack return str(self._data) class MyQueue: def __init__(self): self._data = collections.deque([]) def enqueue(self, value): self._data.append(value) def dequeue(self): return self._data.popleft() def size(self): #return the number of elements in the queue return len(self._data) queue1 = MyQueue() dq = MyStack() stack1 = MyStack() stack1.push(['stone', 'atone']) print "size of stack is now :" ,stack1.size() queue1.enqueue(stack1) print "size of queue is now :", queue1.size() print "size of stack is now :" ,stack1.size() stack1.push(['stone', 'shone']) stack1.push(['stone', 'scone']) dq = queue1.dequeue() # i would like dq to be ['stone','atone'] print dq.toString() This is a school assignment, I'm not allowed to modify codes for the functions enqueue and dequeue and def__init__(self). I'm trying to use popleft as a means to dequeue an item from a queue. However, the compiler returns the whole queue rather than only the first stack of the queue while I'm using popleft. That being said , the size of the queue decreases by one. Any explanation for this? The compiler returns [['stone', 'atone'], ['stone', 'shone'], ['stone', 'scone']] when I only want it to return ['stone', 'atone'].
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83695381
tagged with: python
tagged with: queue
score: -1
type: Question
has answer: http://stackoverflow.com/a/48354519
has title: How do I dequeue using popLeft in a queue properly?
upvote count: 0
tagged with: stack
answer count: 1
has comment: http://stackoverflow.com/comment/83695528
accepted answer: http://stackoverflow.com/a/48354519

http://stackoverflow.com/q/48405569
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48405634
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48405634
favorite count: 0
type: Question
has body: Below is an example of the data set I am working with. I am trying to do a group by on Location for only the top 3 locations based on KGs. Location KG Dollars BKK 7 2 BKK 5 3 BKK 4 2 BKK 3 3 BKK 2 2 HKG 8 3 HKG 6 2 HKG 4 3 HKG 3 2 HKG 2 3 The output would look like below. Grouped on the location, summing both KG and Dollars for the top 3 KG records for each location. Location KG Dollars BKK 16 7 HKG 18 8 I've tried different types of groupbys, just having a problem only specifying the top n KG records for the groupby.
tagged with: python
type: AnsweredQuestion
has title: Groupby top n records based on another column
tagged with: pandas-groupby

http://stackoverflow.com/comment/83806477
type: Comment
has text: thanks all for the downvotes, and @DavidG thanks for your comment and edit, i mean what kind of a structure it is? how does it know what to do without any inputs provided?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48398923

http://stackoverflow.com/q/48427385
downvote count: 0
answer count: 1
has title: Speed up parameter testing using Dask
has comment: http://stackoverflow.com/comment/83849553
has body: I have a time series dataframe with about 10 columns where I am performing manipulations on the time series to return results of strategy data. I would like to test 2 parameters as they may or may not effect each other. When tested independently, each run take over 10 sec per unit(over 6.5 hours for the total run) and I'm looking to speed this up..I have been reading about dask and it seems that its the right module to use. My current code iterates over each parameter range with a nested loops. I know it can be paralleled as the data per day is mutually exclusive. Here is the code: amount1=np.arange(.001,.03,.0005) amount2=np.arange(.001,.03,.0005) def getResults(df,amount1,amount2): final_results=[] for x in tqdm(amount1): for y in amount2: df1=None df1=function1(df.copy(), x, y ) #takes about 2sec. df1=function2(df1) #takes about 2sec. df1=function3(df1) #takes about 3sec. final_results.append([x,y,df1['results'].iloc[-1]]) return final_results UPDATE: So it looks like the improvements should come by adjusting the function to remove the iteration from the calls and to create a list of jobs(my understanding. Here is where I am so far. I probably will need to move my df to a dask dataframe, so that the data can be chunked into smaller pieces. The question is do I leave the function1,2 and 3 functions as pandas vector manulipulations or do they need to move to complete dask functions? def getResults(df,amount): df1=None df1=dsk.delayed(function1)(df,amount[0],amount[1] ) df1=dsk.delayed(function2)(df1) df1=dsk.delayed(function2)(df1) return [amount[0],amount[1],df1['results'].iloc[-1]] #Create a list of processes from jobs. jobs is a list of tuples that replaces the iteration. processes =[getResults(df,items) for items in jobs] #Create a process list of results results=[] for i in range(len(processes): results.append(processes[i])
favorite count: 0
type: Question
tagged with: dask
accepted answer: http://stackoverflow.com/a/48430907
has answer: http://stackoverflow.com/a/48430907
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83849725
has comment: http://stackoverflow.com/comment/83917997
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83926687
tagged with: pandas
score: 1

http://stackoverflow.com/comment/83672630
has text: Yeah, but... where's the "Price" or whatever? You probably need to make a multidimensional array containing the name **and** the price, then you can sort the array.
comment on: http://stackoverflow.com/q/48343525
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48353766
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83694302
has answer: http://stackoverflow.com/a/48355435
accepted answer: http://stackoverflow.com/a/48354949
has answer: http://stackoverflow.com/a/48355070
has answer: http://stackoverflow.com/a/48354949
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/48358592
type: AnsweredQuestion
has title: How to remove a particular substring from a list of strings?
tagged with: list
linked to: http://stackoverflow.com/q/3559559
upvote count: 0
has answer: http://stackoverflow.com/a/48357339
has body: I have two lists, y1=['fem j sex / male \n', " father's name diwan singh saggu \n", "elector's name rahul saggu \n", 'identity card \n', 'zfk0281501', 'age as on 1.1.2008 23 \n'] word=["sex","father's","name","elector's","name","identity","card","age"] I need to remove all the strings in y1 which is in word. I need to get output as output=['fem j /male','diwan singh saggu','rahul saggu','zfk0281501','as on 1.1.2008 23'] I have split individual elements in y1 and tried comparing it with word.But i dont know what to do next? How to remove the strings??Here is what i tried, y1new=[] for y in y1: tmp=y.split() y1new.append(tmp) for i in y1new: for j in i: if j in word: y1new[i].remove(y1new[i][j]) How can i achieve this?
has answer: http://stackoverflow.com/a/48353797
score: -7
tagged with: string
possible better answer: http://stackoverflow.com/a/48355435
downvote count: 7

http://stackoverflow.com/comment/83911722
score: 1
comment on: http://stackoverflow.com/q/48459455
type: QuestionComment
has text: Umm... why not just `import scriptN` then access with `scriptN.myfunc`?
type: Comment

http://stackoverflow.com/a/48370062
answers question: http://stackoverflow.com/q/48369505
type: Answer
has body: Some way of doing this for a general case, using itertools: import itertools as it files = [ '/home/pi/Documents/Test/name.txt', '/home/pi/Documents/Test/state.txt', '/home/pi/Documents/Test/status.txt' ] def loadData(fpath): with open(fpath, "r") as f: yield from f.redlines() with open('/home/pi/Documents/Test/final.txt') as f: for e in it.chain.from_iterable(zip(*map(loadDAta, files))): f.write(e)
score: 0

http://stackoverflow.com/a/48742150
score: 0
answers question: http://stackoverflow.com/q/48452274
accepted answer of: http://stackoverflow.com/q/48452274
type: AcceptedAnswer
has body: I Solved this first by writing a new file with \t separations and then using pandas.read_csv('file_name',sep='\t'). The main trick here was to count the '/' and '.'s in each split of line: def classify(strx): #call this on each line next_hop = 0 prefix = "" #path = "" path = [] for i in strx.split(' '): slash_counter,dot_counter = i.count('/'),i.count('.') #print(i.count('.'),i.count('/')) if dot_counter == 3 and slash_counter == 1: prefix = i elif dot_counter == 3 and slash_counter == 0: next_hop = i elif len(i) &gt; 1 and dot_counter == 0 and slash_counter == 0: #path = path.join(i) path.append(i) #print("Sanity check on paths",path,"\t",i) #path = path.join(' ') path_ = path path = " ".join([str(i) for i in path_]) protocol = strx[-1] #print(protocol) #print("prefix = {0}, next hop = {1}, path = {2}".format(prefix,next_hop,path)) return(prefix,next_hop,path,protocol) an example: original line: '0 1.0.128.0/17 80.249.208.85 3257 38040 9737 i' after converting with above function: 1.0.128.0/17 80.249.208.85 3257 38040 9737 i
type: Answer
has comment: http://stackoverflow.com/comment/85052950

http://stackoverflow.com/q/48435200
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
has body: I'm trying to crawl a website. url = "http://www.hellotrade.com/business/" headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36", 'Connection':'close' } res = requests.get(url, headers = headers, timeout = 30) It runs perfectly at the beginning, but after running a while later, it comes out the error message. Traceback (most recent call last): File "C:\Users\millshih\Desktop\hellotrade.py", line 32, in &lt;module&gt; res = s.get(url, headers = headers, timeout = 30) File "C:\Python27\lib\site-packages\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "C:\Python27\lib\site-packages\requests\adapters.py", line 508, in send raise ConnectionError(e, request=request)requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.hellotrade.com', port=80): Max retries exceeded with url: /business/ (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x0294F3D0&gt;: Failed to establish a new connection: [Errno 10060] \xb3s\xbdu\xb9\xc1\xb8\xd5\xa5\xa2\xb1\xd1\xa1A\xa6]\xac\xb0\xb3s\xbdu\xb9\xef\xb6H\xa6\xb3\xa4@\xacq\xae\xc9\xb6\xa1\xa8\xc3\xa5\xbc\xa5\xbf\xbdT\xa6^\xc0\xb3\xa1A\xa9\xce\xacO\xb3s\xbdu\xab\xd8\xa5\xdf\xa5\xa2\xb1\xd1\xa1A\xa6]\xac\xb0\xb3s\xbdu\xaa\xba\xa5D\xbe\xf7\xb5L\xaak\xa6^\xc0\xb3\xa1C',)) After this error, I have to wait until next day then it can run again, but it will have same problem after running couple minutes later. But my browser is doing well to surf this website. So, it means my IP is not banned by this website. I've tried this and some other ways from the internet, but it can't work at all. I'm wondering maybe it is because of my internet connection problem?
tagged with: python-requests
favorite count: 0
tagged with: proxy
linked to: http://stackoverflow.com/q/15820739
has title: python requests requests.exceptions.ConnectionError: Failed to establish a new connection: [Errno 10060]
tagged with: python
tagged with: web-crawler
type: Question
answer count: 0

http://stackoverflow.com/comment/83886578
has text: You've got this correct, you just cut on the entire table. You should be cutting on a series i.e. `pd.cut(original_table['column_name'], bins, labels=values)`
type: Comment
comment on: http://stackoverflow.com/q/48447147
score: 0
type: QuestionComment

http://stackoverflow.com/a/48485641
type: Answer
upvote count: 1
has body: Minimal changes to your code that works as desired, though I suggest you to understand the first answer by Gerges Dib. def polynomial_to_string(p_list): terms = [] degree = 0 for coeff in p_list: if coeff &gt; 0: if coeff == 1: coeff = '' if degree == 0: terms.append(str(coeff)) elif degree == 1: terms.append(str(coeff) + 'x') else: term = str(coeff) + 'x^' + str(degree) terms.append(term) degree += 1 terms.reverse() final_string = ' + '.join(terms) return final_string
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83964471
answers question: http://stackoverflow.com/q/48485289

http://stackoverflow.com/q/48477268
downvote count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83951618
answer count: 1
tagged with: tk-toolkit
tagged with: memory
has body: I wrote simple application that dynamically creates labels from list of dictionaries. my dict dictionary is result of fetching data from api but in example code below I changed it for minimize the code. This work as I expected but after few loops it is slower and stop responding. How I can fix that? Thank you for help in advance! from tkinter import * import threading import time idn = 0 zbior_naglowkow = ('id' , 'date',) zbior_frame = ('BC', 'LC', ) mydict = [{'typ': 'LC', 'id': 12, 'date': '2018-01-26 19:49:15'}, {'typ': 'LC', 'id': 16, 'date': '2018-01-16 19:49:15'}, {'typ': 'BC', 'id': 1, 'date': '2018-01-26 19:49:15'}, {'typ': 'BC', 'id': 2, 'date': '2018-01-26 19:49:15'}, {'typ': 'LC', 'id': 3, 'date': '2018-01-26 19:49:15'}, {'typ': 'BC', 'id': 4, 'date': '2018-01-26 19:49:15'}, {'typ': 'BC', 'id': 5, 'date': '2018-01-26 19:49:15'}] def raise_frame(frame): frame.tkraise() def ap(): threading.Timer(0, apka).start() def dane(): zbior_frame = ('BC', 'LC', ) nr_ = 1 nn = 0 for nazwa_typ in zbior_frame: row_naglowek = 190 row_oferta = 200 col_id = 30 col_cena_zakupu_obliczona = 40 col_date = 50 ramka = 'f'+str(nr_)+'_'+nazwa_typ ramka = eval(ramka) nr_ +=1 for offert in mydict: if offert['typ'] == nazwa_typ: naglowek_Label = Label(ramka, text=zbior_naglowkow[0]) naglowek_Label.grid(row = row_naglowek, column = col_id) id_Label = Label(ramka, text=offert['id']) id_Label.grid(row = row_oferta, column = col_id) naglowek_Label = Label(ramka, text=zbior_naglowkow[1]) naglowek_Label.grid(row = row_naglowek, column = col_date) date = offert['date'] date_Label = Label(ramka, text=date) date_Label.grid(row = row_oferta, column = col_date) row_oferta += 10 col_id +=10 col_date += 10 def apka(): global idn idn += 1 mydict.append({'typ' : 'LC' , 'id': idn , 'date' : '2018-01-26 19:49:15',}) print(mydict) dane() root.after(1000,apka) root = Tk() root.title('App') root.geometry('1200x900') f0_dashboard = Frame(root) f1_BC = Frame(root) f2_LC = Frame(root) zbior_fnr = (f0_dashbo…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48478396
type: UnansweredQuestion
score: -2
tagged with: python
has title: tkinter freezes after few loops
upvote count: 0

http://stackoverflow.com/q/48422569
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/83834816
tagged with: machine-learning
tagged with: scikit-learn
has title: Sklearn PCA function - unhashable type: 'slice'
favorite count: 0
has body: my code's major objective is transform a 3D dataframe to 2D by PCA decomposition , but unable to executed it, i assume the question is the return , but dont know how to correct it , please review: def do_PCA(x, svd_solver): from sklearn.decomposition import PCA pca = PCA(n_components=2, svd_solver='full') pca.fit(x) PCA(copy=True, iterated_power='auto', n_components=2, random_state=None, svd_solver='full', tol=0.0, whiten=False) return x pca = do_PCA(x, "full") fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('Full PCA') ax.scatter(pca[:,0], pca[:,1], c='blue', marker='.', alpha=0.75) plt.show() The error I get: TypeError Traceback (most recent call last) &lt;ipython-input-66-94cd1f5059d5&gt; in &lt;module&gt;() 3 ax = fig.add_subplot(111) 4 ax.set_title('Full PCA') -&gt; 5 ax.scatter(pca[:,0], pca[:,1], c='blue', marker='.', alpha=0.75) 6 plt.show() TypeError: unhashable type: 'slice'
has comment: http://stackoverflow.com/comment/83834572
has comment: http://stackoverflow.com/comment/83834994
tagged with: python
has comment: http://stackoverflow.com/comment/83835429
has comment: http://stackoverflow.com/comment/83835314
has comment: http://stackoverflow.com/comment/83835100
has comment: http://stackoverflow.com/comment/83834610
type: Question
has comment: http://stackoverflow.com/comment/83835446
has comment: http://stackoverflow.com/comment/83835129
score: 0
tagged with: pca
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/83698642
comment on: http://stackoverflow.com/q/48355942
type: Comment
type: QuestionComment
has text: @ArashHatami no. Something else is making it look like you can only use lists, but really, Python uses ducktyping, so anything that *behaves* like a list will work. So: Use a proper data management tool (ORM, Pandas), see my answer.
score: 2

http://stackoverflow.com/q/48398486
has title: If value in 'amount' is < 0 then move to new array
has comment: http://stackoverflow.com/comment/83784713
tagged with: python
has comment: http://stackoverflow.com/comment/83785889
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21608228
has comment: http://stackoverflow.com/comment/83786235
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
score: 1
has comment: http://stackoverflow.com/comment/83786147
has body: I have tried several different ways to solve this problem but none of them helped me out. I'm importing csv data out of Finanzblick, and I have an array called amount. If the values within this array' (e.g. 19.34) are positive (greater than zero) then it should be transferred to the array inflow. If the value is negative (e.g. -19.34) it should be transferred to 'outflow' import pandas as pd import numpy as np from pandas.core.tools.numeric import to_numeric df=pd.read_csv("C:/Users/PD/Desktop/Finanzblick Dokumente/2017_11/2017_11- DB.csv", sep=';',usecols=(0,1,2,3,4), encoding='utf-8', decimal=',') df.columns = ['Date', 'Payee', 'Verwendungszweck', 'Buchungstext', 'Betrag'] df['Memo'] = df'Buchungstext', 'Verwendungszweck'.apply(lambda x: ' -- '.join(x), axis=1) Betrag = df.Betrag.astype(int) df['Inflow'] = np.where(df.Betrag &gt; 0, df.Betrag, "") df['Outflow'] = np.where(df.Betrag &lt; 0, df.Betrag*(-1), "") df.to_csv('C:/Users/PD/source/repos/Finanzblick YNAB/Finanzblick YNAB/2017_11-DB-import.csv',sep=';', index = False, columns=['Date', 'Payee', 'Memo', 'Inflow', 'Outflow'], decimal='.') Greetings Phil
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83785206
upvote count: 1
has comment: http://stackoverflow.com/comment/83785394
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48399057
has comment: http://stackoverflow.com/comment/83785246
has comment: http://stackoverflow.com/comment/83784766
has answer: http://stackoverflow.com/a/48399057

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

http://stackoverflow.com/comment/83830304
score: 1
comment on: http://stackoverflow.com/q/48420022
type: Comment
has text: @VikasDamodar It's not the same then! The content is the same, not the file!
type: QuestionComment

http://stackoverflow.com/comment/83767936
has text: correct. rpm will not be able to resolve dependencies and `yum` does that for you. Unfortunately, there is no other way than downloading the dependencies one by one. Since you have a system that is up and running, I would assume this list not to be too long.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48389805
score: 0

http://stackoverflow.com/a/48446186
has body: One can use following function to determine if all words in a list are present in sent text: def allpresent(text, wordlist): for word in wordlist: if text.find(word) == -1: return False return True Following code can then be used to get new dataframe: newdf = pd.DataFrame(index=df.doc.tolist(), columns=labels.keys()) for rownum in range(len(df)): txt = df.text[rownum] for k,v in labels.items(): if allpresent(df.text[rownum], v): newdf.loc[df.doc[rownum], k] = 1 else: newdf.loc[df.doc[rownum], k] = 0 print(newdf) Output: item_4278 item_4279 item_4276 doc1 0 0 1 doc2 0 1 1 doc3 0 0 0
has comment: http://stackoverflow.com/comment/83887707
answers question: http://stackoverflow.com/q/48443426
type: Answer
score: 0

http://stackoverflow.com/comment/83742386
type: QuestionComment
comment on: http://stackoverflow.com/q/48377585
score: 0
type: Comment
has text: @brunodesthuilliers I guess this would work but I'd prefer to achive this without modifying data or adding another field with normalized code.

http://stackoverflow.com/comment/83805882
score: 0
comment on: http://stackoverflow.com/q/48408263
type: QuestionComment
has text: Cleaning up the code now, will post shortly. I agree that append is the best and most pythonic way to do this. The only reason I feel like I shouldn't be using it is technically I'm not supposed to know how yet. I only know it's an option because I've been researching this exercise for a week now and append seems to be the best and only choice. I feel like there must be another, if less elegant way, to accomplish the same thing.
type: Comment

http://stackoverflow.com/a/65528688
score: 0
answers question: http://stackoverflow.com/q/48367283
has body: If you are using Jupyter notebook an easiest way to install mglearn is by entering this: !pip install mglearn And then import the module by usual way: import mglearn this worked for me:
type: Answer

http://stackoverflow.com/q/48422533
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83836509
has title: Django ORM: List of Foreign Key values
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/83872477
answer count: 0
has comment: http://stackoverflow.com/comment/83872014
has comment: http://stackoverflow.com/comment/83836077
has comment: http://stackoverflow.com/comment/83982739
has comment: http://stackoverflow.com/comment/83835653
has comment: http://stackoverflow.com/comment/83997248
type: Question
has comment: http://stackoverflow.com/comment/83863288
has comment: http://stackoverflow.com/comment/83835738
has comment: http://stackoverflow.com/comment/83835301
has body: I have a table which has a column which stores a list of values. These values are basically Foreign key values of another table. Tables are: groups ( id TEXT PRIMARY KEY, users TEXT [], name TEXT NOT NULL, user_count INT NOT NULL, group_type TEXT NOT NULL CHECK (group_type IN ('random', 'friends')) DEFAULT 'random', validity_period INT NOT NULL, user_add_time INT NOT NULL, winner TEXT [], energy_drink_fee INT DEFAULT 0, energy_bar_fee INT DEFAULT 0, winnings INT DEFAULT 0, -- can be 0 (for free tournaments), 40, 150 (for paid tournaments) created_at TIMESTAMP DEFAULT now(), updated_at TIMESTAMP DEFAULT now() ); In Django, it is: class Groups(models.Model): id = models.TextField(primary_key=True) users = ArrayField(blank=True, null=True, base_field=models.CharField) name = models.TextField() user_count = models.IntegerField() group_type = models.TextField() validity_period = models.IntegerField() user_add_time = models.IntegerField() winner = ArrayField(blank=True, null=True, base_field=models.CharField) energy_drink_fee = models.IntegerField(blank=True, null=True) energy_bar_fee = models.IntegerField(blank=True, null=True) winnings = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) 'users' and 'winners' are the columns which store ids of User table (username is the id). I am not changing the database, the tables are the same, except that I am using Django for reading into this database (Legacy DBs). I am still not sure about the ArrayField though. This is the query I had written in SQL: SELECT COUNT(g.*) AS match_count, TEXT(g.created_at::DATE) AS created_at FROM groups g JOIN users u ON u.username = ANY (g.winner) WHERE g.created_at::DATE &gt;= '2018-01-01' AND g.created_at::DATE &lt;= '2018-01-20' AND g.winnings = 0 AND g.group_type = 'random' AND u.type = 'u' AND g.winner IS NOT NULL GROUP BY g.created_at::DATE I need to migrate this query into Django's ORM…
has comment: http://stackoverflow.com/comment/83876254
tagged with: django

http://stackoverflow.com/comment/84154225
has text: You need add VM's NIC id.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48378190

http://stackoverflow.com/comment/104571760
score: 0
type: Comment
has text: I believe --download is deprecated. `pip download <package>` works though.
type: AnswerComment
comment on: http://stackoverflow.com/a/53135936

http://stackoverflow.com/a/48433723
answers question: http://stackoverflow.com/q/48433642
score: 7
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/83858957
has comment: http://stackoverflow.com/comment/83859229
has comment: http://stackoverflow.com/comment/83858928
has comment: http://stackoverflow.com/comment/83859050
type: AcceptedAnswer
downvote count: 0
has body: The syntax error is because you left out the FROM clause in your query. Once you fix that, you need to have as many ? in the IN() list as there are elements in df_col. placeholders = ", ".join(["?"] * len(df_col)) sql = """ SELECT columnA, columnB, columnC FROM yourTable WHERE columnc IN (""" + placeholders + ")" execu = mycursor.execute(sql, df_col) rows = mycursor.fetchall() print(rows)
accepted answer of: http://stackoverflow.com/q/48433642
has comment: http://stackoverflow.com/comment/83859250

http://stackoverflow.com/a/48358369
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48358320
has comment: http://stackoverflow.com/comment/83703459
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83703743
has body: Such a code would work in python 2, but python 3 range doesn't return a list but it is kept as a range object where len works (and does its best to emulate an actual list). But in python 3: &gt;&gt;&gt; range(1,4) range(1, 4) &gt;&gt;&gt; list(range(1,4)) [1, 2, 3] &gt;&gt;&gt; [1,2,3] == range(1,4) False &gt;&gt;&gt; list(range(1,4)) == [1,2,3] True The list and range types are different and according to the documentation Objects of different types, except different numeric types, never compare equal. to get equality you need to explicitly convert n to a list n = list(range(1, len(A)+1)) more concise working approach: def solution(A): return int(sorted(A) == list(range(1,len(A)+1))) IMHO keeping the int conversion isn't required unless you explicitly want to return 0 or 1 instead of natural False or True Why you got 1 or 0 depending on your debugging or not is probably because you're using 2 different installs of python, one for debugging, and one for running. I suggest that you get rid of python 2 installation if you already use python 3.
has comment: http://stackoverflow.com/comment/83703693
has comment: http://stackoverflow.com/comment/83703453
has comment: http://stackoverflow.com/comment/83703575
type: Answer
answers question: http://stackoverflow.com/q/48358320

http://stackoverflow.com/q/48464671
favorite count: 0
type: Question
tagged with: tkinter
tagged with: canvas
has body: I had a program when I could move with a word thing, but when I add message box it stopped working. How to fix it? This is my program: from tkinter import * from random import * canvas = Canvas(width=1920, height=1080) canvas.pack() from tkinter import messagebox dialog_title = '?????????????' dialog_text = 'Question?' answer = messagebox.askquestion(dialog_title, dialog_text) if answer == 'yes': canvas.create_text(960,300,text="yes",font="Arial 50",fill="Blue") else: # 'no' canvas.create_text(960,300,text="no",font="Arial 50",fill="Blue") y=canvas.create_text(1000,500, text="thing",font="Arial 30",fill="pink") def r (event): canvas.move(y,15,0) def l (event): canvas.move(y,-15,0) def d (event): canvas.move(y,0,15) def u (event): canvas.move(y,0,-15) canvas.bind_all('&lt;Right&gt;',r) canvas.bind_all('&lt;Left&gt;',l) canvas.bind_all('&lt;Down&gt;',d) canvas.bind_all('&lt;Up&gt;',u) o=randrange(100,1800,15) p=randrange(100,980,15) i=canvas.create_text(o,p,text="end",fill="red",font="Arial 50")
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83922993
has answer: http://stackoverflow.com/a/48468625
has title: Can´t move object when I add messagebox
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/11418625
downvote count: 1

http://stackoverflow.com/a/48399148
type: Answer
score: 0
has body: You could use regex (such as [0-9]{4} ([01]\d|2[0123]):([012345]\d):([012345]\d) ) but in the example posted the date is always in the beginning of the string. If that is the case, you could just use the position of the string to parse the date. import datetime lines =[] lines.append("2Sun, 17 Mar 2013 18:58:06 Pro IDS2.0 10E22E37-B2A1-4D55-BE20-84661D420196 nCWgKUtjalmYx053ykGeobwgWW V3") lines.append("3Sun, 17 Mar 2013 19:17:33 &lt;AwaitingDHKey c i FPdk 1:0 pt 0 Mrse&gt; 0000000000000000000000000000000000000000 wo&gt; HomeKit keychain state:HomeKit: mdat=2017-01-01 01:41:47 +0000,cdat=2017-01-01 01:41:47 +0000,acct=HEDF3,class=genp,svce=AirPort,labl=HEDF3") lines.append("4Sun, 13 Apr 2014 19:10:26 values in decoded form... oak: &lt;C: gen:'[ 21:10 5]' ak&gt; &lt;PI@0x7fc01dc05d90: [name: Bourbon] [--SrbK-] [spid: zP8H/Rpy] [os: 15G31] [devid: 49645DA6] [serial: C17J9LGKDTY3] -") for l in lines: datetime_object = datetime.datetime.strptime(l[6:26], '%d %b %Y %H:%M:%S') print(datetime_object) Which gives the correct output for the three examples you provided 2013-03-17 18:58:06 2013-03-17 19:17:33 2014-04-13 19:10:26 The datetime object has attributed such as month() and year() so you can use a simple equality to check whether two dates are in the same month and/or year.
answers question: http://stackoverflow.com/q/48393590

http://stackoverflow.com/a/48451275
has body: As Alexander points out in the comments, list addition is concatenation. a = [1,2,3,4] b = [10] + a # N.B. that this is NOT `10 + a` # [10, 1, 2, 3, 4] You can also use list.extend a = [1,2,3,4] b = [10] b.extend(a) # b is [10, 1, 2, 3, 4] and newer versions of Python allow you to (ab)use the splat (*) operator. b = [10, *a] # [10, 1, 2, 3, 4] Your choice may reflect a need to mutate (or not mutate) an existing list, though. a = [1,2,3,4] b = [10] DONTCHANGE = b b = b + a # (or b += a) # DONTCHANGE stays [10] # b is assigned to the new list [10, 1, 2, 3, 4] b = [*b, *a] # same as above b.extend(a) # DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh! # b is too, of course...
has comment: http://stackoverflow.com/comment/83895525
type: Answer
has comment: http://stackoverflow.com/comment/124605883
score: 197
has comment: http://stackoverflow.com/comment/124600918
accepted answer of: http://stackoverflow.com/q/48451228
type: AcceptedAnswer
downvote count: 1
upvote count: 198
answers question: http://stackoverflow.com/q/48451228
has comment: http://stackoverflow.com/comment/83895568
has comment: http://stackoverflow.com/comment/90020198

http://stackoverflow.com/comment/83871388
has text: I am currius to know why clang has a total execution time larger than GCC. Does clang++ used libc++ and g++ stdlibc++?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48438678
type: AnswerComment

http://stackoverflow.com/comment/83855539
comment on: http://stackoverflow.com/q/48432038
type: Comment
type: QuestionComment
has text: Thanks for your feedback...I'm embarking on a rebuild of my conda environment...hope it will solve it!
score: 0

http://stackoverflow.com/q/48366209
type: Question
answer count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/48366357
has body: So I am a bit stuck right now.I know about django user model and what means to extend it..kinda. The thing is that I don't know how to get started... I have a student model where name, surname and student ID are entered in by the admin. Fields of email, phone and photo, are readonly. I want that a student can make an account, where he can enter all those fields himself, but name, surname and student ID need to match with those from database, otherwise he cannot make account. What is a good approach ? class Student(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') email = models.EmailField() phone = models.CharField(max_length=15, ) def __str__(self): return self.name + self.surname This is how I started.
has answer: http://stackoverflow.com/a/48366357
type: AnsweredQuestion
score: 0
has title: Django custom authentication with email as username
tagged with: python

http://stackoverflow.com/comment/83830639
type: Comment
has text: Not that it matters, but I'm only responsible for the comment. Regarding your Q - So you mean, you want to know if a script that ran (for example the script created an instance), was executed from a workstation, or from an EC2 instance / other AWS object?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48419066

http://stackoverflow.com/comment/83925951
type: AnswerComment
score: 0
has text: Thanks for your response. Are you referring to the OpenAI Gym step(action) method ? How can I ensure it runs on GPU ? Also, please take a look at my updated question with code.
type: Comment
comment on: http://stackoverflow.com/a/48464976

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/48333390

http://stackoverflow.com/a/48415152
type: Answer
answers question: http://stackoverflow.com/q/48413991
score: 0
has body: Option 1 Here is a standard itertools.groupby approach: key = "subject" [{key: k, "Result": {k_: v for d in g for k_, v in d.items() if k_ != key}} for k, g in it.groupby(lst, lambda x: x[key])] For simplicity, if given the form [k: g for k, g in itertools.groupby(iterable, key)], here g simply is substituted with a filtered dictionary comprehension. lst is the input list of dicts. Option 2 more_itertools.groupby_transform is a third-party recipe that extends itertools.groupby to allow changes to the resulting groups: import copy import more_itertools as mit def get_scores(iterable, key): """Return resulting ditctionaries grouped by key.""" iterable = copy.deepcopy(iterable) # optional kfunc = lambda x: x[key] def vfunc(x): del x[key] return x return [{key: k, "Result": list(g)} for k, g in mit.groupby_transform(iterable, keyfunc=kfunc, valuefunc=vfunc)] get_scores(lst, "subject") Here duplicate keys are deleted from the resulting groups. Deleting items will mutate the nested dictionaries. To preserve some level of the former nested dicts, make deepcopies, i.e.g. see the optional line.

http://stackoverflow.com/comment/83772847
type: Comment
type: AnswerComment
has text: Yes, but it can broke your code, so I recommend to use a new virtualenv to test if everything still working normal. If you are using python 3.5+ you can create a new one with: python -m venv test To active use: source test/bin/activate
comment on: http://stackoverflow.com/a/48388690
score: 0

http://stackoverflow.com/comment/83673566
comment on: http://stackoverflow.com/a/48343449
type: AnswerComment
score: 0
has text: "Regarding the files, those are just for demonstration purposes" : SO is read by lot of newcomers or non-programmers that might not know why not closing files is bad. Our duty when we answer here is to try and teach readers good practices along the way. So please don't post faulty code "for example", or _at least_ mentions where and how the code is faulty and what should be handled in real code.
type: Comment

http://stackoverflow.com/q/48425264
has comment: http://stackoverflow.com/comment/83840641
has comment: http://stackoverflow.com/comment/83840422
has comment: http://stackoverflow.com/comment/83843055
tagged with: python
tagged with: dictionary
has body: I have a project where I have to open json1 file (with multiple key values) and compare the desired fields to what is in the json2 file and If json1 has data where json2 is incorrect or blank, create an output JSON file . I know how to work with dictionaries (json files). But I am having hard time trying to wrap my head around how to go about completing this project. Example data of json files. Im dealing with over 3k hosts json1 ={ "host.com": { "parent": "undefined", "sys_os": "redhad", "zone": "qa ", "jdk": "undefined", "appName": "someapp", "admin": "undefined", "ip": "127.0.0.1", "notes": "undefined", } } json2 ={ "host.com": { "parent": "undefined", "sys_os": "redhad", "zone": "dev", "jdk": "undefined", "appName": "someapp", "admin": "", "ip": "168.192.1.1", "notes": "new to python", } } this is some code that I found, but am not sure if this is the correct path for this project. data1 = json.load(open(json1)) data2 = json.load(open(json2)) The files that Im dealing with are dicts, but I didn't do a good job in trying to add that info this question. sorry if my format is not correct. print type(data1) &lt;type 'dict'&gt; for key in set(data.keys()).union(data.keys()): if key not in data1: print "json1 doesn't contain", key elif key not in data2: print "json2 doesn't contain", key elif data1[key] == data2[key]: print "match", key else: print "don't match", key I'm still trying to under data structures. I want my output to be the updated values from json1 to json2. json3 ={ "host.com": { "parent": "undefined", "sys_os": "redhad", "zone": "qa ", "jdk": "undefined", "appName": "someapp", "admin": "undefined", "ip": "127.0.0.1", "notes": "undefined", } }
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83840432
answer count: 1
has title: If json1 has data where json2 is incorrect or blank, create an output JSON file with the updated data
has answer: http://stackoverflow.com/a/48429045
accepted answer: http://stackoverflow.com/a/48429045
type: Question
has comment: http://stackoverflow.com/comment/83845327

http://stackoverflow.com/a/48456357
answers question: http://stackoverflow.com/q/48456145
has comment: http://stackoverflow.com/comment/83953964
type: Answer
has comment: http://stackoverflow.com/comment/83906265
upvote count: 4
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48456145
score: 3
has body: I assume that a and b are NumPy arrays. You can construct the TM as a SciPy sparse matrix: import numpy as np import scipy.sparse as sp from itertools import chain from collections import Counter a = np.array([[1,2,3],[3,2,1],[2,1,3]]) b = np.array([[3,2,1],[1,2,3],[3,2,1]]) Find and count all actual transitions: cntr = Counter(chain.from_iterable(list(zip(*x)) for x in (zip(a,b)))) #Counter({(3, 1): 3, (1, 3): 2, (2, 2): 2, (1, 2): 1, (2, 3): 1}) Construct a sparse matrix of counts, where the rows and columns represent the states: transition = sp.csr_matrix((list(cntr.values()), zip(*cntr.keys()))) Normalize the matrix: transition[1:,1:] / transition[1:,1:].sum(axis=1) #array([[ 0. , 0.33333333, 0.66666667], # [ 0. , 0.66666667, 0.33333333], # [ 1. , 0. , 0. ]])

http://stackoverflow.com/q/48464960
has answer: http://stackoverflow.com/a/48465740
has answer: http://stackoverflow.com/a/48465216
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83923632
possible better answer: http://stackoverflow.com/a/48465740
has comment: http://stackoverflow.com/comment/83923704
favorite count: 0
tagged with: object
tagged with: int
has comment: http://stackoverflow.com/comment/83925446
has answer: http://stackoverflow.com/a/48465183
type: AnsweredQuestion
score: 1
has body: Is it possible to define a data object in python that behaves like a normal integer when used in mathematical operations or comparisons, but is also able to store instance variables? In other words, it should be possible to do the following things: pseudo_integer = PseudoInteger(5, hidden_object="Hello World!") print(5 + pseudo_integer) # Prints "10" print(pseudo_integer == 5) # Prints "True" print(pseudo_integer.hidden_object) # Prints "Hello World!"
has comment: http://stackoverflow.com/comment/83923385
tagged with: instance-variables
linked to: http://stackoverflow.com/q/3238350
answer count: 4
has title: Is it possible to define an integer-like object in Python that can also store instance variables?
has comment: http://stackoverflow.com/comment/83923372
has answer: http://stackoverflow.com/a/48465107
accepted answer: http://stackoverflow.com/a/48465216
tagged with: integer
type: Question

http://stackoverflow.com/a/48355699
type: Answer
has body: We use [:] to do array slice-op for every element in the array. (1) for channel in channels: channel[:] = channel * alpha Assign the result of channel * alpha to original channel. (2) for channel in channels: channel = channel * alpha Create a new variable named channel and assign the result of channel * alpha to new channel, has no effect on the original. Here I do an experiment: #!/usr/bin/python3 # 2018.01.20 19:28:35 CST import cv2 import numpy as np img = cv2.imread("test.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) alpha = (1.0 / 255) * (255 - gray) channels = cv2.split(img) for channel in channels: print("Before:", id(channel), channel.shape, channel.dtype) channel[:] = channel * alpha print("After:", id(channel), channel.shape, channel.dtype) dst1 = cv2.merge(channels) channels = cv2.split(img) for channel in channels: print("Before:", id(channel), channel.shape, channel.dtype) channel = channel * alpha print("After:", id(channel), channel.shape, channel.dtype) dst2 = cv2.merge(channels) dst2 = cv2.merge(channels) cv2.imshow("dst1", dst1) cv2.imshow("dst2", dst2) cv2.waitKey() The output: Before: 140130414391088 (480, 480) uint8 After: 140130414391088 (480, 480) uint8 Before: 140130413969616 (480, 480) uint8 After: 140130413969616 (480, 480) uint8 Before: 140130413969776 (480, 480) uint8 After: 140130413969776 (480, 480) uint8 Before: 140130413969936 (480, 480) uint8 After: 140130414391088 (480, 480) float64 Before: 140130413970016 (480, 480) uint8 After: 140130414391088 (480, 480) float64 Before: 140130413970096 (480, 480) uint8 After: 140130414391088 (480, 480) float64 We can clearly see the id of channel keeps the same then do channel[:] = channel * alpha, so assign on the original channel; while id changes when doing channel = channel * alpha, so assign on the new channel, keep the original. The result is as expected:
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83720678
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48355436
answers question: http://stackoverflow.com/q/48355436
score: 1

http://stackoverflow.com/comment/83925856
score: 0
has text: I've added an alternative solution, you can try that out if possible
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48465998

http://stackoverflow.com/comment/84104263
type: QuestionComment
type: Comment
has text: Oh it might have something to do with ubuntu version. Generally, if you are not a Linux enthusiast and don't want to spend time debugging random issues you should use LTS version (16.04 in this case)
comment on: http://stackoverflow.com/q/48482265
score: 0

http://stackoverflow.com/comment/83857568
comment on: http://stackoverflow.com/q/48429882
has text: what do you mean by clipboard? The place where files get stored when you do `Ctrl+C`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48450492
type: AcceptedAnswer
has body: 2 solutions for you: either you try another module like MSS (easy, efficient and creates high quality PNG pictures), either you change the code of the function SaveJPEG: // https://pastebin.com/xAv30gK1 at line 169 return jpeg_save(pbyBuffer, uWidth, uHeight, 85, pszFileName) != 0; You see the 85? It is the picture quality. Just change to 100 ;)
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48332282
answers question: http://stackoverflow.com/q/48332282

http://stackoverflow.com/comment/83874446
type: QuestionComment
comment on: http://stackoverflow.com/q/48440753
type: Comment
has text: I've added my traceback in my edit (it's the same error for each import) @SadiaArif
score: 0

http://stackoverflow.com/q/48431483
possible better answer: http://stackoverflow.com/a/48431687
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
has body: I am working on large log files (4 Gig) with 1000 of variables (ABCD,GFHTI,AAAA,BBBB,...)but I am only interested in 50 of these variables (ABCD,GFHTI,..). The structure of the log file is as follow: 20100101_00:01:33.436-92.451 BLACKBOX ABCD ref 2183 value 24 20100101_00:01:33.638-92.651 BLACKBOX GFHTI ref 2183 value 25 20100101_00:01:33.817-92.851 BLACKBOX AAAA ref 2183 value 26 (Not interested in this one) 20100101_00:01:34.017-93.051 BLACKBOX BBBB ref 2183 value 27 (Not interested in this one) I am trying to make a pandas data frame out of the this log file which look like this. Time ABCD GFHTI 20100101_00:01:33.436-92.451 24 NaN 20100101_00:01:33.638-92.651 NaN 25 I could do this by using loop and appending to pandas data frame but that is not very efficient. I can find the value and dates of the value of the interest in the log files but I don't know how to put NaN for the rest of variables for that specific date and time and at the end convert it to a data frame. I really appreciate if anyone can help. Here is part of my code ListOfData={} fruit={ABCD, GFHTI} for file in FileList: i=i+1 thefile = open('CleanLog'+str(i)+'.txt', 'w') with open(file,'rt') as in_file: i=0 for linenum, line in enumerate(in_file): # Keep track of line numbers. if fruit.search(line) != None:# If substring search finds a match, i=i+1 Loc=(fruit.search(line)) d = [{'Time': line[0:17], Loc.group(0): line[Loc.span()[1]:-1]}] for word in Key: if word == Loc.group(0): ListOfData.append(d)
accepted answer: http://stackoverflow.com/a/48432392
has answer: http://stackoverflow.com/a/48431687
type: Question
has answer: http://stackoverflow.com/a/48432392
has title: Filling Data to pandas dataframe using loop with text file that have missing data
tagged with: missing-data

http://stackoverflow.com/comment/83862998
has text: ok thanks I got it to work in the end. I think it's my tag finder code that was creating issues. One final question is how would be the best way to handle exceptions for example if I'm looking through an url in my list but cannot find the relevant tag how could I move on to the next url instead of getting an error which breaks my loop and forces me to start the loop all over again?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48415135

http://stackoverflow.com/comment/83755372
score: 0
has text: How are you typing in the characters? Are you doing this manually?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48384176

http://stackoverflow.com/comment/83936610
type: Comment
score: 0
type: AnswerComment
has text: well, I think a better question is why are you looping over `website_details` and adding it to a `result` list? Unfortunately I'm not versed in soup at all, so I'm not sure what type of object `website_details` is, but ideally, it's some type of `soup` object that allows you to continue calling `find`/`find_all` on it?
comment on: http://stackoverflow.com/a/48471243

http://stackoverflow.com/comment/83756783
comment on: http://stackoverflow.com/q/48384709
score: 0
has text: Second result for the exception name: http://atodorov.org/blog/2017/08/04/transactionmanagementerror-during-testing-with-django-110/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83929719
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48468074
has text: the database already exists, yes. it is our main database, i just have a default schema set for the username. this is the same way i handled the previous project without issue.

foreground
type: Tag
tag name: foreground
tags question: http://stackoverflow.com/q/48466626

http://stackoverflow.com/comment/83705008
has text: yes It says correct , just run it like a simple command in cmd prompt . Don't run it in python shell . eg: C:\Users\hp>pip install --upgrade spyder 3.2.6
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48359063

http://stackoverflow.com/comment/83941702
type: QuestionComment
comment on: http://stackoverflow.com/q/48474087
has text: Do you need `ploting_data = data"Date", "Fatalities", "Injuries".transpose()` ?
score: 0
type: Comment

http://stackoverflow.com/q/48483210
type: Question
has title: cannot import name 'Cursor' or 'Character'
has answer: http://stackoverflow.com/a/48483289
has comment: http://stackoverflow.com/comment/83959416
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83964242
tagged with: class
downvote count: 0
has comment: http://stackoverflow.com/comment/83959400
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83959367
has comment: http://stackoverflow.com/comment/83959508
answer count: 1
tagged with: import
favorite count: 0
has comment: http://stackoverflow.com/comment/83959466
has comment: http://stackoverflow.com/comment/83959791
has body: I can't for the life of me figure out why I can't import any of the other classes after the Document class. I'm try to run the code in the python console, but I keep getting import errors like this: ImportError: cannot import name 'Character' Here is the code: class Document: def __init__(self): self.characters = [] self.cursor = Cursor(self) self.filename = '' def insert(self, character): if not hasattr(character, 'character'): character = Character(character) self.characters.insert(self.cursor.position, character) self.cursor += 1 def delete(self): del self.characters[self.cursor.position] def save(self): f = open(self.filename, 'w') f.write(''.join(self.characters)) f.close() class Cursor: def __init__(self, document): self.document = document self.position = 0 def forward(self): self.position += 1 def back(self): self.position -= 1 def home(self): while self.document.characters[self.position-1] != '\n': self.position -= 1 if self.position == 0: # Got to beginning of file before newline break class Character: def __init__(self, character, bold=False, italic=False, underline=False): assert len(character) == 1 self.character = character self.bold = bold self.italic = italic self.underline = underline

http://stackoverflow.com/q/48412401
score: 2
has answer: http://stackoverflow.com/a/48412763
has answer: http://stackoverflow.com/a/48412632
tagged with: amazon-iam
type: Question
upvote count: 2
has body: I've created the following resources on API Gateway: https:/myapp.execute-api.us-east-1.amazonaws.com/zzz/yyy/xxx It Can be only used it with AWS Credentials which I have: access_key :"access_example" secret_key:"secret_example" session_token: "session_example" I know how to use it with postman, but not with python requests. Can you help me? I tried passing the credentials in headers, but it didn't work.
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: python-requests
has title: How Can I send AWS credentials with Python requests?
tagged with: aws-api-gateway
tagged with: amazon-web-services
favorite count: 0

http://stackoverflow.com/q/48460234
has title: Pandas apply ValueError: The truth value of a Series is ambigous
upvote count: 1
has comment: http://stackoverflow.com/comment/83913538
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83913458
type: Question
has comment: http://stackoverflow.com/comment/83913518
has comment: http://stackoverflow.com/comment/97940276
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83913598
linked to: http://stackoverflow.com/q/22591174
has answer: http://stackoverflow.com/a/48460273
tagged with: python
has comment: http://stackoverflow.com/comment/83913619
has comment: http://stackoverflow.com/comment/83913551
score: 0
has answer: http://stackoverflow.com/a/55621120
answer count: 2
has body: I'm trying to create a new feature using df_transactions['emome'] = df_transactions['emome'].apply(lambda x: 1 if df_transactions['plan_list_price'] ==0 &amp; df_transactions['actual_amount_paid'] &gt; 0 else 0).astype(int) But it raises error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How can I create a new column that returns 1 when plan_list_price is 0 and actual_amount_paid is >0 else 0? I would like to still use pandas apply.
tagged with: pandas
has comment: http://stackoverflow.com/comment/83913494

http://stackoverflow.com/comment/83821729
type: QuestionComment
comment on: http://stackoverflow.com/q/48414984
has text: What exactly do you want to print to the export file? The contents of ```embeddings_to_file```, which will be something like ```["a", "b", "c"]```?
score: 0
type: Comment

http://stackoverflow.com/q/48395681
tagged with: python
has answer: http://stackoverflow.com/a/48416640
type: AnsweredQuestion
answer count: 3
has title: Add a new column in dataframe with user defined values. (pyspark)
possible better answer: http://stackoverflow.com/a/48406150
score: 0
accepted answer: http://stackoverflow.com/a/48416640
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48397351
tagged with: apache-spark-sql
has body: Three values of array A1 getting from some function - A1 = [1,2,3,4] A1 = [5,6,7,8] A1 = [1,3,4,1] My dataframe in which I want to add a new column with my array values - +---+---+-----+ | x1| x2| x3| +---+---+-----+ | 1| A| 3.0| | 2| B|-23.0| | 3| C| -4.0| +---+---+-----+ I tried like this(Suppose 'df' is my dataframe) - for i in range(0, 2): df = df.withColumn("x4", array(lit(A1[0]), lit(A1[1]), lit(A1[2])) But problem with this code is it is updating column with last value of array 'A1' like this - +---+---+-----+---------+ | x1| x2| x3| x4| +---+---+-----+---------+ | 1| A| 3.0|[1,3,4,1]| | 2| B|-23.0|[1,3,4,1]| | 3| C| -4.0|[1,3,4,1]| +---+---+-----+---------+ But I want like this - +---+---+-----+---------+ | x1| x2| x3| x4| +---+---+-----+---------+ | 1| A| 3.0|[1,2,3,4]| | 2| B|-23.0|[5,6,7,8]| | 3| C| -4.0|[1,3,4,1]| +---+---+-----+---------+ What i need to add extra in my code?
tagged with: pyspark
has answer: http://stackoverflow.com/a/48406150

http://stackoverflow.com/q/48471216
type: UnansweredQuestion
downvote count: 2
answer count: 1
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83936375
has title: Python For Loop - Hierachy
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I am trying to do some web scraping and going to run two for loops to dive into, what I ultimately want, is the web link href. website_details = soup.find_all("div", attrs={'class': 'bodyText'}) result = [] for tag in website_details: result.append(tag) result2 = [] p_tag = result.find_all("p") for tag in p_tag: result2.append(tag) I get the error below. p_tag = result.find_all("p") AttributeError: 'list' object has no attribute 'find_all'
has answer: http://stackoverflow.com/a/48471243

http://stackoverflow.com/comment/83708706
comment on: http://stackoverflow.com/q/48360915
has text: Can you post a small sample of `master_df` and what the desired result would be for that small sample?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48467472
has body: I'm not sure what kind of data is supposed to be in the "text" property, but it sure isn't text. You'll need to analyze the application that made this request to figure this out. The decoded text starts out with the following data, which doesn't contain any readable text, and doesn't match with any known file format: 00000000: e2a1 7614 9214 be79 5194 3352 a680 7a29 ..v....yQ.3R..z) 00000010: e064 8850 0375 fe03 f106 0ab6 1351 55cf .d.P.u.......QU. 00000020: ad32 a1ef d6fb a2a4 96e4 30ab 203e eb8c .2........0. &gt;.. 00000030: e3f1 46dd 155c 2e56 21c4 7987 df94 833f ..F..\.V!.y....? An analysis of the data shows that it's virtually incompressible. This means that it may be encrypted, or compressed with an unknown algorithm.
answers question: http://stackoverflow.com/q/48467245
score: 0
has comment: http://stackoverflow.com/comment/83928422
type: Answer

http://stackoverflow.com/q/48470671
tagged with: python
answer count: 0
tagged with: hsv
score: 1
linked to: http://stackoverflow.com/q/47483951
tagged with: image-processing
downvote count: 1
has body: I am working on a project that needs to identify the shape of an object in a field. My goal right now is to filter out any colors the background could be such as green, brown, or gray. import cv2 import numpy as np img = cv2.imread('pic1.png') hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_green = np.array([0,0, 150]) upper_green = np.array([255, 255, 255]) mask = cv2.inRange(hsv, lower_green, upper_green) res = cv2.bitwise_and(img, img, mask=mask) cv2.imshow('res1.png', res) cv2.waitKey(0) The image is showing a sample of the shapes in the field. This code results in this image: Why do the values I use for the lower and upper greens remove all the green when I have only included red values? Are there any ways to get filters that remove only one color so I am able to pick and choose which colors I would want to keep and which to remove?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83936560
tagged with: numpy
tagged with: opencv
has comment: http://stackoverflow.com/comment/83936108
upvote count: 2
has title: How does filtering out the colors of a hsv image in opencv python work?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83937844

http://stackoverflow.com/a/48473661
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48473646
has body: c = [p + str(q) for p, q in zip(a, b)]
upvote count: 6
type: Answer

http://stackoverflow.com/q/48359354
has answer: http://stackoverflow.com/a/48359991
answer count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83706901
has comment: http://stackoverflow.com/comment/83705741
upvote count: 2
has comment: http://stackoverflow.com/comment/83705430
has comment: http://stackoverflow.com/comment/83705738
possible better answer: http://stackoverflow.com/a/48359822
has comment: http://stackoverflow.com/comment/83706204
downvote count: 1
has title: Access only once to a csv file with header using pd.read_csv() in Python
has comment: http://stackoverflow.com/comment/83705667
has answer: http://stackoverflow.com/a/48359822
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48360039
has answer: http://stackoverflow.com/a/48440843
has comment: http://stackoverflow.com/comment/83705424
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
accepted answer: http://stackoverflow.com/a/48359991
has comment: http://stackoverflow.com/comment/83706554
has body: I have to deal with csv file on a distant server, so it takes a very long time. My csv file is such that the 8 first rows contains a kind of header formatted like key : value. Then, at the ninth line comes the columns index formatted as a usual csv file. Since it is long to access the file, I want to open it only once, but I don't know how to it. Indeed, from what I understood pd.read_csv() only takes a file as input, not only its content. So this is where I am for the moment : import pandas as pd with open(r'myFile.csv', "r", encoding = "utf-8") as file: header = file.readlines()[:8] metaData = [value.split(':') for value in header] metaData = {value[0].strip() : value[1].strip() for value in metaData} data = pd.read_csv(file, sep=';', header = 8) And the associated error message : EmptyDataError: No columns to parse from file Edit with a sample input csv file : key1:value1 key2:value2 key3:value3 key4:value4 key5:value5 key6:value6 key7:value7 key8:value8 column1;column2;column3 values;values;values values;values;values values;values;values values;values;values
tagged with: python

http://stackoverflow.com/q/48456597
has comment: http://stackoverflow.com/comment/84108663
answer count: 0
has comment: http://stackoverflow.com/comment/84066263
has comment: http://stackoverflow.com/comment/84703605
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84193589
downvote count: 0
has comment: http://stackoverflow.com/comment/83909490
has comment: http://stackoverflow.com/comment/83905905
tagged with: virtual-machine
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47137372
has title: Script moving the mouse on a virtual machine
has comment: http://stackoverflow.com/comment/84000335
tagged with: pywin32
tagged with: python
score: 4
has body: I prepared a script which does some operation on a web page, recognize colors and simulate mouse click and keyboard send keys while running. It works fine. The problem is that I want it to run on a virtual machine (I'm trying greencloudvps) and it works fine as long as have my eyes on it. As soon as I close the "remote desktop connection" tool, the script crashes, because (I guess) there is no more a monitor where to move the mouse. I use the following Python code: win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) Is there any solution? UPDATE:i tried to run my script also on Amazon virtual machine but i got the same problem. Which could be the solution? Basically I need to click with mouse, read pixel colors and send skeys with keyboard automatically on a virtual machine even when I don’t witness the session, using python
tagged with: mouseevent
upvote count: 4

http://stackoverflow.com/a/48750592
upvote count: 4
score: 3
answers question: http://stackoverflow.com/q/48340392
downvote count: 1
has body: You can also use the following code to have the warning lines erased from the terminal by using the following lines at the beginning of your code. Code With warning: import numpy as np, sys, tensorflow as tf print('\nStart of Code...\n') Output: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters Start of Code... Code with Warning Erased: import numpy as np, sys, tensorflow as tf for i in range(3): # Add this for loop. sys.stdout.write('\033[F') # Back to previous line. sys.stdout.write('\033[K') # Clear line. print('\nStart of Code...\n') Output: Start of Code...
type: Answer
has comment: http://stackoverflow.com/comment/87076878

http://stackoverflow.com/comment/83952827
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48476160
has text: @Bart, thanks for taking the effort to benchmark. I've changed my logic very slightly to use a list comprehension (small speed up). Where you lose with the `df` merge method is creation of `convert_df`. Including set-up costs of `convert_df` and `convert_dict`, I see very close timings for n_rows = 10000, cats = 5. If you try n_rows = 10000, cats = 50, I find that the setup cost for `convert_df` is ~1.5s (~600x worse than `convert_dict`). So you are right to go with `df.merge`, but only if the mapping is static / built once / not repeatedly read from csv.

http://stackoverflow.com/q/48343096
answer count: 1
tagged with: timesten
has comment: http://stackoverflow.com/comment/83742156
type: Question
has comment: http://stackoverflow.com/comment/83908884
type: UnansweredQuestion
tagged with: oracle-database
has comment: http://stackoverflow.com/comment/83731935
tagged with: python
has title: TimesTen database connection issue in python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/58831564
linked to: http://stackoverflow.com/q/7982224
score: 0
has body: I have 2 machines setup: RDP terminal with timesten client 11.2.1 and pyodbc==3.0.7 and works great. I use this connection string: cnxn = pyodbc.connect('DSN=myhostip;UID=myusername;PWD=mypass') local machine with timesten client 11.2.2 and pyodbc==4.0.22 (I've also tried older versions, like 3.0.7) and when I use the connection string: cnxn = pyodbc.connect('DSN=myhostip1;UID=myusername1;PWD=mypass1') I get this error: pyodbc.Error: ('HY010', u'[HY010] [Microsoft][ODBC Driver Manager] The driver is incapable of supporting the current environment attributes. (0) (SQLDriverConnect)'). Both databases on both machines are practically the same, so difference is only in timesten driver version. Or what else could be the problem? I have set up DSNs on both machines, and I connect to them in SQLDeveloper. I've tried different timesten clients and pyodbc versions, but got same error everytime. It's the only way that I know of to connect to timesten DB, can anyone please help me solve this error, or maybe tell about another way,except pyodbc, to connect?

http://stackoverflow.com/comment/83766986
score: 0
comment on: http://stackoverflow.com/q/48385781
has text: I think this question needs more detail. What is it that you are trying to accomplish? Are you trying to add data from a large file into a single dataframe?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48439860
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83895260
has comment: http://stackoverflow.com/comment/83874329
has answer: http://stackoverflow.com/a/48442844
upvote count: 0
downvote count: 2
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/83874560
has comment: http://stackoverflow.com/comment/83874867
has comment: http://stackoverflow.com/comment/83874141
has body: I am a new to Selenium. I click a button and this gives me a modal form. I want to fill text area on this modal. &lt;input id="name" name="name" class="form-control ng-pristine ng-invalid ng-invalid-required ng-touched" ng-model="model.newInstanceSpec.name" ng-required="true" required="required" type="text"&gt; I tried find_element_by_id, find_element_by_class_name etc. I didn't find anything. The error stack: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="name"] below is the screenshot of modal form Thanks for your reply.
has comment: http://stackoverflow.com/comment/83871122
has comment: http://stackoverflow.com/comment/83874514
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83874773
accepted answer: http://stackoverflow.com/a/48442844
has title: Python + Selenium: fill text input in the modal form
score: -2
has comment: http://stackoverflow.com/comment/83871262
tagged with: python
has comment: http://stackoverflow.com/comment/83870912
has comment: http://stackoverflow.com/comment/83875009

http://stackoverflow.com/comment/83880233
type: Comment
type: QuestionComment
score: 0
has text: @Rakesh No data is a list of dict. data = [{'a': 12, 'name':'abc'}, {'a': 16, 'name':xyz}, {'a': 17, 'name': lmn}]. If i try to return data as it is it throws error.
comment on: http://stackoverflow.com/q/48443287

http://stackoverflow.com/q/48362903
type: Question
has comment: http://stackoverflow.com/comment/83712670
linked to: http://stackoverflow.com/q/48362364
accepted answer: http://stackoverflow.com/a/48366301
has comment: http://stackoverflow.com/comment/83712758
has comment: http://stackoverflow.com/comment/83712781
has answer: http://stackoverflow.com/a/48366301
has comment: http://stackoverflow.com/comment/83718349
has body: Method 1 : Error : ufunc 'add' did not contain a loop with signature matching types dtype(' x = numpy.array(x) x_5= x + 5 Method 2 : Error : must be str, not int x_5 = [x+5 for x in x] Method 3 : Error : invalid literal for int() with base 10: '-0.081428368' I tried to convert the x data first to integer x_int = list(map(int, x)) x_5 = [x+5 for x in x] method 4 : Error : 'numpy.float64' object is not iterable x = numpy.array(x, dtype=float) x = numpy.array(x) x_piu_5= x + 5 Method 5 : Error : float object is not iterable x_piu_5=[] xfl=[float(i) for i in x] x_piu_5[:] = [x + 5 for x in xfl] Hi All I am trying to add an integer number to my list which contains a lot of numbers like 0.00085695 , etc, and I have used two methods but I have been unsuccessful Update 1 : Added method 4 , I have obtained the values I wanted, but the problem now is that it say the numpy.float is not iterable Update 2 : Added method 5, Should I convert the float to string before iteration ?
has comment: http://stackoverflow.com/comment/83712847
has comment: http://stackoverflow.com/comment/83712869
has comment: http://stackoverflow.com/comment/83712725
tagged with: python
has comment: http://stackoverflow.com/comment/83712735
upvote count: 6
has comment: http://stackoverflow.com/comment/83712733
has comment: http://stackoverflow.com/comment/83712891
score: 2
has comment: http://stackoverflow.com/comment/83712703
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83712791
tagged with: list
downvote count: 4
has comment: http://stackoverflow.com/comment/83714129
has comment: http://stackoverflow.com/comment/83712843
has title: Adding an integer number to all elements of a list that are not integer
tagged with: spyder
answer count: 1
has comment: http://stackoverflow.com/comment/83712690
has comment: http://stackoverflow.com/comment/83712718
favorite count: 0

http://stackoverflow.com/q/48369561
has answer: http://stackoverflow.com/a/48369693
has comment: http://stackoverflow.com/comment/83725860
has title: Incorrect output for Binary Search with strings
has answer: http://stackoverflow.com/a/48369623
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83725802
has comment: http://stackoverflow.com/comment/83727223
tagged with: python
accepted answer: http://stackoverflow.com/a/48369623
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83725949
has body: I have a typical Binary Search algorithm implementation: def binarySearch(arr, element): first = 0 last = len(arr) - 1 while first &lt;= last: i = (first + last) // 2 if arr[i] == element: return 'Found at position: {}'.format(i) elif arr[i] &gt; element: last = i - 1 elif arr[i] &lt; element: first = i + 1 The test data is as follows: arr = ['0006', '000e', '000f', '0023', '002a', '002E1627', '0032A542', '0037'] When I make a call to the binarySearch() function as follows: element = '002E1627' print (binarySearch(arr, element)) I get the output as: Found at position: 5 However, with the following input: element = '002a' print (binarySearch(arr, element)) I get the output as: None What is the reason behind this output? The expected output for the second case is: Found at position: 4.
has comment: http://stackoverflow.com/comment/83725804
possible better answer: http://stackoverflow.com/a/48369693

http://stackoverflow.com/q/48348714
type: Question
has comment: http://stackoverflow.com/comment/83685529
score: 0
has comment: http://stackoverflow.com/comment/83683777
has title: PYTHON TKINTER How to check if Button Exists, delete if it does and carry on if not?
possible better answer: http://stackoverflow.com/a/48348785
accepted answer: http://stackoverflow.com/a/48349761
tagged with: python
has comment: http://stackoverflow.com/comment/83685066
has answer: http://stackoverflow.com/a/48348785
has comment: http://stackoverflow.com/comment/83685669
has answer: http://stackoverflow.com/a/48349761
type: AnsweredQuestion
tagged with: tkinter
answer count: 2
upvote count: 1
has body: I am creating a quiz app. Once logged in, the user is presented with a home screen which is created in a function. On completion of a quiz, there is an end screen (created in another function) with the option to take another quiz which will take the user back to the home screen. What I am trying to do is delete the end screen buttons &amp; labels within the home screen function if labels/buttons created in the end screen function exist. Simplified version of the code I am trying to run. from tkinter import * def homeScreen(): global endtext, againbutton if endtext.winfo_exists() == 1: endtext.destroy() againbutton.destroy() successlogin=label(window, text=("You are logged in as: " + Username)) successlogin.grid(column=1, row=4) global startquiz startquiz=Button(window, text="Start Quiz", command=quiz) startquiz.grid(column=1, row=4) def quiz(): global startquiz startquiz.destroy() #Display questions and check answers etc. etc. endscreen() #On completion of quiz def endScreen(): global endtext, againbutton endtext=Label(window, text="quiz complete") endtext.grid(column=1, row=1) againbutton=Button(window, text="again", command=homescreen) againbutton.grid(column=1, row=2) window=Tk() window.mainloop() homeScreen() I have tried to do this by using endtext.winfo_exists() but I get a name error saying endtext isn't defined. Even just putting print(endtext.winfo_exists()) results in the name error. When againbutton is pressed, homescreen() is called but the endtext and againbutton stay on the window getting in the way of the other labels and buttons. Note how {startquiz} is created in one function but deleted in the next. My intention is for everything created in {endscreen()} to be deleted IF the user presses {againbutton} The issue I think being that because on the first run through, the code is trying to delete something that has not been declared. That is why I am checking to see if it exists and have so far been unsuccessful in doing this
has comment: http://stackoverflow.com/comment/83686131
downvote count: 1
has comment: http://stackoverflow.com/comment/83685475
favorite count: 0

http://stackoverflow.com/comment/83711135
type: QuestionComment
has text: At the moment in my script there are two classes, one is the main one (where the program runs), the second one is the Player one."self.group = self.game.spritesPlayer" the Player class picks up the group that is contained in the main class ("self.spritesPlayer = OrderedDict ()")
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48360675

http://stackoverflow.com/comment/83916100
has text: Can you give an example?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48460104
type: Comment

http://stackoverflow.com/comment/83656521
comment on: http://stackoverflow.com/a/48334919
type: Comment
has text: Well, for one thing, Batman gave a completely different answer, with none of the problems I mentioned, and an additional solution using `get`.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48350925
favorite count: 0
has answer: http://stackoverflow.com/a/48355726
type: Question
has title: Where can I find a list of all available ChromeOptions with selenium?
possible better answer: http://stackoverflow.com/a/48354084
tagged with: python
has body: Where can I find a list of all available Chrome Options with selenium? While crawling with selenium in a python environment, I had to use flash in the chrome webdriver. so I tried to find a setting that would allow Flash and I found these answers. https://sqa.stackexchange.com/questions/30312/enable-flash-player-on-chrome-62-while-running-selenium-test Selenium.Chrome where can I find a list of all available ChromeOption arguments? C# but I really want to find official document about these arguments : profile.default_content_setting_values.plugins profile.content_settings.plugin_whitelist.adobe-flash-player I think that exist because some people said like above two answers. but I can't found it.
tagged with: selenium-chromedriver
type: AnsweredQuestion
tagged with: chrome-options
answer count: 2
score: 7
tagged with: selenium
downvote count: 0
linked to: http://stackoverflow.com/q/38335671
accepted answer: http://stackoverflow.com/a/48355726
upvote count: 7
tagged with: google-chrome
has answer: http://stackoverflow.com/a/48354084

http://stackoverflow.com/q/48348910
tagged with: python
tagged with: ip-address
has comment: http://stackoverflow.com/comment/83685539
score: 0
has body: I am crawling through the ARIN whois API to find all network ranges. The code below takes a starting IP address, sends it to ARIN, and returns the ending IP address of that network. That ending address is then incremented by one, and this new value becomes the next address sent to ARIN. This works well, but it is inefficient when ISPs have swaths of unassigned addresses because each starting address has to be checked until another assigned network is found. The code is a self-contained example that shows how there are a few network ranges assigned, and then a period of addresses that are unassigned by AT&amp;T. How should these unassigned networks be checked without checking each and every address? import requests from ipaddress import ip_address IPAddress = str.replace('12.31.71.56','.','-') while True: try: url = 'https://whois.arin.net/rest/net/NET-' + IPAddress + '-1.json' request = requests.get(url) response = request.json() endAddress = response['net']['endAddress']['$'] IPAddress = str.replace((ip_address(endAddress) + 1).compressed,'.','-') print(IPAddress) print(response['net']['orgRef']['@name']) except ValueError: IPAddress = str.replace(IPAddress,'-','.') IPAddress = str.replace((ip_address(IPAddress) + 1).compressed,'.','-') print(IPAddress) if IPAddress == '12-31-71-150': break
has comment: http://stackoverflow.com/comment/83685447
answer count: 0
type: UnansweredQuestion
has title: How to efficiently ignore unassigned parent ip address networks?
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83685687
type: Question
tagged with: ip
tagged with: network-programming
has comment: http://stackoverflow.com/comment/83685586

http://stackoverflow.com/q/48396103
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83779865
accepted answer: http://stackoverflow.com/a/48396588
has comment: http://stackoverflow.com/comment/83791144
has answer: http://stackoverflow.com/a/48396588
has body: So my app has the following structure: base.html, which contains the nav and the links to the stylesheets and the home.html file, which loads the nav via extends. However, i can't really modify the css inside my home.html file, any suggestions whats wrong? base.html: {% load staticfiles %} App ...## navbar etc. {% block page %} {% endblock %} home.html: {% extends 'base.html' %} {% load staticfiles %} {% block page %} {% endblock %} As you can see in the base.html file, i load the app.css file via static method. However, changing for example the banner class in the home.html isn't working at all: #body .banner { width: 100%; margin-bottom: 150px; } No errors in the terminal / console. The app.css file works for the base.html by the way.
tagged with: django
has comment: http://stackoverflow.com/comment/83782203
tagged with: python
answer count: 1
tagged with: css
has comment: http://stackoverflow.com/comment/83779815
has title: Django static css not loaded?
has comment: http://stackoverflow.com/comment/83779711
type: Question
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/67247345
type: Answer
answers question: http://stackoverflow.com/q/48350692
has body: A solution without installing Anaconda, or conda: sudo easy_install pip==20.3.4 pip2 install virtualenv virtualenv jupyter source jupyter/bin/activate pip2 install jupyter jupyter notebook This solution was tested on: Distributor ID: Ubuntu Description: Ubuntu 16.04.7 LTS Release: 16.04 Codename: xenial It was run on 32bit Chromenotebook, with Firefox vs NetSurf installed on xenial Jupyter notebook will be open automatically. However, everytime loging in on Jupiter again, at first source needs to be activated: source jupyter/bin/activate and then: jupyter notebook to start
score: 0

http://stackoverflow.com/a/48435983
has body: in one line you can do something like this: data=[ {'name': 'Joe', 'score': 98, 'subject': 'Math'}, {'name': 'Bob', 'score': 90, 'subject': 'Math'}, {'name': 'Bill', 'score': 88, 'subject': 'English'}, {'name': 'Jane', 'score': 95, 'subject': 'English'}] import itertools print({i:list(j) for i,j in itertools.groupby(data,key=lambda x:x['subject'])}) output: {'English': [{'subject': 'English', 'score': 88, 'name': 'Bill'}, {'subject': 'English', 'score': 95, 'name': 'Jane'}], 'Math': [{'subject': 'Math', 'score': 98, 'name': 'Joe'}, {'subject': 'Math', 'score': 90, 'name': 'Bob'}]}
answers question: http://stackoverflow.com/q/48413991
type: Answer
score: 0

http://stackoverflow.com/comment/83890195
score: 0
type: QuestionComment
type: Comment
has text: From the name Surrey Spice, I'm guessing that permitted is a set of postcode districts like `{'GU1', 'GU2', ...}`, and the OP wants `pcode` to be in one of those districts.
comment on: http://stackoverflow.com/q/48448450

http://stackoverflow.com/q/48369647
downvote count: 0
has title: How to log a data-frame to an output file
tagged with: python
tagged with: logging
has body: I'm starting to use logging to an output file but can't see how to log the head of a data-frame. Is it possible? I've tried debug (logger.debug("snaptable", snap_date.head()), where snap_table is a data-frame, but I can't see any output when I interrogate the output file. Is there a type of logging that can do this?
has answer: http://stackoverflow.com/a/48369926
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48369926
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48356638
has comment: http://stackoverflow.com/comment/83700234
favorite count: 0
has body: Thank you in advance for your time. If I fire a bullet with space key, a stream of bullets are created. If I would set a delay with time.sleep() inside 'if keys[pygame.K_SPACE]:' it would also freeze the loop for the set amount of seconds. How could I make it so only 1 bullet fires at a time? This is the copy of my game loop, please tell me if more of the code is needed: def game_loop(): global pause x = (display_width * 0.2) y = (display_height * 0.2) x_change = 0 y_change = 0 blob_speed = 3 velocity = [2, 2] pos_x = display_width/1.2 pos_y = display_height/1.2 gameExit = False while not gameExit: for event in pygame.event.get():#monitors hardware movement/ clicks if event.type == pygame.QUIT: pygame.quit() quit() pos_x += velocity[0] pos_y += velocity[1] if pos_x + blob_width &gt; display_width or pos_x &lt; 601: velocity[0] = -velocity[0] if pos_y + blob_height &gt; display_height or pos_y &lt; 0: velocity[1] = -velocity[1] # Checks to see if any keys are held down and remembers them with the variable keys. keys = pygame.key.get_pressed() for b in range(len(bullets)): bullets[b][0] += 6 for bullet in bullets: if bullet[0] &gt; 1005: bullets.remove(bullet) if keys[pygame.K_SPACE]: bullets.append([x+25, y+24]) # If the player is holding down one key or the other the blob moves in that direction if x &lt; 0: x = 0 if keys[pygame.K_a]: x_change = -blob_speed if x &gt; 401 - blob_width: x = 401 - blob_width if keys[pygame.K_d]: x_change = blob_speed if keys[pygame.K_p]: pause = True paused() # If the player is holding down both or neither of the keys the blob stops if keys[pygame.K_a] and keys[pygame.K_d]: x_change = 0 if not keys[pygame.K_a] and not keys[pygame.K_d]: x_change = 0 if y &lt; 0: y = 0 if keys[pygame.K_w]: y_change = -blob_speed if y &gt; display_height - blob_height: y = display_height - blob_height if keys[pygame.K_s]: y_change = blob_speed if keys[pygame.K_w] and keys[pygame.K_s]: y_change = 0 if not keys[pygame.K_w] and not keys[pygame.K_s]: y_change…
accepted answer: http://stackoverflow.com/a/48357144
linked to: http://stackoverflow.com/q/24042420
linked to: http://stackoverflow.com/q/30720665
type: Question
has answer: http://stackoverflow.com/a/48357144
has comment: http://stackoverflow.com/comment/83699987
tagged with: python
tagged with: pygame
answer count: 1
has comment: http://stackoverflow.com/comment/83700155
has comment: http://stackoverflow.com/comment/83699913
has title: Python how to delay bullet shooting
type: AnsweredQuestion
upvote count: 3
score: 3
linked to: http://stackoverflow.com/q/21567250
downvote count: 0

http://stackoverflow.com/a/48358698
has body: You are passing in a function that returns a fixed number: shuffle(num_list, lambda: seed) Here seed is one of your floating point values. That's very different from the default random() function; you are returning the same number repeatedly, forever. From the documentation: The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). You produced the Dilbert accounting department random number generator here: When you pass in an alternative random() function as the second argument, the value it returns is used to pick what preceding index to swap the 'current' index with (starting from the end); the source code that is run essentially does this: x = list_to_shuffle for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] So your fixed number would always pick the same relative index to swap with. For small enough differences in that fixed value the rounding down to the nearest integer would result in the exact same indices being used to swap with. This is what happens for 0.5 to 0.55, for example; in both cases the indices picked are (5, 4, 4, 3, 3, 2, 2, 1, 1), not much of a 'random' shuffle. Ditto for 0 and 0.05, when you swap everything with index 0, and for 0.9 and 0.95, when you swap each index with itself. If you wanted to test how seeding works, create an instance of the random.Random() class with your seed and call shuffle() on that object: from random import Random seed_list = [ 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95 ] last_list = ten_digits = list(range(10)) for seed in seed_list: num_list = ten_digits[:] Random(seed).shuffle(num_list) print("Seed {}:\t {} {}".format(seed, num_list, num_list==last_list)) last_list = num_list which outputs Seed 0.0: [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] False Seed 0.05: [3, 8, 5, 4, 2, 1, 9, 7, 0, 6] …
has comment: http://stackoverflow.com/comment/83705070
type: Answer
accepted answer of: http://stackoverflow.com/q/48358500
has comment: http://stackoverflow.com/comment/83705094
has comment: http://stackoverflow.com/comment/83704281
has comment: http://stackoverflow.com/comment/83704367
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83714361
has comment: http://stackoverflow.com/comment/83715767
answers question: http://stackoverflow.com/q/48358500
has comment: http://stackoverflow.com/comment/83704362
downvote count: 0
has comment: http://stackoverflow.com/comment/83704491
has comment: http://stackoverflow.com/comment/83704225
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83704642
has comment: http://stackoverflow.com/comment/83704347
has comment: http://stackoverflow.com/comment/83705108
has comment: http://stackoverflow.com/comment/83714218
has comment: http://stackoverflow.com/comment/83722531
has comment: http://stackoverflow.com/comment/83704087
has comment: http://stackoverflow.com/comment/83714278

http://stackoverflow.com/comment/83745764
comment on: http://stackoverflow.com/q/48379118
score: 0
type: Comment
type: QuestionComment
has text: I mean show the code you are using to verify that the file is not uploaded.

http://stackoverflow.com/q/48480972
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/48481955
type: AnsweredQuestion
downvote count: 0
has body: I have 2 models : User &amp; UserSummary. UserSummary has a foreign key to User. I just noticed that if I set depth= 1 within UserSummarySerializer, the password field is included in the output. It's hashed, but it would still be best to exclude this field. To hide the password field, I've just set the user field explicitly in the serializer, just like this : class UserSerializer(serializers.ModelSerializer): """A serializer for our user profile objects.""" class Meta: model = models.User extra_kwargs = {'password': {'write_only': True}} exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at') def create(self, validated_data): """Create and return a new user.""" user = models.User( email = validated_data['email'], firstname = validated_data['firstname'], lastname = validated_data['lastname'], mobile = validated_data['mobile'] ) user.set_password(validated_data['password']) user.save() return user class UserSummarySerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = models.UserSummary fields = '__all__' depth = 1 The downside of this way of doing is that, the field password is not available anymore on the POST request when creating a new user. How could I hide the password field on the GET request of UserSummary but display it in the POST request of User ?
has answer: http://stackoverflow.com/a/66328854
accepted answer: http://stackoverflow.com/a/48481955
tagged with: django-serializer
has answer: http://stackoverflow.com/a/61416070
favorite count: 0
type: Question
tagged with: rest
has answer: http://stackoverflow.com/a/57451671
possible better answer: http://stackoverflow.com/a/57451671
answer count: 5
has answer: http://stackoverflow.com/a/51396618
has title: Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer
upvote count: 13
tagged with: django
score: 13
tagged with: python

http://stackoverflow.com/comment/83761073
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48384905
type: Comment
has text: `UnboundLocalError: local variable 'temp_img' referenced before assignment` this error appeared

http://stackoverflow.com/comment/83759213
type: Comment
type: QuestionComment
has text: Just found on another page that the following constraint must hold as well for a "lucky number": li divides lj and lj divides lk
comment on: http://stackoverflow.com/q/48385793
score: 0

http://stackoverflow.com/a/48359137
type: Answer
has comment: http://stackoverflow.com/comment/103151992
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48359053
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/83705127
has comment: http://stackoverflow.com/comment/83705037
has comment: http://stackoverflow.com/comment/103151292
has comment: http://stackoverflow.com/comment/83705564
has body: It's possible to do it efficiently (without using any loops) by leveraging broadcasting like: In [28]: (A[:, np.newaxis] - B).reshape(-1, A.shape[1]) Out[28]: array([[ -9, -18, -27], [ -999, -1998, -2997], [ 11, 22, 5], [ 90, 180, 270], [ -900, -1800, -2700], [ 110, 220, 302]]) Or, for a little faster solution than broadcasting, we would have to use numexpr like: In [31]: A_3D = A[:, np.newaxis] In [32]: import numexpr as ne # pass the expression for subtraction as a string to `evaluate` function In [33]: ne.evaluate('A_3D - B').reshape(-1, A.shape[1]) Out[33]: array([[ -9, -18, -27], [ -999, -1998, -2997], [ 11, 22, 5], [ 90, 180, 270], [ -900, -1800, -2700], [ 110, 220, 302]], dtype=int64) One more least efficient approach would be by using np.repeat and np.tile to match the shapes of both arrays. But, note that this is the least efficient option because it makes copies when trying to match the shapes. In [27]: np.repeat(A, B.shape[0], 0) - np.tile(B, (A.shape[0], 1)) Out[27]: array([[ -9, -18, -27], [ -999, -1998, -2997], [ 11, 22, 5], [ 90, 180, 270], [ -900, -1800, -2700], [ 110, 220, 302]])
answers question: http://stackoverflow.com/q/48359053

http://stackoverflow.com/comment/83693725
type: QuestionComment
comment on: http://stackoverflow.com/q/48353538
has text: Which line is throwing the `SyntaxError` though?
type: Comment
score: 0

http://stackoverflow.com/comment/83651444
comment on: http://stackoverflow.com/a/48332667
type: Comment
has text: @GlennSampson I'd say that your `django_id` is probably Django's Primary key for each object. Anyway, if you want to accept the answer you have to press the check mark next to my answer. I hope I was of assistance.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83698567
comment on: http://stackoverflow.com/q/48355897
has text: @IgorPomaranskiy is right, there is no way you would get user data within the model layer itself. You could pass it as a parameter. Or do it the other way round - make `my_latest_song()` a user's model method (that would be more natural to me) and then pass it the genre id. Middleware seems to be an overkill - although technically possible, you probably want your middleware stack as thin as possible due to performance reasons.
type: QuestionComment
type: Comment
score: 4

http://stackoverflow.com/comment/83784409
comment on: http://stackoverflow.com/a/48398205
score: 0
type: AnswerComment
has text: Thank you! I know my code is inefficient but couldn’t think of an more elegant way to do this, thank you again.
type: Comment

http://stackoverflow.com/comment/83754910
type: Comment
type: QuestionComment
has text: I first installed Anaconda Navigator, had Windows uninstall it. Then I installed Python off their website, installed Atom off their website, got the errors. I then went into my Local Drive and found that there were leftover files from Anaconda and the Python that came with it. I deleted all of that, uninstalled and then reinstalled Python for the 3rd time. Still got the same errors.
comment on: http://stackoverflow.com/q/48383433
score: 0

http://stackoverflow.com/comment/83842343
type: Comment
type: QuestionComment
score: 0
has text: That's why I say it works well, it does not generate Segmentation fault (core dumped), it prints `next` every time the timer fires.
comment on: http://stackoverflow.com/q/48425074

http://stackoverflow.com/comment/83936448
type: QuestionComment
has text: Yep, it might work, if you don't care about having an imprecise location such as a block. And you should probably make the blocks overlap, because some blocks might cut the object in half, resulting in no recognition anywhere. Make sure the blocks are big enough to comprehend the entire objecs.
comment on: http://stackoverflow.com/q/48467000
score: 0
type: Comment

http://stackoverflow.com/a/48462032
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48461808
has comment: http://stackoverflow.com/comment/83925437
upvote count: 0
downvote count: 1
has body: You can use the reduce function from the functools package. The functools package usually comes with a standard installation of Python. So, you could write this: from functools import reduce for key in dict.keys(): dict[key]["KEYS"] = key combined = reduce(lambda x,y: x.append(y), dict.values()) First, you go through each data frame, and create the "KEYS" column. Then, the reduce function will go through the data frames in your dictionary, combining two at a time into one data frame, and then combining that result with the next data frame and so on, until it's gone through all the data frames in the dictionary. This gets stored in the result variable, combined. It looks like DATES is the index of each data frame in the dict, so if that's the case, you could add this: combined["DATES"] = combined.index.tolist() You can then rearrange the columns if you want, as well: combined = combined"KEYS", "DATES", "MAX", "MIN" Please let me know if that works for you.

http://stackoverflow.com/a/48384447
has body: Maybe not the best or elegant way but this will work. I also added the test5 just to be sure. special_chars = ['da', 'de', 'do', 'dos', 'das'] test1 = "Francisco da Sousa Rodrigues" #special split test2 = "Emiliano Rodrigo Carrasco" #normal split test3 = "Alberto de Francia" #special split test4 = "Bruno Rezende" #normal split test5 = 'Francisco da Sousa de Rodrigues' def cut(test): t1 = test.split() for i in range(len(t1)): if t1[i] in special_chars: t1[i+1] = t1[i] + ' ' + t1[i+1] for i in t1: if i in special_chars: t1.remove(i) print(t1) cut(test1) cut(test2) cut(test3) cut(test4) cut(test5) The results are: ['Francisco', 'da Sousa', 'Rodrigues'] ['Emiliano', 'Rodrigo', 'Carrasco'] ['Alberto', 'de Francia'] ['Bruno', 'Rezende'] ['Francisco', 'da Sousa', 'de Rodrigues']
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48383199

http://stackoverflow.com/a/48470674
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48470114
score: 1
type: Answer
has body: from bs4 import BeautifulSoup import requests request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1') soup = BeautifulSoup(request.text, 'html.parser') findNext = soup.find("a", class_="next_page").attrs['href'].split('page=')[1] print(findNext) #Result is 2

http://stackoverflow.com/comment/83746513
has text: Thank you so much.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48376165
score: 0

http://stackoverflow.com/q/48399498
has comment: http://stackoverflow.com/comment/83786949
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/60918254
has comment: http://stackoverflow.com/comment/109055079
has answer: http://stackoverflow.com/a/65473426
has answer: http://stackoverflow.com/a/61301291
has comment: http://stackoverflow.com/comment/83786841
answer count: 7
has body: I was trying to clone a git repo with access key, but when I am trying to run it, it throws an exception saying the Git executable cannot be found. But I have installed Git and the in_it.py shows the correct path "C:\Program Files\Git\bin". Also, I have installed gitpython to use the library in python. Here's my code: import git git.Git("D:/madhav/myrep/").clone("@github.com:myrepo/scripts") ========= and it throws the following exception ================= Traceback (most recent call last): File "C:\Users\1096506\Desktop\gitclone.py", line 1, in <module> from git import Repo File "C:\Users\1096506\AppData\Local\Programs\Python\Python36-32\lib\site-packages\git\__init__.py", line 84, in <module> refresh() File "C:\Users\1096506\AppData\Local\Programs\Python\Python36-32\lib\site-packages\git\__init__.py", line 73, in refresh if not Git.refresh(path=path): File "C:\Users\1096506\AppData\Local\Programs\Python\Python36-32\lib\site-packages\git\cmd.py", line 293, in refresh raise ImportError(err) ImportError: Bad git executable. The git executable must be specified in one of the following ways: - be included in your $PATH - be set via $GIT_PYTHON_GIT_EXECUTABLE - explicitly set via git.refresh() All git commands will error until this is rectified. This initial warning can be silenced or aggravated in the future by setting the $GIT_PYTHON_REFRESH environment variable. Use one of the following values: - quiet|q|silence|s|none|n|0: for no warning or exception - warn|w|warning|1: for a printed warning - error|e|raise|r|2: for a raised exception Example: export GIT_PYTHON_REFRESH=quiet
downvote count: 1
favorite count: 0
tagged with: git
type: Question
has answer: http://stackoverflow.com/a/55943328
has answer: http://stackoverflow.com/a/51038428
tagged with: gitpython
upvote count: 12
has answer: http://stackoverflow.com/a/78840019
type: UnansweredQuestion
has title: git executable not found with gitpython: "Bad git executable."
has comment: http://stackoverflow.com/comment/83787435
has answer: http://stackoverflow.com/a/66130640

http://stackoverflow.com/a/48430853
has comment: http://stackoverflow.com/comment/83853856
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: from time import perf_counter while True: start_time = perf_counter() + 300 # Set limit to 5 minutes (60 seconds * 5) if price &lt;= buy: print ("BUY!") if perf_counter() &gt; start_time: #send message code
accepted answer of: http://stackoverflow.com/q/48430355
type: Answer
answers question: http://stackoverflow.com/q/48430355

http://stackoverflow.com/q/48390412
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48390777
tagged with: math
has comment: http://stackoverflow.com/comment/83768709
tagged with: python
type: AnsweredQuestion
tagged with: fractions
score: 0
has comment: http://stackoverflow.com/comment/83787631
answer count: 2
has body: EDIT: solved but since the solution was in the comments and I cant accept my own solution reffering to the comment till tomorrow it is still open. Once again a big thank you to this great community and its people optional context: I am computing sollutions for the Pell equation http://mathworld.wolfram.com/PellEquation.html On the buttom of the page is a table with values for D -> x, y. My code works perfectly for EVERY VALUE EXCEPT D = 61. I believe it could have something to do with the values of x and y being very big and maybe the fraction module cant handle such big numbers and there is an overflow? I made the observation, that whether I give my input/ starting value as a fraction or a decimal changes my solution (but only for D = 61). Why is my code failing with the value of D = 61? What do I need to change/use to get it to work? Thank you very much for your time and help. code: from math import sqrt, floor from fractions import Fraction def continued_fraction(D): # to make sure it is not a problem on converting decimals to fractions I made EVERYTHING a fraction (which shouldnt and didnt affect the output) # input is the value for D, output is a tuple with (x, y) D = Fraction(sqrt(D)) aS = [] a0 = D r1 = Fraction(D - floor(D)) a = Fraction(a0 - r1) r = Fraction(-1) count = 0 while a &lt;= 2*floor(D): aS.append((a, count)) if a == 2*floor(D): if count % 2 == 0: break else: r = count if count == 2*r: break try: a0 = Fraction(1/r1) except ZeroDivisionError: break r1 = Fraction(a0 - floor(a0)) a = Fraction(a0 - r1) count += 1 pS = [] qS = [] a0 = Fraction(floor(D)) p0 = a0 p1 = Fraction(a0 * aS[1][0] + 1) q0 = Fraction(1) q1 = Fraction(aS[1][0]) count = 2 while count &lt; len(aS): pS.append((p0, count - 2)) qS.append((q0, count - 2)) pn = Fraction(aS[count][0] * p1 + p0) qn = Fraction(aS[count][0] * q1 + q0) p0 = Fraction(p1) p1 = Fraction(pn) q0 = Fraction(q1) q1 = Fraction(qn) count += 1 pS.append((p0, count-1)) #pS.append((p1, count)) qS.append((q0, count - 1))…
has answer: http://stackoverflow.com/a/48390777
has comment: http://stackoverflow.com/comment/83770486
has title: working with large numbers in the fraction module in Python
has answer: http://stackoverflow.com/a/48400919
accepted answer: http://stackoverflow.com/a/48400919
type: Question
tagged with: continued-fractions

http://stackoverflow.com/comment/83900319
comment on: http://stackoverflow.com/a/48453614
type: Comment
has text: The complicated explanation is the answer to the stated question: "I am trying to use an if statement to check whether a variable has been assigned (...) What's going on?"
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83710991
type: Comment
comment on: http://stackoverflow.com/a/48338439
type: AnswerComment
has text: @coldspeed I just tried this on the sample paste I made and it works fine. It must be an index issue. How do I call result.reset_index() ?
score: 0

http://stackoverflow.com/comment/83955120
score: 0
type: AnswerComment
has text: but what arg do i set it to bind an IntVar()?
comment on: http://stackoverflow.com/a/48478816
type: Comment

http://stackoverflow.com/comment/83744594
comment on: http://stackoverflow.com/a/48378908
type: AnswerComment
has text: I understand that there is a disconnection causing this error, but I have an extremely large graph, and I already checked the easy, obvious things (like searching for cast operations). I also ran the network to make sure that the output indeed changes when I change the input. But somewhere the gradient is breaking down (which prevents me from optimizing the network). Tracking this down is the hard part
score: 0
type: Comment

http://stackoverflow.com/q/48468365
tagged with: python
has body: Its my first question. I was lookoing through forum but cannot find fiiting aswer. I need to send in one message a ASCII text followed by 4 bytes (no less) composition of binary flags and than followed ASCII text The format of bit flags is defined as follows: Length 4 bytes b. The presence of an optional element or group of optional elements is indicated by a set bit (= 1), the absence by a non-set bit (= 0). Bits not required are 0. A value of 0b00000000 00000000 00000000 00000011 means that only the Fields in the Optional Elements section are sent, where the “Top. Lab” column is 1 or 2. For 0b00000000 00000000 00000000 01111111 all the Optional elements fields are sent where the “Top. Lab” column is one of the numbers 1 to 7. For 0b00000000 00000000 00000000 10000000 only the Fields in the Optional elements section are sent where the “Top. Lab” column is 8. lets say I want to send flags for field 1 and 4 so I prepared code: ba=bytearray(4) #for bits array of flags ba[0]=17 #set bits 1 and 4 message='string1'.encode('ascii') + ba + 'string2'.encode('ascii') #message to send socket.send(message) Is there better way to: build up 4 bytes bites value ? send it together with ascii text in socket message? I was trying before to send bytes directly but this gives error of concatenating or if is byte string b'0000.....0' it send it as length of 32 bytes instead of 4 bytes. Update: The 'string1' has defined length 22bytes (its header of message) and include information about and include type of message, sender id, length of 'string2'. This part is working as expected, only sending bit flags is problem for me. Up till now I was just sending 4 bytes of ascii encoded string 0000 which make me possible to receive message on other side correctly. This of course not mean 0b00000000 00000000 00000000 00000000 so other side interpret message content wrong way.
has comment: http://stackoverflow.com/comment/83946397
type: UnansweredQuestion
score: 0
answer count: 1
type: Question
has title: Python3 socket sending ASCII text and binary (4byte) flag in one message
has comment: http://stackoverflow.com/comment/83932910
tagged with: sockets
has answer: http://stackoverflow.com/a/48477183
tagged with: bit

http://stackoverflow.com/a/48351719
has body: how about something like this? counter = 0 new_list = [] for data in data_list: new_list.append([header_list[counter%len(header_list)],data]) counter+=1
has comment: http://stackoverflow.com/comment/83690241
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83690181
answers question: http://stackoverflow.com/q/48351673

http://stackoverflow.com/q/48352587
tagged with: python-3.x
linked to: http://stackoverflow.com/q/33771317
has answer: http://stackoverflow.com/a/48357840
has comment: http://stackoverflow.com/comment/83691965
has body: I have some wonderfully broken HTML that, long story short, is preventing me from using the normal nested , , structure that would make it easy to reconstruct tables. Here's a snippet with line numbers for reference: 1 2 3 4 06-30-95 5 6 7 8 9 10 1382 11 12 (23) 13 14 15 16 17 18 19 20 06-18-14 21 22 23 24 25 The nesting of trs within tds within trs has no scheme to it whatesover, and is coupled with unclosed tags to boot. The HTML tree in no way resembles how it is structurally rendered. (In this case, I suppose there are technically no missing closing tags, but the actual rendering of the page makes it clear there should be no nested tds.) However, playing by the following set of rules would work in this case: For any that is followed by an opening before its closing , (i.e. any nested td) assume that the latter opening (line 7) serves as closure for the first (line 1); Otherwise, just grab (open, close) ... tags as usual (where the opener and closer have no in between them; example would be lines 17 & 23 above. Desired result here would be something like: ['06-30-95', '1382\n(23)', '06-18-14'] How can this be addressed in BeautifulSoup? I would show an attempt, but have picked through the docs and some of the source and not found much at all. Currently this would parse to: html = """ 06-30-95 1382 (23) 06-18-14 """ from bs4 import BeautifulSoup, SoupStrainer strainer = SoupStrainer('td') soup = BeautifulSoup(html, 'html.parser', parse_only=strainer) [tag.text.replace('\n', '') for tag in soup.find_all('td')] [' 06-30-95 1382 (23) 06-18-14 ', ' 1382 (23) ', ' 06-18-14 '] And my issue with that result is not the whitespace; it's the repetition of substrings. It almost seems like I'd need to recursively work upwards from the innermost tags, popping off each and working outwards. But I have to guess there's more built-in functionality for dealing with missing closing tags (handle_endtag stands out from the BeautifulSoup constructor?).
tagged with: python
has title: Working with broken HTML + BeautifulSoup
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/48357840
answer count: 2
accepted answer: http://stackoverflow.com/a/48353397
upvote count: 3
has answer: http://stackoverflow.com/a/48353397
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/a/48362210
answers question: http://stackoverflow.com/q/48361882
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83799273
has body: You have 7 columns but are returning only 6. The error: Requested unknown parameter '6' for row 0, column 6 Is basically saying that there is no data for column 7. You will need to return a blank for your checkbox column. Something like this: columns = [ "", ColumnDT(sparkDB.ioc), ColumnDT(sparkDB.ioc_type), ColumnDT(sparkDB.active_mon), ColumnDT(sparkDB.lifecycle_mon), ColumnDT(sparkDB.added_by), ColumnDT(sparkDB.tags), ] The error is stopping the Datatables init process causing the checkboxes to not show. It looks like you are using Gyrocode Checkboxes plugin. I assume you are loading the include files for the plugin: https://www.gyrocode.com/projects/jquery-datatables-checkboxes/
has comment: http://stackoverflow.com/comment/83799044
type: Answer
has comment: http://stackoverflow.com/comment/83774351
downvote count: 0

http://stackoverflow.com/a/48386007
type: Answer
answers question: http://stackoverflow.com/q/48385231
has body: Your program doesn't wait for anything. It just runs through, tests if the button has been pressed in the few milliseconds it took to initialize and then stops. For testing you can add a simple time.sleep(5) to your code which will let the script wait for five seconds and then evaluate if you pressed the button in the meantime. You could also do: try: while True: if GPIO.event_detected(7): api.update_status(status=tweetStr) print "Tweeted: " + tweetStr time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() print "\nBye" This will run forever until you press Ctrl-C and respond to your keypresses once each second. However the better way to handle this would be to hand a callback function to the keyboard interrupt. Watch out that the callback function can only communicate with the main script via global variables (please someone correct me if there's a better way!). import time api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) tweetStr = "@raspberrytest34 deneme 1-2-3" def send_tweet(channel): global tweetStr global api api.update_status(status=tweetStr) print "Tweeted: " + tweetStr GPIO.add_event_detect(7, GPIO.FALLING, callback=send_tweet) try: while True: time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() print "\nBye"
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/83769568
type: Comment
has text: I think you could use something like PyInstaller (or similar) to select only the libraries you use, but I've never used it myself so can't be of real help there
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48389178

http://stackoverflow.com/comment/83768105
has text: @neo4k then using the `__add__` hook should work, no? How would it fail to work as you'd expect?
comment on: http://stackoverflow.com/q/48390030
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83775066
score: 0
type: Comment
type: QuestionComment
has text: Thanks for looking, but my code is the same in the examples the post you linked, the issue is that the form is considered valid, like the clean_postcode method is not run at all? the form is validating even though i am not inputting "fred@example.com"??
comment on: http://stackoverflow.com/q/48393582

http://stackoverflow.com/a/48456134
has comment: http://stackoverflow.com/comment/84021017
score: 0
answers question: http://stackoverflow.com/q/48455837
has body: Your step parameter is too large. You need to decrease it a lot. Try values like 0.001 or 0.0001
type: Answer

http://stackoverflow.com/comment/83800463
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48405799
has text: You say the sequence you need starts with `0x98`, whilst what you show has 11 bytes, but your code tries to grab 13 from the serial port. Which is right?

http://stackoverflow.com/comment/83795241
comment on: http://stackoverflow.com/a/48403142
has text: Hmmm, so what solution is the fastest?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48352405
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: opencv
tagged with: crash
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48415976
tagged with: ubuntu
has title: Ubuntu OpenCV: Program Crashing when loading video file
tagged with: video
has body: I'm trying to load a video file with opencv in python. The program crashes and returns: $ python bg_reduction.py Segmentation fault (core dumped) After hours of digging through forums I'm beginning to realize that the problem may be with my build of opencv. I'm a novice programmer and linux user so most of what I've found was over my head anyways. Here's the gist of my program -- which works when streaming video from webcam, fails when loading from file. cap = cv2.VideoCapture('SuccessPrint.mp4') fgbg = cv2.createBackgroundSubtractorMOG2() while (cap.isOpened()): try: ret, frame = cap.read() except cv2.error: cap.release() cv2.destroyAllWindows() k = cv2.waitKey(30) &amp; 0xFF if k == 27: break cap.release() cv2.destroyAllWindows() Here is the codec information returned from: $ffmpeg -i SuccessPrint.mp4 Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x480 [SAR 1:1 DAR 4:3], 557 kb/s, 24 fps, 24 tbr, 12288 tbn, 48 tbc (default) And finally here is the information from the core: $gdb bg_reduction.py core Returns(I've removed the path): /bg_reduction2.py": not in executable format: File format not recognized [New LWP 12398] [New LWP 12401] [New LWP 12399] [New LWP 12400] Core was generated by `python bg_reduction2.py'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0x00007fe3c7364fd1 in ?? () [Current thread is 1 (LWP 12398)] (gdb) Any advice would be incredible. Thanks in advance!

http://stackoverflow.com/comment/83659755
type: Comment
comment on: http://stackoverflow.com/a/48336735
score: 0
type: AnswerComment
has text: Although I agree with your opinion regarding the readability, I didn't want to change the construct. I just want to break it into multiple lines.

http://stackoverflow.com/comment/83860504
has text: Note: This will still output only one decimal point when the second would be `0`. You'd need to use string formatting operations if you wanted to output an exact number of decimal places.
comment on: http://stackoverflow.com/a/48434436
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/67266239
answers question: http://stackoverflow.com/q/48369578
type: Answer
has body: Generic solution would be as follows: df.assign( **df.select_dtypes(['datetime']).astype(str).to_dict('list') ).to_json(orient="records") Based on the dtype it selects the datetime columns and set these as str objects so the date format is kept during serialization.
score: 0

http://stackoverflow.com/comment/83775183
has text: @Vijaysachin, ...why would any intelligently-designed tool use `.py` files as a data format? Unlike better-designed formats, it's *inherently* Turing-complete and allows arbitrary code execution, making it bad for security; it's much slower to parse than formats built for speed, and much larger than formats built for size.
type: Comment
comment on: http://stackoverflow.com/q/48365792
score: 0
type: QuestionComment

http://stackoverflow.com/a/48383752
downvote count: 0
has comment: http://stackoverflow.com/comment/83754582
type: Answer
answers question: http://stackoverflow.com/q/48383549
has body: If I'm not mistaken the TIME_ZONE setting sets the "local" timezone, so change that from UTC to your local time zone. There is no HTTP-Header that shows the server the client's time zone. Most websites that use localized times ask the user what timezone they are in and save that in the users profile. See Django Documentation https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#selecting-the-current-time-zone Javascript has a way of accessing the UTC offset, maybe you can use that to send the information to your server along with the request.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83754417

http://stackoverflow.com/a/48363903
answers question: http://stackoverflow.com/q/48363560
type: Answer
score: 0
has body: Looking at your code, you can probably bypass sending the interger to string and back. Especially since you are padding a 8-bit binary array to 16 bits with zeros, only to split it in half again. Instead, try: zb = np.zeros(1, dtype=np.uint8)[0].tobytes() for j in range(100000): crc=0xffff tmp_data = array1[j].tobytes() crc=binascii.crc_hqx(zb, crc) crc=binascii.crc_hqx(tmp_data, crc) tmp_data = array2[j].tobytes() crc=binascii.crc_hqx(zb, crc) crc=binascii.crc_hqx(tmp_data, crc)

http://stackoverflow.com/comment/84018607
comment on: http://stackoverflow.com/q/48486757
type: QuestionComment
has text: Can redshift servers host file storage? Or interact with a remote storage? It's possible to point the NLTK another location if a remote disk is mounted locally with `nltk.data.path.append`
score: 0
type: Comment

http://stackoverflow.com/comment/83736524
score: 2
comment on: http://stackoverflow.com/q/48374664
has text: It's still there. You didn't remove it or anything, so you don't need to do anything to put it back.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83850945
type: AnswerComment
has text: sorry the formatting on the comment isn't what I expected.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48429736

http://stackoverflow.com/q/48435538
tagged with: numpy
has comment: http://stackoverflow.com/comment/83862815
answer count: 1
has title: Create a scatter chart by matplotlib with mysql database
has answer: http://stackoverflow.com/a/48435645
type: Question
type: AnsweredQuestion
score: 0
has body: I want to create a simple chart with these library written below. Here is how I did: import matplotlib.pyplot as plt import numpy as np import pandas as pd import MySQLdb def mysql_select_all(): conn = MySQLdb.connect(host='localhost', user='root', passwd='password', db='databse') cursor = conn.cursor() sql = "SELECT price,size1 FROM 008_table" cursor.execute(sql) result = cursor.fetchall() df = pd.DataFrame(list(sql),columns=["price","size1"]) x = df.price y = df.size1 plt.title("Table", fontsize="24") plt.scatter(x, y, s=100) plt.xlabel("Size1") plt.ylabel("Price") plt.tick_params(axis='both',which='major',labelsize=14) cursor.close() print("Start") mysql_select_all() print("End") I got the Value Error with this code, where should I fix this code ?
tagged with: pandas
has comment: http://stackoverflow.com/comment/83862362
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83862429
tagged with: python
tagged with: mysql
accepted answer: http://stackoverflow.com/a/48435645

http://stackoverflow.com/a/48405450
has body: Assuming time interval is fixed to 5mins,we can create start time and end time for each fruit in df_fruit and join them as, &gt;&gt;&gt;import datetime &gt;&gt;&gt; from pyspark.sql import functions as F &gt;&gt;&gt; from pyspark.sql.types import StringType &gt;&gt;&gt; maxtimeudf = F.udf(lambda x : (datetime.datetime.strptime(x,'%H:%M')+datetime.timedelta(minutes=5)).strftime('%H:%M'),StringType()) &gt;&gt;&gt; mintimeudf = F.udf(lambda x : (datetime.datetime.strptime(x,'%H:%M')+datetime.timedelta(minutes=-5)).strftime('%H:%M'),StringType()) &gt;&gt;&gt; df_fruit = df_fruit.withColumn('starttime',mintimeudf(df_fruit['Time'])).withColumn('endtime',maxtimeudf(df_fruit['Time'])) &gt;&gt;&gt; df_fruit.show() +------+-----+---------+-------+ | Fruit| Time|starttime|endtime| +------+-----+---------+-------+ | Apple|10:00| 09:55| 10:05| |Orange|12:35| 12:30| 12:40| | Apple|11:36| 11:31| 11:41| | Apple|12:48| 12:43| 12:53| | Pear|11:00| 10:55| 11:05| +------+-----+---------+-------+ &gt;&gt;&gt; df = df_fruit.join(df_calories,((df_fruit.Fruit == df_calories.Fruit) &amp; (df_calories.Time.between(df_fruit.starttime,df_fruit.endtime))),'left_outer') &gt;&gt;&gt; df.select(df_fruit['Fruit'],df_fruit['Time'],df_calories['Time'],df_calories['Weight'],df_calories['Calories']).show() +------+-----+-----+------+--------+ | Fruit| Time| Time|Weight|Calories| +------+-----+-----+------+--------+ |Orange|12:35|12:39| 75g| 14cal| |Orange|12:35|12:33| 75g| 2cal| | Pear|11:00| null| null| null| | Apple|10:00|10:02| 86g| 1cal| | Apple|10:00|10:04| 9g| 47cal| | Apple|11:36| null| null| null| | Apple|12:48|12:46| 25g| 9cal| +------+-----+-----+------+--------+ Hope this helps !
answers question: http://stackoverflow.com/q/48403619
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83831158
has comment: http://stackoverflow.com/comment/83802222
type: Answer
accepted answer of: http://stackoverflow.com/q/48403619
score: 4
upvote count: 4

http://stackoverflow.com/comment/83651313
type: QuestionComment
has text: print for me `data_all.iterrows()`
score: 0
comment on: http://stackoverflow.com/q/48332632
type: Comment

http://stackoverflow.com/comment/132022793
has text: np.int8(img) didn't worked for my case but np.float32(img) worked. Thanks.
comment on: http://stackoverflow.com/a/48453577
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48338413
tagged with: prompt
has title: Applications not related to python output weird error message: SyntaxError: invalid syntax
has body: Hello everybody reading this message, Since I set PYTHONPATH on my desktop, whenever I try to use commands like gdb, or yum, which I think not related to python, I have this "SyntaxError: invalid syntax" slapping my face. I have tried several thing to debug the shell prompt, to figure out what the heck was going on, but so far I stucked with this problem. I goes like this: [charly@sn04 ~]$ gdb File "/opt/anaconda3/lib/python3.5/site.py", line 176 file=sys.stderr) ^ SyntaxError: invalid syntax This seems to be related to PYTHONPATH. When I unset this, everything works fine. My PYTHONPATH: export PYTHONPATH=/opt/anaconda3/lib/python3.5/ I have tried to debug the shell with -x and -v, but the debug information is not helpful: [charly@sn04 ~]$ gdb gdb + gdb File "/opt/anaconda3/lib/python3.5/site.py", line 176 file=sys.stderr) ^ SyntaxError: invalid syntax I tried as well to set a trap: trap "PARENT_COMMAND=\"$(ps -o comm= $PPID)\"" ERR [charly@sn04 ~]$ gdb gdb + gdb File "/opt/anaconda3/lib/python3.5/site.py", line 176 file=sys.stderr) ^ SyntaxError: invalid syntax PARENT_COMMAND="xterm" ++ PARENT_COMMAND=xterm , to see which process was calling this error, but so far I was unable to figure out how to solve this problem. Thank you in advance for any clue or hint.
tagged with: python
tagged with: shell
has answer: http://stackoverflow.com/a/53264897
upvote count: 4
tagged with: syntax-error
answer count: 2
linked to: http://stackoverflow.com/q/10641201
has answer: http://stackoverflow.com/a/48338786
type: UnansweredQuestion
tagged with: pythonpath
downvote count: 0
score: 4
linked to: http://stackoverflow.com/q/26243956
favorite count: 0
type: Question

http://stackoverflow.com/q/48471040
tagged with: python
has title: super().__init__ overwrites an attribute
tagged with: inheritance
has body: I'm setting an attribute in a subclass initialiser, which seems to be overwritten by a call to super().__init__. from keras.layers import GRU, wrappers class Dummy(wrappers.Wrapper): def __init__(self, layer, **kwargs): self.stateful = True print(self.stateful) super().__init__(layer, **kwargs) print(self.stateful) In [3]: dummy = Dummy(GRU(64, stateful=True)) True False In [4]: dummy.stateful Out[4]: False I would assume something in wrappers.Wrapper overwrites the attribute, but a built-in wrapper subclass Bidirectional with an almost identical superclass init call (I basically followed the pattern from this subclass in my implementation) class Bidirectional(Wrapper): def __init__(self, layer, merge_mode='concat', weights=None, **kwargs): ... self.stateful = layer.stateful ... super(Bidirectional, self).__init__(layer, **kwargs) doesn't demonstrate this behaviour In [6]: bidir = wrappers.Bidirectional(GRU(64, stateful=True)) In [7]: bidir.stateful Out[7]: True I can't wrap my head around this. I'm using Keras 2.1.3 under Python 3.6. P.S. I've already tried replacing super().__init__(layer, **kwargs) with super(Dummy, self).__init__(layer, **kwargs) in my subclass to no avail.
tagged with: super
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48471120
downvote count: 0
has answer: http://stackoverflow.com/a/48471120
score: 1
upvote count: 1
tagged with: keras
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/83813706
type: Comment
score: 1
type: QuestionComment
has text: Try using `obj.__class__.__module__`, the accepted answer is not correct.
comment on: http://stackoverflow.com/q/48411818

http://stackoverflow.com/comment/83897617
type: Comment
type: QuestionComment
has text: [Can't you provide a toy data set and your code](https://stackoverflow.com/help/mcve), so people can reproduce and identify your problem? Imho at the moment, there is not sufficient information to address this problem.
comment on: http://stackoverflow.com/q/48398869
score: 1

http://stackoverflow.com/a/49503311
downvote count: 0
has body: This is due to a version conflict between h5py and numpy. All you need to do is degrade your numpy version through command as below: pip install numpy==1.13.0
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/48340392

http://stackoverflow.com/comment/117553660
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/64486726
has text: With tk backend, I am currently testing toolbar.mode (returns True if pan/zoom button is selected, False if not), not sure if its supported though,
type: Comment

http://stackoverflow.com/comment/83699462
score: 0
has text: Do you have PYTHONPATH environment also set somewhere?
comment on: http://stackoverflow.com/q/48356435
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48425707
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
score: 0
has comment: http://stackoverflow.com/comment/83843072
answer count: 1
has body: I normally use raw to download the .ipynb files from Github using a mac. However, lately, I encountered some .ipynb files that can only be saved as Archive or Web Scourse. Any reason for this, please?
has answer: http://stackoverflow.com/a/48428394
has comment: http://stackoverflow.com/comment/83841206
has title: Error in Downloading Jupiter Notebook from Github
type: Question

http://stackoverflow.com/q/48428157
has answer: http://stackoverflow.com/a/48430400
tagged with: python
score: 2
tagged with: turtle-graphics
upvote count: 2
has title: Consecutive onscreenclick events in Python turtle graphics
downvote count: 0
answer count: 1
has body: My aim is to call a series of functions (consecutively), each with two arguments, upon left-clicking the screen/canvas, automatically supplied with the coordinates of the point clicked. My goal is for these to be sequential, not all at once with one click. So, click the screen, call function 1, click the screen again (with new coordinates), call function 2 with new coordinates supplied etc. Here's what I have tried: from turtle import * def f(x, y): goto(x, -y) def g(x, y): goto(-x, y) def main(): onscreenclick(f) onscreenclick(g) main() After reading through the literature on 'onclick', 'onscreenclick', I gather it is related to whether you put 'True','False' or 'None' for the third argument. After trying various combinations of these, all it does is either call all of them upon first click or just call the last one. If anyone knows of anywhere I can find a more detailed explanation of mouse click events in Python, especially with Turtle graphics I would be most grateful. Or if you can answer the question yourself of course.
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/48425228
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48426202
possible better answer: http://stackoverflow.com/a/48425391
has answer: http://stackoverflow.com/a/48425391
downvote count: 0
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48425443
answer count: 4
has answer: http://stackoverflow.com/a/48425443
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48425807
score: 3
upvote count: 3
has body: I want to use python in order to manipulate a string I have. Basically, I want to prepend"\x" before every hex byte except the bytes that already have "\x" prepended to them. My original string looks like this: mystr = r"30336237613131\x90\x01\x0A\x90\x02\x146F6D6D616E64\x90\x01\x06\x90\x02\x0F52656C6174\x90\x01\x02\x90\x02\x50656D31\x90\x00" And I want to create the following string from it: mystr = r"\x30\x33\x62\x37\x61\x31\x31\x90\x01\x0A\x90\x02\x14\x6F\x6D\x6D\x61\x6E\x64\x90\x01\x06\x90\x02\x0F\x52\x65\x6C\x61\x74\x90\x01\x02\x90\x02\x50\x65\x6D\x31\x90\x00" I thought of using regular expressions to match everything except /\x../g and replace every match with "\x". Sadly, I struggled with it a lot without any success. Moreover, I'm not sure that using regex is the best approach to solve such case.
tagged with: string
has title: Match everything except a pattern and replace matched with string

http://stackoverflow.com/q/48351558
upvote count: 1
has comment: http://stackoverflow.com/comment/83691381
has title: Pulling up "dict" value of nested JSON by one level
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83808041
tagged with: python
accepted answer: http://stackoverflow.com/a/48351587
has comment: http://stackoverflow.com/comment/83694259
tagged with: dictionary
tagged with: chef-infra
has body: I'm looking at converting some Chef run_lists to tags, and would like to automate the process. So far what I've done is created a variable that runs: # write to file instead of directly to variable for archival purposes os.system("knife search '*:*' -a expanded_run_list -F json &gt; /tmp/hostname_runlist.json") data = json.load(open('/tmp/hostname_runlist.json')) From there, I have a dict within a dict with list values similar to this: {u'abc.com': {u'expanded_run_list': None}} {u'foo.com': {u'expanded_run_list': u'base::default'}} {u'123.com': {u'expanded_run_list': [u'utils::default', u'base::default']}} ... I would like to convert that to a more simpler dictionary by removing the 'expanded_run_list' portion, as it it's not required at this point, so in the end it looks like this: abc.com:None foo.com:'base::default' 123.com:['utils::default', 'base::default'] I would like to keep the values as a list, or a single value depending on what is returned. When I run a 'for statement' to iterate, I can pull the hostnames from i.keys, but would need to remove the expanded_run_list key from i.values, as well as pair the key values up appropriately. From there, I should have an easier time to iterate through the new dictionary when running an os.system Chef command to create the new tags. It's been a few years since I've written in python, so am a bit rusty. Any descriptive help would be much appreciated.
has answer: http://stackoverflow.com/a/48351587
type: AnsweredQuestion
tagged with: list
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48450396
has comment: http://stackoverflow.com/comment/83894706
favorite count: 0
type: Question
score: 3
tagged with: python
tagged with: pygame
has body: After crashing my head against the monitor for 2 hours I realised that: display.blit(mypic, posx, posy) pygame.display.update() would just not work (i.e. wouldn't blit anything on the screen) unless I call: pygame.event.get() Is this the weirdest bug on earth, or am I missing something? I'm running pygame on python 2.7, mac os high sierra, and yes I would be the least surprised if this was due to the goddam incompatibility between pygame and mac os. Any hint about what is going wrong here? Example code: import pygame winWidth = 800 winHeight = 600 posx = 200; posy = 200 mypic = pygame.image.load("path_to_my_picture.jpg") COL_BACKGROUND = (255,255,255) DISPLAYSURF = pygame.display.set_mode((winWidth, winHeight)) pygame.init() display.fill(COL_BACKGROUND) display.blit(mypic, posx, posy) # only including the following line it will blit the picture: # pygame.event.get() pygame.display.update()
type: AnsweredQuestion
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48451116
has title: pygame does not blit unless I call pygame.event.get()
tagged with: event-handling
tagged with: macos
has answer: http://stackoverflow.com/a/48451116

http://stackoverflow.com/q/48389174
has body: TL;DR: My input_fn at one step produces 7 images from 1. I would like to use each of them individually (1x1000x1000x3 7 times) rather than as a single image (7x1000x1000x3), as to be able to shuffle them and mix them among multiple batches. My data, images, is quite large: 5000x9000x3 features and 5000x9000x1 labels, so I store them as JPEG and feed the compressed image to input_fn, gen_fn uncompresses them and parser_fn outputs 7x1000x1000x3 & 7x1000x1000x1 (7 random crops, as a nested tuple always). Now the thing is, I don't want my input to be those 7 images, but rather to take that 7 as "the batch size". My attempt is as follows: # Where `gen_fn` outputs JPEG encoded strings (bytes in python) dataset = tf.dataset.Dataset.from_generator(gen_fn, (tf.string, tf.string)) print(dataset) # debug, shown below # Produces ([7, 1000, 1000, 3], [7, 1000, 1000, 1]) dataset = dataset.map(lambda features, labels: parser_fn) print(dataset) # debug, shown below # Attempts to flatten out the 0th dimension # Effectively produces ([1000, 1000, 3], [1000, 1000, 1]) dataset = dataset.flat_map(lambda x,y: tf.dataset.Dataset.from_tensor_slices((x, y)) print(dataset) # debug, shown below # Shuffle all of them to avoid biasing the network # dataset = dataset.shuffle(63) # 9*7 # Prefetch, repeat (does not have any effect, tested) dataset = dataset.prefetch(1) print(dataset) # debug, shown below dataset = dataset.repeat(1) print(dataset) # debug, shown below # Batch dataset = dataset.batch(1) print(dataset) # debug, shown below itr = dataset.make_one_shot_iterator() features, labels = itr.get_next() return features, labels Which prints to console <FlatMapDataset shapes: (<unknown>, <unknown>), types: (tf.string, tf.string)> <MapDataset shapes: ((7, 1000, 1000, 3), (7, 1000, 1000, 1)), types: (tf.float32, tf.float32)> <FlatMapDataset shapes: ((1000, 1000, 3), (1000, 1000, 1)), types: (tf.float32, tf.float32)> <PrefetchDataset shapes: ((1000, 1000, 3), (1000, 1000, 1)), types: (tf.float32, …
has comment: http://stackoverflow.com/comment/84476074
has title: Tensorflow Dataset API: map function producing multiple outputs per one input
linked to: http://stackoverflow.com/q/45955241
has comment: http://stackoverflow.com/comment/84512629
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-datasets
accepted answer: http://stackoverflow.com/a/48757440
has answer: http://stackoverflow.com/a/48757440
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84511383
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48428506
has answer: http://stackoverflow.com/a/48428956
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
has title: Comment form in django didn't save the new comments
answer count: 2
has body: I've created a new form for comments the articles on a website. When I add the new comment from django admin everything works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles. here are my files models.py: class Komentarz(models.Model): post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE) name = models.CharField(max_length=80, verbose_name="Imię") email = models.EmailField(verbose_name="Email") content = models.TextField(verbose_name="Treść komentarza") created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True) active = models.BooleanField(verbose_name="Aktywny?", default=True) class Meta: ordering = ('created_date',) verbose_name="Komentarz" verbose_name_plural="Komentarze" def __str__(self): return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post) vies.py with the function of details from django.shortcuts import render, get_object_or_404 from .models import Wpisy, Komentarz from .forms import KomentarzeForma .... def detale_bajki(request, slug, ): detale_bajki = get_object_or_404(Wpisy, slug=slug) komentarze = detale_bajki.komentarze.filter(active=True) if request.method == 'POST': formularz_komentarza = KomentarzeForma(data=request.POST) if formularz_komentarza.is_valid(): nowy_komentarz = formularz_komentarza.save(commit=False) nowy_komentarz.detale_bajki = detale_bajki nowy_komentarz.save() else: formularz_komentarza = KomentarzeForma() return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza}) forms.py from .models import Komentarz from django import forms class KomentarzeForma(forms.ModelForm): class Meta: model = Komentarz fields = ('name', 'email', 'content') and detail.html ... {% with komentarze.count as total_komentarze %} {{ total_komentarze }} komentarz{{ tota…
type: Question
has comment: http://stackoverflow.com/comment/83847777
has answer: http://stackoverflow.com/a/48430518
has comment: http://stackoverflow.com/comment/83851390

http://stackoverflow.com/comment/83807525
has text: @JamesSchinner Thanks for the tip! The book I'm using uses camelCase but it's good to know the general practice before I pick up a bad habit.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48394789

http://stackoverflow.com/a/48453443
score: 0
answers question: http://stackoverflow.com/q/48452559
type: Answer
has body: Firebase does not have any service/feature that allows you to periodically run Python or any other code. The closest thing to that is Cloud Functions, which can be triggered through an external service like cron-job.org. For more in this, see: Firebase Hosting Flask Application (on running Python on Firebase Hosting) Using google cloud function to spawn a python script (for an elaborate way where you might apparently run Python on Cloud Functions, but I never have, nor am likely to ever try this myself) Cloud Functions for Firebase trigger on time? (for running Cloud Functions periodically either through AppEngine, or cron-job.org).

http://stackoverflow.com/comment/83801358
comment on: http://stackoverflow.com/q/48406251
score: 0
has text: Perhaps the `decimal` module can help? I'm not sure if your problem is related to floating point error, but if it is, I'd look into that.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83774351
score: 0
type: Comment
has text: Thank you for the response! I added in the blank in my flask app and I am receiving a different error now. DataTables warning: table id=sparkdb - 'str' object has no attribute 'sqla_expr' I think you're right about defining a value in the columns list variable, but I'm not sure it likes the empty string.
comment on: http://stackoverflow.com/a/48362210
type: AnswerComment

http://stackoverflow.com/comment/83828013
score: 0
comment on: http://stackoverflow.com/q/48405228
type: Comment
has text: @Nullman You're right, len(containers) equals 0. That means, my soup is actually not generating a list of divs? I printed the single variables one by one and didn't get an output as well.
type: QuestionComment

http://stackoverflow.com/comment/102923648
comment on: http://stackoverflow.com/q/48419099
type: Comment
has text: Dask dataframes might help you. [Stackoverflow reference](https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe)
type: QuestionComment
score: 0

http://stackoverflow.com/q/48370122
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48371434
has title: Finding a suitable move from minimax using the values returned from evaluation function
has answer: http://stackoverflow.com/a/48371434
type: AnsweredQuestion
tagged with: algorithm
tagged with: python
tagged with: artificial-intelligence
has body: So, I am trying to implement minimax algorithm for a simple game that has 2 players each having 2 queens. So total 4 queens on a 7X7 board. So on each turn, the players moves both of his queens to a new position. I try to find the min and max by recursing over, minimax function as shown below. The base case is supposed to return an integer, which is a score returned by the evaluation function. But how do I find the min and the max after I have traversed till the leaf node? This function should be able to return the best move for queen1 and the queen2. But I do not understand, as to how to proceed to find the min and max from leaf node value. How do I propagte the values. I just cannot understand/visualize this.
tagged with: minimax
type: Question
tagged with: graph

http://stackoverflow.com/a/48470836
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48470636
has body: From the comments given above, the answer is as follows. Add a header to the image (second last line in this code block): # image logo = "image1.png" fp = open(logo, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', '<image>') msg.attach(img) For the text, add an image tag with attribute src corresponding to what you modified. Note that cid is short for Content-ID. Also note that the content id must be enclosed in angle brackets. # body text text = " Read this text!" bodytext = MIMEText(text, 'html') msg.attach(bodytext)

http://stackoverflow.com/q/48385748
score: 0
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83758922
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83759343
has comment: http://stackoverflow.com/comment/83758955
tagged with: flask
has title: Error 404 on Flask app
has body: I'm starting off with flask, I have this code on my app.py: from flask import Flask, render_template, request from flask.ext.uploads import UploadSet, configure_uploads, IMAGES app = Flask(__name__) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'static/img' configure_uploads(app, photos) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST' and 'photo' in request.files: filename = photos.save(request.files['photo']) return filename return render_template('upload.html') if __name__ == '__main__': app.run(debug=True) My upload.html code: Upload This is the file hyerarchy: ├── image_upload │ ├── app │ │ ├── app.py │ │ ├── app.pyc │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── routes.py │ │ ├── routes.pyc │ │ └── upload.html │ ├── image_upload.py │ ├── image_upload.pyc │ └── static │ ├── img │ └── templates │ └── upload.html └── install.sh My __init__.py file: from flask import Flask app = Flask(__name__) My routes.py although I'm not using it: from app import app @app.route('/') @app.route('/upload') def index(): return upload And the image_upload.py file: from app import app It always throws Error 404 when I browse it, could it be the routes.py file? I'm a fresher on flask so any help would be greatly appreciated. Also if I import the routes file from init it throws me: Traceback (most recent call last): File "/home/kristian/.virtualenvs/paper_flask/bin/flask", line 11, in <module> sys.exit(main()) File "/home/kristian/.virtualenvs/paper_flask/local/lib/python2.7/site-packages/flask/cli.py", line 513, in main cli.main(args=args, prog_name=name) File "/home/kristian/.virtualenvs/paper_flask/local/lib/python2.7/site-packages/flask/cli.py", line 380, in main return AppGroup.main(self, *args, **kwargs) File "/home/kristian/.virtualenvs/paper_flask/local/lib/python2.7/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/kristian/.virtualenvs/paper_flask/local/lib/python2.7/site-pa…

http://stackoverflow.com/comment/83825688
score: 0
type: AnswerComment
has text: Thank you. so there is no way to extract from classification_report? what about the other reports?
type: Comment
comment on: http://stackoverflow.com/a/48418031

http://stackoverflow.com/q/48343244
tagged with: python
score: -2
has body: num_array = list() num = int(raw_input("Enter how many elements you want:")) print 'Enter numbers in array: ' for i in range(int(num)): n = raw_input("num :") num_array.append(int(n)) print 'ARRAY: ',num_array b = 0 count = 0 while b&lt; num -1 or b&gt;0: count = count+1 if num_array[b]!= 0: b = b + num_array[b] else: b = (b + num_array[b])*2 print count i am trying to get an array as an input anD storing a index value in a variable which is updating its values. But i am getting an error of list out of range Please help me
has comment: http://stackoverflow.com/comment/83671956
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83671896
downvote count: 2
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/83671937
has answer: http://stackoverflow.com/a/48343302
has title: list index out of range with if condition

http://stackoverflow.com/comment/83698626
type: AnswerComment
comment on: http://stackoverflow.com/a/48355994
has text: OK, one question - length of lists is same?
type: Comment
score: 0

http://stackoverflow.com/comment/86867315
has text: I found out that this has a bug. `row_elem.select('> td,> th')` doesn't not follow the order of the columns. Instead it selects td first then th. If a row has td and th, while th is in front of td, the order will be wrong.
comment on: http://stackoverflow.com/a/48451104
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83861529
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48424823
has text: Great, thanks. I partially solve my issue. At first it worked out as I want, but the more I run the code, the different concatenation is given (not only the correct), plus sometimes it does not recognize a variable and sometimes does it. I am wondering if this is because some bug in my code ..? pretty weird. I checked that I am using python 3.5.2

http://stackoverflow.com/a/48386257
type: Answer
answers question: http://stackoverflow.com/q/48386112
has body: I think you are missing some key concepts, you are doing online hosting even if its only available on a local intranet. to accomplish this task you need to expose your program to the internet, flask makes this really really easy my_python_server.py from my_prog import count_cars_opencv import flask app = flask.Flask(__name__) @app.route("/count_cars") def do_count_some_cars(): return "There are %d cars"%count_cars_opencv() app.run(host="0.0.0.0",debug=True) then the easiest is probably to use something like ionic to build a simple webpage that has an ajax call to your "server" and updates a div something like my_ionic.js $("#my_info_div").load("http://192.168.1.133:5000/count_cars") then just build the ionic app targeting the phonetype you want (android or ios or both) ... alternatively if you have already exposed that url... they could just open the url in their phones webbrowser
score: 0
has comment: http://stackoverflow.com/comment/83911746

http://stackoverflow.com/comment/83897833
type: Comment
has text: I have just added links for the source code file and the datafiles. Thank you.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48398869

http://stackoverflow.com/comment/83969397
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48488256
type: QuestionComment
has text: So... You would need to click that button using Python, then. Find the form responsible for that, specify the parameters and send it!

http://stackoverflow.com/comment/83783592
type: QuestionComment
score: 0
has text: Thanks for the references, but they're not fully applicable to this problem. The other users have problems with using pip in virtualenv. My problem is in the step before, when creating the virtualenv. Since it's a rights problem I could use sudo for installing the virtualenv and sudo for pip, but eventually this code will be used in a script that needs to run without root permissions, so that's not an option.
comment on: http://stackoverflow.com/q/48386418
type: Comment

http://stackoverflow.com/comment/83848589
has text: I understood the (.*) and (.), thanks for that. :D @RyanWilson Thanks a lot. It works for me. :)
type: QuestionComment
comment on: http://stackoverflow.com/q/48428916
type: Comment
score: 0

http://stackoverflow.com/comment/83691244
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48336473
score: 0
has text: Thanks for that, could you also provide a [mcve]? The error you're getting seems unusual to me.

http://stackoverflow.com/comment/83658917
comment on: http://stackoverflow.com/q/48336715
type: QuestionComment
type: Comment
has text: @BaileyParker, that is the correct way of doing it, ofc using just the flag is not atomic, so what you said is what should be done ;)
score: 0

http://stackoverflow.com/comment/83685861
type: QuestionComment
has text: In this example trying to pass something simple such as string from the command line.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48346025

http://stackoverflow.com/comment/83807837
has text: Thanks @juanpa.arrivillaga. Good point re: df.col1, which is yet another method of column selection. I've actually looked at that other question before, several times. It's great for explaining loc and iloc. However, this question is about the other method: "df['col1']". I'm just confused as to why there are two (or three) equivalent ways of doing what appears to be the same thing.
type: Comment
comment on: http://stackoverflow.com/q/48409128
score: 0
type: QuestionComment

http://stackoverflow.com/q/48423534
score: 4
accepted answer: http://stackoverflow.com/a/48424587
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48424587
tagged with: apache-spark
has title: PySpark DataFrame: Change cell value based on min/max condition in another column
answer count: 1
downvote count: 0
favorite count: 0
has body: I have the following pySpark dataframe: +------------------+------------------+--------------------+--------------+-------+ | col1| col2| col3| X| Y| +------------------+------------------+--------------------+--------------+-------+ |2.1729247374294496| 3.558069532647046| 6.607603368496324| 1| null| |0.2654841575294071|1.2633077949463256|0.023578679968183733| 0| null| |0.4253301781296708|3.4566490739823483| 0.11711202266039554| 3| null| | 2.608497168338446| 3.529397129549324| 0.373034222141551| 2| null| +------------------+------------------+--------------------+--------------+-------+ It is a rather simple operation and I can easily do it with pandas. However, I need to do it using only pySpark. I want to do the following (I`ll write in sort of pseudocode): In row where col3 == max(col3), change Y from null to 'K' In the remaining rows, in the row where col1 == max(col1), change Y from null to 'Z' In the remaining rows, in the row where col1 == min(col1), change Y from null to 'U' In the remaining row: change Y from null to 'I'. Therefore, the expected output is: +------------------+------------------+--------------------+--------------+-------+ | col1| col2| col3| X| Y| +------------------+------------------+--------------------+--------------+-------+ |2.1729247374294496| 3.558069532647046| 6.607603368496324| 1| K| |0.2654841575294071|1.2633077949463256|0.023578679968183733| 0| U| |0.4253301781296708|3.4566490739823483| 0.11711202266039554| 3| I| | 2.608497168338446| 3.529397129549324| 0.373034222141551| 2| Z| +------------------+------------------+--------------------+--------------+-------+ Having that done, I need to use this table as lookup for another table: +--------------------+--------+-----+------------------+--------------+------------+ | x1| x2| x3| x4| X| d| +--------------------+--------+-----+------------------+--------------+------------+ |0057f68a-6330-42a...| 2876| 30| 5.989999771118164| 0| 20171219| |05cc0191-4ee4-412...| 108381| 34|24.97999954…
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/48386066
has comment: http://stackoverflow.com/comment/83761382
has comment: http://stackoverflow.com/comment/83768606
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48385577
answers question: http://stackoverflow.com/q/48385577
has body: There are two directives to handle the problem you described: Iterate over all the rows of the table, using driver.find_elements_by_&lt;something&gt;(). I'd recommend using this with a static webpage. It's more natural, given the fact that you actually take advantage of Selenium's functions. Download the webpage's HTML code, parse and manipulate it "offline". This would work better when the page is constantly updating, and will guarantee you don't call stale elements in the page. However it'll force you to parse HTML code, which is never a fun thing to do. Choose what best for you, and then you can move forward with the more technical issues. Good luck! Edit: Note how the method is calling elements, hence you're not suppose to mention the element's index. So in your case you can use: row = driver.find_elements_by_xpath('/html/body/app-root/app-home/div/div/table/tbody/tr') # And not: row = driver.find_elements_by_xpath('/html/body/app-root/app-home/div/div/table/tbody/tr[number]') It'll return all the element that have the mentioned property (in this case, the given xpath).
type: Answer
has comment: http://stackoverflow.com/comment/83768845
has comment: http://stackoverflow.com/comment/83762185
has comment: http://stackoverflow.com/comment/83767167

http://stackoverflow.com/a/48399278
has body: I see a couple of problems here: 1.) do() is not preceded by def. 2.) expect should be except 3.) Your while loop is blocking the flow of your program. Instead you should use Tk().after(wait_time, method) With that being said, I'm assuming that you want to count up after the button is pressed. This starts counting from 0 after the button is clicked. When the button is clicked again, it stops printing count and resets it: from tkinter import * class App: def __init__(self): self.root = Tk() self.count = 0 self.do_count = False self.button = Button(self.root, text="Click me.", command=self.do) self.button.pack() self.root.mainloop() def do(self): self.do_count = not self.do_count if not self.do_count: self.count = 0 self.update() def update(self): if self.do_count: print(self.count) self.count += 1 self.root.after(1000, self.update) app = App()
downvote count: 0
answers question: http://stackoverflow.com/q/48398991
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48398991
has comment: http://stackoverflow.com/comment/83787795
has comment: http://stackoverflow.com/comment/83787063
has comment: http://stackoverflow.com/comment/83788961
type: Answer
has comment: http://stackoverflow.com/comment/83787185
has comment: http://stackoverflow.com/comment/83788715
has comment: http://stackoverflow.com/comment/83787274

http://stackoverflow.com/comment/83761686
type: Comment
type: QuestionComment
has text: @MarkRansom, appreciate your expert advise, would be great if you quote example when you have time.
comment on: http://stackoverflow.com/q/48386829
score: 0

http://stackoverflow.com/comment/83789934
type: Comment
has text: So this db lives as long as the app lives right? Do you intend to run migrations live? How does that work? How are you "hot-updating" your models?
type: QuestionComment
comment on: http://stackoverflow.com/q/48350091
score: 1

http://stackoverflow.com/comment/83811044
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48409315
type: Comment
has text: I was able to understand and tried to implemented the same in actual scenario. Its working fine, Thanks for your timely help!

http://stackoverflow.com/comment/83705445
type: Comment
has text: @abra interesting. Is that in use in America? Other than that, which I'm not familiar with, it should be possible to generate some rules to get at these numbers. Maybe there's another "MM" type I'm not familiar with...
score: 0
comment on: http://stackoverflow.com/q/48359255
type: QuestionComment

http://stackoverflow.com/comment/83924222
score: 0
type: AnswerComment
has text: I'm honored to be your 3000th. Will be your 4000th soon :)
comment on: http://stackoverflow.com/a/48451284
type: Comment

http://stackoverflow.com/q/48351231
score: 2
upvote count: 2
answer count: 1
tagged with: highcharts
downvote count: 0
tagged with: selenium
has body: I am testing a web application that uses highcharts. The selectors look like this, and the highchart number of the same chart is always different. For example: #highcharts-4 &gt;div:nth-child(1) &gt; span &gt; div &gt; span When there is only one chart on a page, I do the following, and it works perfectly: [id^='highcharts-'] &gt; div:nth-child(1) &gt; span &gt; div &gt; span It selects the first element where id begins with the string 'highcharts-', but how can I select the second and the third elements if let's say I have several charts present on the same page? For example, when there are three identical charts, the same element on each chart would have the following selectors with ID being different by two all the time: #highcharts-4 &gt;div:nth-child(1) &gt; span &gt; div &gt; span #highcharts-6 &gt;div:nth-child(1) &gt; span &gt; div &gt; span #highcharts-8 &gt;div:nth-child(1) &gt; span &gt; div &gt; span How can I grab the second and the third ones?
has comment: http://stackoverflow.com/comment/83694485
linked to: http://stackoverflow.com/q/41829000
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48351936
type: UnansweredQuestion
tagged with: python
has title: How to grab correct highchart number in selectors using Selenium Webdriver with Python with several charts on the page?
tagged with: selenium-webdriver

http://stackoverflow.com/q/48344963
has comment: http://stackoverflow.com/comment/83675623
answer count: 1
tagged with: maya
has body: I'm a bit new in scripting and french so exuse me if my explanations are not perfectly clear. I'm trying to make a script in Maya to manage easily the keys value for animation. So I created a window reproducing Maya's ChannelBox with another organisation. And now I'm trying to get the attribute values of a selected object inside the different textField (transX, Y, Z, rotX..). Here is what I have for now : transX_value = cmds.textField( w=100 , h=22 , tx= cmds.getAttr("%s.translateX" %selected) ) But when I select my cube for tests and launch my script this error appears: TypeError: Object [u'pCube1'].translateX is invalid So I tried something like this to see if the problem is coming from my formulation: transX_value = cmds.textField( w=100 , h=22 , tx= cmds.getAttr("pCube1.translateX") ) It worked and printed the good value inside the textField. How can I call the attribute of any selected object? I just discovered the %s command, so I'm sure that I'm not using it right.
has answer: http://stackoverflow.com/a/48404504
type: Question
type: UnansweredQuestion
has title: How to put the getAttr of any selected object inside a textField?
has comment: http://stackoverflow.com/comment/83675948
tagged with: python
score: 0

http://stackoverflow.com/comment/83727943
type: QuestionComment
comment on: http://stackoverflow.com/q/48369959
score: 0
type: Comment
has text: I didn't fire up tensorboard, but aren't you getting this error when you run the model? Does it matter whether I start tensorboard or not?

http://stackoverflow.com/comment/83660390
type: QuestionComment
has text: Yes, it is linked to Eclipse console in its debug mode, ie. not a serious problem, but first time I noticed this kind of "false error"
comment on: http://stackoverflow.com/q/48336521
score: 0
type: Comment

bipartite
type: Tag
tags question: http://stackoverflow.com/q/48420223
tag name: bipartite

http://stackoverflow.com/a/48452349
has comment: http://stackoverflow.com/comment/83919826
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48452276
has comment: http://stackoverflow.com/comment/83919812
has comment: http://stackoverflow.com/comment/83905919
score: 1
has body: You could use the following regex r'@@(.*?)@@' to capture everything inside of the key phrase you've chosen. Sample Output: &gt;&gt;&gt; import re &gt;&gt;&gt; f = lambda s: re.match(r'@@(.*?)@@', s).group(1) &gt;&gt;&gt; f("@@whatever@@") whatever &gt;&gt;&gt; f = lambda s: re.findall(r'@@(.*?)@@', s) &gt;&gt;&gt; f("a @@comment@@ does something like @@this@@ @@I can grab@@ everything between the @ symbols as separate inputs/calls.") ['comment', 'this', 'I can grab'] How does it work? (1) We state the string constant head and tail for the capture group 1 between the brackets (). Great, almost there! (2) We then match any character .*? with greedy search enforced so that we capture the whole string. Suggested Readings: Introduction to Regex in Python - Jee Gikera
downvote count: 0
has comment: http://stackoverflow.com/comment/83907806

http://stackoverflow.com/q/48405046
type: UnansweredQuestion
score: -2
has title: Python negative values in variables in multiplication
has answer: http://stackoverflow.com/a/48405197
has comment: http://stackoverflow.com/comment/83798637
tagged with: python
has body: I'm working on a program from Guttag's book, specifically altering the code from page 33 to work with negative numbers. The program is trying to find the square root of a number by using bisection search. My problem in short: &gt;&gt;&gt; print(ans) -12.0 &gt;&gt;&gt; print(ans**2) 144.0 &gt;&gt;&gt; print(-12**2) -144 &gt;&gt;&gt; -12.0**2 -144.0 Squaring a number (in this case -12) gives the correct answer that I expect when put in IDLE as a number. However, when it comes from a variable it suddenly turns positive. Any idea why this is happening and how to fix it? My problem in the longer version in case I have understood something else wrong too: x = float(input("Enter an integer, which square root you want to find: ")) epsilon = 0.01 numGuesses = 0 low = min(0.0, x) high = max(1.0, x) ans = (high + low)/2.0 while abs(ans**2 - x) &gt;= epsilon: print("low =", low, "high =", high, "ans =", ans) numGuesses += 1 if (ans**2) &lt; x: low = ans else: high = ans ans = (high + low)/2.0 print("Number of guesses =", numGuesses) print(ans, "is close to square root of", x) So where the while loop is deciding whether to assign the variable ans to high or low, it can't do so if working with a negative number from the beginning. If I, for example, run this program with x = -25, it will print out the following: Enter an integer, which square root you want to find: -25 low = -25.0 high = 1.0 ans = -12.0 low = -25.0 high = -12.0 ans = -18.5 Though ans (-12) squared should be -144, which would assign that to "low" rather than to high and making the program work. All advice appreciated.
tagged with: negative-number
downvote count: 3
answer count: 1
upvote count: 1
tagged with: variables
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83798698

http://stackoverflow.com/a/48349159
has comment: http://stackoverflow.com/comment/83685940
answers question: http://stackoverflow.com/q/48349088
type: Answer
has body: You should build the Counter only once. There's no guarantee that the two separate Counter objects will iterate over their contents in the same order (Plus for large inputs it's just inefficent). from collections import Counter elements = [1,6,9,4,1,2] for val, freq in sorted(Counter(elements).items()): print(val, ' : ', freq) Here sorted(Counter(elements).items()) is a sorted list containing tuples (val, freq): [(1, 2), (2, 1), (4, 1), (6, 1), (9, 1)]
upvote count: 2
has comment: http://stackoverflow.com/comment/83686078
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48349088
score: 2

http://stackoverflow.com/comment/83866101
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48435132
has text: On my system, this fix loops forever. A possible reason is that the turtle wanders a floating point plane so you don't always come back to *exactly* where you started. The fix likely involves using `brad.distance(start_position)` to see if you're close to your starting point or ignoring the starting point and using a fixed number of iterations.
type: AnswerComment

http://stackoverflow.com/comment/83667985
score: 0
type: AnswerComment
type: Comment
has text: Provided the full code, ensure you are on latest Selenium 3.8.1, ChromeDriver 2.35 and Chrome 64.x. In production use `ChromeOptions` class to maximize the view instead of `driver.maximize_window()`. I can share the `video` of the `execution` as well :)
comment on: http://stackoverflow.com/a/48339216

http://stackoverflow.com/a/52310025
answers question: http://stackoverflow.com/q/48475354
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: It's corresponding to the version of the pyspark, you must make sure this spark-submit --jars /Users/alexsun/spark-streaming-kafka-0-8-assembly_2.11-2.2.0.jar comsumer.pynter code here at the spark-streaming-kafka-0-8-assembly_2.11-2.2.0.jarenter code here must use the same pyspark version, in this case you're using pyspark=2.2.0 Another things, I encounter this problem too, but I encounter it when I try it with --packages maybe you can consider to use --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:{version of pyspark} instead of the --jar option

http://stackoverflow.com/comment/83895616
has text: have you tried root.update instead of Controller.update?
type: QuestionComment
comment on: http://stackoverflow.com/q/48450867
score: 0
type: Comment

http://stackoverflow.com/a/48333568
has comment: http://stackoverflow.com/comment/83653228
has body: Wow, that was tough :) Your string was in the wrong encoding and wrong character case, too. s = 'Carlos Lã³Pez' s.upper().encode('cp1252').decode().title() #'Carlos López' This code works in Python3, but not in Python2.
downvote count: 0
has comment: http://stackoverflow.com/comment/83652794
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83652819
accepted answer of: http://stackoverflow.com/q/48333346
answers question: http://stackoverflow.com/q/48333346
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83652953

http://stackoverflow.com/comment/83757595
score: 0
type: Comment
has text: waw, this is brilliant, thank you so much. I went for the `groupby` option and used `calendar.month_abbr[1:]` for the reindexing.
type: AnswerComment
comment on: http://stackoverflow.com/a/48384569

http://stackoverflow.com/comment/83838602
comment on: http://stackoverflow.com/q/48424465
type: QuestionComment
type: Comment
has text: os.system will always return 0 or 1 which is success or failure. It will useful only if you share your subprocess code also.
score: 2

heroku
tags question: http://stackoverflow.com/q/48464893
tags question: http://stackoverflow.com/q/48470962
tags question: http://stackoverflow.com/q/48341454
tags question: http://stackoverflow.com/q/48481221
tags question: http://stackoverflow.com/q/48367534
type: Tag
tags question: http://stackoverflow.com/q/48432386
tags question: http://stackoverflow.com/q/48436229
tags question: http://stackoverflow.com/q/48360763
tags question: http://stackoverflow.com/q/48455469
tags question: http://stackoverflow.com/q/48453543
tags question: http://stackoverflow.com/q/48402868
tags question: http://stackoverflow.com/q/48403728
tag name: heroku

http://stackoverflow.com/q/48481364
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83955836
has body: I am trying to run a function in parallel with the multiprocessing module. However there seems to be a deadlock. It seems to be due to the numpys: np.linalg.eig If I uncomment this function my code runs as expected. Does this occur due to some low level blas/laplack implementation? And is there a way to circumvent this? EDIT: Ok, this took a while. This is the minimum I could reduce my code, while keeping the problem. The model class makes a neural net. This NN is modified in a loop and then the parallel functions are called. The model isn't needed for the evaluation of these functions. However the code only finishes if I: reduce the models parameters (i.e. setting N_MAX = 100) don't call perturbate() don't call np.linal.eig() in build_single_bridge() ``` import numpy as np import torch import torch.nn as nn import torch.multiprocessing as mp class Model(torch.nn.Module): def __init__(self, n_in, n_out, hidden_layers=1, hidden_neurons=(64,)): """ Make a multi-layer-perceptron. :param n_in: (int) Input of the model. :param n_out: (int) Output of the model. :param hidden_layers: (int) No. of hidden layers. :param hidden_neurons: (tpl) Hidden neuron per hidden layer. """ super(Model, self).__init__() self.n_in = n_in self.n_out = n_out self.hidden_layers = hidden_layers self.hidden_neurons = hidden_neurons self.dense_in = nn.Linear(n_in, hidden_neurons[0]) self.hidden = [] for i in range(hidden_layers): exec(f"self.hidden_{i + 1} = nn.Linear(hidden_neurons[{i}], hidden_neurons[{i}])") exec(f"self.hidden.append(self.hidden_{i + 1})") self.dense_out = nn.Linear(hidden_neurons[-1], n_out) def es_params(self): """ The parameters that will be trained by ES. :return: (list) """ return [(k, v) for k, v in zip(self.state_dict().keys(), self.state_dict().values())] def perturbate(model, seed, sigma=0.05): """ Create two new models. And modify both in opposite direction. :param model: (Model) :param seed: (int) :param sigma: (flt) :return: [Model, Model] """ import copy new_mode…
tagged with: python
has comment: http://stackoverflow.com/comment/83955815
has title: Does numpy linalg.eig() block multiprocessing?
answer count: 0
score: 1

http://stackoverflow.com/q/48366776
has comment: http://stackoverflow.com/comment/83721880
tagged with: python
has comment: http://stackoverflow.com/comment/83721672
has body: I have finished application that was written in pyqt5 and compilled for windows(.exe file) with pyinstaller. Can i do the same for mac? I wanna get the same application but for mac. How can i do this? Thanks.
has title: Compiling application for mac with PyQt5
has comment: http://stackoverflow.com/comment/83721952
answer count: 0
downvote count: 0
tagged with: pyqt5
upvote count: 1
score: 1
tagged with: macos
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83722015
type: UnansweredQuestion

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/48409989

http://stackoverflow.com/a/48440145
type: Answer
answers question: http://stackoverflow.com/q/48439821
downvote count: 0
score: 7
upvote count: 7
has body: I fiddled with different packing options and discovered that using use_bin_type=True when packing the object solves the problem. import msgpack import numpy as np import msgpack_numpy as m m.patch() d = {'key': np.arange(5)} binary = msgpack.packb(d, use_bin_type=True) ret = msgpack.unpackb(binary, encoding='utf-8') ret.keys() &gt;&gt;&gt; dict_keys(['key']) ret['key'] &gt;&gt;&gt; array([0, 1, 2, 3, 4])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48439821
has comment: http://stackoverflow.com/comment/95864607

http://stackoverflow.com/comment/83829750
comment on: http://stackoverflow.com/q/48416570
type: Comment
type: QuestionComment
score: 0
has text: @VikasDamodar, it's not an inode number. Windows doesn't have inodes. It's just using the `st_ino` field as the closest analog. The file number should be stable for NTFS, and the same for all hard links, unless of course the file is completely deleted and replaced with a new file that has the same name. In FAT32, the file number is not stable since it's based on the first cluster number of the parent directory and byte offset of the file entry in the directory. For example, disk defragmenting programs can change FAT32 file numbers (the built-in defrag in Windows does not).

http://stackoverflow.com/a/48452477
has comment: http://stackoverflow.com/comment/83960783
type: Answer
answers question: http://stackoverflow.com/q/48450548
score: 0
has body: The first thing you have to do is install the asyncioreactor so that Twisted's native event loop works in parallel with the asyncio event loop. import twisted.internet.asyncioreactor twisted.internet.asyncioreactor.install() # add your imports + code here I'm not sure how ready the asyncioreactor is for production use, which may be the reason why there isn't much in terms of documentation. Resources https://gist.github.com/ldjebran/4febf298232a6fd86871df25d4dc00dd https://twistedmatrix.com/trac/ticket/9279 https://github.com/twisted/twisted/blob/ed075dad7339456c47fe43a51a12ee4b5910e0fd/src/twisted/internet/asyncioreactor.py

http://stackoverflow.com/comment/83737393
comment on: http://stackoverflow.com/q/48375171
score: 2
type: Comment
type: QuestionComment
has text: If you don't really need to coordinate between these, I'd just write a bash script: `for f in scripts/*.py; do python3 $f &; done`. No need to pull out `multiprocessing` if you don't need to (note that threading here would likely not help you because of the GIL, threading isn't good for computation bound things).

http://stackoverflow.com/q/48467859
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
tagged with: sql-server
tagged with: django-pyodbc-azure
score: 1
tagged with: python
has title: Introspection Bug - Looks for django_migrations at the Database Level Instead of Schema Level
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48468074
has body: Update 6: After discussing the issue on the IRC #django, I think django-pyodbc-azure is introspecting the database and looking for django_migrations at the database level, not the schema level. Therefore, it's finding it at the database level (from the original app), and therefore cannot create it. This might be a bug in the introspection of django-pyodbc-azure. Update 5: I have triple checked the schemas, and they are identical besides the name. I also updated django-pyodbc-azure and django to the latest 1.11 versions. I am at a loss. Update 4: I added a table called django_migrations to the new schema, and the error changed to invalid column name 'app'. So it seems like the tables are expected to be there initially. However, as mentioned in my original question, this is impossible and not how it has been done in the past. Update 3: No other schema works except the schema for the original project (which already has tables, including django_migrations). When that schema was created, it did not have any tables in it prior to running things like python manage.py runserver. UPDATE 2: The schema difference is the root issue. I changed the default schema of the original user to the new default schema I want the new app to use, and the same error occurred. Why is one schema working, and the other is not? UPDATE: It seems to be a problem with the different users. Both users have the same SQL Server permissions. Each user has a different default schema that was created for this purpose. The user for the original project has tables (including django_migrations) already in the database. Original: Python: 3.6.4 django: 1.11.9 django-pyodbc-azure: 1.11.9 I have a django project (myProject) with one django app (myApp). This project is run on a conda environment that includes django-pyodbc-azure to connect to SQL Server. The only changes made from the default setup are the following: Added myApp.apps.MyAppConfig to INSTALLED_APPS Changed DATABASES to this: DATABASES = { 'default'…
type: UnansweredQuestion

http://stackoverflow.com/comment/83704868
score: 0
type: Comment
type: QuestionComment
has text: A quick test confirms that this is the correct answer. I'm mystified *why* though.
comment on: http://stackoverflow.com/q/48358992

http://stackoverflow.com/comment/83826714
has text: how this perfect if this did not handle one of the problem you suggested - when `a = False` ???
comment on: http://stackoverflow.com/a/48418356
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48461426
downvote count: 0
answers question: http://stackoverflow.com/q/48461065
upvote count: 1
has body: You can us the StringIO module to write the content as a file object to the tar file. Sample: import tarfile import StringIO tar = tarfile.TarFile("archfile.tar.gz","w") with open("testfile.txt", 'rb') as f: s = StringIO.StringIO(f.read()) info = tarfile.TarInfo(name="testfile.txt") info.size = len(s.buf) tar.addfile(tarinfo=info, fileobj=s) tar.close()
type: Answer
score: 1

http://stackoverflow.com/comment/83928422
type: AnswerComment
score: 0
has text: Thanks for your answer. What I don't get is that the browser (in this case Firefox through Selenium) decodes everything effortlessly (JS, CSS and HTML are encoded this way). Could it be that Browsermob does something to the response before putting it in the HAR?
type: Comment
comment on: http://stackoverflow.com/a/48467472

http://stackoverflow.com/comment/83963472
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48485289
has text: post the code you want to adjust

http://stackoverflow.com/q/48469709
upvote count: 5
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/73527042
has title: How to read parquet file into pandas from Azure blob store
tagged with: azure
answer count: 1
tagged with: jupyter
has comment: http://stackoverflow.com/comment/89905744
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84234583
score: 5
tagged with: parquet
has body: I need to read and write parquet files from an Azure blob store within the context of a Jupyter notebook running Python 3 kernel. I see code for working strictly with parquet files and python and other code for grabbing/writing to an Azure blob store but nothing yet that put's it all together. Here is some sample code I'm playing with: from azure.storage.blob import BlockBlobService block_blob_service = BlockBlobService(account_name='testdata', account_key='key-here') block_blob_service.get_blob_to_text(container_name='mycontainer', blob_name='testdata.parquet') This last line with throw an encoding-related error. I've played with storefact but coming up short there. Thanks for any help
type: UnansweredQuestion

http://stackoverflow.com/a/48432158
upvote count: 1
score: 1
has body: From the flask documentation, If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None. The key there is that .json is the parsed JSON data, not the original string. If you want to write it to a file, you'll need to convert it back to a string it first, perhaps by using json.dumps(): with open("C:\\test.txt", 'w') as f: f.write(json.dumps(regions))
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48432016

http://stackoverflow.com/q/48429194
has title: Python scipy.optimize using fsolve
type: UnansweredQuestion
has body: I'm trying to find the solutions of 19 quotations and 19 unknown variables by python as follows: import numpy as np from scipy.optimize import fsolve def f(x) : y = np.zeros(np.size(x)) y[0] = -29.79 + 1.795*x[1] + 6.33*x[0] + -0.305*x[3] - 0.024*x[1]*x[3] + 0.222*x[0]*x[3] -2.063*x[4] + 0.122*x[1]*x[4] + 0.864*x[0]*x[4] + x[5] - x[6] y[1] = -23.269 + 1.795*x[0] + 4.547*x[2] - 0.342*x[1] - 0.024*x[0]*x[3] + 0.072*x[2]*x[3] - 0.052*x[1]*x[3] - 1.545*x[4] + 0.122*x[0]*x[4] + 0.367*x[2]*x[4] + 0.114*x[1]*x[4] + x[7] - x[8] y[2] = 0.587 + 4.547*x[1] + 0.046*x[3] + 0.072*x[1]*x[3] - 0.211*x[4] + 0.367*x[1]*x[4] + x[9] - x[10] y[3] = -1.657 - 0.305*x[0] - 0.230*x[1] + 0.046*x[2] - 0.024*x[0]*x[1] + 0.072*x[1]*x[2] + 0.111*x[0]**2.0 - 0.026*x[1]**2.0 + 0.78981 + x[11]**2.0 y[4] = -0.106 - 2.063*x[0] - 1.545*x[1] - 0.211*x[2] + 0.122*x[0]*x[1] + 0.367*x[1]*x[2] + 0.432*x[0]**2.0 + 0.057*x[1]**2.0 + 1.34744 + x[12]**2.0 y[5] = x[0] - 0.3 + x[13]**2.0 y[6] = -x[0] + 0.1 + x[14]**2.0 y[7] = x[1] - 80 + x[15]**2.0 y[8] = -x[1] + 30 + x[16]**2.0 y[9] = x[2] - 230 + x[17]**2.0 y[10] = -x[2] + 200 + x[18]**2.0 y[11] = 2*x[3]*x[11] y[12] = 2*x[4]*x[12] y[13] = 2*x[5]*x[13] y[14] = 2*x[6]*x[14] y[15] = 2*x[7]*x[15] y[16] = 2*x[8]*x[16] y[17] = 2*x[9]*x[17] y[18] = 2*x[10]*x[18] return y x0 = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) x =fsolve(f, x0) print ("x = ", x) print ("f(x) = ", f(x)) I have received the following results: C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\minpack.py:161: RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last five Jacobian evaluations. warnings.warn(msg, RuntimeWarning) x = [ 9.76123765e-01 5.63951267e-01 1.35631697e+02 -1.60706299e+00 -1.22811614e+01 -1.75589904e+01 -2.57132821e+01 1.89445174e-02 -2.20966436e+01 -6.49294303e-03 2.75617457e-01 3.02518539e-01 2.28775428e-09 9.62647461e-07 -9.50310077e-03 8.91207176e+00 -7.7204…
has answer: http://stackoverflow.com/a/48439448
tagged with: python
linked to: http://stackoverflow.com/q/46423069
score: -1
has comment: http://stackoverflow.com/comment/83850247
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83857099
downvote count: 1
tagged with: scipy
favorite count: 0
type: Question

http://stackoverflow.com/a/79178734
type: Answer
answers question: http://stackoverflow.com/q/48407790
downvote count: 0
has body: In Django 5.1 you can use the LoginRequiredMiddleware. From the docs (2024/11/11): Redirects all unauthenticated requests to a login page, except for views excluded with login_not_required(). The login page defaults to settings.LOGIN_URL, but can be customized. Enable this middleware by adding it to the MIDDLEWARE setting after AuthenticationMiddleware: MIDDLEWARE = [ "...", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.auth.middleware.LoginRequiredMiddleware", "...", ] Make a view public, allowing unauthenticated requests, with login_not_required(). For example: from django.contrib.auth.decorators import login_not_required @login_not_required def contact_us(request): ...
upvote count: 1
score: 1

http://stackoverflow.com/a/48478389
type: Answer
has comment: http://stackoverflow.com/comment/83971798
has comment: http://stackoverflow.com/comment/83967911
has body: You can do this using after to call a method periodically to update the GUI. time.sleep is not as easy to work with as it blocks main-thread which the GUI runs on. You could periodically replace the label's single character text with next letter in the string: try: import tkinter as tk except: import Tkinter as tk def update_label_letter(): global label label['text'] = label.string[label.current_char_index] label.current_char_index += 1 label.current_char_index %= len(label.string) label.after(250, update_label_letter) if __name__ == '__main__': root = tk.Tk() label = tk.Label(root) label.string = "Hello World!" label.current_char_index = 0 root.after(250, update_label_letter) label.pack() root.mainloop() One way would be to periodically append the letters of a single label. Vertical: try: import tkinter as tk except: import Tkinter as tk def update_label_letters(): global label _no_of_space_replacements = label['text'].count('\n') _last_char_index = len(label['text']) - _no_of_space_replacements if _last_char_index &lt; len(label.string): label['text'] += label.string[_last_char_index].replace(" ", " \n") else: label['text'] = "" label.after(250, update_label_letters) if __name__ == '__main__': root = tk.Tk() label = tk.Label(root, wraplength=1) label.string = "Hello World!" root.after(250, update_label_letters) label.pack() root.mainloop() Horizontal: try: import tkinter as tk except: import Tkinter as tk def update_label_letters(): global label _last_char_index = len(label['text']) if _last_char_index &lt; len(label.string): label['text'] += label.string[_last_char_index] else: label['text'] = "" label.after(250, update_label_letters) if __name__ == '__main__': root = tk.Tk() label = tk.Label(root) label.string = "Hello World!" root.after(250, update_label_letters) label.pack() root.mainloop() Another way would be to write the letters periodically to empty but shown letter_labels. Vertical: try: import tkinter as tk except: import Tkinter as tk def update_label_l…
has comment: http://stackoverflow.com/comment/83957738
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83958255
score: 1
answers question: http://stackoverflow.com/q/48476348

http://stackoverflow.com/comment/83768149
type: QuestionComment
comment on: http://stackoverflow.com/q/48345857
type: Comment
has text: https://discuss.pytorch.org/t/batch-norm-momentum-default-value/11955
score: 0

http://stackoverflow.com/comment/83700215
has text: There are at least two problems: the segmentation fault and the inefficient treatment of your `checkedFile`. Membership testing in a list is very inefficient. Replace it with `checkedFile = set()` (to make a set) and replace `checkedFile.append(fileHash)` with `checkedFile.add(fileHash)`. That way at least you won't be burning a lot of time just on the bookkeeping.
comment on: http://stackoverflow.com/q/48356592
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48366707
has comment: http://stackoverflow.com/comment/83720270
has comment: http://stackoverflow.com/comment/83720198
has answer: http://stackoverflow.com/a/48370394
score: 1
has body: I have developed a simple django project in which photos will be stored and displayed. The problem is whenever I redirect to a page, the page gets loaded but the url does not change in the address bar. So when i refresh the page again, I am getting errors. For example, I created an album. For that the url is: 127.0.0.1:8000/create_album/ Then it has to redirect to the albums page where all albums of user are stored. That url is 127.0.0.1:8000/10/ But i am not getting that url when i redirect to that page. The views.py: **def create_album(request): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] album.save() return render(request, 'photo/detail.html', {'album': album}) context = { "form": form, } return render(request, 'photo/create_album.html', context) def detail(request, album_id): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: user = request.user album = get_object_or_404(Album, pk=album_id) return render(request, 'photo/detail.html', {'album': album, 'user': user})** The page has to be redirected to photo/detail.html. It redirects to the required page but the url doesn't change. Please help me with this.
answer count: 1
has comment: http://stackoverflow.com/comment/83720281
downvote count: 0
upvote count: 1
favorite count: 0
has title: URL is not changing though page redirects in django
type: Question
has comment: http://stackoverflow.com/comment/83720346
tagged with: http-redirect
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48370394
type: AnsweredQuestion

http://stackoverflow.com/comment/84525435
type: QuestionComment
has text: add a code and data snippet (a cuople of strings) it is unclear what is going on. Btw, try to read this with spark directly from s3 path it can be a workaround, but bookmarks will not work in that case.
type: Comment
comment on: http://stackoverflow.com/q/48421974
score: 0

http://stackoverflow.com/q/48384322
has comment: http://stackoverflow.com/comment/83789168
has comment: http://stackoverflow.com/comment/83788722
tagged with: sympy
tagged with: symbolic-math
answer count: 1
downvote count: 0
has body: I would like SymPy to evaluate an expression like the following: How would I define the symbols and the expression so that SymPy could handle it nicely? I would like to keep N as just a symbol, i.e. not make an actual finite list of x's. I have tried various combinations of IndexedBase and Sum /Product, but didn't get it working right.
score: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48385223
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48385223
tagged with: python
has comment: http://stackoverflow.com/comment/83788307
has title: Sum of partial derivatives of a product over a symbolic number of variables
upvote count: 4

http://stackoverflow.com/a/48389429
score: 0
answers question: http://stackoverflow.com/q/48385721
type: Answer
has body: You should be able to achieve what you want using sklearn's KFold provided your data sets are of an equal size and you combine them in one set using pd.concat([df1, df2... df10], ignore_index = True). Shuffling is turned off by default and you can specify the number of folds using n_splits. The default for the latter is 3. Here is an example: import pandas as pd # Load a data frame df = pd.read_csv('C:\df.csv') print(df) # CROSS VALIDATION from sklearn.model_selection import KFold # Instantiate KFold kf= KFold(n_splits = 2) X = df.iloc[:, :-1] y = df.iloc[:, -1] # Show the indices of the train and test sets print('kf indices:') for train_index, test_index in kf.split(X): print(train_index, test_index) A B Name Surname Country Points 0 96 100 Roger Federer Switzerland 9600.0 1 80 100 Grigor Dimitrov Bulgaria 8000.0 2 72 100 Dominic Thiem Austria 7200.0 3 65 100 Pablo Busta Spain 6500.0 4 58 100 Stan Wawrinka Switzerland 5800.0 5 56 100 Jack Sock USA 5600.0 6 44 100 Marin Cilic Croatia 4400.0 7 43 100 David Goffin Belgium 4300.0 8 25 100 Alexander Zverev Germany 2500.0 9 14 100 Rafael Nadal Spain 1400.0 kf indices: [5 6 7 8 9] [0 1 2 3 4] [0 1 2 3 4] [5 6 7 8 9]

http://stackoverflow.com/q/48370562
upvote count: 9
tagged with: matplotlib
tagged with: python
has title: how to add regression line and regression line equation on graph
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48370770
downvote count: 0
has answer: http://stackoverflow.com/a/48370770
possible better answer: http://stackoverflow.com/a/48370732
favorite count: 0
score: 9
type: Question
has answer: http://stackoverflow.com/a/48370732
has body: I have the below input file and the code/script to add the regression line on the graph but the code gives this error:ValueError: x and y must have same first dimension. I couldn't figure out that error. How can I add the regression line and regression line equation on graph? Input file: -5.06 -4.27 -6.69 -7.28 -3.80 -3.51 -3.88 -2.79 -0.90 -0.81 2.10 2.59 -1.08 0.28 -5.00 -3.39 2.67 2.92 2.48 2.85 -5.10 -3.49 2.88 3.09 2.30 2.67 -3.47 -2.20 -0.90 -0.79 Script: #!/usr/bin/python import numpy as np import pylab as plot import matplotlib.pyplot as plt import numpy, scipy, pylab, random from matplotlib.ticker import MultipleLocator import matplotlib as mpl from matplotlib.ticker import MaxNLocator from scipy import stats with open("input.txt", "r") as f: x=[] y=[] for line in f: if not line.strip() or line.startswith('@') or line.startswith('#'): continue row = line.split() x.append(float(row[0])) y.append(float(row[1])) fig = plt.figure(figsize=(2.2,2.2), dpi=300) ax = plt.subplot(111) plt.xlim(4, -8) plt.ylim(4, -8) ax.xaxis.set_major_locator(MaxNLocator(6)) ax.yaxis.set_major_locator(MaxNLocator(6)) ax.xaxis.set_minor_locator(MultipleLocator(1)) ax.yaxis.set_minor_locator(MultipleLocator(1)) #regression part slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) line = slope*x+intercept plt.plot(x, line, 'r', label='fitted line') #end plt.scatter(x,y,color=['black','black','black','black','black','black','black','black','black','black','black','black','black','black','black'], s=3.5) plt.savefig("output.png", dpi=300)

http://stackoverflow.com/q/48372873
tagged with: python
has answer: http://stackoverflow.com/a/49953393
has comment: http://stackoverflow.com/comment/86746462
tagged with: tesseract
has comment: http://stackoverflow.com/comment/86748283
tagged with: python-tesseract
has title: No such file or directory: 'tesseract': 'tesseract' even though where to find tesseract is specified in pytesseract.py
has comment: http://stackoverflow.com/comment/83732870
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50709982
linked to: http://stackoverflow.com/q/49829307
has body: So I have been working on this problem for awhile and while others have had questions similar to this but nothing has worked for me: I am trying to use pytesseract for a project and I have it installed under User/Environments/testEnv/lib/python3.6/site-packages/pytesseract/ I have tesseract installed under usr/local/bin I have gone into Users/User/Environments/testEnv/lib/python3.6/site-packages/pytesseract/pytesseract.py and changed tesseract_cmd = 'tesseract' to tesseract_cmd = '/usr/local/bin/tesseract' as suggested here: OSError: [Errno 2] No such file or directory using pytesser This did not work. I tried to run this: try: import Image except ImportError: from PIL import Image import pytesseract img = Image.open('screenshot.png') img.load() i = pytesseract.image_to_string(img) print (i) and I get this: Traceback (most recent call last): File "/Users/User/Environments/testEnv/testTess.py", line 26, in &lt;module&gt; i = pytesseract.image_to_string(img) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 122, in image_to_string config=config) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytesseract/pytesseract.py", line 46, in run_tesseract proc = subprocess.Popen(command, stderr=subprocess.PIPE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'tesseract': 'tesseract' This is telling me that tesseract can't be found even though I specified in pytesseract.py. This befuddles me. Note: You can probably tell but I am using a virtualenv - could this be an issue due to the fact that tesseract is not in the environment but pytesseract is? I am u…
favorite count: 0
has answer: http://stackoverflow.com/a/66762188
score: 8
upvote count: 8
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83764887
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35609773

http://stackoverflow.com/comment/128689236
has text: It's sad that `pip install -q ...` (quiet flag) doesn't automatically disable this progress bar.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49931524
type: Comment

http://stackoverflow.com/comment/83891902
has text: So qs = [username10, lastname10, firstname10, email10]. I need to get result of qs = [[username1, lastname1, firstname1, email1], [username2, lastname2, firstname2, email2]...[username10, lastname10, firstname10, email10]]
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48439513
type: Comment

http://stackoverflow.com/a/48454948
type: AcceptedAnswer
score: 2
has body: You should assign it back s=pd.to_datetime(s,format='%H:%M:%S %p').dt.time s.max() Out[1294]: datetime.time(10, 9, 57) Data Input s=pd.Series(['10:09:57 AM','9:59:55 AM']) Update s=pd.Series(['10:09:57 AM','9:59:55 AM']) s=pd.to_datetime(s,format='%H:%M:%S %p') s-s.max() Out[1313]: 0 00:00:00 1 -1 days +23:49:58 dtype: timedelta64[ns]
accepted answer of: http://stackoverflow.com/q/48454918
type: Answer
has comment: http://stackoverflow.com/comment/83903718
has comment: http://stackoverflow.com/comment/83903879
has comment: http://stackoverflow.com/comment/83903909
has comment: http://stackoverflow.com/comment/83903930
answers question: http://stackoverflow.com/q/48454918
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83734774
score: 0
comment on: http://stackoverflow.com/q/48373228
type: QuestionComment
has text: Why did you choose that shape for G?
type: Comment

http://stackoverflow.com/comment/83972129
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48489587
type: Comment
has text: Indeed, this is what I was currently investigating. Actually, I can read correctly the compressed content if I do `gzip.open(output_path)`, but I cannot if I use 7-Zip or WinRar. I looked at the source code on Github, and I found [the behavior you are describing](https://github.com/python/cpython/blob/a4d00012565d716db6e6abe1b8f33eaaa4de416e/Lib/gzip.py#L230-L231). If I manually edit the module source code on my computer, and add `else: fname = b''` it seems to fix it. So I guess I will open an issue on the Python bug tracker and propose a patch to see what Python core developers think of it.

http://stackoverflow.com/comment/83846754
score: 0
type: Comment
type: AnswerComment
has text: @BryanOakley perhaps not in this specific context, but the OP claimed to be interested in constants in general.
comment on: http://stackoverflow.com/a/48427071

http://stackoverflow.com/comment/83824612
comment on: http://stackoverflow.com/a/48380400
type: Comment
score: 0
type: AnswerComment
has text: Try requesting it from support and give them the head ID of your robot. Carefully read the list of changes first, some modules are deprecate: http://doc.aldebaran.com/2-7/news/index.html

http://stackoverflow.com/comment/83889386
has text: Is it a dictionary or a List? coz dictionary is created like this a={"a_key":2,"akey1":4}
type: Comment
comment on: http://stackoverflow.com/a/48448400
score: 0
type: AnswerComment

http://stackoverflow.com/comment/115712124
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48476719
has text: Ok, with the last list cmd I do not get anything, but empty list instead of you who gets a `b`.

http://stackoverflow.com/comment/83998329
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48488611
has text: maybe you are talking about getting a clearer output with no loss or less loss, but i want to check what output my classifier gives at each layer on giving an image as input.
score: 0

http://stackoverflow.com/comment/121697560
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48371770
has text: @4756C Not really. It's from the question code and I just assumed them to be 3d cartesian coordinates (hence I used Boost Geomretry to do the closest point query and distance calculation).

http://stackoverflow.com/comment/83739989
has text: Assuming your keywords list is really a list of single words, remove the `.__str__()` as this is giving you the string representation of the list. And then the `in` statement searches for your words in that string instead of in the list.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48376460

http://stackoverflow.com/comment/83759887
comment on: http://stackoverflow.com/q/48385793
type: Comment
type: QuestionComment
has text: I have done that, as well as using other test cases I have found online. I cannot think of a very efficient way of generating test cases, testing them in both my [relatively] efficient method, and the inefficient method, or what kind of lists may lead to a weird "special case"
score: 0

http://stackoverflow.com/comment/83850772
score: 0
type: Comment
type: AnswerComment
has text: Could you provide an example of how to do this with curses?
comment on: http://stackoverflow.com/a/48429908

http://stackoverflow.com/q/48449136
type: AnsweredQuestion
answer count: 3
has title: Python password generator that creates a new password on user input
has comment: http://stackoverflow.com/comment/83891543
accepted answer: http://stackoverflow.com/a/48449333
possible better answer: http://stackoverflow.com/a/48449493
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48449333
has answer: http://stackoverflow.com/a/48449493
has answer: http://stackoverflow.com/a/52735778
upvote count: 0
has body: I'm just starting to learn Python and have started a small project for our Service Desk, a password generator. It works, however I'd like it to take a users input and create another password. I've done a lot of searching and have found tons of password generators, I've figured out how to repeat one password, but not how to generate a new passowrd on input. My code is below that will repeat a password on input. Any help would be greatly appreciated. import random alphabet = "abcdefghijklmnopqrstuvwxyz" pw_length = 6 mypw = "" for i in range(pw_length): next_index = random.randrange(len(alphabet)) mypw = mypw + alphabet[next_index] # replace 1 or 2 characters with a number for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2) mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:] # replace 1 or 2 letters with an uppercase letter for i in range(random.randrange(1,3)): replace_index = random.randrange(len(mypw)//2,len(mypw)) mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:] print("Your password is" + (mypw)) inp = input() while inp != "": print(mypw) inp = input()
has comment: http://stackoverflow.com/comment/83890911
tagged with: python
downvote count: 1
tagged with: passwords

http://stackoverflow.com/q/48354274
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to get the name from a list such as similar an input string?
tagged with: python
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has body: I have a list as follows [&lt;tf.Variable 'resnet_v1_101/conv1/weights:0' shape=(7, 7, 3, 64) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/conv1/BatchNorm/beta:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/conv1/BatchNorm/gamma:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/conv1/BatchNorm/moving_mean:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/conv1/BatchNorm/moving_variance:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/weights:0' shape=(1, 1, 64, 256) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/beta:0' shape=(256,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/gamma:0' shape=(256,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_mean:0' shape=(256,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm/moving_variance:0' shape=(256,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/weights:0' shape=(1, 1, 64, 64) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/beta:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/gamma:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_mean:0' shape=(64,) dtype=float32_ref&gt;, &lt;tf.Variable 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_variance:0' shape=(64,) dtype=float32_ref&gt;] I want to get the all name that store BatchNorm in the list and store in a new list without duplication. The name will be cut until the BatchNorm. For example Input 'resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm/moving_mean Output 'resnet_v1_101/bloc…

http://stackoverflow.com/comment/83906467
has text: DanielleM.: `You need to tell the green_foreground function to use the logger defined in first.py. How might you do that? ` — this is the question, that I asked :-) . Thanks.
comment on: http://stackoverflow.com/a/48448501
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84994625
comment on: http://stackoverflow.com/a/48479567
has text: try killing it from shell and start using shell
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83790767
score: 0
comment on: http://stackoverflow.com/q/48400514
type: Comment
type: QuestionComment
has text: Your regex works [like this](https://ideone.com/8555rZ). What are the expected matches? See also [this regex fiddle](https://regex101.com/r/EMaG1q/1).

http://stackoverflow.com/comment/83657399
type: Comment
comment on: http://stackoverflow.com/a/48336120
score: 0
type: AnswerComment
has text: Thnks for the info. Can you give me the correct syntax then?@Carl

http://stackoverflow.com/comment/83716092
type: AnswerComment
comment on: http://stackoverflow.com/a/48364502
score: 2
has text: I think normal distribution might be better, but I'm not specialized in this domain. You might find this paper https://arxiv.org/pdf/math-ph/0609050.pdf helpful, especially section 4, where this kind of issues are discussed in detail.
type: Comment

http://stackoverflow.com/comment/83823340
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48396601
has text: its is 1.0.12 .
type: Comment

return-value
tags question: http://stackoverflow.com/q/48399116
type: Tag
tag name: return-value

http://stackoverflow.com/comment/83934060
score: 2
type: Comment
type: AnswerComment
has text: You're right. The `np.arange` had a wrong range. Was obviously still thinking in integer indicies when I wrote this part, it did round up to the next second. Now it rounds only up to the next stepsize.
comment on: http://stackoverflow.com/a/48466007

http://stackoverflow.com/q/48484615
has comment: http://stackoverflow.com/comment/83962310
has comment: http://stackoverflow.com/comment/83964020
has body: I have 3 coulms, isTrade (indicating if a quote or a trade by 0/1), daetTime (time of the event), and tradeBid (how much volume traded. I have values and 0 which I can not make null as I am counting and aggregating it). I am trying to groupby only the trades (['isTrade'] == 1) and to display the sum (np.sum)but i also want to count the amount of them. Is there any way to use lambda with countif (lambda x: x.isnull().count() returns count of the 0 values as well)? I tried to use: groups = df[df['isTrade'] == 1].groupby('dateTime') grouped = (groups.agg({'tradeBid': [np.sum,lambda x: (x=='tradeBid').count()],})) but I get an error: raise TypeError("invalid type comparison") I tried with 'count' / 'nunique' but it counts the 0 as well and not what is &lt;>0 All the answers I found or here refer to the parent condition as I already do here with isTrade==1 Edited: The expected results will be per dateTime, sum of column tradeBi, count of values > 1 Added sample file of data: SecurityID,dateTime,ask1,ask1Volume,bid1,bid1Volume,ask2,ask2Volume,bid2,bid2Volume,ask3,ask3Volume,bid3,bid3Volume,tradePrice,tradeBid,isTrade 2318276,2017-11-20 08:00:09.052240,12869.0,1,12868.0,3,12870.0,19,12867.5,2,12872.5,2,12867.0,1,0.0,0,0 2318276,2017-11-20 08:00:09.052260,12869.0,1,12868.0,3,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12861.0,1,1 2318276,2017-11-20 08:00:09.052260,12869.0,1,12868.0,2,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052270,12869.0,1,12868.0,2,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,1 2318276,2017-11-20 08:00:09.052270,12869.0,1,12868.0,1,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052282,12869.0,1,12868.0,1,12870.0,19,12867.5,2,12872.5,2,12867.0,1,12868.0,1,1 2318276,2017-11-20 08:00:09.052282,12869.0,1,12867.5,2,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12868.0,1,0 2318276,2017-11-20 08:00:09.052291,12869.0,1,12867.5,2,12870.0,19,12867.0,1,12872.5,2,12865.5,1,12867.5,1,1 2318276,201…
score: 1
has comment: http://stackoverflow.com/comment/83963784
tagged with: python
has comment: http://stackoverflow.com/comment/83962449
has comment: http://stackoverflow.com/comment/83962069
has comment: http://stackoverflow.com/comment/83964003
has comment: http://stackoverflow.com/comment/83964063
type: Question
has comment: http://stackoverflow.com/comment/83962285
has comment: http://stackoverflow.com/comment/83963819
has comment: http://stackoverflow.com/comment/83962464
answer count: 0
downvote count: 0
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/83962523
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/12589481
has title: How to count if inside / under a groupby in python
linked to: http://stackoverflow.com/q/43321455
has comment: http://stackoverflow.com/comment/83962354
linked to: http://stackoverflow.com/q/40710811
has comment: http://stackoverflow.com/comment/83964262
duplicate of: http://stackoverflow.com/q/12589481
has comment: http://stackoverflow.com/comment/83962276
favorite count: 0
has comment: http://stackoverflow.com/comment/83964139
has comment: http://stackoverflow.com/comment/83962254

http://stackoverflow.com/q/48438158
answer count: 1
has comment: http://stackoverflow.com/comment/83879723
tagged with: apache-kafka
has comment: http://stackoverflow.com/comment/84132075
type: Question
has answer: http://stackoverflow.com/a/49019581
has title: Async not working when using pykafka and asyncio
tagged with: pykafka
has body: I try to call multiple pykafka consumer function using async. However, the first pykafka consumer function will block the other function from working. The QueueConsumer lib: import json from pykafka import KafkaClient import configparser import asyncio class QueueConsumer(object): def __init__(self): config = configparser.ConfigParser() config.read('config.ini') self.config = config async def test(self): defaultTopic = 'test' client = KafkaClient(hosts=self.config['kafka']['host']) topic = client.topics[defaultTopic.encode('utf-8')] consumer = topic.get_simple_consumer() # msg = next(consumer) for message in consumer: print(defaultTopic+' '+message.value.decode("utf-8")) async def coba(self): defaultTopic = 'coba' client = KafkaClient(hosts=self.config['kafka']['host']) topic = client.topics[defaultTopic.encode('utf-8')] consumer = topic.get_simple_consumer() # msg = next(consumer) for message in consumer: print(defaultTopic+' '+message.value.decode("utf-8")) Then I call those function using: import asyncio queueConsumer = QueueConsumer() loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather( queueConsumer.test(), queueConsumer.coba(), )) loop.close() The result will only return queue message from topic 'test' only. Edit: I try to add another function async def factorial(self, name, number): f = 1 for i in range(2, number+1): print("Task %s: Compute factorial(%s)..." % (name, i)) await asyncio.sleep(1) f *= i print("Task %s: factorial(%s) = %s" % (name, number, f)) And then called like: queueConsumer.test(), queueConsumer.coba(), queueConsumer.factorial('a',3), queueConsumer.factorial('b',5), queueConsumer.factorial('c',7), Some print from factorial function is executed. But when print from either test or coba is called, then it just stop the others.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83867420
score: 0
tagged with: asynchronous

http://stackoverflow.com/q/48357265
tagged with: python-2.7
tagged with: python-import
duplicate of: http://stackoverflow.com/q/12201928
has comment: http://stackoverflow.com/comment/83701360
has answer: http://stackoverflow.com/a/48358692
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83702474
has title: IOError: [Errno 2] No such file or directory: 'data.json'
has comment: http://stackoverflow.com/comment/83701171
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83701308
upvote count: 5
linked to: http://stackoverflow.com/q/12201928
tagged with: python
has body: Here is my code: import json from difflib import get_close_matches data = json.load(open("data.json")) # I get an error here def translate(w): w = w.lower() if w in data: return data[w] elif len(get_close_matches(w, data.keys())) &gt; 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: ") output = translate(word) if type(output) == list: for item in output: print(item) else: print(output) On this line: data = json.load(open("data.json")), I get the following error: IOError: [Errno 2] No such file or directory: 'data.json' How can I fix this error?
has comment: http://stackoverflow.com/comment/83702695
score: 4

http://stackoverflow.com/a/48448476
score: -1
has comment: http://stackoverflow.com/comment/83889468
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/83889508
answers question: http://stackoverflow.com/q/48448206
has body: OP takes a part of a Dictionary out of context which can be seen at timepoint 17:47min. a is declared as a = tf... etc and thus has content and context. [1,3] are list items. then a:[1,3] in dict: a = keyname. [1,3] = values try this: a = 'alot of words for a keyname' b = 17.47 my_dict = {a:["sing along song", "the voice of"], b:(12, 'candidates', None, "wins")} print my_dict.keys()
type: Answer

http://stackoverflow.com/a/48392881
has body: You need to do a check on pre_clean first before invoking a method on it if pre_clean is None or pre_clean.group('group1') is None: raise AttributeError this is self explanatory and you wont get the same error you encountered.
accepted answer of: http://stackoverflow.com/q/48392848
type: Answer
answers question: http://stackoverflow.com/q/48392848
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83773733

http://stackoverflow.com/comment/83789649
has text: What if you start your parent script with the same command line parameters instead of adding them to the import statement?
comment on: http://stackoverflow.com/q/48400740
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83790500
type: Comment
has text: Simplify! Show us just ONE output array that differs, with the code for just that one, and let's debug that. No need to show us 9 different arrays, some of which have no errors.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48399718

http://stackoverflow.com/comment/83685183
type: Comment
has text: Does `Decimal` use `math.fmod()`? They both have the same behaviour. [From the Python documentation](https://docs.python.org/3/library/math.html): "For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers."
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/48347516

http://stackoverflow.com/comment/83857544
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48433052
has text: Thanks for your reply, i'll check and let you know

http://stackoverflow.com/comment/83827134
comment on: http://stackoverflow.com/q/48395849
score: 0
type: Comment
type: QuestionComment
has text: Hello all, sorry for the delay, I've got it solved by using l = (a,b,c) l = np.transpose(l)

http://stackoverflow.com/q/48472227
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48472867
has answer: http://stackoverflow.com/a/48472293
answer count: 2
type: UnansweredQuestion
has title: How can one create a heatmap from a 2D scatterplot data in Python?
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/7778343
tagged with: heatmap
upvote count: 3
score: 3
linked to: http://stackoverflow.com/q/2369492
has body: How can one create a heatmap from a 2D scatterplot data in Python, where for each (x,y) point in the scatterplot one has a z value associated to it? The z value will be the value used to color the heatmap. For example, in R, I can use : # This example is from http://knowledge-forlife.com/r-creating-heatmap-scatterplot-data/ #I'm just setting the seed so you can see the same example on your computer set.seed(1) #Our X data x &lt;- runif(150) #Our Y data y &lt;- runif(150) #Our Z data z &lt;- c(rnorm(mean=1,100),rnorm(mean=20,50)) #Store the length of our data N &lt;- length(x) # View the scatterplot plot(x, y) #Here is the interpolation to give the heatmap effect. #Use xo and yo to set the output grid you want to use. #xo and yo are used to change the resolution of the interpolation #Here, I have included a somewhat standard protocol for these parameters s &lt;- interp(x,y,z,xo=seq(min(x),max(x),length=N), yo=seq(min(x),max(x),length=N),duplicate="mean") #Here's where the fun happens #Note you can add your typical plotting paramaters here, such as xlab or ylab image.plot(s,xlim=c(0,1),ylim=c(0,1),zlim=c(-2,25)) Scatterplot (each (x,y) point in this scatterplot one has a z value associated to it; the z values aren't visible in the scatterplot): Corresponding heatmap (the color represents the z values): Note that this question is different from Generate a heatmap in MatPlotLib using a scatter data set, where the color in the heatmap represents the density of the (x,y) points).

http://stackoverflow.com/comment/83895193
type: Comment
has text: @Behinoo I tried the code with your setup, and it worked perfectly for me. What is the output of the `df.columns` after the set_index+unstack operation?
type: AnswerComment
comment on: http://stackoverflow.com/a/48449277
score: 0

firefox
type: Tag
tags question: http://stackoverflow.com/q/48402238
tags question: http://stackoverflow.com/q/48469706
tag name: firefox
tags question: http://stackoverflow.com/q/48449611

http://stackoverflow.com/comment/83666091
has text: Your question explanation is ambiguous; please try to explain again what you need.
comment on: http://stackoverflow.com/q/48339961
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48361971
answers question: http://stackoverflow.com/q/48360836
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48360836
score: 0
type: Answer
has body: in python 3.x you can use: for k,v in std.items(): print(k,v['Uid']) in python 2.x: for k,v in std.iteritems(): print(k,v['Uid']) python 3.x code: std={} n=int(input("How many Entries you have to fill:")) for i in range (n): name=input("Enter name:") uid=input("ID:") age=input("Age:") print("----Marks----") math=input("Maths:") phy=input("Physics:") chem=input("Chemistry:") std[name]={'Uid':uid,'Age':age,'subject':{'math':math,'phy':phy,'chem':chem}} print('\n') for k,v in std.items(): print(k,v['Uid']) input and results for 2 different names will be: How many Entries you have to fill:2 Enter name:John ID:15895 Age:18 ----Marks---- Maths:15 Physics:15 Chemistry:15 Enter name:Beck ID:52256 Age:54 ----Marks---- Maths:52 Physics:52 Chemistry:21 John 15895 Beck 52256

http://stackoverflow.com/q/48379434
has title: Django error when trying to display the sign up form
answer count: 1
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/48379492
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48379492
has body: So I have this form which extends the User and I just want to allow the student to create and account and be able to select the courses from the course list.But when I try, I get the error: __init__() takes 1 positional argument but 2 were given I can't find any solution to this yet. I need some advice. These are my files: {% block body %} Sign up as a {{ user_type }} {% csrf_token %} {{ form }} Sign up {% endblock %} class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) path('signup/', views.StudentSignUpView, name='signup') class StudentSignUpForm(UserCreationForm): attended_courses = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.save() student = Student.objects.create(user=user) student.attended_courses.add(*self.cleaned_data.get('attended_courses')) return user class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index')
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/56850961
score: 0
has body: When working with time series related visualization you will need to set up a default DATETIME field from your database table before processing. To add main DATETIME column in superset you simply go to Sources-&gt;tables-&gt;edit table then set a default DATETIME column from your table. For this you do not need to write a SQL query. Just choose the columns you want the visualization on in the table while creating slice.You can also choose time column and grain of time.
answers question: http://stackoverflow.com/q/48434895
type: Answer

http://stackoverflow.com/comment/83932895
comment on: http://stackoverflow.com/q/48409610
score: 0
type: Comment
type: QuestionComment
has text: @Basj moved the answer here https://stackoverflow.com/questions/48459493/sqlite-concurrency-the-2nd-process-doesnt-get-db-updates/48469535, so the sqlite would be ok in the simplest scenario (1 writer and multiple readers). BUT if you need multiple writers with high concurrency of writes everything could be trickier

http://stackoverflow.com/comment/83763388
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48387480
score: 0
has text: haha)) True, he did it. But thank you @tom

http://stackoverflow.com/q/48385577
has answer: http://stackoverflow.com/a/48386066
tagged with: python
score: -1
tagged with: dictionary
has body: I am trying to download the table from this website https://coinmunity.co/ and then manipulate the data in an easy manner with Pandas. The problem is that the table is dynamically-generated so I cannot easily understand its structure or detect the "tr"s that I need to do a looping job. I tried with Requests and BeautifulSoup before and did not work, so someone here recommended Selenium, but did not tell me more. On Selenium I have already tried many things, including xpaths, css selectors,etc...but nothing worked. My idea is to extract the data in an orderly fashion for each row, but the row names seem to have a very strange name including "_ngcontent" and I can't make sense of it. This is my (non functioning) code: from selenium import webdriver import pandas as pd import time from bs4 import BeautifulSoup driver = webdriver.Firefox() driver.implicitly_wait(10) #driver.get("https://coinmunity.co/") url = 'file:///C:/Users/nique/PycharmProjects/untitled/test1.html' driver.get(url) html = driver.page_source.encode('utf-8') #html = driver.page_source.encode('utf-8') soup = BeautifulSoup(html, 'lxml') results = [] symbol_list = [] #items = driver.find_elements_by_class_name('coin-link') items = driver.find_elements_by_css_selector('.inner-container &gt; table:nth-child(1) &gt; tbody:nth-child(2) &gt; tr:nth-child(2)') #how_many = driver.find_elements_by_css_selector('html body app-root app-home div.outer-container div.inner-container table tbody tr') count = 1 for el in range(1,3): #row = driver.find_elements_by_css_selector('.inner-container &gt; table:nth-child(1) &gt; tbody:nth-child(2) &gt; tr:nth-child((count))') row = driver.find_elements_by_xpath('/html/body/app-root/app-home/div/div/table/tbody/tr[count]') symbol = row.find_element_by_class_name('coin-link') followers = driver.find_elements_by_class_name('stats')[0] changefollowers = driver.find_elements_by_class_name('stats')[1] # subscribers = driver.find_elements_by_class_name('stats')[2] # changesubscribers…
type: AnsweredQuestion
tagged with: html-table
answer count: 1
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83761129
accepted answer: http://stackoverflow.com/a/48386066
has comment: http://stackoverflow.com/comment/83761331
upvote count: 0
has title: Python / Selenium: how to iterate over tr in dynamically-generated table

http://stackoverflow.com/comment/83859965
has text: Should `****`, `******`, and `*******` be considered valid matches?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48433673
type: AnswerComment

http://stackoverflow.com/a/48485460
accepted answer of: http://stackoverflow.com/q/48485387
upvote count: 2
type: AcceptedAnswer
has body: The Beautiful Soup library is for parsing HTML and similar tagged languages, not JSON. If your requests return JSON responses then you should call the r.json() method. This will return a dictionary of the JSON structure. Suppose you used j = r.json() then you probably want j['item-html']['linkComplex-target'] or something similar. If you access the dictionary interactively you will probably find what you want.
downvote count: 0
answers question: http://stackoverflow.com/q/48485387
score: 2
type: Answer

http://stackoverflow.com/comment/83896159
has text: What does it change though?
type: QuestionComment
comment on: http://stackoverflow.com/q/48450648
type: Comment
score: 0

http://stackoverflow.com/q/48331905
type: AnsweredQuestion
score: 0
has body: I wrote the following code, import numpy as np from random import gauss from random import seed from pandas import Series import matplotlib.pyplot as plt import math ###variable declaration R=0.000001 #radiaus of particle beta=0.23 # shape factor Ad=9.2#characteristic nanoscale defect area gamma=4*10**-2 #surface tension tau=.0001 #line tension phi=-(math.pi/2)#spatial perturbation lamda=((Ad)/(2*3.14*R)) #averge contcat line position mu=0.001#viscosity of liquid lamda_m=10**-9# characteristic size of adsorption site KbT=(1.38**-24)*293 # boltzman constant with tempartaure nu=0.001#moleculer volume in liquid phase 1 khi=3 #scaling factor #deltaF=(beta*gamma*Ad)#surface energy perturbation deltaF=19*KbT # seed random number generator seed(0) # create white noise series series = [gauss(0.0, 1.0) for i in range(1)] series = Series(series) ######################################### Z=0.0000001 #particle position time=1 dt=1 for time in np.arange(1, 100, dt): #####simulation loop####### theta=np.arccos(-Z/R) #contact angle theta_e=((math.pi*110)/180) #equilibrium contact angle Z_e=-R*np.cos(theta_e)#equilibrium position of particle C=3.14*gamma*(R-Z_e) #additive constant Fsz= (gamma*math.pi*(Z-Z_e)**2)+(tau*2*math.pi*math.sqrt(R**2-Z**2))+C Fz=Fsz+(0.5*deltaF*np.sin((2*math.pi/lamda)*(Z-Z_e)-phi))#surface force #dFz=(((gamma*Ad)/2)*np.sin(2*math.pi/lamda))+((Z-Z_e)*(2*gamma*math.pi))-((tau*2*math.pi*Z)/(math.sqrt(R**2-Z**2))) dFz=(deltaF*np.sin(2*math.pi/lamda))+((Z-Z_e)*(2*gamma*math.pi))-((tau*2*math.pi*Z)/(math.sqrt(R**2-Z**2))) w_a=gamma*lamda_m**2*(1-np.cos(theta_e)) #work of adhesion epsilon_z=2*math.pi*R*np.sin(theta)*mu*(nu/(lamda_m**3))*np.exp(w_a/KbT)#transitional drag epsilon_s=khi*mu*((4*math.pi**2*R**2)/math.sqrt(Ad))*(1-(Z/R)**2) epsilon=epsilon_z+epsilon_s Ft=math.sqrt(2*KbT*epsilon)*series #thermal force v=(dFz+Ft)/epsilon ##new velocity Z=Z+v*dt #new position print('z=',Z) print('v=',v) print('Fz=',Fz) print('dFz',dFz) print('time',time) plt.plot(Z,time) …
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83682595
possible better answer: http://stackoverflow.com/a/48338427
accepted answer: http://stackoverflow.com/a/48349250
has answer: http://stackoverflow.com/a/48338427
has answer: http://stackoverflow.com/a/48349250
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/83658923
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has title: Plotting in matplotlib

http://stackoverflow.com/comment/83920816
has text: You're welcome. Feel free to accept it as an answer if it helped you.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48463864
type: AnswerComment

http://stackoverflow.com/a/48352249
has comment: http://stackoverflow.com/comment/83691382
has comment: http://stackoverflow.com/comment/83691421
has comment: http://stackoverflow.com/comment/83691644
answers question: http://stackoverflow.com/q/48352230
has comment: http://stackoverflow.com/comment/83691667
has comment: http://stackoverflow.com/comment/83691684
has comment: http://stackoverflow.com/comment/83691560
has comment: http://stackoverflow.com/comment/83691353
has comment: http://stackoverflow.com/comment/83691538
type: Answer
has comment: http://stackoverflow.com/comment/83691253
has comment: http://stackoverflow.com/comment/83691268
upvote count: 4
has comment: http://stackoverflow.com/comment/83691330
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48352230
score: 4
has body: You can importlib.import_module to import a given module using a string: Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). (emphasis mine) &gt;&gt;&gt; from importlib import import_module &gt;&gt;&gt; module_name = 're' &gt;&gt;&gt; module = import_module(module_name) &gt;&gt;&gt; module &lt;module 're' from 'C:\\Users\\Christian\\AppData\\Local\\Programs\\Python\\Python36\\lib\\re.py'&gt; &gt;&gt;&gt; Also, as a side recommendation, if you plan on getting command line arguments from the user, use a dedicated command line argument parsing library instead of using bare sys.argv. There are several good ones out there. In fact, Python has one in the standard library; argparse.
has comment: http://stackoverflow.com/comment/83691694

http://stackoverflow.com/comment/83826024
has text: Yes. A google doc is not the same as a .txt file with regard to 'mimeType'. The list of google file mimeType is found [here](https://developers.google.com/drive/v3/web/mime-types). That's 'application/vnd.google-apps.document'.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48399789
score: 0

http://stackoverflow.com/q/48427118
tagged with: addition
has comment: http://stackoverflow.com/comment/83849028
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48435148
tagged with: merge
tagged with: excel
has answer: http://stackoverflow.com/a/48435148
has comment: http://stackoverflow.com/comment/83848623
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
has body: I am relatively new to python, and have tried a couple different methods I have seen throughout this website, but nothing seems to work with what I need. I have an excel file, with two columns of information, and multiple sheets. I would like to add a column to each of these sheets with the header "System". Under the header I need to have all the cells in sheet 1 fill with "System 1" and for sheet 2 "System 2". Each sheet has a different amount of entries, and all are over 1000. At the end I want to merge all the sheets together making one master file, which I was able to figure out, but I can seem to add a column to the individual sheets. Below is the code I have so far: import pandas as pd import openpyxl import pprint fileName= input("Enter file name here (Case Sensitve) &gt; ") df = pd.read_excel(fileName +'.xlsx', sheetname=None, ignore_index=True) xl = pd.ExcelFile(fileName +'.xlsx') df1 = pd.read_excel(xl, 'System 1') df2 = pd.read_excel(xl, 'System 2') df3 = pd.read_excel(xl, 'System 3') df4 = pd.read_excel(xl, 'System 4') df5 = pd.read_excel(xl, 'System 5') The excel document looks along the lines of this: employee_number email 7000 test1@test.com 11552 test2@test.com 21356 test3@test.com 21365 test4@test.com 22022 test5@test.com 24280 test6@test.com 26279 test7@test.com there are 5 sheets within one document that resemble this.
downvote count: 0
linked to: http://stackoverflow.com/q/26521266
favorite count: 0
type: Question
has title: PYTHON: How to add a column to Excel Sheet with multiple Sheets
has comment: http://stackoverflow.com/comment/83846464

http://stackoverflow.com/a/48414364
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/48414202
has body: Assuming your endpoint in Project 2 returns a JSON response with the fields that you need: { "clinicId": 1, "time": some-time-string, "queueNo": 2 } You can retrieve the response after making the request by calling r.json(). Based on this you can then treat r.json() as a dictionary and create the instance using Appointment.objects.create(**r.json()). Here's how it might look. @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) if r.status_code == 200 and request.method == 'POST': # Convert response into dictionary and create Appointment data = r.json() # Construct required dictionary appointment_attrs = { "clinicId": data["some-key-that-points-to-clinicid"], "time": data["some-key-that-points-to-time"], "queueNo": data["some-key-that-points-to-queue-num"] } appointment = Appointment.objects.create(**appointment_attrs) # r.text, r.content, r.url, r.json return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.text) return HttpResponse('Could not save data')
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83825996
has comment: http://stackoverflow.com/comment/83819445
has comment: http://stackoverflow.com/comment/83818658
has comment: http://stackoverflow.com/comment/83819696
has comment: http://stackoverflow.com/comment/83827536
has comment: http://stackoverflow.com/comment/83825503
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83826389
accepted answer of: http://stackoverflow.com/q/48414202
has comment: http://stackoverflow.com/comment/83819656
has comment: http://stackoverflow.com/comment/83824552
has comment: http://stackoverflow.com/comment/83819457

http://stackoverflow.com/comment/83762123
has text: regarding your query on identical elements : think of 3 machines`(m1,m2,m3)` and each of these machines can be asigned to either of `(g1,g2,g3)` except for `m2` which can only be part of `g2` because of some characteristics : like `m1&m3` take `t1` sec to perform a job and hence are equivalent. But `m2` takes `t2` sec and hence belongs to different category. Therefore, `1st` and `3rd`position can be interchanged but not the second one. This is convincing ?
type: Comment
comment on: http://stackoverflow.com/a/48375446
type: AnswerComment
score: 0

http://stackoverflow.com/q/48480400
type: AnsweredQuestion
has title: Unable to resolve the Error "string index out of range"
has body: import sys x=input("Enter the string") `# getting the input#` i=1 ctr=0 print(len(x)) #printing the length of the whole line while(i&lt;=len(x)): if(x[i]=='a'): ctr=ctr+1 i=int(i+1) print(ctr)
accepted answer: http://stackoverflow.com/a/48480430
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/48480430
has comment: http://stackoverflow.com/comment/83953874
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/83956198
score: -3
tagged with: python

http://stackoverflow.com/q/48343698
tagged with: python
has title: Python/Tkinter Frontend Frame
has answer: http://stackoverflow.com/a/48344258
has comment: http://stackoverflow.com/comment/83674215
type: AnsweredQuestion
tagged with: responsive-design
tagged with: windows
answer count: 1
accepted answer: http://stackoverflow.com/a/48344258
has body: When opened normally Fullscreen i'm working on my first ever project, and i'm using python/tkinter. i've come up with this design(above) but i can't make it responsive. i want the bottom section to stay the same but i want to extend the top part through the bottom. from tkinter import * root = Tk() topFrame = Frame(root) topFrame.pack(side=TOP, fill=BOTH) scrollbar = Scrollbar(topFrame) scrollbar.pack(side=RIGHT, fill=Y) listbox = Listbox(topFrame) listbox.pack(fill=BOTH) for i in range(100): listbox.insert(END, i) #attaching list and scroll listbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview) #bottom frame bottomFrame = Frame(root) bottomFrame.pack(side=BOTTOM, fill=X) #bottom laft frame b_leftFrame = Frame(bottomFrame) b_leftFrame.pack(side=LEFT, fill=X) #defining label label1 = Label(b_leftFrame, text="Title") label1.grid(row=0, column=0, sticky=E) label2 = Label(b_leftFrame, text="Author") label2.grid(row=0, column=2, sticky=E) label3 = Label(b_leftFrame, text="Publisher") label3.grid(row=0, column=4, sticky=E) label4 = Label(b_leftFrame, text="Year") label4.grid(row=0, column=6, sticky=E) label5 = Label(b_leftFrame, text="Translator") label5.grid(row=0, column=8, sticky=E) #defining labels title_text =StringVar() entry1 = Entry(b_leftFrame, textvariable=title_text) entry1.grid(row=0, column=1) author_text =StringVar() entry2 = Entry(b_leftFrame, textvariable=author_text) entry2.grid(row=0, column=3) publisher_text =StringVar() entry3 = Entry(b_leftFrame, textvariable=publisher_text) entry3.grid(row=0, column=5) year_text =StringVar() entry4 = Entry(b_leftFrame, textvariable=year_text) entry4.grid(row=0, column=7) translator_text =StringVar() entry4 = Entry(b_leftFrame, textvariable=translator_text) entry4.grid(row=0, column=9) #bottom right b_rightFrame = Frame(bottomFrame) b_rightFrame.pack(side=RIGHT) #buttons b1=Button(b_rightFrame, text="View All", width=12) b1.grid(row=2, column=3) b1=Button(b_rightFrame, text="Search Entry"…
favorite count: 0
type: Question
tagged with: tkinter
upvote count: 0
score: -2
downvote count: 2
tagged with: desktop-application

http://stackoverflow.com/a/48356427
has body: Just added this and it solved the problem. author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING,)
has comment: http://stackoverflow.com/comment/83699426
answers question: http://stackoverflow.com/q/48356148
type: Answer
score: 0

http://stackoverflow.com/comment/83801547
type: Comment
type: QuestionComment
score: 0
has text: Looks like the application does not have access to the folder/log file. try chmod 777 to the folder and try again.
comment on: http://stackoverflow.com/q/48405330

http://stackoverflow.com/comment/83940865
comment on: http://stackoverflow.com/q/48473457
has text: I believe it is here: https://github.com/python/cpython/blob/9b6c60cbce4ac45e8ccd7934babff465e9769509/Objects/floatobject.c line 685. As you see, you cannot beat the C implementation with a Python implementation.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83881901
has text: The problem arises because the `converted_timezone_tweets.csv` file saves the timezone offset. When the date strings are parsed, the date strings are converted to datetimes in UTC but with the timezone offset taken into account. If you want to load a CSV without having to convert from UTC to US/Eastern, then I think you would need to drop the timezone offsets when saving converted_timezone_tweets.csv. I've modified the post above to show what I mean.
comment on: http://stackoverflow.com/a/48429323
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48483976
has body: If values search_row and search_column are unique in all data use np.where for positions and select by DataFrame.iloc: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,500,4], 'C':[7,8,9,4,2,3], 'D':[1,300,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}, index = [1] * 6) df.columns = ['A'] * 6 print (df) A A A A A A 1 a 4 7 1 5 a 1 b 5 8 300 3 a 1 c 4 9 5 6 a 1 d 5 4 7 9 b 1 e 500 2 1 2 b 1 f 4 3 0 4 b a = np.where(df == 500)[0] b = np.where(df == 300)[1] print (a) [4] print (b) [3] c = df.iloc[a[0],b[0]] print (c) 1 But if values should be duplicated is possible select only first occurence, because np.where return array(s) with length &gt; 1: a = np.where(df == 5)[0] b = np.where(df == 2)[1] print (a) [0 1 2 3] print (b) [2 4] c = df.iloc[a[0],b[0]] print (c) 7 a = np.where(df == 2)[0] b = np.where(df == 5)[1] print (a) [4 4] print (b) [4 1 3 1] c = df.iloc[a[0],b[0]] print (c) 2
answers question: http://stackoverflow.com/q/48483787
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48483787
has comment: http://stackoverflow.com/comment/83961510
type: Answer

http://stackoverflow.com/comment/83969035
comment on: http://stackoverflow.com/a/48487716
has text: What about the `total_fee = int ...` line? Try changing the division to `100.00`. If that doesn't work, hard-code this value `total_fee = 999` to make sure it's actually updating.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48369148
type: Question
possible better answer: http://stackoverflow.com/a/48370219
answer count: 2
has answer: http://stackoverflow.com/a/48370219
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50687351
tagged with: psycopg2
has body: I am uploading a csv file in Django : $('#import-file-dialog').on('change', function(event) { $('#upload-files').click(); }); Upload Bulk Upload Bulk Now i want to use psycopg2 copy_from for inserting csv data to Posgresql. In django model: fa = StringIO(import_data.read().decode("utf-8")) cursor.copy_from(fa , table_name, sep=',') commit_changes() csv file data is getting store with csv header name in my table. How i remove csv header so that i could store that data to table. Thanks for your precious time.
favorite count: 0
tagged with: postgresql
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/50687351
score: 1
has title: Django upload csv file copy to postgresql table

http://stackoverflow.com/comment/83896430
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48446259
has text: This should be the accepted answer. This behavior also explains why `[] = {}` and `() = {}` are possible, but not the reverse. The values in the dictionary can be iterated and assigned to the variables in the list/tuple, but it can't be reversed because the dictionary can't be used to hold a "list of variables" to assign to like the other two.

http://stackoverflow.com/comment/83773750
has text: Likely a mismatched parents or bracket. Try breaking up the expression into something more readable
score: 1
comment on: http://stackoverflow.com/q/48392926
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48426917
type: Answer
accepted answer of: http://stackoverflow.com/q/48424813
answers question: http://stackoverflow.com/q/48424813
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: The line ddf = ddf.set_index("sort_col").compute() is actually pulling the whole dataframe into memory and converting to pandas. You want to remove the .compute(), and apply whatever logic (filtering, groupby/aggregations, etc.) that you want first, before calling compute to produce a result that is small enough. The important thing to remember, is that the resultant output must be able to fit into memory, and each chunk that is being processed by each worker (plus overheads) also needs to be able to fit into memory.
score: 3

http://stackoverflow.com/q/48469254
has comment: http://stackoverflow.com/comment/83932395
possible better answer: http://stackoverflow.com/a/48469402
tagged with: alphabetical-sort
downvote count: 2
has comment: http://stackoverflow.com/comment/83934053
has comment: http://stackoverflow.com/comment/83932593
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48471372
has comment: http://stackoverflow.com/comment/83934756
has comment: http://stackoverflow.com/comment/83932275
has answer: http://stackoverflow.com/a/48469462
accepted answer: http://stackoverflow.com/a/48469462
has answer: http://stackoverflow.com/a/48469402
type: Question
has comment: http://stackoverflow.com/comment/83944760
tagged with: python
score: -1
tagged with: sorting
has answer: http://stackoverflow.com/a/48469367
has title: python sort strings with leading numbers alphabetically
answer count: 4
has comment: http://stackoverflow.com/comment/83932259
has comment: http://stackoverflow.com/comment/83932295
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83944698
has comment: http://stackoverflow.com/comment/83932322
has comment: http://stackoverflow.com/comment/83932464
has comment: http://stackoverflow.com/comment/83934866
upvote count: 1
has body: I have a list of filenames, each of them beginning with a leading number: 10_file 11_file 1_file 20_file 21_file 2_file ... I need to put it in this order: 1_file 10_file 11_file 2_file 21_file 22_file ... If they were just numbers as strings ('1') without the underscore I could sort them with sorted(). I have tried different sort-methods with different key-attributes, also the module "natsort", but with no result. Do I have to write my own algorithm for this? Maybe I could extract the leading numbers and use them for sorting? UPDATED desired list to correct listing

http://stackoverflow.com/comment/83668447
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48341053
score: 0
has text: @deceze is `which php` a command..? Where do I try it? Because in the Visual code it gives nothing.

http://stackoverflow.com/q/48391750
type: AnsweredQuestion
has title: Disable Python requests SSL validation for an imported module
answer count: 3
possible better answer: http://stackoverflow.com/a/71334348
accepted answer: http://stackoverflow.com/a/48391751
linked to: http://stackoverflow.com/q/15445981
downvote count: 0
has answer: http://stackoverflow.com/a/71334348
score: 23
has answer: http://stackoverflow.com/a/48391751
tagged with: python-requests
upvote count: 23
favorite count: 0
type: Question
has body: I'm running a Python script that uses the requests package for making web requests. However, the web requests go through a proxy with a self-signed cert. As such, requests raise the following Exception: requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)",) I know that SSL validation can be disabled in my own code by passing verify=False, e.g.: requests.get("https://www.google.com", verify=False). I also know that if I had the certificate bundle, I could set the REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE environment variables to point to those files. However, I do not have the certificate bundle available. How can I disable SSL validation for external modules without editing their code?
tagged with: ssl
tagged with: python
has answer: http://stackoverflow.com/a/77417373

http://stackoverflow.com/q/48405976
possible better answer: http://stackoverflow.com/a/48406003
score: 7
has body: I have a pandas dataframe in the following format: user percent x 0.2 x 0.5 x 0.8 y 0.1 y 0.6 y 0.2 y 0.6 I am trying to multiply the percents in the rows for each user. In the example, the result for x will be 0.2*0.5*0.8 = 0.08 The dataframe should therefore look like that: user result x 0.08 y 0.0072 How to get my expected output?
tagged with: python
has answer: http://stackoverflow.com/a/48406003
accepted answer: http://stackoverflow.com/a/48406004
has comment: http://stackoverflow.com/comment/83800730
type: AnsweredQuestion
answer count: 2
has title: How to multiply rows of one column after groupby in pandas?
tagged with: pandas
downvote count: 0
upvote count: 7
linked to: http://stackoverflow.com/q/42290729
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48406004

v8
tags question: http://stackoverflow.com/q/48462767
type: Tag
tag name: v8

http://stackoverflow.com/comment/83827303
has text: Well I'm glad you got to the bottom of it, dynamic imports can be really powerful. Enjoy!
type: AnswerComment
comment on: http://stackoverflow.com/a/48411808
score: 0
type: Comment

http://stackoverflow.com/comment/83681911
type: AnswerComment
score: 0
has text: How else would you use modulus?
type: Comment
comment on: http://stackoverflow.com/a/48347037

http://stackoverflow.com/q/48385273
has title: 3D biplot in Plotly in Python
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/43164909
accepted answer: http://stackoverflow.com/a/48396331
tagged with: data-visualization
tagged with: python
has body: I want to plot something like a biplot in python Plotly ,but using 3 principal components so as to make a 3d plot. How do I go about plotting the direction vectors(the red lines) of principal components in plotly python? There is exactly the same question , but for R, here. I am not able to translate the code perfectly.
upvote count: 2
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/44393823
has answer: http://stackoverflow.com/a/48396331
tagged with: pca
downvote count: 0
tagged with: plotly
answer count: 1

http://stackoverflow.com/q/48374357
upvote count: 3
downvote count: 0
tagged with: python-docx
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/docx
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57262229
tagged with: python
has title: How to add hyperlink to an image in python-docx
score: 3
answer count: 2
has body: I added an image using python docx. Now, I want to add a hyper-link. How to do that? import io import urllib from docx import Document from docx.shared import Inches document = Document() p = document.add_paragraph() r = p.add_run() url = r'http://www.example.com/a.jpg' io_url = io.BytesIO(urllib.request.urlopen(url).read()) r.add_picture(io_url) #TODO: add a hyperlink 'http://mywebsite.com' to r document.save('example.docx') Thank you very much.
has answer: http://stackoverflow.com/a/48374468

pca
tag name: pca
tags question: http://stackoverflow.com/q/48422569
tags question: http://stackoverflow.com/q/48402337
tags question: http://stackoverflow.com/q/48385273
type: Tag

http://stackoverflow.com/q/48401413
answer count: 2
has comment: http://stackoverflow.com/comment/83790796
possible better answer: http://stackoverflow.com/a/48401808
has answer: http://stackoverflow.com/a/48401808
accepted answer: http://stackoverflow.com/a/48401713
upvote count: 1
has answer: http://stackoverflow.com/a/48401713
downvote count: 1
type: AnsweredQuestion
has body: I am reading a text file and passing it to the API, but then I am getting the result only for the first line in the file, the subsequent lines are not being read. code below : filename = 'c:\myfile.txt' with open(filename) as f: plain_text = f.readline() response = client_comprehend.detect_entities( Text=plain_text, LanguageCode='en' ) entites = list(set([x['Type'] for x in response['Entities']])) print response print entites
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83790908
has title: using readline() in python to read a txt file but the second line is not read in aws comprehend api
favorite count: 0
type: Question

http://stackoverflow.com/comment/83794597
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48403142
type: Comment
has text: Thank you Coldspeed! Your answer works perfectly too! Now I am stuck having to choose between yours and jezraels answer as the accepted one as they both work perfectly. I guess yours is shorter!

http://stackoverflow.com/a/48448370
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48448288
type: Answer
has body: You can open the file and read each line, splitting at the space present. To be able to access any line and thus any letter, it may be best to use a dictionary: with open('filename.txt') as f: f = [i.strip('\n').split() for i in f] final_data = {a:list(b) for a, b in f} Output: {'JD830': ['B', 'D', 'D', 'C', 'D', 'B', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'D'], 'JC124': ['D', 'A', 'C', 'B', 'D', 'B', 'B', 'A', 'C', 'B', 'D', 'C', 'D', 'C'], 'JB651': ['A', 'C', 'D', 'C', 'C', 'A', 'D', 'B', 'C', 'A', 'D', 'C', 'D', 'A'], 'JB831': ['A', 'C', 'A', 'C', 'C', 'B', 'B', 'B', 'B', 'B', 'D', 'D', 'A', 'C'], 'JD329': ['B', 'A', 'A', 'C', 'D', 'B', 'A', 'B', 'C', 'C', 'D', 'D', 'A', 'B'], 'JI428': ['D', 'C', 'B', 'C', 'C', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'A']} You can access the rows by passing a key from the first column: print(final_data['JD830']) Output: ['B', 'D', 'D', 'C', 'D', 'B', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'D']

http://stackoverflow.com/q/48459191
has title: What is the best data structure for one to many relation on Django?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48459469
has body: For instance, let's suppose we have a webapp with Pizza and Toppings. One pizza can have many toppings but a topping cannot have many pizzas, which seems logical so far. I'm using a structure like this one below but I am not sure wether I should use ManyToMany Field or ForeignKey since OneToMany doesn't exist on Django. class Pizza(models.Model): created_at = models.DateTimeField(auto_now_add=True) order_id = models.CharField(max_length=255) def __str__(self): return self.order_id class Topping(models.Model): created_at = models.DateTimeField(auto_now_add=True) custom_topping_name = models.CharField(max_length=255) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) #if a pizza is deleted, delete its toppings. def __str__(self): return self.topping_name If I'm doing this right, should I access a pizza and all its toppings like this ? pizzas = Pizza.topping_set.filter(order_id=my_order_id) Is there a better way or is it optimal to keep it like this?
tagged with: django
tagged with: python
tagged with: data-structures
possible better answer: http://stackoverflow.com/a/48459469
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48459262
score: 0
has answer: http://stackoverflow.com/a/48459262

http://stackoverflow.com/q/48487876
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48489802
upvote count: 3
downvote count: 0
has body: I'm trying to scrape information on greyhound races. For example, I want to scrape http://www.gbgb.org.uk/RaceCard.aspx?dogName=Hardwick%20Serena. This page shows all results for the dog Hardwick Serena, but it is split over several pages. Inspecting the page, it shows under the 'next page' button: &lt;input type="submit" name="ctl00$ctl00$mainContent$cmscontent$DogRaceCard$lvDogRaceCard$ctl00$ctl03$ctl01$ctl12" value=" " title="Next Page" class="rgPageNext"&gt;. I was hoping for a HTML link, that I could use for the next iteration of the scrape, but no luck. Further inspection, by looking at network traffic, shows that the browser send a horribly long (hashed?) string for __VIEWSTATE, among others. Likely to protect the database? I'm looking for a way to scrape all pages of one dog, either by iterating over all pages, or by increasing the page length to show 100+ lines on page 1. The underlying database is .aspx. I'm using Python 3.5 and BeautifulSoup. current code: import requests from bs4 import BeautifulSoup url = 'http://www.gbgb.org.uk/RaceCard.aspx?dogName=Hardwick%20Serena' with requests.session() as s: s.headers['user-agent'] = 'Mozilla/5.0' r = s.get(url) soup = BeautifulSoup(r.content, 'html5lib') target = 'ctl00$ctl00$mainContent$cmscontent$DogRaceCard$btnFilter_input' data = { tag['name']: tag['value'] for tag in soup.select('input[name^=ctl00]') if tag.get('value') } state = { tag['name']: tag['value'] for tag in soup.select('input[name^=__]') } data.update(state) numberpages = int(str(soup.find('div', 'rgWrap rgInfoPart')).split(' ')[-2].split('&gt;')[1].split('&lt;')[0]) # for page in range(last_page + 1): for page in range(numberpages): data['__EVENTTARGET'] = target.format(page) #data['__VIEWSTATE'] = target.format(page) print(10) r = s.post(url, data=data) soup = BeautifulSoup(r.content, 'html5lib') tables = soup.findChildren('table') my_table = tables[9] rows = my_table.findChildren(['th', 'tr']) tabel = [[]] for i in range(len(rows)): cells = ro…
has comment: http://stackoverflow.com/comment/83969265
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Scraping and parsing multi-page (aspx) table
answer count: 1
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/83969239
has answer: http://stackoverflow.com/a/48489802

http://stackoverflow.com/q/48366592
type: Question
tagged with: anaconda
tagged with: python
has comment: http://stackoverflow.com/comment/83929643
answer count: 0
has body: I'm trying to retrain the last layer of inception model to recognize my own classes which are images of ornaments form two different styles. I'm getting high accuracy results during training, high validation value, and low cross entropy. However, the final accuracy is: Final test accuracy = 100.0% INFO:tensorflow:Froze 2 variables. INFO:tensorflow:Froze 2 variables. Converted 2 variables to const ops. I used the arguments: python retrain_new.py --bottleneck_dir= --how_many_training_steps 2000 --model_dir= --output_graph= --image_dir= --summaries_dir= --output_labels= The problem is after training is completed when I run the labeling script on an image file to test, I get predictions results using the labels from flowers tutorial and not my new labels (Islamic, baroque) which are included in a generated labels file during the process. The question is what is wrong with my training process? and how I can extract my labels form graph on tensorboard ?
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83884452
has title: error image labeling after training
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83760218

http://stackoverflow.com/a/48379664
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48367292
has comment: http://stackoverflow.com/comment/84063633
has body: The content will be displayed after the users scroll down. So you have to use JS Executor to scroll down. See my code below. driver.get('http://tieba.baidu.com/p/5513911529') SCROLL_PAUSE_TIME = 0.5 SCROLL_LENGTH = 200 page_height = int(driver.execute_script("return document.body.scrollHeight")) scrollPosition = 0 while scrollPosition &lt; page_height: scrollPosition = scrollPosition + SCROLL_LENGTH driver.execute_script("window.scrollTo(0, " + str(scrollPosition) + ");") time.sleep(SCROLL_PAUSE_TIME) time.sleep(5) print(driver.page_source)
answers question: http://stackoverflow.com/q/48367292
has comment: http://stackoverflow.com/comment/84245431
has comment: http://stackoverflow.com/comment/83821947
type: Answer
has comment: http://stackoverflow.com/comment/83820811
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/83718101
type: Comment
type: QuestionComment
has text: @DanielRoseman I added the perimeter, because I wanted only user from those 3 particular user to be able to be assign as project manager
comment on: http://stackoverflow.com/q/48364817
score: 0

http://stackoverflow.com/q/48457087
tagged with: python
tagged with: stride
has body: I wrote (with a little help from SO) a function to extract sliding windows with overlap L from a serie a, filling with fillval either on the right or left when L/(L-overlap) is not integer,using numpy strides: def strided_axis0_overlap(a, fillval, L,overlap,pad='left'): # a is 1D array assert(overlap&lt;L) if pad=='left': a_ext = np.concatenate(( np.full(L-1,fillval) ,a)) elif pad=='right': a_ext = np.concatenate((a,np.full(L-1,fillval))) n = a_ext.strides[0] strided = np.lib.stride_tricks.as_strided if pad=='left': return strided(a_ext, shape=(a.shape[0],L), strides=(n,n))[[np.arange(0,len(a),L-overlap)],:] elif pad=='right': return strided(a_ext, shape=(a.shape[0],L), strides=(n,n))[[np.arange(0,len(a),L-overlap)],:] It works fine, beside that for the padding. If I do v=np.array(range(182)).T strided_axis0_overlap(v,np.nan,5*6,0,pad='right') I get the following which is expected: array([[[ 0., 1., 2., ..., 27., 28., 29.], [ 30., 31., 32., ..., 57., 58., 59.], [ 60., 61., 62., ..., 87., 88., 89.], ..., [ 120., 121., 122., ..., 147., 148., 149.], [ 150., 151., 152., ..., 177., 178., 179.], [ 180., 181., nan, ..., nan, nan, nan]]]) However, if I pad on the left array([[[ nan, nan, nan, ..., nan, nan, 0.], [ 1., 2., 3., ..., 28., 29., 30.], [ 31., 32., 33., ..., 58., 59., 60.], ..., [ 91., 92., 93., ..., 118., 119., 120.], [ 121., 122., 123., ..., 148., 149., 150.], [ 151., 152., 153., ..., 178., 179., 180.]]]) whereas I wanted the last window finishing with 182, and the first being like array([[[ nan, nan, nan, ..., nan, 0, 1.],
type: AnsweredQuestion
score: 0
tagged with: sliding-window
answer count: 1
accepted answer: http://stackoverflow.com/a/48457600
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48457600
has title: padding numpy strides on left and right side

http://stackoverflow.com/comment/83837771
type: AnswerComment
has text: Great to hear ;) If you don't mind, and the problem is solved, please mark the question as answered :)
comment on: http://stackoverflow.com/a/48422911
type: Comment
score: 0

http://stackoverflow.com/q/48349169
has body: I'm aware of how to create a basic Tkinter menu bar, but I'm not sure how to implement it such that the menu appears on every frame of a multi-frame GUI. I will be using the menu bar to switch between frames. Therefore, I need to run the controller.show_frame command within the menu commands. I am currently using buttons to do this. I'm unable to find a way to do this, as (as far as I am aware) the menu must be created in the frame class rather than the tk.Tk class, in order to allow me to run the function. Here is the code: """ Messing about with tkinter """ import tkinter as tk LARGE_FONT = ("Verdana", 12) class Window(tk.Tk): """ Main class """ def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for frame in (Main, Checker): current_frame = frame(container, self) self.frames[frame] = current_frame current_frame.grid(row=0, column=0, sticky="nsew") self.show_frame(Main) def show_frame(self, cont): """ Raises a particular frame, bringing it into view """ frame = self.frames[cont] frame.tkraise() def qprint(quick_print): """ Function to print a string """ print(quick_print) class Main(tk.Frame): """ Main frame of program """ def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Main Menu", font=LARGE_FONT) label.pack(pady=10, padx=10) class Checker(tk.Frame): """ Password Strength Checker """ def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Password Checker", font=LARGE_FONT) label.pack(pady=10, padx=10) APP = Window() APP.geometry("350x200") APP.mainloop()
has answer: http://stackoverflow.com/a/48349550
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/79535780
accepted answer: http://stackoverflow.com/a/48349254
has answer: http://stackoverflow.com/a/48349254
tagged with: python
has title: How to create a menu on every frame of a Tkinter application
type: Question
has comment: http://stackoverflow.com/comment/83684990
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/83685192
possible better answer: http://stackoverflow.com/a/48349550

http://stackoverflow.com/comment/83944881
has text: what am I doing wrong?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48426093

http://stackoverflow.com/comment/83945298
comment on: http://stackoverflow.com/q/48475960
type: QuestionComment
score: 0
type: Comment
has text: Related: https://stackoverflow.com/questions/38539993/named-colors-in-tkinter

http://stackoverflow.com/a/54161768
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/48399871
has body: Saving into s3 buckets can be also done with upload_file with an existing .csv file: import boto3 s3 = boto3.resource('s3') bucket = 'bucket_name' filename = 'file_name.csv' s3.meta.client.upload_file(Filename = filename, Bucket= bucket, Key = filename)
downvote count: 0
has comment: http://stackoverflow.com/comment/109321634
has comment: http://stackoverflow.com/comment/109424115
score: 9

http://stackoverflow.com/comment/83833216
has text: Looks like the error is in your views.py
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48421885

http://stackoverflow.com/comment/83772320
comment on: http://stackoverflow.com/q/48391959
score: 0
has text: I tried -l before the library and it still isn't working, is there a reference to the flags anywhere? maybe I've got the wrong flag
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48436434
has comment: http://stackoverflow.com/comment/83864526
tagged with: python
has title: Activate Virtual Enviroment using Python Code
type: Question
upvote count: 0
has body: I m using Windows 7, I wanted a way where I could run my python file and it would execute my virtual environment. I have read the following commands activate_this_file = "/path/to/virtualenv/bin/activate_this.py" execfile(activate_this_file, dict(__file__=activate_this_file)) I need to know what is /path/to/virtualenv/bin/ and what is activate_this.py? Anyone know better solution for this?
downvote count: 2
has comment: http://stackoverflow.com/comment/83865210
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48456955
has comment: http://stackoverflow.com/comment/83865992
answer count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/83864389
tagged with: virtualenvwrapper
favorite count: 0
score: -2

http://stackoverflow.com/a/48466848
has comment: http://stackoverflow.com/comment/83927176
has comment: http://stackoverflow.com/comment/83927503
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83927133
answers question: http://stackoverflow.com/q/48466725
has body: {% if request.user.is_authenticated %} Welcome, {{ request.user.<name_of_one_to_one_model_in_lower_case>.surname }}. Thanks for logging in. {% else %} Welcome, new user. Please log in. {% endif %}
type: Answer
accepted answer of: http://stackoverflow.com/q/48466725

http://stackoverflow.com/comment/83903388
type: AnswerComment
comment on: http://stackoverflow.com/a/48455137
has text: Wow! This appears to be doing it. Do you mind explaining the `valLeft = length` portion? I only ask because I would've thought that would be overwriting my existing length parameter... but I must be wrong on that. Thanks so much for your time already.
score: 0
type: Comment

http://stackoverflow.com/comment/83784553
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48397873
type: AnswerComment
has text: sure, this is right way for implementing custom tags and filter in Django.

http://stackoverflow.com/q/48410288
tagged with: mechanize
tagged with: python
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48412604
has body: I'm writing a Python app that will interact with certain websites. I need to select the 1st input box in the website, how do I do this without knowing the name of said input box? I currently have br = mechanize.Browser() br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open("http://localhost") br.select_form(nr=0) # ??? br.method = "GET" response = br.submit() print response But I'm stuck on what to do next? I've looked on various webpages but none seem to answer my question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48410493
has title: Select first input box Mechanize
score: 0

http://stackoverflow.com/comment/83669015
has text: Nice catch @brunodesthuilliers, but the thing is: a) I'm not always working with requests(I used it here for simplicity) b) Some of the urls have a lot more query params and I may need to change different parts of those which is why I prefer the string-formatting approach
comment on: http://stackoverflow.com/q/48337735
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48427792
has title: Transforming from image coordinates to world coordinates
has comment: http://stackoverflow.com/comment/83945929
answer count: 1
tagged with: image-processing
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83945686
has comment: http://stackoverflow.com/comment/83868382
score: 0
tagged with: homography
has body: I have homography matrix H which is 3x3. I have an image that only contains 0s and 1s to denote whether the pixel is occupied. I would like to take this image and transform it into world coordinates using H. Is there an easy way to do this using cv2 in python? Otherwise, do I need to convert each pixel location using H? EDIT: Here's my code: image = plt.imread('image.png') obs = np.where(image &gt; 0) obs_map = np.vstack((obs[0], obs[1])) obs_map = np.vstack((obs_map, np.ones(obs[0].shape[0]))) obs_map = np.dot(H, obs_map) obs_map = np.dot(R, obs_map) plt.scatter(obs_map[0, :], obs_map[1, :]) plt.show() This seems to work but the scale seems off. What value do I need for z value? H is 1.1048200e-02 6.6958900e-04 -3.3295300e+00 -1.5966000e-03 1.1632400e-02 -5.3951400e+00 1.1190700e-04 1.3617400e-05 5.4276600e-01 and image consisting of 0s and 1s looks like this: and my plot looks like this:
has answer: http://stackoverflow.com/a/48427916

http://stackoverflow.com/comment/139842279
type: AnswerComment
score: 0
has text: `awk` and `xargs` are linux commands, which are not recognized when typed into anaconda prompt on Windows
comment on: http://stackoverflow.com/a/66012782
type: Comment

http://stackoverflow.com/q/48480252
has body: I'm working on my first program in python using cloud9 where I connect to twitter API and do sentiment analysis, but when I run the code I get this problem: Your code is running at https://x-x.c9users.io. Important: use os.getenv(PORT, 8080) as the port and os.getenv(IP, 0.0.0.0) as the host in your scripts! File "/home/ubuntu/workspace/demo.py", line 23 SyntaxError: Non-ASCII character '\xd8' in file /home/ubuntu/workspace/demo.py on line 23, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details This is my code after I looked on a few solutions but I still get the same problem: import os import tweepy from textblob import TextBlob port = os.getenv('PORT', '8080') host = os.getenv('IP', '0.0.0.0') # Step 1 - Authenticate consumer_key= 'xx' consumer_secret= 'xx' access_token='xx' access_token_secret='xx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #Step 3 - Retrieve Tweets public_tweets = api.search('school') for tweet in public_tweets: print(tweet.text) analysis = TextBlob(tweet.text) print(analysis.sentiment) print("") I also tried something called "Flask" but nothing changed. Thank you
tagged with: cloud9
has comment: http://stackoverflow.com/comment/83953622
has title: PORT 8080 / IP 0000 cloud09 python
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83953924
type: Question
has comment: http://stackoverflow.com/comment/83953710
has comment: http://stackoverflow.com/comment/83953537
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83650337
type: Comment
has text: Does the code you posted look *exactly* like the code in your actual script (for instance lines 15 through 19)? If it doesn't (which is my guess): fix that. We can't help you when code you posted is different from the code that is actually causing the problem.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48331191

http://stackoverflow.com/comment/83808178
type: Comment
has text: @yeger: That other question involves taking the difference of *all* consecutive pairs of numbers in a list. The solution there is definite overkill for the simple problem here. Also, the other question assumes the list is formed before the calculation, while in this question the list is formed during the process.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48409282

http://stackoverflow.com/comment/83769854
comment on: http://stackoverflow.com/a/48389344
score: 0
type: AnswerComment
has text: Yes, of course, `a_as_string` is not a valid JSON.
type: Comment

http://stackoverflow.com/comment/83755754
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48376528
has text: I think this question's considered to be too broad for stackoverflow, see [How to Ask](https://stackoverflow.com/help/how-to-ask).
type: QuestionComment

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/48392891
type: Tag

http://stackoverflow.com/a/48458834
upvote count: 0
downvote count: 2
answers question: http://stackoverflow.com/q/48458526
score: -2
type: Answer
has body: Your question was not clear, so I thought this code would be useful. import array L = list("someList") for i in L: a=array.array('c', 'X_String_you_need_to_change') a[0] = i print a.tostring()

http://stackoverflow.com/comment/83895857
comment on: http://stackoverflow.com/a/48451345
type: Comment
has text: can't format a comment apparently. error: 'StringProperty' is not defined
score: 0
type: AnswerComment

http://stackoverflow.com/a/48431453
upvote count: 3
downvote count: 0
score: 3
has body: the __init__.py file doesn't work that way. You need to import all requirements in the file where they are needed. So in your case, you will need to import requests in example.py and any other file that uses requests. You can use __init__.py to have a cleaner import for your packages. So in your libs library, you can setup __init__.py to look like this: from .scraper import MyScraper from .vulnlookup import MyFunction Then if you use need to use your libs somewhere else, you can simplify the imports like this: from .libs import MyScrapper #instead of: #from .libs.scraper import MyScraper
type: Answer
answers question: http://stackoverflow.com/q/48431345

http://stackoverflow.com/comment/83903128
type: AnswerComment
comment on: http://stackoverflow.com/a/48455043
score: 0
type: Comment
has text: One more thing: Will this not read the entire blob which you wanted to avoid in the 1st place?

http://stackoverflow.com/comment/83827123
has text: Yes, I included them
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48412539
type: Comment

http://stackoverflow.com/comment/85945540
type: QuestionComment
has text: Perhaps you are not using the numpy from the same Python environment. Try explicitly set your environment using `use_python()`.
comment on: http://stackoverflow.com/q/48373082
score: 1
type: Comment

http://stackoverflow.com/q/48377709
upvote count: 2
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: How tensorflow works?
tagged with: python
has body: I'm trying to use tensorflow with python to recognize some roi with size 28x28. At the first time i use this code : https://github.com/niektemme/tensorflow-mnist-predict/blob/master/predict_2.py, and he recognize 4/5 numbers in 10, so i try to modify the code, now i can see the percentage of precision and recognize 8/9 numbers in 10. The problem is i need to recognize all numbers and i see if i change the posiztion of the 20x20 inside the 28x28 it recognize every number, so, how tensorflow works? I read many documents about tensorflow, and i don't understand how it works, why if i move the 20x20 of 1 pixel change totally the number? this is my number: https://i.sstatic.net/gVKmN.jpg, it recognize it like 5, but if i move it 1 pixel down and 1 pixel right it find it like 3, why?
has answer: http://stackoverflow.com/a/48378351
score: 0

http://stackoverflow.com/q/48419372
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48419709
has body: I want to use multi domain for one django project one domain name for one app now my project like this test.com/ -&gt; Homepage test.com/appa -&gt; App A test.com/appb -&gt; App B I want to change to www.test.com -&gt; Homepage appa.test.com -&gt; App A appb.test.com -&gt; App B I think I can use nginx virtual host to solve this problem but now I have no idea pleas help me. now I use rewrite it works but not pretty good nginx server { ... server_name domain2 ... location / { rewrite / /app1/ ... } } when I browse domain2/ it can redirect to domain2/app1/ but i want domain2/ as /app1/
favorite count: 0
type: Question
tagged with: nginx
has answer: http://stackoverflow.com/a/48440467
tagged with: django
has title: How to run multi domainname in one django with nginx and uwsgi
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48440597

http://stackoverflow.com/q/48385853
tagged with: sql
has comment: http://stackoverflow.com/comment/83803163
accepted answer: http://stackoverflow.com/a/48390612
tagged with: sqlalchemy
has body: Rather than learn Pandas syntax, which would take some time, I'd like to use my existing SQL skills to manipulate Pandas dataframes in Python. My data are already in Pandas dataframes for various reasons. If someone knows the answer, can you show me a simple example to get me started? Something like the following, I'm guessing: import sqlalchemy query = """ select trunc(date, 'MM') as month , avg(case when hour_ending &gt; 7 and hour_ending &lt; 24 then volume else null end) as volume_peak , avg(case when hour_ending &lt;= 7 or hour_ending = 24 then volume else null end) as volume_off_peak from pandas_df where date &gt;= add_months(trunc(sysdate, 'DD'), -2) group by trunc(date, 'MM') order by trunc(date, 'MM'); """ new_df = sqlalchemy.run_query(query) Thanks! Sean
has answer: http://stackoverflow.com/a/48390612
type: Question
has comment: http://stackoverflow.com/comment/83759318
has title: Can SQLAlchemy be used to manipulate Pandas dataframes in Python?
tagged with: python
has comment: http://stackoverflow.com/comment/83763211
possible better answer: http://stackoverflow.com/a/48390368
has comment: http://stackoverflow.com/comment/83764521
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48390368
tagged with: pandas

http://stackoverflow.com/comment/87954238
type: QuestionComment
has text: What is `control`?
comment on: http://stackoverflow.com/q/48410579
score: 0
type: Comment

http://stackoverflow.com/comment/84061690
score: 0
type: Comment
has text: @Ryan I apologize for the confusion. A direct `.find` for "span" is the best approach for your smaller example posted, however, for longer `html`, you would search for a more specific tag. Please see my recent edit for a solution to find the `src`. It appears that you are trying to solve multiple problems in just a few steps. With `BeautifulSoup`, you have to break down the task you are trying to complete into smaller parts that can be solved separately. It may also be helpful for you to explore an in-depth tutorial regarding `BeautifulSoup`: goo.gl/NVqiFM
type: AnswerComment
comment on: http://stackoverflow.com/a/48471107

http://stackoverflow.com/q/48446293
has title: Python passing an object as side_effect to mock.patch
answer count: 1
tagged with: python
score: 1
favorite count: 0
type: Question
tagged with: mocking
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/52980604
has body: I'm in an argument with my lecturer -- he insists that an object can be passed to mock.patch as value of side_effect to mock out an original function in program, while still taking the arguments passed to that function -- in this particular case, storing them inside the object. Basically: with mock.patch('function_to_be_mocked', side_effect=my_object) as m: function_to_be_mocked(arg1, arg2) After these two lines of code, arg1 and arg2 will be stored as attributes in my_object. However according to documentation for side_effect, the only objects that can be passed to side_effect are either Exceptions or iterables, and neither cares about the arguments passed to original function. I tried to point out this error, but my lecturer said there's a way to get it around. Is there actually a way to do it, or just my lecturer refused to admit his mistake?

http://stackoverflow.com/comment/83671544
comment on: http://stackoverflow.com/q/48333752
score: 0
has text: Is-MacBook-Pro:~ d$ which python3 /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Is-MacBook-Pro:~ d$ which python2 /Applications/anaconda2/bin/python2 Is-MacBook-Pro:~ d$
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48404491
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48404453
has comment: http://stackoverflow.com/comment/131758166
has comment: http://stackoverflow.com/comment/131766161
has comment: http://stackoverflow.com/comment/83797500
score: 10
upvote count: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/48404453
downvote count: 0
has body: I believe you need: df = df1[df1.columns.intersection(df2.columns)] Or like @Zero pointed in comments: df = df1[df1.columns &amp; df2.columns]

http://stackoverflow.com/a/48339837
has comment: http://stackoverflow.com/comment/83669713
type: Answer
has comment: http://stackoverflow.com/comment/83670311
upvote count: 15
score: 15
has comment: http://stackoverflow.com/comment/83669620
downvote count: 0
has comment: http://stackoverflow.com/comment/83670408
has comment: http://stackoverflow.com/comment/83670500
answers question: http://stackoverflow.com/q/48338847
has body: One way to do that is by implementing __copy__ in the C Class like so: class A: def __init__(self): self.var1 = 1 self.var2 = 2 self.var3 = 3 class C(A): def __init__(self, a=None, b=None, **kwargs): super().__init__() self.a = a self.b = b for x, v in kwargs.items(): setattr(self, x, v) def __copy__(self): self.normalizeArgs() return C(self.a, self.b, kwargs=self.kwargs) # THIS IS AN ADDITIONAL GATE-KEEPING METHOD TO ENSURE # THAT EVEN WHEN PROPERTIES ARE DELETED, CLONED OBJECTS # STILL GETS DEFAULT VALUES (NONE, IN THIS CASE) def normalizeArgs(self): if not hasattr(self, "a"): self.a = None if not hasattr(self, "b"): self.b = None if not hasattr(self, "kwargs"): self.kwargs = {} cMain = C(a=4, b=5, kwargs={'r':2}) del cMain.b cClone = cMain.__copy__() cMain.a = 11 del cClone.b cClone2 = cClone.__copy__() print(vars(cMain)) print(vars(cClone)) print(vars(cClone2))
has comment: http://stackoverflow.com/comment/83673717
has comment: http://stackoverflow.com/comment/83670651
has comment: http://stackoverflow.com/comment/83669677

http://stackoverflow.com/a/48436334
has comment: http://stackoverflow.com/comment/83908710
answers question: http://stackoverflow.com/q/48436078
upvote count: 2
has comment: http://stackoverflow.com/comment/84058797
score: 1
accepted answer of: http://stackoverflow.com/q/48436078
has comment: http://stackoverflow.com/comment/83908665
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83897460
has comment: http://stackoverflow.com/comment/83899132
has comment: http://stackoverflow.com/comment/83898234
has body: Your system is heterogeneous, meaning you need some sort of serialisation that is platform / language agnostic. For your purposes the most convenient one to use is likely to be Google Protocol Buffers. This supports both C++ and Python very nicely. With this you'll be defining your messages / data structures in a schema file (file extension .proto), and using protoc to compile that to both C++ source code and also to Python source code. These give you classes that can serialise/deserialise to/from the same wireformat. The serialisation / deserialisation can nicely integrated with ZMQ message buffers. There are others; Apache Avro is a possibility. I would avoid XSD schemas; in principle they're fine, but finding code generators that actually do a proper and complete job is difficult / expensive. For example, xsd.exe (from Microsoft) can compile an XSD schema to C++ classes (I think), but ignores the constraint fields in the schema (e.d. MinInclusive). ASN1 is really good, but I've yet to find a decent implementation for Python. There is a code-first implementation of ASN.1 for python (pyasn), but that rather misses the whole point of having an ASN.1 schema...
type: Answer

http://stackoverflow.com/comment/83893154
comment on: http://stackoverflow.com/q/48450004
score: 0
type: QuestionComment
has text: Maybe off-topic, but any reason to use signals rather than overriding `save()` model method? It's a lot easier and clearer to me, and would probably help to debug this kind of problem.
type: Comment

http://stackoverflow.com/comment/83903437
has text: I initialized all three variables with value 0 at the same time. It's the same as `p = 0` `last = 0` `sum = 0`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48455137
type: AnswerComment

http://stackoverflow.com/q/48369463
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
has title: Python: 'function' object has no attribute x
upvote count: 5
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48369502
accepted answer: http://stackoverflow.com/a/48369502
has body: Hello I'm having an issue calling a function on an object in Python. This is the Method im trying to call def getCenter(self): cx = 0 cy = 0 for p in self.points: cx += p.x cy += p.y cx /= len(self.points) cy /= len(self.points) return Point(cx,cy,self.cid) this is the call im trying to make for c in clusters: print(c.points,c.cid) poi = c.getCenter print(poi.x) clusters have a list of points called "points". A point looks like this class Point: x = 0 y = 0 cluster = -1 def __init__(self, x = 0, y = 0): self.x = x self.y = y I'm getting the error message 'function' object has no attribute 'x'. I'm calling the getCenter-method on a Cluster which returns a point. And im calling the x attribut on that point. So i dont know why this error is appearing
answer count: 1
tagged with: python
score: 4
downvote count: 1

http://stackoverflow.com/comment/83885446
type: AnswerComment
score: 0
has text: @glglgl It's the same as doing `[] = ()` but inside an empty dict. I'm just saying that in case of a dict you need to use a key becuase the dict doesn't unpack like a tuple or list.
type: Comment
comment on: http://stackoverflow.com/a/48446169

http://stackoverflow.com/q/48426235
type: AnsweredQuestion
upvote count: 0
downvote count: 2
tagged with: tkinter
answer count: 3
has body: I have an app with 1 video frame and 5 Buttons. I want the video frame on top and the buttons nicely under the frame all in one row. Here is my code: self.root = tki.Tk() self.panel = None #create a button, that when pressed, will take the current #frame and save it to file btn= tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) btn.grid(sticky = tki.S) btnturnl= tki.Button(self.root, text="Left", command = self.EinsRechts) btnturnl.grid(sticky = tki.SW) btnturnl2= tki.Button(self.root, text="Two Left", command = self.ZweiRechts) btnturnl2.grid(sticky = tki.SW) btnturnr= tki.Button(self.root, text="Right", command = self.EinsLinks) btnturnr.grid(sticky = tki.SE) btnturnr2= tki.Button(self.root, text="Two Right", command = self.ZweiLinks) btnturnr2.grid(sticky = tki.SE) self.panel = tki.Label(image=image) #in this panel the video feed gets shown self.panel.image = image self.panel.grid(sticky = tki.N) This is how it really looks: what am I doing wrong? I am not that experienced with Tkinter so if I maybe have missed a function that would be better suited for me I'd gladly change my code. If you have questions feel free to ask and thanks for the help.
favorite count: 0
has answer: http://stackoverflow.com/a/48431326
type: Question
accepted answer: http://stackoverflow.com/a/48431326
has comment: http://stackoverflow.com/comment/83842887
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/48426339
possible better answer: http://stackoverflow.com/a/48426339
has title: tkinter grid manager doesnt fit buttons correctly
has answer: http://stackoverflow.com/a/48426441

http://stackoverflow.com/q/48448385
accepted answer: http://stackoverflow.com/a/48448490
has answer: http://stackoverflow.com/a/48448490
score: 1
has comment: http://stackoverflow.com/comment/83889230
has comment: http://stackoverflow.com/comment/83889618
tagged with: arrays
has body: I am having trouble converting a python list-of-list-of-list to a 3 dimensional numpy array. a = [ [ [1,2,3,4], # = len 4 ... ], # = len 58 ... ] # = len 1245 when I call a = np.array(a) on it, it reports shape as (1245,) and I cannot reshape it. a.reshape(1245,58,4) It gives me the error: ValueError: cannot reshape array of size 1245 into shape (1245,58,4) But If I print a[0] it gives me a 58 element list and a[0][0] gives me a 4 element list, as I expected, so the data is there. I see plenty of stack exchange posts wanting to flatten it, but I just want to make it into a numpy array in the shape that it already is. I don't know why numpy.array() is not seeing the other dimensions.
answer count: 1
downvote count: 0
upvote count: 1
has title: Convert multidimensional list to multidimensional numpy.array
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: multidimensional-array
tagged with: python
tagged with: numpy

http://stackoverflow.com/a/48369113
answers question: http://stackoverflow.com/q/48368841
score: 0
has body: I would recommend writing to a text file rather than writing to the actual python file. A python file (Python Program /Python Script) is used to carry out the tasks you desire (the actual program). Where as a text file is commonly used to store and read the data for the python program. Working with .txt or text files in python is really easy. You could also use mySQL to create a Data Base to store and retrieve data but I would suggest starting with the text files for now and once you understand that method progress to mySQL, that way you will learn two common methods of storing and fetching data. PS: Working with text files is quick and simple it will save a headache. Also look up some free PDF books via a google advanced search, you will have so much tutorials, you will not know where to start !!. Hope this helps. Happy Coding :).
type: Answer

http://stackoverflow.com/comment/83950764
comment on: http://stackoverflow.com/q/48478746
score: 0
has text: Which version of Python are you using? How are you calling the `ElementExtractorTest.py` script exactly? Is it `python3 ./ElementExtractorTest.py` or is it `python3 ./test/ElementExtractorTest.py`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83983538
type: QuestionComment
comment on: http://stackoverflow.com/q/48480009
type: Comment
has text: I'm afraid I dont know how to do that. at gunicorn.py? if I run with $ python app.py, I get an signal error, telling me spider must be on the main thread, which is the reason I've used the flag --thread 2
score: 0

http://stackoverflow.com/comment/83660653
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48337392
has text: @BaileyParker Awesome - do you happen to have a pointer for me where I should look in the Python docs or source to get clued up about this? Do I have to slog through https://docs.python.org/2/reference/datamodel.html or do you a more accessible place?
score: 0

http://stackoverflow.com/a/48377761
has body: Using numpy: rows = np.split(z, np.where(arr == '\n')[0] + 1)[:-1] mat = np.array(rows).astype(np.float) Alternatively, if we're sure to be dealing with a matrix, you could simply search for the first occurrence of '\n', reshape, and slice using that. first = np.argmax(arr == '\n') mat = arr.reshape(-1, first + 1)[:, 0:first].astype(np.float) This might be faster.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48377399

http://stackoverflow.com/q/48449611
has comment: http://stackoverflow.com/comment/83894828
tagged with: python
has comment: http://stackoverflow.com/comment/83895200
has comment: http://stackoverflow.com/comment/83894974
has answer: http://stackoverflow.com/a/53036155
score: 0
has comment: http://stackoverflow.com/comment/83982930
answer count: 1
has comment: http://stackoverflow.com/comment/84294249
tagged with: selenium
has comment: http://stackoverflow.com/comment/83893640
type: Question
linked to: http://stackoverflow.com/q/44072022
has title: Why is Firefox not using the profile preferences via selenium?
type: UnansweredQuestion
has body: I am trying to download a PDF files using Firefox in Selenium but the preferences I have set below do not seem to be working. Whenever I run the code, I am still getting the "You have chosen to open:" dialog box even though the preferences state that PDF files should automatically be downloaded. Am I missing something? def setUp(self): downloads_folder = initialSearch.download_path(self) profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.download.dir", downloads_folder) profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf") self.driver = webdriver.Firefox(profile)
tagged with: firefox
tagged with: geckodriver

http://stackoverflow.com/comment/83933522
has text: @juanpa.arrivillaga sorry not conflicting, more so just comparing the results, edited comment. Obviously it's a small use-case but both perform relatively similar
score: 0
comment on: http://stackoverflow.com/q/48469708
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83726885
has text: I used search string "jones", but it didn't return 4 in the data frame mentioned in this question. Does this search over all columns?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48355413

http://stackoverflow.com/q/48482751
type: Question
has comment: http://stackoverflow.com/comment/83969581
accepted answer: http://stackoverflow.com/a/48483012
tagged with: python
has title: Check for a repeating sequence in a pandas dataframe
has body: I have a pandas Dataframe, a column of which has a repeating sequence of values which almost looks like the following: Cell 0 x_a 1 x_b 2 x_c 3 x_a 4 x_b 5 x_c 6 x_a 7 x_b 8 x_b 9 x_c 10 x_c 11 x_b 12 x_a I need to check through this entire column to see that the repetition of this sequence "x_a, x_b, x_c" is exactly maintained in this order, i.e. "x_c" follows x_b" follows "x_a". Wherever this order is broken, e.g. in indices 7 and 8 where "B" is repeated twice or 10, 11, 12 where the order is wrong, I need to be able to find out which value is playing foul? Any pointers on how to do it? I've been scratching my head with df.loc all this while but to no avail and I'm fairly certain df.loc is not the right way. Thanks in advance guys.
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83969567
answer count: 1
has comment: http://stackoverflow.com/comment/83958581
has answer: http://stackoverflow.com/a/48483012
has comment: http://stackoverflow.com/comment/83964176

http://stackoverflow.com/a/48338837
has comment: http://stackoverflow.com/comment/83663268
downvote count: 1
has body: Using Dict comprehension reverted_dict = {value: key for key, value in cyphertable.items()} Using zip reverted_dict = dict(zip(cyphertable.values(), cyphertable.keys()))
type: Answer
upvote count: 1
score: 0
answers question: http://stackoverflow.com/q/48338816

http://stackoverflow.com/q/48468951
type: Question
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
tagged with: pytest
upvote count: 2
downvote count: 0
has title: Override pytest ids for test case name
has body: In my conftest.py file, I have: def pytest_generate_tests(metafunc): if 'item_id' in metafunc.fixturenames: metafunc.parametrize("item_id", item_id_data, ids=item_id_data) I also have a test_item.py file, e.g.: def test_item(item_id): assert True How can I overwrite the value of 'ids' inside 'test_item' method (or inside test_item.py) to be something else? For example, when I want my tests to run, I want them to be: test['blah'] instead of test[item_id_data].
favorite count: 0

object
tags question: http://stackoverflow.com/q/48455038
tag name: object
tags question: http://stackoverflow.com/q/48377506
tags question: http://stackoverflow.com/q/48410401
tags question: http://stackoverflow.com/q/48335791
tags question: http://stackoverflow.com/q/48442307
tags question: http://stackoverflow.com/q/48394741
tags question: http://stackoverflow.com/q/48360650
type: Tag
tags question: http://stackoverflow.com/q/48364107
tags question: http://stackoverflow.com/q/48390030
tags question: http://stackoverflow.com/q/48464960

http://stackoverflow.com/q/48358088
has body: I am trying to have my Listbox automatically run a query and populate immediately when corresponding Entry box has a value. This would be done without the use of a UPDATE or SELECT button(command=). If all fails I will have to resort to a button function call... I was hoping this could be accomplished without the use of a button. Essentially the autoquery would get (l) from 'team_input' and update levlistbox with the database result. def autoquery(l): levListbox.delete(0, "end") l = team_input.get() cursor = dbi.cursor() cursor.execute("""SELECT level FROM teamstatus WHERE game='%s'"""%(l,)) rows = cursor.fetchall() for results in rows: levListbox.insert("end", results) root.after(5000, autoquery) root = Tk() teamLabel=Label(topListFrame, text="Team", font="Verdana 8 bold") teamLabel.grid(row=0,column=0) team_input = StringVar() team_input = Entry(topListFrame, textvariable=team_input, width=10) team_input.grid(row=1,column=0) levLabel=Label(topListFrame, text="Level", font="Verdana 8 bold") levLabel.grid(row=0,column=1) levListbox=Listbox(topListFrame, height=1,width=8) #TRIED TO USE lambda WITH autoquery(team_input)) levListbox.grid(row=1, column=1) autoquery() root.mainloop()
score: 0
answer count: 1
has title: How to autocall a function with a Listbox based on data in a separate Entry Widget without a button
type: Question
tagged with: tkinter
type: UnansweredQuestion
tagged with: listbox
has answer: http://stackoverflow.com/a/48358196
tagged with: python

http://stackoverflow.com/comment/96841109
score: 0
has text: Did you ever work this out? There does not appear to be any useful examples for python workdocs
comment on: http://stackoverflow.com/q/48347269
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48483538
accepted answer of: http://stackoverflow.com/q/48483507
downvote count: 0
has comment: http://stackoverflow.com/comment/84008737
type: Answer
has comment: http://stackoverflow.com/comment/83968938
has body: Without using something like Selenium or another browser (headless or otherwise) which will actually run the JavaScript in a normal-ish manner, the only other method would be to manually reverse engineer the JavaScript, see what kind of calls it's making, and make them yourself directly. There wouldn't be any other kind of "one-size-fits-all" solution.
score: 1
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/83962030
answers question: http://stackoverflow.com/q/48483507

inheritance
tags question: http://stackoverflow.com/q/48379405
tags question: http://stackoverflow.com/q/48376607
tags question: http://stackoverflow.com/q/48364044
tags question: http://stackoverflow.com/q/48480575
tags question: http://stackoverflow.com/q/48471040
tags question: http://stackoverflow.com/q/48473158
tags question: http://stackoverflow.com/q/48483447
tags question: http://stackoverflow.com/q/48341893
tag name: inheritance
tags question: http://stackoverflow.com/q/48422875
tags question: http://stackoverflow.com/q/48386100
tags question: http://stackoverflow.com/q/48452702
tags question: http://stackoverflow.com/q/48465797
tags question: http://stackoverflow.com/q/48409078
tags question: http://stackoverflow.com/q/48465788
tags question: http://stackoverflow.com/q/48458272
tags question: http://stackoverflow.com/q/48407880
type: Tag
tags question: http://stackoverflow.com/q/48419414

http://stackoverflow.com/a/48388865
answers question: http://stackoverflow.com/q/48388675
type: Answer
score: 0
has body: You're doing a double job with the regex (split is also basically regex based) just do the whole thing with a 10 digit number matching regex, like so: comment = "Sues phone numbers are P#3774794773 and P#6047947730." nums = re.findall(r'\d{10,10}', comment) print(nums) If you want the numbers also to be exact (not to match longer sequences) you can do the following: comment = "Sues phone numbers are P#3774794773 123145125125215 and P#6047947730." nums = re.findall(r'\b\d{10,10}\b', comment) print(nums) (\b is an interesting regex symbol which doesn't really match a part of the string but rather matches "the space between characters" in the string) both result in: ['3774794773', '6047947730']

http://stackoverflow.com/q/48471466
answer count: 0
favorite count: 0
tagged with: excel
type: Question
has body: I am trying to write to an excel file and then load the result into a DF. However, calculated values are returning N/A in the DF even though when I open the excel sheet they are correctly displayed. If I open and then save the excel sheet manually after updating using python, loading the dataframe works. Here is the code: from openpyxl import load_workbook import pandas as pd if __name__ == '__main__': portfolio_values = getBalances('USD') wb = load_workbook(filename = 'Client_Portfolio_Tracker.xlsx') clients = wb['Clients'] clients['F2'] = portfolio_values clients['G2'] = datetime.datetime.now().strftime("%m/%d/%y %H:%M") wb.save('Client_Portfolio_Tracker.xlsx') client_df = pd.read_excel('Client_Portfolio_Tracker.xlsx', sheetname = 'Clients') print(client_df) Output of dataframe Thanks in advance!
linked to: http://stackoverflow.com/q/9282967
has comment: http://stackoverflow.com/comment/83936968
has comment: http://stackoverflow.com/comment/83937072
tagged with: python
has title: Trying to write values to an excel sheet using python. Calculated values in that sheet do not update when trying to import the result into a dataframe
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83936981
has comment: http://stackoverflow.com/comment/83937010
upvote count: 1
downvote count: 1

python-multiprocessing
tags question: http://stackoverflow.com/q/48369331
tags question: http://stackoverflow.com/q/48367591
tags question: http://stackoverflow.com/q/48437429
tags question: http://stackoverflow.com/q/48444590
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/48449501
tags question: http://stackoverflow.com/q/48355157
tags question: http://stackoverflow.com/q/48332391
tags question: http://stackoverflow.com/q/48352049
tags question: http://stackoverflow.com/q/48373637
type: Tag

http://stackoverflow.com/comment/83851674
score: 0
type: AnswerComment
has text: New error: `ValueError: Cannot add integral value to Timestamp without offset.`
comment on: http://stackoverflow.com/a/48403764
type: Comment

homography
tags question: http://stackoverflow.com/q/48427792
tags question: http://stackoverflow.com/q/48424598
tag name: homography
type: Tag

http://stackoverflow.com/a/48444384
type: Answer
has comment: http://stackoverflow.com/comment/83880188
answers question: http://stackoverflow.com/q/48444281
score: 1
has body: use subprocess: import subprocess with open(logFileName, 'w') as fp: p = subprocess.Popen( [myexec], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) fp, error_msg = p.communicate()
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83882384

bin
tag name: bin
tags question: http://stackoverflow.com/q/48392166
type: Tag

http://stackoverflow.com/comment/83808333
type: Comment
type: QuestionComment
has text: Have you actually installed matplotlib?
comment on: http://stackoverflow.com/q/48408670
score: 0

http://stackoverflow.com/q/48364814
tagged with: python
has body: I'm trying to scrape some data from baseball-reference.com. I've written some code to get the data from other parts of the site, where the tables are coded a little more simply, but the particular set of pages is apparently more complicated. Here's the code I have so far. from urllib.request import urlopen from bs4 import BeautifulSoup # Declare URL test_url = 'https://www.baseball-reference.com/boxes/SLN/SLN201704020.shtml' # Query the website and return the HTML page = urlopen(test_url) # Parse the HTML and store soup = BeautifulSoup(page, 'lxml') table = soup.find("div", {"class": "table_outer_container"}) This doesn't find the tables that I want though (on this particular page, the two tables with At-Bats, RBIs, HRs, runs, etc.). I've tried a few other things, e.g. table = soup.find_all("table" , {"class": "sortable stats_table"}) but it doesn't work either. I've also tried to read the site using pandas, with no luck, so if there's an easier way with pandas, I'm open to that too.
type: Question
upvote count: 2
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/83716732
downvote count: 1
possible better answer: http://stackoverflow.com/a/48369480
tagged with: web-scraping
favorite count: 0
has comment: http://stackoverflow.com/comment/83716654
has answer: http://stackoverflow.com/a/48369480
tagged with: beautifulsoup
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33138937
has answer: http://stackoverflow.com/a/48368724
accepted answer: http://stackoverflow.com/a/48368724
has title: Scraping data with BS4 in Python, nested table

http://stackoverflow.com/a/48485410
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48485070
type: Answer
has body: In First function call b is empty See here In second function call b is already fill with element So this condition not run if i not in b and return empty list Try this def func(a): res=list() b=set() for i in a: if i not in b: res.append(i) b|={i} return res print(func([1,1,2,2,3,4])) print(func([1,1,2,2,3,4])) Output [1, 2, 3, 4] [1, 2, 3, 4]
downvote count: 0

http://stackoverflow.com/a/48375029
score: 0
answers question: http://stackoverflow.com/q/48373198
type: AcceptedAnswer
has body: The webElement your are trying to interact with is either not clickable or it is disabled or may be it is out of browser's viewport. Selenium API is successful only on active interact-able webelements. Use Javascript, as a last mile solution.
type: Answer
has comment: http://stackoverflow.com/comment/83810980
accepted answer of: http://stackoverflow.com/q/48373198

http://stackoverflow.com/q/48371778
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/15347174
tagged with: math
has body: I am trying to output numbers that have only 3 factors. I wrote a code to output all the factors, but can't get it to output the number that has 3 factors. For instance, if a list has 1,5,6,7 .. it Will output 6 .. since 6 has three factors : 1, 2 and 3 .. (itself) not being a factor. This is what I have till now: def factors(n): result = [] for i in range(1, n + 1): if n % i == 0: result.append(i) return result
accepted answer: http://stackoverflow.com/a/48373111
has comment: http://stackoverflow.com/comment/83732305
has answer: http://stackoverflow.com/a/48373111
has comment: http://stackoverflow.com/comment/83732082
type: Question
has title: Finding list of numbers with 3 factors
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83733256

http://stackoverflow.com/comment/83725720
comment on: http://stackoverflow.com/a/48368632
type: Comment
score: 0
type: AnswerComment
has text: @Toto well `\w` checks for `0-9` also. So you could replace `\d\w` with `\w`. Anyways both works perfectly. Thank you for pointing that out.

http://stackoverflow.com/comment/83775827
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48394081
score: 0
has text: that's pretty much what I have written, problem is upon continue it goes to page 2 if it failed on page 1.. I need it to take a stepback upon failing example request = example.com/page=1 proxy failed so continue request = example.com/page=2

http://stackoverflow.com/comment/83840036
has text: Look into grequests: https://github.com/kennethreitz/grequests. I've used it before do many requests at once and it worked fine for me. It seems they are directing people to request-threads (https://github.com/requests/requests-threads) and requests-futures (https://github.com/ross/requests-futures), so these all may be worth looking into.
comment on: http://stackoverflow.com/q/48425108
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48436712
tagged with: python
favorite count: 0
type: Question
has body: Normally we are checking if script is running in the main scope just like in Python docs: __main__, like this: if __name__ == "__main__": # execute only if run as a script main() This is simple and clear, but there is also a problem – indentation. Whole def main(): have additional indent. Does it hurt? Me – yes, a bit. In Python we are particularly sensitive to line length. This is important to respect space every time, not only while writing 79th character. Because of that I'm looking for good method to reduce redundant indentation. In my opinion – there is one. Also simple, clear and elegant. if __name__ != "__main__": exit() # execute only if run as a script Almost every of our ideas is wrong or already used somewhere, so – I was looking for usage of this method and got nothing. Looks like I'm the only one using that. I can't belief that at all, but why then (if there is no hidden, tragic surprises) isn't it as popular as it should be?
has comment: http://stackoverflow.com/comment/83864968
upvote count: 2
has comment: http://stackoverflow.com/comment/83864700
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83865082
accepted answer: http://stackoverflow.com/a/48436888
has comment: http://stackoverflow.com/comment/83864990
has answer: http://stackoverflow.com/a/48436888
type: AnsweredQuestion
has title: Isn't checking if python script is NOT running in the main scope better?
score: 0
has comment: http://stackoverflow.com/comment/83864871

http://stackoverflow.com/comment/83934657
type: Comment
type: AnswerComment
has text: When you print out your `sys.path`, what are there? If one of the path can eventually lead to your `Testovnik\lib` directory then it *should* work already. But otherwise you can just add that line to your `question_test.py`. Better way would be update the path to be dynamic.
comment on: http://stackoverflow.com/a/48470173
score: 0

http://stackoverflow.com/comment/83755017
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48383963
score: 0
has text: any reason why you are trying to call python scripts from your python script instad of importing them?

http://stackoverflow.com/comment/83717362
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48365385
type: AnswerComment
has text: it's solved, I moved my cell up before any other changes were made to `dataframe`

http://stackoverflow.com/q/48371199
has answer: http://stackoverflow.com/a/48372417
linked to: http://stackoverflow.com/q/28714599
tagged with: python
has title: Count gear (Python, OpenCV)
has body: For a prototype I need to build a 3d model of a gear. This have a "many" number of teeth. So I am trying to count them using OpenCV and Python. I found this (only?) post which explain how to do it in C++. I am following the steps and, for now this is the code I made. import numpy as np import cv2 img = cv2.imread('C:\\Users\\Link\\Desktop\\gear.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) kernel = np.ones((3, 3), np.uint8) img_erosion = cv2.erode(thresh, kernel, iterations=1) edges = cv2.Canny(img_erosion, 50, 150) img_dilate = cv2.dilate(edges, kernel, iterations=1) cv2.imshow('i', thresh) cv2.waitKey(0) cv2.imshow('i', img_erosion) cv2.waitKey(0) cv2.imshow('i', edges) cv2.waitKey(0) cv2.imshow('i', img_dilate) cv2.waitKey(0) What stopped me from go ahead is this: the image at some point became really a mess. This is the original on which I am working: And this is the output of image_dilate As you can see, the teeth at the bottom is not displayed properly, maybe because of the shaddow in the original image. How can I get rid of this ?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83730592
answer count: 2
has comment: http://stackoverflow.com/comment/83730716
accepted answer: http://stackoverflow.com/a/48374509
has answer: http://stackoverflow.com/a/48374509
has comment: http://stackoverflow.com/comment/83730582
type: Question
tagged with: opencv
possible better answer: http://stackoverflow.com/a/48372417

http://stackoverflow.com/q/48405677
type: Question
tagged with: split
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83800739
tagged with: python
has comment: http://stackoverflow.com/comment/83800580
has answer: http://stackoverflow.com/a/48405777
tagged with: regex
has body: Currently I want to split a line with all the matching special characters of the regex. As it is hard to explain, here are a few examples: ('.+abcd[0-9]+\.mp3', 'Aabcd09.mp3') -> [ 'A', '09' ] .+ is a special expression of the regex and this is the match that I want [0-9]+ is another regex expression and I want what it matches too ('.+\..+_[0-9]+\.mp3', 'A.abcd_09.mp3') -> [ 'A', 'abcd', '09' ] .+ is the first special expression of the regex, it matches A .+ is the second special expression of the regex, it matches abcd [0-9]+ is the third special expression of the regex, it matches 09 Do you know how to achieve this? I didn't find anything.
has comment: http://stackoverflow.com/comment/83800125
has title: Split a line with matching regex special characters
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48406187
linked to: http://stackoverflow.com/q/48401402
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/48446108
score: 2
has body: [EDIT: changed to only find first name] for name in ('tribe', 'ailec', 'tfly'): if name in entry: print ('Name =', name) print('Plugin Found!') rating = easy sheet.cell(row=i, column=12).value = rating break
has comment: http://stackoverflow.com/comment/83884238
type: Answer
has comment: http://stackoverflow.com/comment/83884481
has comment: http://stackoverflow.com/comment/83884277
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83884413
answers question: http://stackoverflow.com/q/48446052

http://stackoverflow.com/comment/89359412
type: AnswerComment
comment on: http://stackoverflow.com/a/51188024
has text: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/20212428)
score: 1
type: Comment

http://stackoverflow.com/comment/83933665
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48466428
has text: The problem is, that the product of two variables is in general not linear and you are doing linear-programming. Start [here](https://orinanobworld.blogspot.de/2013/07/integer-variables-and-quadratic-terms.html).
score: 1

http://stackoverflow.com/comment/83812990
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48411485
has text: If you don't redirect the output, do you see the child process's output on the terminal?

http://stackoverflow.com/a/48369155
has body: Try to use merge: In [186]: df1.merge(df2, how='left').fillna(0) Out[186]: file is_about_heroes is_about_pony is_about_wolf 0 4.txt 1 1 0.0 1 5.txt 0 1 1.0 2 6.txt 0 1 0.0
answers question: http://stackoverflow.com/q/48369117
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83732714
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83760949
comment on: http://stackoverflow.com/q/48386479
score: 0
has text: https://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab Another dupe
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83674108
score: 0
has text: @glibdud realy? t1 = [1,2,3,4] def r(t1): t1[0] = 10 r(t1) print(t1) - i see, list change
comment on: http://stackoverflow.com/q/48344129
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48407506
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83888033
downvote count: 0
has comment: http://stackoverflow.com/comment/84087276
has comment: http://stackoverflow.com/comment/84046862
upvote count: 2
answers question: http://stackoverflow.com/q/48407081
type: Answer
has comment: http://stackoverflow.com/comment/83887992
accepted answer of: http://stackoverflow.com/q/48407081
has comment: http://stackoverflow.com/comment/83869897
has body: It is possible that the font is not being recognized in your application. Check to see if you have installed the font. You can also try adding the preeti.ttf file to resources and adding it to the app using: QFontDatabase::addApplicationFont(“:/fonts/preeti.ttf”); I found stylesheets to be more reliable (than using setFont(QFont)) for setting font. Use textEdit->setStyleSheet(font-family: 'Preeti');. EDIT setting stylesheet from QFontDialog() can be done in following way in python @pyqtSlot() def select_font(self): font, ok = QFontDialog.getFont(self) if ok: params = font.toString().split(",") # The string is :"Preeti,9,-1,5,50,0,0,0,0,0" self.ui.text_edit.setStyleSheet("font-family :%s;font-size:%spt;" % (params[0], params[1]))

http://stackoverflow.com/a/48357295
type: AcceptedAnswer
downvote count: 0
has body: use Series.agg() method: In [49]: tuple(df['Finals'].agg(['idxmax','max']).values) Out[49]: (10, 3728) UPDATE: using df.loc[]: In [74]: tuple(df.loc[[df['Finals'].idxmax()], 'Finals'].reset_index().values[0]) Out[74]: (10, 3728)
has comment: http://stackoverflow.com/comment/83701605
has comment: http://stackoverflow.com/comment/83701519
type: Answer
answers question: http://stackoverflow.com/q/48357259
accepted answer of: http://stackoverflow.com/q/48357259
upvote count: 3
score: 3

http://stackoverflow.com/q/48369377
has comment: http://stackoverflow.com/comment/83725557
tagged with: python
has comment: http://stackoverflow.com/comment/83725452
has comment: http://stackoverflow.com/comment/83725436
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83725479
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83725577
type: Question
has answer: http://stackoverflow.com/a/48369452
possible better answer: http://stackoverflow.com/a/48369452
has answer: http://stackoverflow.com/a/48369436
has comment: http://stackoverflow.com/comment/83725440
has comment: http://stackoverflow.com/comment/83725428
has body: I'm creating a Login &amp; Password program in Python for my school, I've created already the sign up part with many validations and it fully works &amp; the login part partly works. The login part has a issue. It locates the username and also the password however it also locates the password beginning with that initial and it lets you log in the account (bug). For example, my password is "mat" if I type ma or m it will let me log into the account. But the good thing is it doesn't let me log in with other letters just those. PATH=("pass"+" "+username+".txt") if os.path.isfile(PATH) and os.access(PATH, os.R_OK): print ("Username does exist please enter password: ") w = input("Password: ") with open("pass"+" "+username+".txt") as f: found = False for line in f: if w in line: loginuser() found = True if not found: print("Wrong password. Please re-enter") login() else: print("Username not found.")
has answer: http://stackoverflow.com/a/48369437
has comment: http://stackoverflow.com/comment/83725489
has comment: http://stackoverflow.com/comment/83725382
has comment: http://stackoverflow.com/comment/83725402
has answer: http://stackoverflow.com/a/48369410
has title: How can I fix this program that accepts passwords with partial matching
accepted answer: http://stackoverflow.com/a/48369410

http://stackoverflow.com/q/48376580
type: Question
has answer: http://stackoverflow.com/a/63484269
has answer: http://stackoverflow.com/a/52820025
has answer: http://stackoverflow.com/a/63201584
has answer: http://stackoverflow.com/a/53094059
has answer: http://stackoverflow.com/a/54447199
has answer: http://stackoverflow.com/a/53592023
linked to: http://stackoverflow.com/q/48735600
accepted answer: http://stackoverflow.com/a/48385944
has answer: http://stackoverflow.com/a/63021235
linked to: http://stackoverflow.com/q/47374971
possible better answer: http://stackoverflow.com/a/52300696
tagged with: python
has body: I have some data on gDrive, for example at /projects/my_project/my_data*. Also I have a simple notebook in gColab. So, I would like to do something like: for file in glob.glob(&quot;/projects/my_project/my_data*&quot;): do_something(file) Unfortunately, all examples (like this - https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb, for example) suggests to only mainly load all necessary data to notebook. But, if I have a lot of pieces of data, it can be quite complicated. How to solve this issue?
has answer: http://stackoverflow.com/a/72181479
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/56190582
score: 276
has title: How to read data in Google Colab from my Google drive?
has answer: http://stackoverflow.com/a/52300696
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48437552
has answer: http://stackoverflow.com/a/74929813
upvote count: 276
has answer: http://stackoverflow.com/a/56034635
has answer: http://stackoverflow.com/a/53696854
downvote count: 0
has answer: http://stackoverflow.com/a/63648255
has comment: http://stackoverflow.com/comment/98344913
has answer: http://stackoverflow.com/a/48385944
has answer: http://stackoverflow.com/a/60054424
answer count: 17
favorite count: 0

http://stackoverflow.com/comment/110110847
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48361515
has text: I am facing the same issue with dice loss. By the way I did not quite understand what do you mean by 'The zero results from the sum of all loss values which at some point can no longer be stored and becomes zero'?
type: Comment

http://stackoverflow.com/comment/83663812
type: Comment
has text: Thank you. I search for the python documentation "reason" attribute still stay for this error. But I will try it. Additionally, how can I overcome the request limit or irresponsiveness?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48336934

http://stackoverflow.com/comment/83743344
has text: Well, it's because you haven't plotted anything?
comment on: http://stackoverflow.com/q/48378343
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48453525
type: Question
has answer: http://stackoverflow.com/a/48453814
has title: Using Python to Analyze Retail Data - Trying to get all orders that contain a specific sku and at least one other sku
type: UnansweredQuestion
has body: I'm a python beginner that's working with a large csv file of online order data. I'm trying to see what skus people most frequently purchase with a specific sku, we'll call it grey-shirt711. I'm struggling to express how to say "show all orders that contain grey-shirt771 and at least one other sku". I keep merely retrieving all orders that have grey-shirt711 in it, which 90% of the time is only that sku. Assuming I'm only dealing with these two columns ('sku' and 'orderID'), what's the simplest way I could express this statement? Thank you!
tagged with: python
has comment: http://stackoverflow.com/comment/83900591
score: 1
tagged with: sku
tagged with: e-commerce
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/27012151
linked to: http://stackoverflow.com/q/22546425
favorite count: 0

http://stackoverflow.com/a/48487012
score: 0
answers question: http://stackoverflow.com/q/48486911
has comment: http://stackoverflow.com/comment/118297918
type: Answer
has body: It looks like namespace issue, Just clean the pyc files, this Link can help you.

http://stackoverflow.com/q/48378996
type: Question
has comment: http://stackoverflow.com/comment/83745590
has comment: http://stackoverflow.com/comment/83746645
has comment: http://stackoverflow.com/comment/83744839
has comment: http://stackoverflow.com/comment/83744828
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83745548
has title: error when saving the str(getting from response.content) as an image
tagged with: base64
tagged with: python
tagged with: request
tagged with: image
has comment: http://stackoverflow.com/comment/83745565
score: 0
has body: i am using the requests in python to hit an api and get a response: response = requests.request("POST", url, data=payload, headers=headers) i have image data in response.content print type(response.content) gives: &lt;type 'str'&gt; now i have to save this data as an image file on my local : i am using ubuntu 16.04 and python 2.7 i am trying this: image=response.content result=open('img.png','wb') result.write(image) but when trying to open the resulting file, this error is shown: Fatal error reading PNG image file: Not a PNG file response.content looks like this (shortened sample): eyJpZCI6IndzX2Y5YnVqaWVwamVzMnRyNWpjM2RpXzE1MTY2MTM5MjgzMzMi‌​LC.............YTZPZ‌​UVjWkwva0FBQUFBRWxGV‌​GtTdVFtQ0MifQ== i have also tried encoding response.content to base64 encoding and then tried writing my image without success. what should i do?
has comment: http://stackoverflow.com/comment/83744995
has comment: http://stackoverflow.com/comment/83744625
has answer: http://stackoverflow.com/a/48379165
answer count: 1

http://stackoverflow.com/q/48363942
tagged with: django
has comment: http://stackoverflow.com/comment/83714774
has body: so this is what I print in python with flushing: import sys print "getting detailed" sys.stdout.flush() then i check the logs file and it is empty, so then I stop the server: supervisorctl stop my-project and the logs file is filled with messages from the print above, so the question is how to make it print to the log file without stopping the server?
has comment: http://stackoverflow.com/comment/83714730
has comment: http://stackoverflow.com/comment/83714739
has comment: http://stackoverflow.com/comment/83714851
tagged with: python
has comment: http://stackoverflow.com/comment/83714751
type: Question
score: 0
answer count: 0
has title: supervisord prints logs only when stopped server
type: UnansweredQuestion
tagged with: supervisord

http://stackoverflow.com/comment/83737562
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48374558
type: QuestionComment
has text: You could implement such using `onkeypress()` and `onkeyrelease()` in combination. Here's the catch: some operating systems implement key repeat such that you'll get a series of press and release events while the key is being held down. You won't be able to distinguish the user action from the system repeat. Unless you turn off key repeat at the OS level.

http://stackoverflow.com/comment/83857548
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48433076
has text: I just edited the question to add the data

http://stackoverflow.com/a/48429045
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83884509
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48425264
has body: Understanding/Assumptions based on inferring provided data. Host data is in a json file and each host is a disctionary having several key/value pairs. problem: data migration was done but during migrations certain keys were missed. keys we migrated but values are not orrect or left balnk. missed migration of some hosts. Solution: orig_data_locn was the original json data that was migrated. migrated_data_locn is the migrated json data. result locn will the locn where the fixed migrated data will be written to. iterate over each host in json1_datagrab the corresponding host from json2_data, if host not available in json_2_data update json_2_data with the host details from json_1_data. if host is availale in both orig and migrated data then iterate over each key/value in orig data and check if key value is available in migrated_data if key found in both orig and migrated data and equal -> no operation if key found in both original and migrated but not equal -> update migrated key/value with orig key/value if key not found in migrated then add orig key/value to migrated ... more comments inside code def fix_migrated_data(orig_data_locn, migrated_data_locn, result_locn): """ compares the original data and migrated data json files and produces a result json files which has all migration errors fixed """ orig_data = json.loads(open(orig_data_locn).read()) migrated_data = json.loads(open(migrated_data_locn).read()) for orig_host, orig_host_data in orig_data.iteritems(): # check if the host in original data is availale in migrated data migrated_host_dict = migrated_data.get(orig_host, None) # if host available in migrated data if migrated_host_dict: print 'host {} found in migrated data'.format(orig_host) # compare original and migrated key/values for orig_key, orig_value in orig_host_data.iteritems(): # check if key is available in migrated host dict migrated_value = migrated_host_dict.get(orig_key, None) # if key is available in migrated host dict # check if values are sam…
accepted answer of: http://stackoverflow.com/q/48425264

http://stackoverflow.com/comment/83730267
has text: I tried your code, it always says I overshot
comment on: http://stackoverflow.com/q/48371615
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83968625
type: AnswerComment
score: 0
has text: Thanks, I did and now its complaining that: dropbox_auth_start() missing 1 required positional argument: 'web_app_session'
type: Comment
comment on: http://stackoverflow.com/a/48483600

http://stackoverflow.com/comment/83754484
type: Comment
comment on: http://stackoverflow.com/a/48382865
type: AnswerComment
has text: @eugenhu Answer overhauled.
score: 0

http://stackoverflow.com/comment/83812594
comment on: http://stackoverflow.com/q/48350091
score: 0
type: QuestionComment
type: Comment
has text: @georgexsh I edited to clarify where do I want to use all this: on unit test scripts. So the first piece of code is actually where I init my engine and the second is where I invoke alembic. The piece of code on env.py is just the alembic env configuration script

http://stackoverflow.com/comment/83661871
score: 0
has text: Thanks for accepting! You can also upvote answers if they were useful, so please consider doing so. Thanks.
comment on: http://stackoverflow.com/q/48337371
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83895318
type: AnswerComment
comment on: http://stackoverflow.com/a/48451129
has text: What do you mean by follow True?
type: Comment
score: 0

http://stackoverflow.com/comment/83783014
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48397589
type: Comment
has text: It is very hard to help you if you don't show us enough *real* data.

http://stackoverflow.com/q/48480325
has title: Print statement not printing anything on console in python
favorite count: 0
tagged with: http://stackoverflow.com/tag/json
tagged with: scripting
has comment: http://stackoverflow.com/comment/83962385
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83954354
has comment: http://stackoverflow.com/comment/83962586
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has body: Print statement not printing anything on console in python. I am printing the key, value of the JSON file where the key starts with @id found = False for key, di in json.loads(json_data).iteritems(): for k, v in di.items(): if k.startswith('@id'): found = True print k, v sys.stout.flush() break if found: break I think have done a mistake. Any help will be appreciated.
has comment: http://stackoverflow.com/comment/83963525
answer count: 1
has answer: http://stackoverflow.com/a/48486100

http://stackoverflow.com/comment/84016560
score: 0
comment on: http://stackoverflow.com/a/48501417
type: Comment
has text: sorry, fixed it. your solution has a typo: you set the sqlite.url option which doesn't makes sense, must be the sqlalchemy.url option.
type: AnswerComment

http://stackoverflow.com/comment/83932653
has text: I need to execute many commands written in pip, don't want to use conda unless necessary
comment on: http://stackoverflow.com/q/48468975
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48457124
answer count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48457379
tagged with: keras
favorite count: 0
type: Question
has body: I am using a convolutional neural net (CNN) called make_unet from here. It works and code is able to run with this CNN. But I know that in deep learning you have to initialize weights for optimization of the neural network. The documentation in Keras clearly indicates the use of a kernel_initializer for weight initialization. However, I do not see any kernel_initializer in the make_unet function I am using. Anyone who can provide some insight would be appreciated.
tagged with: python
accepted answer: http://stackoverflow.com/a/48457379
score: 4
upvote count: 4
has title: Where is the kernel weight initialization in my CNN model?
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: deep-learning
downvote count: 0

http://stackoverflow.com/q/48469593
has comment: http://stackoverflow.com/comment/83933019
answer count: 1
accepted answer: http://stackoverflow.com/a/48478816
favorite count: 0
has comment: http://stackoverflow.com/comment/83950231
type: Question
has answer: http://stackoverflow.com/a/48478816
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83933093
score: 0
has body: I'm making a cipher app that can allow you to choose the rotation you will use to encode your text. Preferably instead of using a drop-down menu with 93 different options, I would want a small box with up/down buttons where you can scroll through the options. EX: I would do something like this: status = IntVar() list = ['a', 'b', 'c'] scrollmenu = tk.ScrollMenu(root, options=list, variable=status, command=check_value()) And when I place it the widget appears like this: Is there a way to do this?
upvote count: 1
tagged with: python
has title: Is there a way in tkinter to have a scrolling menu?
downvote count: 1
has comment: http://stackoverflow.com/comment/83954661
type: AnsweredQuestion

http://stackoverflow.com/a/48449214
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48445280
answers question: http://stackoverflow.com/q/48445280
has body: You can produce multiple mappers for one class – found in the non-traditional mappings section of the documentation: However, there is a class of mapper known as the non primary mapper with allows additional mappers to be associated with a class, but with a limited scope of use. This scope typically applies to being able to load rows from an alternate table or selectable unit, but still producing classes which are ultimately persisted using the primary mapping. So instead of a subclass you'd produce a non primary mapper ActiveUser: In [9]: ActiveUser = mapper( ...: User, ...: User.__table__.select(). ...: where(User.status == "active"). ...: alias(), ...: non_primary=True) ...: In [10]: print(session.query(ActiveUser)) SELECT anon_1.id AS anon_1_id, anon_1.status AS anon_1_status, anon_1.age AS anon_1_age, anon_1.yet_another_property AS anon_1_yet_another_property FROM (SELECT user.id AS id, user.status AS status, user.age AS age, user.yet_another_property AS yet_another_property FROM user WHERE user.status = ?) AS anon_1 On the other hand all of this might be rather unnecessary and you could simply query for active users when you need such.

http://stackoverflow.com/comment/83661865
type: QuestionComment
comment on: http://stackoverflow.com/q/48337778
has text: I've googled it to see if anyone has faced the same problem, some people say you gotta install XQuartz and you'll be good, but this app is for mac, is there any similar app for windows ?
score: 0
type: Comment

http://stackoverflow.com/a/48453544
score: 0
has body: That is indeed a bit confusing. What is meant here is of course that an array of M x N elements has shape (n,m), where N=n and M=m. This however deviates from the usual convention of defining matrix dimensions. The usual convention for matrices is "N by M" meaning a matrix of N rows and M columns; this would have "shape (N,M)" (in the numpy convention). For some reason the imshow documentation deviates from that convention. I guess one could change that. Concerning the possible dimensions for imshow the correct version should read X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4) Display the image in X to current axes. X may be an array or a PIL image. If X is an array, it can have the following shapes and types: n x m / (n,m) – values to be mapped (float or int) n x m x 3 / (n,m,3) – RGB (float or uint8) n x m x 4 / (n,m,4) – RGBA (float or uint8) The value for each component of n x m x 4 and n x m x 4 float arrays should be in the range 0.0 to 1.0. n x m arrays are mapped to colors based on the norm (mapping scalar to scalar) and the cmap (mapping the normed scalar to a color). Here n is the number of rows, m is the number of columns.
answers question: http://stackoverflow.com/q/48453346
type: Answer

http://stackoverflow.com/comment/83862725
type: Comment
comment on: http://stackoverflow.com/a/48435633
type: AnswerComment
has text: I guess I forgot to mention that, I was too focus to get to what you just did. I guess if I save this as CSV it will look as a list, how could I get the output as a string, to have the data in columns under with the years as headers.
score: 0

http://stackoverflow.com/a/48466107
type: Answer
answers question: http://stackoverflow.com/q/48463250
has body: Never mind, it was CV2.imread that was causing the problem. CV2 reads BGR instead of RGB, so the images where loaded incorrectly and Tensorflow was showing them as it should.
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48463250

http://stackoverflow.com/comment/83932457
comment on: http://stackoverflow.com/q/48466901
type: QuestionComment
has text: On line 2165 you can see, that both "conv1_1" and "concat" have been defined as input layers
score: 0
type: Comment

http://stackoverflow.com/comment/105886783
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48398061
has text: If my suggestion helped you, would you consider marking it as the accepted answer?

http://stackoverflow.com/comment/83934145
has text: Hmm, I find the key one easier to read. Partially because it's so much shorter. And how did you measure this? For me your way is *slower* (as I expected): https://ideone.com/GUcVhW
type: Comment
comment on: http://stackoverflow.com/a/48469462
score: 0
type: AnswerComment

http://stackoverflow.com/q/48472346
has body: I am trying to extract out all texts including categories (i.e. A, B, C). A &lt;some text1&gt; B &lt;some text2&gt; C &lt;some text3&gt; However, when I apply this regex - ptrn='\n[A-z]*\t' pattern1= '(.*)'+ptrn f = re.findall(pattern1,test_doc) it gives me f[0] = A &lt;some text1&gt; f[1] = &lt;some text2&gt; f[2] = &lt;some text3&gt; But I want - f[0] = A &lt;some text1&gt; f[0] = B &lt;some text2&gt; f[2] = C &lt;some text2&gt; http://csmining.org/tl_files/Project_Datasets/r8%20r52/r8-test-all-terms.txt this link has some raw text of many documents. each document has following pattern: category&lt;tab&gt;&lt;sometext&gt; \n hence the whole corpus looks like this:- category&lt;tab&gt;&lt;sometext1&gt; \n category&lt;tab&gt;&lt;sometext2&gt; \n . . i want doc[0] = category&lt;tab&gt;&lt;sometext1&gt; doc[1] = category&lt;tab&gt;&lt;sometext2&gt; . . and so on Any answer/hint will be very helpful :)
answer count: 1
accepted answer: http://stackoverflow.com/a/48472556
tagged with: regex
has answer: http://stackoverflow.com/a/48472556
tagged with: nlp
type: Question
has comment: http://stackoverflow.com/comment/83938857
has comment: http://stackoverflow.com/comment/83938596
has comment: http://stackoverflow.com/comment/83938802
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/83938557
tagged with: python
has comment: http://stackoverflow.com/comment/83938619
has comment: http://stackoverflow.com/comment/83938723
type: AnsweredQuestion
score: 0
has title: Extract text between two pattern in python using regex

http://stackoverflow.com/q/48485289
tagged with: list
has answer: http://stackoverflow.com/a/48485498
has answer: http://stackoverflow.com/a/48486199
has comment: http://stackoverflow.com/comment/83964813
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48485641
has comment: http://stackoverflow.com/comment/83964449
has answer: http://stackoverflow.com/a/48485606
tagged with: coefficients
answer count: 6
favorite count: 0
has title: Removing and replacing coefficients of polynomials in Python
has comment: http://stackoverflow.com/comment/83963472
has body: I´m having some trouble using python´s list function for polynomials. For example, if I write the poynomial p1 = [0, 0, 0, 1, 1], I get the output 1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0 I want to adjust this so that: Terms with coefficient 1 are written without the coefficients, e.g. "1x^3" should be written as "x^3". Terms with coefficient 0 should not be written at all, e.g. "x^4 + x^3 + 0*x^2 + 0*x + 0" should be simplified as "x^4 + x^3". Is there a command for this in python? Thanks in advance. /Alex //the code def polynomial_to_string(p_list): terms = [] degree = 0 for coeff in p_list: if degree == 0: terms.append(str(coeff)) elif degree == 1: terms.append(str(coeff) + 'x') else: term = str(coeff) + 'x^' + str(degree) terms.append(term) degree += 1 terms.reverse() final_string = ' + '.join(terms) return final_string
type: Question
has comment: http://stackoverflow.com/comment/83963619
tagged with: math
upvote count: 6
has answer: http://stackoverflow.com/a/48485585
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48485594

http://stackoverflow.com/q/48394364
type: UnansweredQuestion
tagged with: python
has body: Suppose I have two dataframe df1 and df2 In df1 date value 0 2018-01-23 10:00:00 10 1 2018-01-23 11:00:00 20 2 2018-01-23 12:00:00 30 In df2 date value 0 2018-01-23 10:02:00 10 1 2018-01-23 10:03:00 20 2 2018-01-23 10:04:00 30 3 2018-01-23 10:05:00 40 4 2018-01-23 10:06:00 50 5 2018-01-23 11:07:00 50 ... Update: I want to calculate the summation of df2.value based on the interval selected by df1.date.iloc[n-1] and df1.date.iloc[n]. I can get index of df2.date by IntervalIndex but unable to select the value inside each interval.
has title: Pandas: How to calculate summation of value based on another dateframe's datetime interval
score: 0
tagged with: pandas
tagged with: datetime
has comment: http://stackoverflow.com/comment/83776292
linked to: http://stackoverflow.com/q/46525786
type: Question
has comment: http://stackoverflow.com/comment/83780599
has comment: http://stackoverflow.com/comment/83821827
answer count: 0

http://stackoverflow.com/comment/111734045
comment on: http://stackoverflow.com/a/48379628
score: 0
type: Comment
has text: @MarianeReis Thanks for notifying me. I have now updated the link.
type: AnswerComment

http://stackoverflow.com/comment/84071542
type: AnswerComment
has text: @Basj IIRC no embedded database engine support concurrent update on same database file because there no central server process to coordinate. What you should be concerned is the throughput db engine could provide and your workload requirement, and that is what this benchmark for.
comment on: http://stackoverflow.com/a/48473953
score: 0
type: Comment

http://stackoverflow.com/comment/83860954
type: QuestionComment
comment on: http://stackoverflow.com/q/48413407
has text: How much time does it take to output the 10KB data if you run the command manually?
score: 0
type: Comment

http://stackoverflow.com/comment/83970915
has text: Can you post the complete stack trace of exception?
type: Comment
comment on: http://stackoverflow.com/q/48425792
type: QuestionComment
score: 0

http://stackoverflow.com/a/48455351
answers question: http://stackoverflow.com/q/48455037
has body: pd.value_counts(df.values.ravel())
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83939409
type: QuestionComment
score: 1
has text: @metatoaster `0x25 ^ (0xFFFFFFFF << 1)` is an integer number, and so is 0x87654321. However, they cannot be divided without a remainder. The problem as written does not seem to have a solution.
comment on: http://stackoverflow.com/q/48472784
type: Comment

http://stackoverflow.com/comment/83767088
type: Comment
type: AnswerComment
has text: what would be the value of each key? Or it's just not an issue for now?
score: 0
comment on: http://stackoverflow.com/a/48389555

http://stackoverflow.com/a/48466360
answers question: http://stackoverflow.com/q/48466139
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: You just need value_counts df['gender'].value_counts()

http://stackoverflow.com/a/48422183
has body: As far as I know there is no easy way to connect to an existing python process once it is started to run another script within this process. The option you have is to work in an interactive session, e.g. within IPython. There you may create your plot and manipulate it as you advance. For example 1: import matplotlib.pyplot as plt 2: import numpy as np 3: fig, ax = plt.subplots() 4: line, = ax.plot([1,3,2]) 5: plt.ion() 6: plt.show() # shows the figure 7: line2, = plt.plot([2,2,1]) # inside the figure shows another line 8: line.remove() # removes the first line from the figure
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48420864
answers question: http://stackoverflow.com/q/48420864
type: Answer

http://stackoverflow.com/q/48450648
type: AnsweredQuestion
tagged with: authentication
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/83896159
has body: So i am quite new to python (knew C# before trying to learn python) and i wanted to make an little login/register program, i wrote it all, theorically (at least to me) it would work, but it doesn´t, it doesn´t logs indenpendently of that account existing or not... How do i make this program work? command = "" username = "" password = "" def Register(): global username global password username = input("Username: ") password = input("Password: ") f = open("userinfo.txt", "a") f.write("--------------------") f.write("\n%s information:\n"%(username)) f.write("%s \n"%(username)) f.write("%s \n"%(password)) f.write("--------------------") def Login(): global username global password f = open("userinfo.txt", "r") f.readline() f.readline() username = f.readline() password = f.readline() f.readline() return username return password def CheckLogin(): global username global password global loginusername global loginpassword if loginusername == username and loginpassword == password: print("You´ve logged in, wait for next updates") elif loginusername == username and loginpassword != password: print("Wrong password") elif loginusername != username and loginpassword == password: print("Wrong username") elif loginusername != username and loginpassword != password: print("Wrong login information, restart the program and register to create an account") else: print("ERROR: Uknown error") command = input("Would you like to login or register?\n") if (command == "register"): Register() print("Done!") elif (command == "login"): print("--------LOGIN--------") loginusername = input("Username: ") loginpassword = input("Password: ") Login() CheckLogin() else: print("Invalid command") print("Please restart the program and try again") So, do i need to make class related stuff? like, users being objects? but how would i save that data? Please help me Edit: did some minor polishing on the code, fixed an error but now i have other...
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
has title: How do i make this python login/register program work? (I am new to python)
accepted answer: http://stackoverflow.com/a/48450701
has comment: http://stackoverflow.com/comment/83895320
has comment: http://stackoverflow.com/comment/83895262
has answer: http://stackoverflow.com/a/48450701

http://stackoverflow.com/comment/83843624
has text: i rectify my comment, how many tabs can we open by winow. In my case, i can't open more than 2 tabs by window
score: 0
comment on: http://stackoverflow.com/q/48398376
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53018737
has body: Steps: Download the spyder-mac-app.zip archive. Unarchive it to /Applications Edit the /Applications/Spyder.app/Contents/MacOS/Spyder file to launch the right environment of Spyder, e.g.: #!/bin/sh $HOME/anaconda3/envs/tensorflow/bin/spyder $@ Launch Spyder from Finder to verify that Finder is launching as expected. Install duti and run duti -s org.spyder .py all Right click any .py file in Finder, click Get Info In Open with menu, select Other and navigate to 'Applications. Select Spyder, Press Add and Click on Change All in Info menu.
has comment: http://stackoverflow.com/comment/117741433
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48468846
type: Answer

http://stackoverflow.com/comment/83927826
score: 0
type: AnswerComment
has text: I'm not sure that this works but, regardless, throw a list into the mix. This might work for a specific example but it's useless _a priori_.
comment on: http://stackoverflow.com/a/48467086
type: Comment

http://stackoverflow.com/comment/83733209
comment on: http://stackoverflow.com/a/48372783
type: Comment
type: AnswerComment
score: 0
has text: Non uniform data types are generally going to be a problem. That error is due to the list being unhashable. That is during the set creation. The set creation is meant to remove duplicates. If duplicates are not an issue, you can remove the `set()`. Alternatively, the lists would need to be deduplicated prior.

http://stackoverflow.com/q/48333043
tagged with: python
tagged with: kivy
type: AnsweredQuestion
score: 0
answer count: 2
has body: How do I remove a parent BoxLayout using a child button? Keep in mind I am going to have many of these similar box layouts. Here is where I am creating each BoxLayout and adding it to a global layout itemsLayout def submitProductToWatch(self, productName, ebay, letGo, mercari): self.current = 'main' newItem = BoxLayout(id="boxID",size_hint_y=None, height=40) myCheck = CheckBox(id="checkID",size_hint_x=None, color=(0.467,.878,.259,1)) prodLabel= Label(text=productName, size_hint_x=None) webCoverageString = self.displayWebsitesForProduct(ebay, letGo, mercari) covLabel= Label(id="coverageID",text=webCoverageString) remButton= Button(id="removeID",text="Remove", color=(1,0,0,.7),size_hint= (.6,.7), font_size= 15) newItem.add_widget(myCheck) newItem.add_widget(prodLabel) newItem.add_widget(covLabel) newItem.add_widget(remButton) itemsLayout.add_widget(newItem)
has answer: http://stackoverflow.com/a/48336781
type: Question
accepted answer: http://stackoverflow.com/a/48359412
has answer: http://stackoverflow.com/a/48359412
has title: Remove an entire boxLayout and its children in Kivy with Python dynamically
has comment: http://stackoverflow.com/comment/83651689
possible better answer: http://stackoverflow.com/a/48336781

http://stackoverflow.com/comment/83680271
score: 0
type: AnswerComment
has text: see updated answer, if you are still unable to resolve it, I request you to post complete traceback and views function that you are using to pass values.
comment on: http://stackoverflow.com/a/48346180
type: Comment

http://stackoverflow.com/comment/83774341
comment on: http://stackoverflow.com/q/48390893
score: 0
has text: What does it mean that it does not work? that description can have multiple interpretations.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83735387
type: AnswerComment
has text: yeah nevermind, that prediction is correct but it also predicts wrongly a lot of other configurations. Like a full black block is a "stairs"...
comment on: http://stackoverflow.com/a/48373247
type: Comment
score: 0

http://stackoverflow.com/comment/83897136
comment on: http://stackoverflow.com/q/48451561
type: Comment
type: QuestionComment
score: 0
has text: @Tanmoy Well, which numbers *should* be added?

restructuredtext
tags question: http://stackoverflow.com/q/48368463
type: Tag
tags question: http://stackoverflow.com/q/48398900
tags question: http://stackoverflow.com/q/48459710
tag name: restructuredtext

http://stackoverflow.com/comment/83871574
comment on: http://stackoverflow.com/q/48439995
has text: L_Church - I thought it was acceptable to have a catch-all except clause?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48389450
answer count: 2
has body: I am trying to scrap a website using beautifulsoup, my problem is that I am only trying to get a link in the Html source but end up with a terrible list of every &lt;div class="table-list-cell py-3 pl-3 v-align-middle member-avatar-cell css-truncate pr-0"&gt; &lt;a href="/Member1"&gt; &lt;img alt="@Member1" class="avatar float-left" height="48" src="https://avatars0.githubusercontent.com/u/xxxxxxx" width="48" /&gt; &lt;/a&gt; I only want to get the /Member1 or @Member1 my code look like this : Membres={} response = requests.get('https://github.com/orgs/xxxxxxxx/people?page=1') soup = BeautifulSoup(response.content, "html.parser") for e in soup.find_all("div",{"class":"table-list-cell py-3 pl-3 v-align-middle member-avatar-cell css-truncate pr-0"}): for d in e.find_all("a"): for f in d.find_all("img alt="): Membres[f]={} So I have try to cut the line 'for f in ....' and creat a direct link such as : for d in e.find_all("a", href=True): Still way to many informations in my keys, if someone got a way to just get the Member1 name. Thank you
has comment: http://stackoverflow.com/comment/83766798
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48389735
has comment: http://stackoverflow.com/comment/83766625
has answer: http://stackoverflow.com/a/48389735
tagged with: python
possible better answer: http://stackoverflow.com/a/48389555
has title: Python - Beautiful Soup - Getting a link find_all
has answer: http://stackoverflow.com/a/48389555
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48447296
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48447412
has answer: http://stackoverflow.com/a/48447412
favorite count: 0
type: Question
has body: I have this df: import pandas as pd datas = [{'A':10, 'B':100}, {'A':11,'B':(-210)}, {'A':12,'B':120}, {"A":14, "B":30}] df = pd.DataFrame(datas) df ["CUMSUM"] = (df["B"].cumsum()) I´m trying to get the following output: 1) If the column "CUMSUM" has any value lower than (-100): print just the first row in which CUMSUM &lt; (-100), and stop running. 2) If the column "CUMSUM" has not any value lower than (-100): print just the last row, and stop running. Can anybody help me?
has title: Print a specific row of a DataFrame
upvote count: 2
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/83869010
score: 0
type: AnswerComment
has text: Ah, ok. See my edit. Let me know if my understanding of the question is correct
type: Comment
comment on: http://stackoverflow.com/a/48436884

http://stackoverflow.com/a/48475275
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48475071
type: Answer
has comment: http://stackoverflow.com/comment/83982917
downvote count: 0
has body: It is much easier to help you if you just include the code in your answer. The inherited method you are trying to override uses two underscores on both sides. Currently the inherited version of __str__ is being used, not yours. Try this: def __str__(self): return self.text
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48475071
has comment: http://stackoverflow.com/comment/83982854

http://stackoverflow.com/comment/83719647
score: 0
comment on: http://stackoverflow.com/q/48366556
type: Comment
type: QuestionComment
has text: also if this helps to know im using the sublime IDE with python 3.6.4

http://stackoverflow.com/a/48456772
has body: you can use sys.argv[i] to parse an argument from commad line at index i Try this: import sys file_to_open=sys.argv[1] # 0 is the index of name of python prog, 1 is the index of first argument in command line. df=pd.read_csv(file_to_open,sep=',') #do whatever you want with the file pd.to_csv() is used to save a pandas dataframe as a csv file if you pass python finalauto.py xyz.txt in the command line, sys.argv[0] will give you finalauto.py and sys.argv[1] will give you xyz.txt
answers question: http://stackoverflow.com/q/48456459
has comment: http://stackoverflow.com/comment/83909323
type: Answer
has comment: http://stackoverflow.com/comment/83906873
has comment: http://stackoverflow.com/comment/83907042
has comment: http://stackoverflow.com/comment/83913450
has comment: http://stackoverflow.com/comment/83914780
score: 0
has comment: http://stackoverflow.com/comment/83908355
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83906925
has comment: http://stackoverflow.com/comment/83906656
has comment: http://stackoverflow.com/comment/83909174
accepted answer of: http://stackoverflow.com/q/48456459
has comment: http://stackoverflow.com/comment/83909582

http://stackoverflow.com/comment/91018829
has text: @Hooked: how does it actually fix the code? Curious to know how did you find this solution. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48340392
score: 0

http://stackoverflow.com/comment/83911748
has text: @anothernode I think the empty string test should be outside the try-except clause altogether, i.e. before the try, you're not expecting the empty string test to raise a ValueError
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48459235
score: 0

http://stackoverflow.com/comment/83947750
score: 0
type: Comment
type: QuestionComment
has text: is that your main urls.py which you posted?
comment on: http://stackoverflow.com/q/48477144

http://stackoverflow.com/a/48365381
answers question: http://stackoverflow.com/q/48365055
type: Answer
upvote count: 2
downvote count: 0
has body: Using glob.glob for filename in glob.glob(os.path.join(dirname, "AB_CDEF17*.*")): try: # Trying to remove a current file os.remove(os.path.join(dirname, filename)) except EnvironmentError: # You don't have permission to do it pass Using os.scandir and re.match pattern = re.compile(r"AB_CDEF17\w+\.\w+") for filename in os.scandir(dirname): if pattern.match(filename): try: os.remove(os.path.join(dirname, filename)) except EnvironmentError: pass
score: 2

http://stackoverflow.com/q/48373228
has answer: http://stackoverflow.com/a/48373246
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
answer count: 1
tagged with: python
has body: when I am trying to run this simple snippet of code a= 2 G = np.random.rand(25,1) H = np.zeros((25,a)) for i in range(a): H[:,i] = .5 * G I receive the ValueError: could not broadcast input array from shape (25,1) into shape (25). I wonder if anyone can point at a solution to this problem? I know it happens quite a bit in image processing, but this one, I don't knwo how to circumvent. Cheers.
score: 2
has comment: http://stackoverflow.com/comment/83734774
has title: ValueError: could not broadcast input array from shape (25,1) into shape (25)
tagged with: valueerror

http://stackoverflow.com/a/48429840
answers question: http://stackoverflow.com/q/48428115
score: 0
has body: In TensorFlow you define a computational graph that is executed with the sess.run() statement. As part of that graph the cost operation is defined by placeholder X and Y. To compute the cost you have to feed a value for X and Y. In your print statement you call sess.run(cost) without feeding X and Y. That is the reason for the error. But you already executed the graph. Just store the resulting values: C, H, _ = sess.run([cost,hypothesis,train], feed_dict={X:x_col[0],Y:y_col[0]}) and print results for cost C and hypothesis H
type: Answer

http://stackoverflow.com/a/57636651
upvote count: 12
downvote count: 0
type: Answer
score: 12
has body: In Keras Tokenizer you have the oov_token parameter. Just select your token and unknown words will have that one. tokenizer_a = Tokenizer(oov_token=1) tokenizer_b = Tokenizer() tokenizer_a.fit_on_texts(["Hello world"]) tokenizer_b.fit_on_texts(["Hello world"]) Outputs In [26]: tokenizer_a.texts_to_sequences(["Hello cruel world"]) Out[26]: [[2, 1, 3]] In [27]: tokenizer_b.texts_to_sequences(["Hello cruel world"]) Out[27]: [[1, 2]]
answers question: http://stackoverflow.com/q/48432300

http://stackoverflow.com/q/48390258
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/59439289
has comment: http://stackoverflow.com/comment/83768556
linked to: http://stackoverflow.com/q/7368789
tagged with: string
has answer: http://stackoverflow.com/a/65409991
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83768826
upvote count: 5
has comment: http://stackoverflow.com/comment/83768374
tagged with: python
has comment: http://stackoverflow.com/comment/83768571
tagged with: numpy
tagged with: python-3.x
answer count: 2
score: 5
has body: I have a list of numbers in string format. I converted that list into numpy array using np.asarray(). How do I convert the string elements to ints?
has title: How to convert numpy array elements from string to int

http://stackoverflow.com/a/48403317
type: Answer
has comment: http://stackoverflow.com/comment/83819593
answers question: http://stackoverflow.com/q/48394493
score: 0
has body: In terms of using the raw API, I believe this is what you are looking for. Depending on which python library you are using, it is actually easier in python. I use elasticesearch-dsl-py, where you build up query objects. You can call delete on these query objects. In regards to spanning multiple indexes, ElasticSearch does support this, either using a wildcard *, or separating the indexes with commas.
has comment: http://stackoverflow.com/comment/83820813

http://stackoverflow.com/comment/83910634
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48457948
has text: @Jamboree I think only this line `out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))` has effect on the `FPS` property. I test your original code, then use `mediainfo output.avi` to get the info, the FPS line is what I posted `Frame rate : 20.000 fps`, different with your result. I don't think webcam fps has effect on it. Such as, when you save the pictures (without FPS info) into video, the fps is decided by the `fps parameter`.
type: Comment

http://stackoverflow.com/q/48484525
has title: Sum of all Nodes Iteratively - Not Recursively - Without 'left' and 'right'
favorite count: 0
tagged with: iteration
type: Question
tagged with: binary-tree
has comment: http://stackoverflow.com/comment/83961721
has answer: http://stackoverflow.com/a/48484636
tagged with: algorithm
tagged with: python
has answer: http://stackoverflow.com/a/48484555
type: AnsweredQuestion
answer count: 3
upvote count: 2
score: 2
possible better answer: http://stackoverflow.com/a/48484555
has body: I have this Binary Tree Structure: # A Node is an object # - value : Number # - children : List of Nodes class Node: def __init__(self, value, children): self.value = value self.children = children I can easily sum the Nodes, recursively: def sumNodesRec(root): sumOfNodes = 0 for child in root.children: sumOfNodes += sumNodesRec(child) return root.value + sumOfNodes Example Tree: exampleTree = Node(1,[Node(2,[]),Node(3,[Node(4,[Node(5,[]),Node(6,[Node(7,[])])])])]) sumNodesRec(exampleTree) &gt; 28 However, I'm having difficulty figuring out how to sum all the nodes iteratively. Normally, with a binary tree that has 'left' and 'right' in the definition, I can find the sum. But, this definition is tripping me up a bit when thinking about it iteratively. Any help or explanation would be great. I'm trying to make sure I'm not always doing things recursively, so I'm trying to practice creating normally recursive functions as iterative types, instead.
accepted answer: http://stackoverflow.com/a/48484613
downvote count: 0
has answer: http://stackoverflow.com/a/48484613

http://stackoverflow.com/a/48450013
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48448966
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83892882
has body: It can be any widget, but there's no advantage to it being anything other than the root widget. The implementation of the Variable class (from which StringVar, etc inherit) simply uses the given master to find the root window. The root window is all it actually cares about, and once it knows the root window, it doesn't use the master for anything else.

http://stackoverflow.com/a/48526540
has comment: http://stackoverflow.com/comment/84048709
has comment: http://stackoverflow.com/comment/84080110
answers question: http://stackoverflow.com/q/48425128
has body: I believe you can accomplish the desired behavior with sklearn's sklearn.preprocessing.MinMaxScaler that can scale each feature is the desired range, as per MinMaxScaler(feature_range=(0, 1), copy=True). This is achieved by setting the feature_range. In terms of calculations the max and min values per feature are calculated during fit and used during predict. svm-scale works similarly and in the file you suggested saves the scaling factors needed to transform the test data. Here, every feature will be transformed in the range set when first calling svm-scale. Scikit's scalers offer more flexibility as you can scale its feature using different scales, which may be count-intuitive though. The transformers of scikit learn are best used for the whole pipeline, when first fitting the training data and then predicting for the test data. You can hack them for the case you have already the file with you indicate, but for the latter case it is probably better to write your own scaling function for having a cleaner code. For instance assuming having the file feats.range: x 0 1 1 -1 1 2 2 18 the following function will produce the desired output. data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]] def svm_scale(X, path="feats.range", new_range = (0,1)): f = open(path).read().splitlines()[2:] f = np.array([x.split() for x in f]).astype(float) my_min, my_max = f[:,1], f[:,2] # second/third col is the feat. mins/max X_std = (X - my_min) / (my_max - my_min) # This brings at (0,1) X_scaled = X_std * (new_range[1] - new_range[0]) + new_range[0] # Modifies min/max return X_scaled svm_scale(data) # returns array([[ 0., 0.],[ 0.25, 0.25],[ 0.5, 0.5 ], [1.,1.]])
has comment: http://stackoverflow.com/comment/84075681
has comment: http://stackoverflow.com/comment/84074213
has comment: http://stackoverflow.com/comment/84078069
has comment: http://stackoverflow.com/comment/84071737
score: 0
type: Answer

http://stackoverflow.com/a/48444472
answers question: http://stackoverflow.com/q/48346403
has body: This happened to me before, some how the Site model does not exist during migration, all I did is wrap the whole thing in a try catch and the exception does not seem to happened again after the initial Site migration. class SiteMiddleware(object): def process_request(self, request): try: try: current_site = Site.objects.get(domain=request.get_host()) except Site.DoesNotExist: current_site = Site.objects.get(id=settings.SITE_ID) request.current_site = current_site if current_site.domain in settings.HOST_MIDDLEWARE_URLCONF_MAP: request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[str(current_site)] except Exception as ex: print('Error: %s' % ex)
score: 0
type: Answer

http://stackoverflow.com/comment/83818843
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48414404
has text: Sorry, forgot to mention that. The number of samples should be uniformly random from 0 to the number of integers in the nested list.

http://stackoverflow.com/q/48342313
has answer: http://stackoverflow.com/a/48391765
downvote count: 1
favorite count: 0
type: Question
tagged with: charts
has comment: http://stackoverflow.com/comment/83671162
has comment: http://stackoverflow.com/comment/83671101
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83671339
has comment: http://stackoverflow.com/comment/83745301
tagged with: python
score: -1
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/83685278
has comment: http://stackoverflow.com/comment/83671408
has comment: http://stackoverflow.com/comment/83670983
has comment: http://stackoverflow.com/comment/83679756
upvote count: 0
tagged with: pyqt
has body: I've started playing with pyqtgraph plotting line charts. I have the need to draw specific dots in some section of the lines. I found that in order for dots to appear on the line, I need to use symbolBrush when plotting E.g curve3 = p1.plot(pen=(2,5) , name="trade" , symbolBrush=2) But the thing is it shows dots on the entire line, and I can't seem to find a way to draw a dot for specific points / sections. Assistance would be appreciated Edit: For example, In the attached image, assume I only want to draw a dot where marked (1,1) without dots being drawn on the other line breaks.
has comment: http://stackoverflow.com/comment/83672061
has title: how can I set a dot / bar on specific section of a line plot in pyqtgraph?
answer count: 1

http://stackoverflow.com/comment/83901488
has text: Can you please provide your model definitions?
type: Comment
comment on: http://stackoverflow.com/q/48454151
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83792424
comment on: http://stackoverflow.com/a/48402010
has text: This advice resolved my problem! Thanks! So There's a hidden file in my folder? But the image is the only file I can see with 'ls' command.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83875807
has text: You don't consider a "Lost connection" to be connection related?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48440957

http://stackoverflow.com/q/48462669
has comment: http://stackoverflow.com/comment/83919866
has answer: http://stackoverflow.com/a/48462863
score: 1
has comment: http://stackoverflow.com/comment/83918550
accepted answer: http://stackoverflow.com/a/48462863
has answer: http://stackoverflow.com/a/48462866
has comment: http://stackoverflow.com/comment/83918417
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83918239
has title: Why is this object regarded as integer when I think it's a list?
type: Question
has body: This is a practice problem, which reads: Define a procedure that takes in a string of numbers from 1-9 and outputs a list with the following parameters: Every number in the string should be inserted into the list. If a number x in the string is less than or equal to the preceding number y, the number x should be inserted into a sublist. Continue adding the following numbers to the sublist until reaching a number z that is greater than the number y. Then add this number z to the normal list and continue. Examples: string = '543987'; result = [5,[4,3],9,[8,7]] string= '987654321'; result = [9,[8,7,6,5,4,3,2,1]] string = '455532123266'; result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]] string = '123456789'; result = [1, 2, 3, 4, 5, 6, 7, 8, 9] My code is as follows: def numbers_in_lists(s): n=len(s) p=[] i=0 while i&lt;=n-1: p.append(int(s[i])) i=i+1 r=[p[0]] if p[1]&lt;=p[0]: r.append([p[1]]) else: r.append(p[1]) if n&lt;=2: return r j=2 while j&lt;=n-1: if p[j]&lt;=p[j-1]: if p[j-1]&lt;=p[j-2]: r[-1].append(p[j]) else: r.append(p[j]) else: if p[j]&lt;=p[j-2]: r[-1].append(p[j]) else: r.append(p[j]) j=j+1 return r When I tried to run print (numbers_in_lists('543987')), I got this: Traceback (most recent call last): File "Lesson14Quiz3.py", line 33, in &lt;module&gt; print (numbers_in_lists(string)) File "Lesson14Quiz3.py", line 20, in numbers_in_lists r[-1].append(p[j]) AttributeError: 'int' object has no attribute 'append' The problem seems to be with this line: r[-1].append(p[j]). But I think when the previous conditions are satisfied, r[-1] should not be an integer, but a list.
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83918609
has comment: http://stackoverflow.com/comment/83919746
has comment: http://stackoverflow.com/comment/83919479
has comment: http://stackoverflow.com/comment/83920300
possible better answer: http://stackoverflow.com/a/48462866
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/48467410
has answer: http://stackoverflow.com/a/48467535
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83928355
has title: Create dataframe from iteration result
type: Question
accepted answer: http://stackoverflow.com/a/48467535
has body: import pandas as pd datas1 = [{'A':10, 'B':100}, {'A':11,'B':-210}, {'A':12,'B':120}, {'A':14, 'B':30}] datas2 = [{'A':25, 'B':90}, {'A':11,'B':-50}, {'A':110,'B':(-15)}, {'A':5, 'B':65}] datas3 = [{'A':5, 'B':-100}, {'A':19,'B':210}, {'A':12,'B':-300}, {'A':14, 'B':30}] for i in [datas1, datas2, datas3]: df = pd.DataFrame(i) df['CUMSUM'] = (df['B'].cumsum()) if (df['CUMSUM'] &lt; -100).any(): print(df.loc[df['CUMSUM'] &lt; -100, :].head(1)) print ("") else: print(df.loc[df['CUMSUM'] &gt;= -100, :].tail(1)) print ("") What would be the code to create a new dataframe with the results obtained in this program?
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83836593
score: 0
has text: why the pandas/ dataframe tags?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48423348

http://stackoverflow.com/q/48411339
tagged with: pandas
type: AnsweredQuestion
tagged with: bigdata
downvote count: 0
has title: Large DataFrame with random columns of a smaller one (Pandas)
upvote count: 1
score: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48411362
has answer: http://stackoverflow.com/a/48411362
type: Question
has body: I am trying to generate a huge dataset in Python 3.6 using Pandas for testing a code but the method I developed is too slow and I would like to know if there is a more efficient way of doing it. I create a smaller dataframe with a few columns and around 3 millions of rows (for example): # assume we have relevant information in 'a','b','c' data = pd.DataFrame(index=range(int(3e6))) data['a'] = 0 data['b'] = 0 data['c'] = 0 Now, I would like to take random rows of this dataframe and build with them a bigger one with approximately 15 million rows, of course, even if rows repeat. I tried taking samples and appending to the new dataframe like this: data_tot = pd.DataFrame(columns=data.columns) for i in range(int(15e6)): samp = data.sample(1) data_tot = data_tot.append(samp) It looks very inefficient but I never had to generate such amount of data. I also tried preallocation and using iloc then, but still very slow.
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/83714719
comment on: http://stackoverflow.com/q/48363912
score: 0
type: Comment
type: QuestionComment
has text: thanks for the reply, I just want to know how to install from a zip in WinPython; sometimes I found packages on the web on zip file and I was no able to install them

http://stackoverflow.com/comment/83830762
score: 0
has text: @Microos even in tensorflow docs https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/eager/run they imported module in nested view. I'm not sure that you should be using short version.
type: Comment
comment on: http://stackoverflow.com/a/48420497
type: AnswerComment

http://stackoverflow.com/q/48415782
favorite count: 0
has body: I am getting the error as Traceback: in &lt;module&gt; in merge_ranges TypeError: 'int' object is not iterable Can someone suggest what is the issue and also for debugging I am using code as meets = [(1,3),(5,8),(8,14),(13,17)] print '{} should be {}'.format(merge_ranges(meets)) def merge_ranges(meets): #sort by start time sorted_meetings = sorted(meets) merged_meetings = sorted_meetings[0] for current_meeting_start, current_meeting_end in sorted_meetings[1:]: last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1] if (current_meeting_start &lt;= last_merged_meeting_end): merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) else: merged_meetings.append((current_meeting_start, current_meeting_end)) # write the body of your function here return merged_meetings
tagged with: python
has answer: http://stackoverflow.com/a/48415814
has title: I am trying to debug python code given but it gives the error as given
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/48415842
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48415889
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83859542
comment on: http://stackoverflow.com/q/48402262
has text: Take the [tour], read [Ask] and [MCVE].
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83922258
score: 1
type: Comment
type: QuestionComment
has text: `print (m.add(n, fill_value=0))`
comment on: http://stackoverflow.com/q/48464467

http://stackoverflow.com/a/48369824
score: 1
answers question: http://stackoverflow.com/q/48369505
downvote count: 0
upvote count: 1
type: Answer
has body: First of all you are writing in final without actually ever reading anything so it can't work. Replace file1, file2, file3 with the variables that have the read() attribute. Just use a for statement with each variable you want to loop. Like this: for i in name: for j in states: for k in status: all = i + '\n` + j + '\n' + k + '\n' final.write(all)

http://stackoverflow.com/comment/83846938
comment on: http://stackoverflow.com/a/48428194
has text: `df.loc[df['Time'] == 'unknown', 'Time'] = df['Time'].shift()` should do.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/48354395
answers question: http://stackoverflow.com/q/48354181
type: AcceptedAnswer
has body: The render_template function from Flask doesn't pass any variable from one language to the other. It just replaces strings inside the html-template that it finds with a variable that you handover to it. With return render_template("sara.html",l=l) you are telling the program to take the sara.html template and insert your variable l anywhere where it finds {{ l }} in the template. You should see it in the actual HTML that you are sending to the client. because you are inserting it under your heading: &lt;h1&gt; HERE COMES!!!&lt;/h1&gt; {{ l }} It is really more helpful if you are using it to render pure HTML and not JavaScript. Of cause you can also replace things inside your JavaScript but that is really not a sensible way to do client-server communication. If you want communication between your client and server you should think about a different architecture. Doing the get call url = 'http://webapi.i2space.co.in/Buses/Sources' payload = {'some': 'data'} headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'} r = requests.get(url, data=json.dumps(payload), headers=headers) inside your server is probably better kept in your client-side Javascript.
accepted answer of: http://stackoverflow.com/q/48354181
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/83856558
comment on: http://stackoverflow.com/q/48432557
has text: not necessarily in a list - but I need them all to perform a follow on function
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48472493
has comment: http://stackoverflow.com/comment/83938803
has body: Is this what you need ? v=df['MA(5)-MA(20)'].gt(0).astype(int).diff().fillna(0).cumsum() df.groupby(v).High.transform('max').mask(df['MA(5)-MA(20)'] == 0,df.groupby(v).Low.transform('min')) 0 90 1 90 2 102 3 102 Name: High, dtype: int64
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48472368

http://stackoverflow.com/comment/83739240
has text: What about writing `import pdb; pdb.set_trace()` in one line where ever you need it?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48376035

oop
tags question: http://stackoverflow.com/q/48431230
tags question: http://stackoverflow.com/q/48475290
tags question: http://stackoverflow.com/q/48415920
tags question: http://stackoverflow.com/q/48429661
tags question: http://stackoverflow.com/q/48331358
tags question: http://stackoverflow.com/q/48480786
tags question: http://stackoverflow.com/q/48390615
tags question: http://stackoverflow.com/q/48403504
tags question: http://stackoverflow.com/q/48404262
tags question: http://stackoverflow.com/q/48476145
tag name: oop
tags question: http://stackoverflow.com/q/48336655
tags question: http://stackoverflow.com/q/48407587
tags question: http://stackoverflow.com/q/48432316
tags question: http://stackoverflow.com/q/48409078
tags question: http://stackoverflow.com/q/48350971
tags question: http://stackoverflow.com/q/48337392
tags question: http://stackoverflow.com/q/48407822
tags question: http://stackoverflow.com/q/48391851
tags question: http://stackoverflow.com/q/48374761
type: Tag
tags question: http://stackoverflow.com/q/48390030

http://stackoverflow.com/a/58856294
accepted answer of: http://stackoverflow.com/q/48484152
type: Answer
has comment: http://stackoverflow.com/comment/128097217
upvote count: 6
type: AcceptedAnswer
has body: A more specific answer to this. Instead of using the command like this in python: os.system("ffmpeg -i /Users/krish/audio.mp3 -acodec pcm_s16le -ar 16000 -ac 1 /Users/krish/converted_audio.wav") First try to find out where is your ffmpeg installation by giving the following command in terminal (Works on linux and mac) which ffmpeg In my case this was the output of the above command: /usr/local/bin/ffmpeg Now, modify the os.system command in python as follows: os.system("/usr/local/bin/ffmpeg -i /Users/krish/audio.mp3 -acodec pcm_s16le -ar 16000 -ac 1 /Users/krish/converted_audio.wav") which should work great without throwing 32512 error!
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48484152

http://stackoverflow.com/comment/83954851
type: Comment
score: 0
has text: @MadPhysicist I didn't particularly understand how item separators functioned (from my textbook), but I will check out that website. Thanks!
comment on: http://stackoverflow.com/q/48472121
type: QuestionComment

http://stackoverflow.com/comment/83823354
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163772/discussion-between-ilja-everila-and-pawan).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48396601
type: AnswerComment

http://stackoverflow.com/comment/139682400
has text: However, it's better to ensure `git` is properly installed (and ensure executable PATH set, if needed) App/package might depend on `git` for a reason.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/65473426
score: 0

http://stackoverflow.com/comment/83752985
score: 0
has text: All right, I seem to get this one: `build`, `compile`, and `sdist|bdist_wheel` should be executed in sequence.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48381805

http://stackoverflow.com/a/48335198
answers question: http://stackoverflow.com/q/48335126
type: Answer
score: 0
has body: Your error says view_user doesn't have permission to query data on 192.168.9.132 this server. You will have to do GRANT SELECT ON *.* TO 'view_user'@'host_or_wildcard' IDENTIFIED BY 'password'; to allow your user to query on specified server. Or GRANT ALL PRIVILEGES ON *.* TO 'view_user'@'192.168.9.132'; to grant all priviliges. P.S. To do above you will have to be root user. Use mysql -u root -p command to connect to mysql server.
has comment: http://stackoverflow.com/comment/83662002
has comment: http://stackoverflow.com/comment/83662070

http://stackoverflow.com/a/48445528
has body: your json file contains a single dict(after json.load), making this line for x in x: unnecessary, unless your file contains many lines like the one you provided the other issue you have is the way you access x["variants"]["option1"] because x["variants"] returns a list of dicts! so your foreach should be there: for item in x["variants"]: item["option1"] #etc...
score: 2
has comment: http://stackoverflow.com/comment/83915946
upvote count: 2
has comment: http://stackoverflow.com/comment/83917857
downvote count: 0
answers question: http://stackoverflow.com/q/48445131
type: Answer

http://stackoverflow.com/comment/83792187
comment on: http://stackoverflow.com/a/48377373
has text: Thank you, I will look into contributing!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83770005
has text: I think you are correct that my server is the problem I just rebooted my machine and it works, I need to find out what is happening/wrong with the ports.
score: 0
comment on: http://stackoverflow.com/q/48390709
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48450599
answers question: http://stackoverflow.com/q/48450284
has comment: http://stackoverflow.com/comment/83898640
has body: You asked about template class, what we usually use in Django is class TemplateView, where you can provide template_name. It is also worth mentioning, that this book is quite old. It refers to version 0.96 (you can check on page 7), while newest Django version is 2.0. There has been a lot of changes since then, so I wouldn't recommend using it with newer versions.
type: Answer
has comment: http://stackoverflow.com/comment/83894756
score: 0
has comment: http://stackoverflow.com/comment/83895086

http://stackoverflow.com/comment/83685733
has text: Assuming your image is in a Label, just update the Label to use a new image with `label_instance.config(image=new_image)`. If you want a specific answer you will have to show us a [mcve].
score: 3
comment on: http://stackoverflow.com/q/48349678
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83708619
type: Comment
has text: This is very bad advice; it uses string formatting and leaves the user more exposed to SQL injection. There is no reason at all not to use a parameterized query for this.
type: AnswerComment
comment on: http://stackoverflow.com/a/48360902
score: 1